From f18dbbb51e5ad7f4c537953473c75593987b8f6d Mon Sep 17 00:00:00 2001 From: Masusder <59669685+Masusder@users.noreply.github.com> Date: Mon, 2 Nov 2026 17:42:03 +0100 Subject: [PATCH] Paper2D support + fixes (#718) --- CUE4Parse | 2 +- FModel/Creator/Bases/FN/BaseIcon.cs | 2 +- FModel/Creator/Utils.cs | 2 +- FModel/Enums.cs | 1 + FModel/Extensions/ClipboardExtensions.cs | 12 +- FModel/FModel.slnx | 1 + FModel/MainWindow.xaml | 2 + FModel/MainWindow.xaml.cs | 1 - FModel/Settings/UserSettings.cs | 10 +- FModel/ViewModels/ApplicationViewModel.cs | 15 -- FModel/ViewModels/AssetsFolderViewModel.cs | 49 +++-- FModel/ViewModels/AssetsListViewModel.cs | 5 +- FModel/ViewModels/CUE4ParseViewModel.cs | 32 ++- FModel/ViewModels/Commands/ImageCommand.cs | 15 +- FModel/ViewModels/ExportOptionsViewModel.cs | 12 +- FModel/ViewModels/GameFileViewModel.cs | 46 ++-- FModel/ViewModels/TabControlViewModel.cs | 201 ++++++++++++------ .../Controls/Explorer/AssetExplorerListBox.cs | 17 +- .../Explorer/ListExplorer/FileRow.xaml | 2 + .../Explorer/TiledExplorer/FileButton.xaml | 3 +- .../Controls/ExportOptionsControl.xaml | 59 +++-- .../Resources/Controls/ImageAnimation.cs | 164 ++++++++++++++ .../Converters/FileToGeometryConverter.cs | 2 +- FModel/Views/Resources/Resources.xaml | 11 +- Snooper | 2 +- 25 files changed, 496 insertions(+), 172 deletions(-) create mode 100644 FModel/Views/Resources/Controls/ImageAnimation.cs diff --git a/CUE4Parse b/CUE4Parse index e76778c1..56e904b3 160000 --- a/CUE4Parse +++ b/CUE4Parse @@ -1 +1 @@ -Subproject commit e76778c10ed25860e11ec488750753224d067d87 +Subproject commit 56e904b39e6be704af6418b3b803dbdbd3c39b6f diff --git a/FModel/Creator/Bases/FN/BaseIcon.cs b/FModel/Creator/Bases/FN/BaseIcon.cs index e6016509..4d349041 100644 --- a/FModel/Creator/Bases/FN/BaseIcon.cs +++ b/FModel/Creator/Bases/FN/BaseIcon.cs @@ -170,7 +170,7 @@ public class BaseIcon : UCreator { if (uObject is UTexture2D texture2D) { - SeriesBackground = texture2D.Decode().ToSkBitmap(); + SeriesBackground = texture2D.Decode(UserSettings.GetExportOptions()).ToSkBitmap(); return; } diff --git a/FModel/Creator/Utils.cs b/FModel/Creator/Utils.cs index 965917d9..1cae8765 100644 --- a/FModel/Creator/Utils.cs +++ b/FModel/Creator/Utils.cs @@ -124,7 +124,7 @@ public static class Utils public static SKBitmap GetB64Bitmap(string b64) => SKBitmap.Decode(new MemoryStream(Convert.FromBase64String(b64)) { Position = 0 }); public static SKBitmap GetBitmap(string fullPath) => TryLoadObject(fullPath, out UTexture2D texture) ? GetBitmap(texture) : null; - public static SKBitmap GetBitmap(UTexture2D texture) => texture.Decode(UserSettings.Default.CurrentDir.TexturePlatform).ToSkBitmap(); + public static SKBitmap GetBitmap(UTexture2D texture) => texture.Decode(UserSettings.GetExportOptions()).ToSkBitmap(); public static SKBitmap GetBitmap(byte[] data) => SKBitmap.Decode(data); public static SKBitmap ResizeWithRatio(this SKBitmap me, double width, double height) diff --git a/FModel/Enums.cs b/FModel/Enums.cs index c9ee59cd..5775c4a6 100644 --- a/FModel/Enums.cs +++ b/FModel/Enums.cs @@ -134,6 +134,7 @@ public enum EAssetCategory : uint GeometryCollection = Mesh + 5, ChaosClothAsset = Mesh + 6, Texture = AssetCategoryExtensions.CategoryBase + (3 << 16), + AnimatedTexture = Texture + 1, Materials = AssetCategoryExtensions.CategoryBase + (4 << 16), Material = Materials + 1, MaterialEditorData = Materials + 2, diff --git a/FModel/Extensions/ClipboardExtensions.cs b/FModel/Extensions/ClipboardExtensions.cs index 571e9156..10063b93 100644 --- a/FModel/Extensions/ClipboardExtensions.cs +++ b/FModel/Extensions/ClipboardExtensions.cs @@ -6,11 +6,21 @@ using System.IO; using System.Runtime.CompilerServices; using System.Text; using System.Windows; +using System.Windows.Media.Imaging; namespace FModel.Extensions; public static class ClipboardExtensions { + public static void SetImage(BitmapSource image, string fileName = null) + { + var encoder = new PngBitmapEncoder(); + encoder.Frames.Add(BitmapFrame.Create(image)); + using var stream = new MemoryStream(); + encoder.Save(stream); + SetImage(stream.ToArray(), fileName); + } + public static void SetImage(byte[] pngBytes, string fileName = null) { Clipboard.Clear(); @@ -195,4 +205,4 @@ public static class ClipboardExtensions return sb.ToString(); } -} \ No newline at end of file +} diff --git a/FModel/FModel.slnx b/FModel/FModel.slnx index 30826f89..fcc25716 100644 --- a/FModel/FModel.slnx +++ b/FModel/FModel.slnx @@ -1,5 +1,6 @@ + diff --git a/FModel/MainWindow.xaml b/FModel/MainWindow.xaml index c9534d38..c78b69a0 100644 --- a/FModel/MainWindow.xaml +++ b/FModel/MainWindow.xaml @@ -423,6 +423,7 @@ @@ -510,6 +511,7 @@ diff --git a/FModel/MainWindow.xaml.cs b/FModel/MainWindow.xaml.cs index 0eb120fc..179b9f61 100644 --- a/FModel/MainWindow.xaml.cs +++ b/FModel/MainWindow.xaml.cs @@ -120,7 +120,6 @@ public partial class MainWindow _applicationView.CUE4Parse.VerifyConsoleVariables(), _applicationView.CUE4Parse.VerifyOnDemandArchives(), _applicationView.CUE4Parse.InitMappings(), - ApplicationViewModel.InitDetex(), ApplicationViewModel.InitVgmStream(), Task.Run(() => { diff --git a/FModel/Settings/UserSettings.cs b/FModel/Settings/UserSettings.cs index f3a16a9e..b805c708 100644 --- a/FModel/Settings/UserSettings.cs +++ b/FModel/Settings/UserSettings.cs @@ -73,7 +73,8 @@ public sealed class UserSettings : ViewModel Default.CompressionFormat, Default.PngCompressionLevel, Default.TgaRleCompression, - Default.IncludeDisabledMeshSections + Default.IncludeDisabledMeshSections, + Default.AnimatedTextureExportFormat ); } @@ -533,6 +534,13 @@ public sealed class UserSettings : ViewModel set => SetProperty(ref _textureExportFormat, value); } + private EAnimatedTextureFormat _animatedTextureExportFormat = EAnimatedTextureFormat.Png; + public EAnimatedTextureFormat AnimatedTextureExportFormat + { + get => _animatedTextureExportFormat; + set => SetProperty(ref _animatedTextureExportFormat, value); + } + private int _textureQuality = 100; public int TextureQuality { diff --git a/FModel/ViewModels/ApplicationViewModel.cs b/FModel/ViewModels/ApplicationViewModel.cs index a4a65b5b..4e3c7ad1 100644 --- a/FModel/ViewModels/ApplicationViewModel.cs +++ b/FModel/ViewModels/ApplicationViewModel.cs @@ -314,21 +314,6 @@ public class ApplicationViewModel : ViewModel await ZlibHelper.InitializeAsync(zlibPath); } - public static async Task InitDetex() - { - var detexPath = Path.Combine(UserSettings.Default.OutputDirectory, ".data", DetexHelper.DLL_NAME); - if (File.Exists(DetexHelper.DLL_NAME)) - { - File.Move(DetexHelper.DLL_NAME, detexPath, true); - } - else if (!File.Exists(detexPath)) - { - await DetexHelper.LoadDllAsync(detexPath); - } - - DetexHelper.Initialize(detexPath); - } - public static async Task InitUnluac() { var unluacPath = Path.Combine(UserSettings.Default.OutputDirectory, ".data", UnluacHelper.DllName); diff --git a/FModel/ViewModels/AssetsFolderViewModel.cs b/FModel/ViewModels/AssetsFolderViewModel.cs index 43d4b964..db0f3181 100644 --- a/FModel/ViewModels/AssetsFolderViewModel.cs +++ b/FModel/ViewModels/AssetsFolderViewModel.cs @@ -60,6 +60,7 @@ public class TreeItem : ViewModel } private string _searchText = string.Empty; + private string[] _searchTerms = []; public string SearchText { get => _searchText; @@ -67,6 +68,7 @@ public class TreeItem : ViewModel { if (SetProperty(ref _searchText, value)) { + _searchTerms = value.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries); RefreshFilters(); } } @@ -104,7 +106,7 @@ public class TreeItem : ViewModel // BulkPopulate sorts Folders before this view is created _filteredFoldersView ??= new ListCollectionView(Folders) { - Filter = e => ItemFilter(e, SearchText.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries)) + Filter = ItemFilter }; return _filteredFoldersView; } @@ -132,7 +134,7 @@ public class TreeItem : ViewModel } PathAtThisPoint = pathHere; - AssetsList.AssetsView.Filter = o => ItemFilter(o, SearchText.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries)); + AssetsList.AssetsView.Filter = ItemFilter; } private void RefreshFilters() @@ -141,27 +143,22 @@ public class TreeItem : ViewModel FilteredFoldersView?.Refresh(); } - private bool ItemFilter(object item, IEnumerable filters) + private bool ItemFilter(object item) => item switch { - var f = filters.ToArray(); - switch (item) + GameFileViewModel entry => (SelectedCategory == EAssetCategory.All || entry.AssetCategory.IsOfCategory(SelectedCategory)) && MatchesSearch(entry.Asset.Name), + TreeItem folder => SelectedCategory == EAssetCategory.All && MatchesSearch(folder.Header), + _ => false + }; + + private bool MatchesSearch(string name) + { + foreach (var term in _searchTerms) { - case GameFileViewModel entry: - { - bool matchesSearch = f.Length == 0 || f.All(x => entry.Asset.Name.Contains(x, StringComparison.OrdinalIgnoreCase)); - bool matchesCategory = SelectedCategory == EAssetCategory.All || entry.AssetCategory.IsOfCategory(SelectedCategory); - - return matchesSearch && matchesCategory; - } - case TreeItem folder: - { - bool matchesSearch = f.Length == 0 || f.All(x => folder.Header.Contains(x, StringComparison.OrdinalIgnoreCase)); - bool matchesCategory = SelectedCategory == EAssetCategory.All; - - return matchesSearch && matchesCategory; - } + if (!name.Contains(term, StringComparison.OrdinalIgnoreCase)) + return false; } - return false; + + return true; } private async Task OnSelectedCategoryChanged() @@ -333,7 +330,7 @@ public class AssetsFolderViewModel : ViewModel } } - private static void SortFolders(RangeObservableCollection folders) + private static void SortEntries(RangeObservableCollection folders) { if (folders.Count > 1) { @@ -342,7 +339,13 @@ public class AssetsFolderViewModel : ViewModel foreach (var folder in folders) { - SortFolders(folder.Folders); + // Keep the source ordered so filtering does not sort the same assets on every edit + if (folder.AssetsList.Assets.Count > 1) + { + folder.AssetsList.Assets.ReplaceRange([.. folder.AssetsList.Assets.OrderBy(x => x.Asset.Path, StringComparer.CurrentCulture)]); + } + + SortEntries(folder.Folders); } } @@ -420,7 +423,7 @@ public class AssetsFolderViewModel : ViewModel lastNode?.AssetsList.Add(entry); } - SortFolders(treeItems); + SortEntries(treeItems); Folders.AddRange(treeItems); VisibleFolders.AddRange(treeItems); diff --git a/FModel/ViewModels/AssetsListViewModel.cs b/FModel/ViewModels/AssetsListViewModel.cs index 1666644c..673dc753 100644 --- a/FModel/ViewModels/AssetsListViewModel.cs +++ b/FModel/ViewModels/AssetsListViewModel.cs @@ -14,10 +14,7 @@ public class AssetsListViewModel { get { - _assetsView ??= new ListCollectionView(Assets) - { - SortDescriptions = { new SortDescription("Asset.Path", ListSortDirection.Ascending) } - }; + _assetsView ??= new ListCollectionView(Assets); return _assetsView; } } diff --git a/FModel/ViewModels/CUE4ParseViewModel.cs b/FModel/ViewModels/CUE4ParseViewModel.cs index b67fd8bf..53c0116b 100644 --- a/FModel/ViewModels/CUE4ParseViewModel.cs +++ b/FModel/ViewModels/CUE4ParseViewModel.cs @@ -964,7 +964,7 @@ public class CUE4ParseViewModel : ViewModel canvas.Translate(-bounds.Left, -bounds.Top); canvas.DrawPicture(svg.Picture); - TabControl.SelectedTab.AddImage(entry.NameWithoutExtension, false, bitmap, saveTextures, updateUi); + TabControl.SelectedTab.AddImage(entry.Name, data, bitmap, saveTextures, updateUi); break; } @@ -1277,6 +1277,34 @@ public class CUE4ParseViewModel : ViewModel TabControl.SelectedTab.SetDocumentText(luaScript.Code, false, false); return true; } + case UPaperSprite when (isNone || saveTextures) && pointer.Object.Value is UPaperSprite paperSprite: + { + if (saveTextures) + { + SaveExport(paperSprite); + } + + if (updateUi) + { + TabControl.SelectedTab.AddImage(paperSprite, false, true); + } + + return false; + } + case UPaperFlipbook when (isNone || saveTextures) && pointer.Object.Value is UPaperFlipbook paperFlipbook: + { + if (saveTextures) + { + SaveExport(paperFlipbook); + } + + if (updateUi) + { + TabControl.SelectedTab.AddImage(paperFlipbook, false, true); + } + + return false; + } case UTexture when (isNone || saveTextures) && pointer.Object.Value is UTexture texture: { if (saveTextures) @@ -1345,7 +1373,7 @@ public class CUE4ParseViewModel : ViewModel } } - TabControl.SelectedTab.AddImage(sourceFile.SubstringAfterLast('/'), false, bitmap, false, updateUi); + TabControl.SelectedTab.AddImage(Path.GetFileName(sourceFile) ?? svgasset.Name + ".svg", data, bitmap, false, updateUi); return false; } case UBiomesMaskTextureData when (isNone || saveTextures) && pointer.Object.Value is UBiomesMaskTextureData biomes && biomes.MaskData is { } maskData: diff --git a/FModel/ViewModels/Commands/ImageCommand.cs b/FModel/ViewModels/Commands/ImageCommand.cs index df4b7735..2542f37a 100644 --- a/FModel/ViewModels/Commands/ImageCommand.cs +++ b/FModel/ViewModels/Commands/ImageCommand.cs @@ -4,19 +4,18 @@ using FModel.Framework; using FModel.Views.Resources.Controls; using System.Windows; using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.IO; using FModel.Views.Resources.Converters; namespace FModel.ViewModels.Commands; -public class ImageCommand : ViewModelCommand +public class ImageCommand(TabItem contextViewModel) : ViewModelCommand(contextViewModel) { - public ImageCommand(TabItem contextViewModel) : base(contextViewModel) - { - } - public override void Execute(TabItem tabViewModel, object parameter) { - if (parameter == null || !tabViewModel.HasImage) return; + if (parameter == null || !tabViewModel.HasImage) + return; switch (parameter) { @@ -33,12 +32,14 @@ public class ImageCommand : ViewModelCommand ImageCtrl = { Source = tabViewModel.SelectedImage.Image } }; RenderOptions.SetBitmapScalingMode(popout.ImageCtrl, BoolToRenderModeConverter.Instance.Convert(tabViewModel.SelectedImage.RenderNearestNeighbor)); + ImageAnimation.SetFrames(popout.ImageCtrl, tabViewModel.SelectedImage.AnimationFrames); popout.Show(); }); break; } case "Copy": - ClipboardExtensions.SetImage(tabViewModel.SelectedImage.ImageBuffer, $"{tabViewModel.SelectedImage.ExportName}.png"); + case BitmapSource: + ClipboardExtensions.SetImage(parameter as BitmapSource ?? tabViewModel.SelectedImage.Image, Path.ChangeExtension(tabViewModel.SelectedImage.ExportName, "png")); break; case "Save": tabViewModel.SaveImage(); diff --git a/FModel/ViewModels/ExportOptionsViewModel.cs b/FModel/ViewModels/ExportOptionsViewModel.cs index dba46049..2cc14289 100644 --- a/FModel/ViewModels/ExportOptionsViewModel.cs +++ b/FModel/ViewModels/ExportOptionsViewModel.cs @@ -151,6 +151,13 @@ public class ExportOptionsViewModel : ViewModel } } + public IEnumerable AnimatedTextureFormats { get; } = Enum.GetValues(); + public EAnimatedTextureFormat SelectedAnimatedTextureFormat + { + get; + set => SetProperty(ref field, value); + } + public bool ShowTextureQuality => SelectedTextureFormat is ETextureFormat.Jpeg or ETextureFormat.Webp; public bool ShowPngCompression => SelectedTextureFormat is ETextureFormat.Png; public bool ShowTgaCompression => SelectedTextureFormat is ETextureFormat.Tga; @@ -213,6 +220,7 @@ public class ExportOptionsViewModel : ViewModel ExportMaterials = UserSettings.Default.SaveEmbeddedMaterials; SelectedTexturePlatform = UserSettings.Default.CurrentDir.TexturePlatform; SelectedTextureFormat = UserSettings.Default.TextureExportFormat; + SelectedAnimatedTextureFormat = UserSettings.Default.AnimatedTextureExportFormat; if (SelectedMeshFormat is EMeshFormat.USD) { _preUsdTextureFormat = SelectedTextureFormat; @@ -243,6 +251,7 @@ public class ExportOptionsViewModel : ViewModel UserSettings.Default.SaveEmbeddedMaterials = ExportMaterials; UserSettings.Default.CurrentDir.TexturePlatform = SelectedTexturePlatform; UserSettings.Default.TextureExportFormat = SelectedTextureFormat; + UserSettings.Default.AnimatedTextureExportFormat = SelectedAnimatedTextureFormat; UserSettings.Default.SaveHdrTexturesAsHdr = ExportHdrTexturesAsHdr; UserSettings.Default.SaveMorphTargets = ExportMorphTargets; UserSettings.Default.TextureQuality = TextureQuality; @@ -274,6 +283,7 @@ public class ExportOptionsViewModel : ViewModel SelectedCompressionFormat, PngCompressionLevel, TgaRleCompression, - IncludeDisabledMeshSections + IncludeDisabledMeshSections, + SelectedAnimatedTextureFormat ); } diff --git a/FModel/ViewModels/GameFileViewModel.cs b/FModel/ViewModels/GameFileViewModel.cs index 519c75f2..ed324771 100644 --- a/FModel/ViewModels/GameFileViewModel.cs +++ b/FModel/ViewModels/GameFileViewModel.cs @@ -7,6 +7,7 @@ using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using CUE4Parse_Conversion.Textures; +using CUE4Parse_Conversion.Textures.Paper2D; using CUE4Parse_Conversion.Dto; using CUE4Parse.FileProvider.Objects; using CUE4Parse.GameTypes.Borderlands3.Assets.Exports; @@ -63,6 +64,7 @@ using CUE4Parse.Utils; using FModel.Framework; using FModel.Services; using FModel.Settings; +using FModel.Views.Resources.Controls; using Serilog; using SkiaSharp; using Svg.Skia; @@ -194,6 +196,7 @@ public class GameFileViewModel(GameFile asset) : ViewModel Resolved |= EResolveCompute.Preview; return Task.CompletedTask; } + if (Asset.NameWithoutExtension.EndsWith("_BuiltData")) { AssetCategory = EAssetCategory.BuildData; @@ -234,7 +237,7 @@ public class GameFileViewModel(GameFile asset) : ViewModel UHoudiniAsset or UHoudiniStaticMesh => EAssetFamily.Houdini, - UPaperTileMap or UPaperTileLayer or UPaperTileSet or UPaperSprite => EAssetFamily.Paper2D, + UPaperTileMap or UPaperTileLayer or UPaperTileSet or UPaperSprite or UPaperFlipbook => EAssetFamily.Paper2D, _ => EAssetFamily.None, }; @@ -262,7 +265,8 @@ public class GameFileViewModel(GameFile asset) : ViewModel UHoudiniAsset => (EAssetCategory.Data, EBulkType.None), - UTexture => (EAssetCategory.Texture, EBulkType.Textures), + UTexture or UPaperSprite => (EAssetCategory.Texture, EBulkType.Textures), + UPaperFlipbook => (EAssetCategory.AnimatedTexture, EBulkType.Textures), UMaterialInterface => (EAssetCategory.Material, EBulkType.None), UMaterialInterfaceEditorOnlyData => (EAssetCategory.MaterialEditorData, EBulkType.None), @@ -324,9 +328,10 @@ public class GameFileViewModel(GameFile asset) : ViewModel _ => (EAssetCategory.All, EBulkType.None), }; + var obj = pointer.Object.Value; if (EmbeddedFilesDto.Supports(dummy)) { - var files = new EmbeddedFilesDto(pointer.Object.Value).Files; + var files = new EmbeddedFilesDto(obj).Files; EmbeddedFileExtensions = string.Join(", ", files.Select(file => "." + file.Extension).Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(extension => extension, StringComparer.OrdinalIgnoreCase)); if (files.Count > 0) AssetActions |= EBulkType.EmbeddedFiles; @@ -334,28 +339,49 @@ public class GameFileViewModel(GameFile asset) : ViewModel switch (AssetCategory) { - case EAssetCategory.Texture when pointer.Object.Value is UTexture texture: + case EAssetCategory.Texture: { if (!resolve.HasFlag(EResolveCompute.Preview)) break; - if (pointer.Object.Value is UTexture2DArray textureArray && textureArray.GetFirstMip() is { SizeZ: > 1 } firstMip) + if (obj is UTexture2DArray textureArray && textureArray.GetFirstMip() is { SizeZ: > 1 } firstMip) NumTextures = firstMip.SizeZ; - var img = texture.Decode(MaxPreviewSize, UserSettings.Default.CurrentDir.TexturePlatform); + var options = UserSettings.GetExportOptions(); + var img = obj switch + { + UTexture texture => texture.Decode(MaxPreviewSize, options), + UPaperSprite sprite => sprite.Decode(options), + _ => null + }; if (img != null) { using var bitmap = img.ToSkBitmap(); using var image = bitmap.Encode(SKEncodedImageFormat.Png, 100); SetPreviewImage(image); } + else + { + Resolved |= EResolveCompute.Preview; + } + + break; + } + case EAssetCategory.AnimatedTexture when obj is UPaperFlipbook flipbook: + { + if (!resolve.HasFlag(EResolveCompute.Preview)) + break; + + var preview = ImageAnimation.CreateThumbnail(flipbook, UserSettings.GetExportOptions(), MaxPreviewSize); + Application.Current.Dispatcher.InvokeAsync(() => PreviewImage = preview); + if (preview == null) Resolved |= EResolveCompute.Preview; break; } case EAssetCategory.ItemDefinitionBase: if (!resolve.HasFlag(EResolveCompute.Preview)) break; - if (pointer.Object.Value is UItemDefinitionBase itemDef) + if (obj is UItemDefinitionBase itemDef) { if (LookupPreview(itemDef.DataList)) break; @@ -372,7 +398,7 @@ public class GameFileViewModel(GameFile asset) : ViewModel !icon.TryLoad(out var texture)) continue; - var img = texture.Decode(MaxPreviewSize, UserSettings.Default.CurrentDir.TexturePlatform); + var img = texture.Decode(MaxPreviewSize, UserSettings.GetExportOptions()); if (img == null) return false; using var bitmap = img.ToSkBitmap(); @@ -515,7 +541,6 @@ public class GameFileViewModel(GameFile asset) : ViewModel using var image = bitmap.Encode(lowercaseExtension == "jpg" ? SKEncodedImageFormat.Jpeg : SKEncodedImageFormat.Png, 100); SetPreviewImage(image); - bitmap.Dispose(); }); } @@ -550,14 +575,12 @@ public class GameFileViewModel(GameFile asset) : ViewModel { using var ms = new MemoryStream(data.ToArray()); ms.Position = 0; - var bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.StreamSource = ms; bitmap.EndInit(); bitmap.Freeze(); - Application.Current.Dispatcher.InvokeAsync(() => PreviewImage = bitmap); } @@ -570,7 +593,6 @@ public class GameFileViewModel(GameFile asset) : ViewModel _previewCts?.Cancel(); _previewCts = new CancellationTokenSource(); var token = _previewCts.Token; - Task.Delay(100, token).ContinueWith(t => { if (t.IsCanceled) return; diff --git a/FModel/ViewModels/TabControlViewModel.cs b/FModel/ViewModels/TabControlViewModel.cs index a2b7ddf7..a6b28af9 100644 --- a/FModel/ViewModels/TabControlViewModel.cs +++ b/FModel/ViewModels/TabControlViewModel.cs @@ -7,9 +7,11 @@ using System.Windows; using System.Windows.Media.Imaging; using CUE4Parse_Conversion.Options; using CUE4Parse.FileProvider.Objects; +using CUE4Parse.UE4.Assets.Exports.Paper2D; using CUE4Parse.UE4.Assets.Exports.Texture; using CUE4Parse.Utils; using CUE4Parse_Conversion.Textures; +using CUE4Parse_Conversion.Textures.Paper2D; using FModel.Extensions; using FModel.Framework; using FModel.Services; @@ -25,31 +27,62 @@ namespace FModel.ViewModels; public class TabImage : ViewModel { + private readonly string _name; + private readonly object _source; + public string ExportName { get; set; } public byte[] ImageBuffer { get; set; } + public ImageAnimation.Frame[] AnimationFrames { get; } + public bool CanDisableAlpha => AnimationFrames == null; + + public TabImage(string name, CFlipbook flipbook) + { + _name = name; + _source = flipbook; + RenderNearestNeighbor = true; + Encode(UserSettings.GetExportOptions()); + AnimationFrames = ImageAnimation.CreateFrames(flipbook); + Image = ImageAnimation.CreateSource(AnimationFrames); + } + public TabImage(string name, bool rnn, SKBitmap img) { - ExportName = name; + _name = name; + _source = img; RenderNearestNeighbor = rnn; SetImage(img); + Encode(UserSettings.GetExportOptions()); } public TabImage(string name, bool rnn, CTexture img) { - ExportName = name; + _name = name; + _source = img; RenderNearestNeighbor = rnn; - SetImage(img); + SetImage(img?.ToSkBitmap()); + Encode(UserSettings.GetExportOptions()); } - private BitmapImage _image; - public BitmapImage Image + public TabImage(string exportName, byte[] data, SKBitmap preview) + { + _name = Path.GetFileNameWithoutExtension(exportName); + _source = data; + ExportName = exportName; + ImageBuffer = data; + SetImage(preview); + } + + private BitmapSource _image; + public BitmapSource Image { get => _image; set { - if (_image == value) return; + if (_image == value) + return; + SetProperty(ref _image, value); } } @@ -67,6 +100,9 @@ public class TabImage : ViewModel get => _noAlpha; set { + if (!CanDisableAlpha) + return; + SetProperty(ref _noAlpha, value); ResetImage(); } @@ -82,49 +118,54 @@ public class TabImage : ViewModel } _bmp = bitmap; - ExportName += "." + (NoAlpha ? "jpg" : "png"); - using var data = _bmp.Encode(NoAlpha ? SKEncodedImageFormat.Jpeg : SKEncodedImageFormat.Png, 100); - using var stream = new MemoryStream(ImageBuffer = data.ToArray(), false); - var image = new BitmapImage(); - image.BeginInit(); - image.CacheOption = BitmapCacheOption.OnLoad; - image.StreamSource = stream; - image.EndInit(); - image.Freeze(); - Image = image; + using var opaque = NoAlpha ? _bmp.Copy(SKColorType.Rgb888x) : null; + using var data = (opaque ?? _bmp).Encode(SKEncodedImageFormat.Png, 100); + using var stream = new MemoryStream(data.ToArray(), false); + Image = CreateImage(stream); } - private void SetImage(CTexture bitmap) + public void Encode(ExportOptions options) { - if (bitmap is null) + string ext; + switch (_source) { - ImageBuffer = null; - Image = null; - return; + case byte[] data: + ImageBuffer = data; + return; + case CFlipbook flipbook: + ImageBuffer = flipbook.Encode(options, out ext); + break; + case CTexture texture: + ImageBuffer = texture.Encode(options, out ext); + break; + case SKBitmap source: + { + using var bitmap = new SKBitmap(new SKImageInfo(source.Width, source.Height, SKColorType.Rgba8888, SKAlphaType.Unpremul)); + using var pixels = source.PeekPixels(); + if (!pixels.ReadPixels(bitmap.Info, bitmap.GetPixels(), bitmap.RowBytes)) + throw new InvalidOperationException("Failed to read image pixels for export."); + + var converted = new CTexture(bitmap.Width, bitmap.Height, EPixelFormat.PF_R8G8B8A8, bitmap.Bytes); + ImageBuffer = converted.Encode(options, out ext); + break; + } + default: + return; } - _bmp = bitmap.ToSkBitmap(); - byte[] imageData = _bmp.Encode(NoAlpha ? SKEncodedImageFormat.Jpeg : SKEncodedImageFormat.Png, 100).ToArray(); + ExportName = _name + "." + ext; + } - if (PixelFormatUtils.IsHDR(bitmap.PixelFormat) || (UserSettings.Default.TextureExportFormat != ETextureFormat.Jpeg && UserSettings.Default.TextureExportFormat != ETextureFormat.Png)) - { - ImageBuffer = bitmap.Encode(UserSettings.Default.TextureExportFormat, UserSettings.Default.SaveHdrTexturesAsHdr, out var ext); - ExportName += "." + ext; - } - else - { - ImageBuffer = imageData; - ExportName += "." + (NoAlpha || UserSettings.Default.TextureExportFormat == ETextureFormat.Jpeg ? "jpg" : "png"); - } - - using var stream = new MemoryStream(imageData); + private static BitmapImage CreateImage(Stream stream) + { + stream.Position = 0; var image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = stream; image.EndInit(); image.Freeze(); - Image = image; + return image; } private SKBitmap _bmp; @@ -231,7 +272,9 @@ public class TabItem : ViewModel get => _highlighter; set { - if (_highlighter == value) return; + if (_highlighter == value) + return; + SetProperty(ref _highlighter, value); } } @@ -242,10 +285,12 @@ public class TabItem : ViewModel get => _selectedImage; set { - if (_selectedImage == value) return; + if (_selectedImage == value) + return; + SetProperty(ref _selectedImage, value); - RaisePropertyChanged("HasImage"); - RaisePropertyChanged("Page"); + RaisePropertyChanged(nameof(HasImage)); + RaisePropertyChanged(nameof(Page)); } } @@ -269,7 +314,7 @@ public class TabItem : ViewModel public TabItem(GameFile entry) { Entry = entry; - _images = new ObservableCollection(); + _images = []; } public void SoftReset(GameFile entry) @@ -281,25 +326,43 @@ public class TabItem : ViewModel { _images.Clear(); SelectedImage = null; - RaisePropertyChanged("HasMultipleImages"); + RaisePropertyChanged(nameof(HasMultipleImages)); Document ??= new TextDocument(); Document.Text = string.Empty; }); } + public void AddImage(UPaperSprite sprite, bool save, bool updateUi) + { + var decoded = sprite.Decode(UserSettings.GetExportOptions()); + if (decoded == null) + return; + + AddImage(sprite.Name, true, decoded, save, updateUi); + } + + public void AddImage(UPaperFlipbook flipbook, bool save, bool updateUi) + { + var decoded = flipbook.Decode(UserSettings.GetExportOptions()); + if (decoded == null) + return; + + AddImage(new TabImage(flipbook.Name, decoded), save, updateUi); + } + public void AddImage(UTexture texture, bool save, bool updateUi) { var appendLayerNumber = false; var img = new CTexture[1]; if (texture is UTexture2DArray textureArray) { - img = textureArray.DecodeTextureArray(UserSettings.Default.CurrentDir.TexturePlatform); + img = textureArray.DecodeTextureArray(UserSettings.GetExportOptions()); appendLayerNumber = true; } else { - img[0] = texture.Decode(UserSettings.Default.CurrentDir.TexturePlatform); + img[0] = texture.Decode(UserSettings.GetExportOptions()); if (texture is UTextureCube) { img[0] = img[0].ToPanorama(); @@ -326,32 +389,27 @@ public class TabItem : ViewModel } public void AddImage(string name, bool rnn, CTexture img, bool save, bool updateUi) - { - Application.Current.Dispatcher.Invoke(() => - { - var t = new TabImage(name, rnn, img); - if (save) SaveImage(t, updateUi); - if (!updateUi) return; - - _images.Add(t); - SelectedImage ??= t; - RaisePropertyChanged("Page"); - RaisePropertyChanged("HasMultipleImages"); - }); - } + => AddImage(new TabImage(name, rnn, img), save, updateUi); public void AddImage(string name, bool rnn, SKBitmap img, bool save, bool updateUi) + => AddImage(new TabImage(name, rnn, img), save, updateUi); + + public void AddImage(string exportName, byte[] data, SKBitmap preview, bool save, bool updateUi) + => AddImage(new TabImage(exportName, data, preview), save, updateUi); + + private void AddImage(TabImage image, bool save, bool updateUi) { Application.Current.Dispatcher.Invoke(() => { - var t = new TabImage(name, rnn, img); - if (save) SaveImage(t, updateUi); - if (!updateUi) return; + if (save) + SaveImage(image, updateUi); + if (!updateUi) + return; - _images.Add(t); - SelectedImage ??= t; - RaisePropertyChanged("Page"); - RaisePropertyChanged("HasMultipleImages"); + _images.Add(image); + SelectedImage ??= image; + RaisePropertyChanged(nameof(Page)); + RaisePropertyChanged(nameof(HasMultipleImages)); }); } @@ -366,15 +424,18 @@ public class TabItem : ViewModel Document.Text = text; Document.UndoStack.ClearAll(); - if (save) SaveProperty(updateUi); + if (save) + SaveProperty(updateUi); }); } public void SaveImage() => SaveImage(SelectedImage, true); private void SaveImage(TabImage image, bool updateUi) { - if (image is null) return; + if (image is null) + return; + image.Encode(UserSettings.GetExportOptions()); var path = Path.Combine(UserSettings.Default.TextureDirectory, UserSettings.Default.KeepDirectoryStructure ? Entry.Directory : "", image.ExportName).Replace('\\', '/'); Directory.CreateDirectory(path.SubstringBeforeLast('/')); @@ -390,7 +451,9 @@ public class TabItem : ViewModel private void SaveImage(TabImage image, string path) { - if (image.ImageBuffer is null) return; + if (image.ImageBuffer is null) + return; + using var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read); fs.Write(image.ImageBuffer, 0, image.ImageBuffer.Length); } @@ -477,7 +540,9 @@ public class TabControlViewModel : ViewModel return; } - if (!CanAddTabs) return; + if (!CanAddTabs) + return; + Application.Current.Dispatcher.Invoke(() => { _tabItems.Add(new TabItem(entry)); diff --git a/FModel/Views/Resources/Controls/Explorer/AssetExplorerListBox.cs b/FModel/Views/Resources/Controls/Explorer/AssetExplorerListBox.cs index b3ea662c..dddb4be3 100644 --- a/FModel/Views/Resources/Controls/Explorer/AssetExplorerListBox.cs +++ b/FModel/Views/Resources/Controls/Explorer/AssetExplorerListBox.cs @@ -1,20 +1,21 @@ -using System.Collections; using System.Windows.Controls; -using System.Windows.Controls.Primitives; -using FModel.Extensions; namespace FModel.Views.Resources.Controls.Explorer; public class AssetExplorerListBox : ListBox { - protected override void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue) + public AssetExplorerListBox() { - base.OnItemsSourceChanged(oldValue, newValue); + AddHandler(ScrollViewer.ScrollChangedEvent, new ScrollChangedEventHandler(OnScrollChanged)); + } - // Always start at the top, otherwise inherited offset can cause items not to be visible when we change folder - if (this.FindVisualChild() is IScrollInfo scroll) + // This is important, when we scroll and then change folder, scroll offset won't be adjusted and we will end up with missing items + // Same applies to filtering assets as that also changes scroll offset + private void OnScrollChanged(object sender, ScrollChangedEventArgs e) + { + if (e.OriginalSource is ScrollViewer scroll && scroll.VerticalOffset > scroll.ScrollableHeight) { - scroll.SetVerticalOffset(0); + scroll.ScrollToVerticalOffset(scroll.ScrollableHeight); } } } diff --git a/FModel/Views/Resources/Controls/Explorer/ListExplorer/FileRow.xaml b/FModel/Views/Resources/Controls/Explorer/ListExplorer/FileRow.xaml index c3d3d40b..0e095d3a 100644 --- a/FModel/Views/Resources/Controls/Explorer/ListExplorer/FileRow.xaml +++ b/FModel/Views/Resources/Controls/Explorer/ListExplorer/FileRow.xaml @@ -4,6 +4,7 @@ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:vm="clr-namespace:FModel.ViewModels" + xmlns:controls="clr-namespace:FModel.Views.Resources.Controls" xmlns:converters="clr-namespace:FModel.Views.Resources.Converters" xmlns:adonisUi="clr-namespace:AdonisUI;assembly=AdonisUI" mc:Ignorable="d" @@ -24,6 +25,7 @@ Height="20" Margin="0 0 8 0"> diff --git a/FModel/Views/Resources/Controls/Explorer/TiledExplorer/FileButton.xaml b/FModel/Views/Resources/Controls/Explorer/TiledExplorer/FileButton.xaml index ec1d1d94..a814b42c 100644 --- a/FModel/Views/Resources/Controls/Explorer/TiledExplorer/FileButton.xaml +++ b/FModel/Views/Resources/Controls/Explorer/TiledExplorer/FileButton.xaml @@ -7,6 +7,7 @@ d:DataContext="{d:DesignInstance Type=vm:GameFileViewModel, IsDesignTimeCreatable=False}" xmlns:vm="clr-namespace:FModel.ViewModels" + xmlns:controls="clr-namespace:FModel.Views.Resources.Controls" xmlns:converters="clr-namespace:FModel.Views.Resources.Converters" xmlns:adonisUi="clr-namespace:AdonisUI;assembly=AdonisUI" Width="128" Height="192" @@ -19,7 +20,7 @@ - + + + + + + + + + + + @@ -243,17 +264,17 @@ - - - - @@ -266,37 +287,37 @@ - - - - + - - - + - - + @@ -306,9 +327,9 @@ - - + @@ -323,8 +344,8 @@ Text="For geometry-only exports, it can be significantly faster to disable this option." /> - - + diff --git a/FModel/Views/Resources/Controls/ImageAnimation.cs b/FModel/Views/Resources/Controls/ImageAnimation.cs new file mode 100644 index 00000000..16087fc1 --- /dev/null +++ b/FModel/Views/Resources/Controls/ImageAnimation.cs @@ -0,0 +1,164 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Threading; +using CUE4Parse.UE4.Assets.Exports.Paper2D; +using CUE4Parse_Conversion.Options; +using CUE4Parse_Conversion.Textures; +using CUE4Parse_Conversion.Textures.Paper2D; + +namespace FModel.Views.Resources.Controls; + +public static class ImageAnimation +{ + public sealed record Frame(BitmapSource Image, TimeSpan Duration); + + public static readonly DependencyProperty FramesProperty = DependencyProperty.RegisterAttached("Frames", typeof(IReadOnlyList), typeof(ImageAnimation), new PropertyMetadata(null, OnFramesChanged)); + + private static readonly DependencyProperty _playbackProperty = DependencyProperty.RegisterAttached("Playback", typeof(Playback), typeof(ImageAnimation)); + + public static IReadOnlyList GetFrames(DependencyObject image) => (IReadOnlyList) image.GetValue(FramesProperty); + public static void SetFrames(DependencyObject image, IReadOnlyList frames) => image.SetValue(FramesProperty, frames); + + public static BitmapSource CreateSource(IReadOnlyList frames) + { + if (frames is not { Count: > 0 }) + return null; + if (frames.Count == 1) + return frames[0].Image; + + var source = frames[0].Image.Clone(); + SetFrames(source, frames); + source.Freeze(); + return source; + } + + internal static Frame[] CreateFrames(CFlipbook flipbook, int maxSize = 0, CancellationToken cancellationToken = default) + { + using var animation = flipbook.ToImage(new ExportOptions(), maxSize: maxSize, cancellationToken: cancellationToken); + var frames = new Frame[animation.Frames.Count]; + var minimumDuration = maxSize > 0 ? 1.0 / 15 : 0.001; + for (var i = 0; i < frames.Length; i++) + { + cancellationToken.ThrowIfCancellationRequested(); + var frame = animation.Frames[i]; + var pixels = new byte[frame.Width * frame.Height * 4]; + frame.CopyPixelDataTo(pixels); + for (var pixel = 0; pixel < pixels.Length; pixel += 4) + { + (pixels[pixel], pixels[pixel + 2]) = (pixels[pixel + 2], pixels[pixel]); + } + + var image = BitmapSource.Create(frame.Width, frame.Height, 96, 96, PixelFormats.Bgra32, null, pixels, frame.Width * 4); + image.Freeze(); + + var seconds = flipbook.FramesPerSecond > 0 ? flipbook.Frames[i].FrameRun / (double) flipbook.FramesPerSecond : 0; + frames[i] = new Frame(image, TimeSpan.FromSeconds(Math.Max(minimumDuration, seconds))); + } + + return frames; + } + + // Only light animations, otherwise use the first frame as a thumbnail + internal static BitmapSource CreateThumbnail(UPaperFlipbook flipbook, ExportOptions options, int maxSize) + { + var cache = new Dictionary(); + if (flipbook.FramesPerSecond > 0 && flipbook.KeyFrames.Length is > 1 and <= 64) + { + var pixels = flipbook.KeyFrames.Where(frame => frame.FrameRun > 0).Select(frame => frame.LoadSprite()).OfType().Distinct() + .Sum(sprite => (double) sprite.BakedSourceDimension.X * sprite.BakedSourceDimension.Y); + if (pixels <= 16 * 1024 * 1024 && flipbook.Decode(options, cache) is { } decoded) + { + var minimumRun = Math.Max(1, (int) Math.Ceiling(decoded.FramesPerSecond / 15)); + var frames = new List(); + foreach (var frame in decoded.Frames) + { + if (frames.Count > 0 && frames[^1].FrameRun < minimumRun) + { + var previous = frames[^1]; + frames[^1] = new CFlipbookFrame(previous.Texture, previous.FrameRun + frame.FrameRun, previous.Offset); + } + else + { + frames.Add(frame); + } + } + + return CreateSource(CreateFrames(new CFlipbook(frames, decoded.FramesPerSecond), maxSize)); + } + } + + var first = flipbook.KeyFrames.Where(frame => frame.FrameRun > 0).Select(frame => frame.LoadSprite()?.Decode(options, cache)).FirstOrDefault(texture => texture != null); + return first == null ? null : CreateSource(CreateFrames(new CFlipbook([new CFlipbookFrame(first)], 1), maxSize)); + } + + private static void OnFramesChanged(DependencyObject element, DependencyPropertyChangedEventArgs args) + { + if (element is not Image image) + return; + + (image.GetValue(_playbackProperty) as Playback)?.Dispose(); + image.ClearValue(_playbackProperty); + if (args.NewValue is not IReadOnlyList { Count: > 0 } frames) + return; + + image.SetCurrentValue(Image.SourceProperty, frames[0].Image); + if (frames.Count > 1) + { + image.SetValue(_playbackProperty, new Playback(image, frames)); + } + } + + private sealed class Playback : IDisposable + { + private readonly Image _image; + private readonly IReadOnlyList _frames; + private readonly DispatcherTimer _timer; + private int _index; + + public Playback(Image image, IReadOnlyList frames) + { + _image = image; + _frames = frames; + _timer = new DispatcherTimer(DispatcherPriority.Render, image.Dispatcher) { Interval = frames[0].Duration }; + _timer.Tick += (_, _) => + { + _index = (_index + 1) % _frames.Count; + _image.SetCurrentValue(Image.SourceProperty, _frames[_index].Image); + _timer.Interval = _frames[_index].Duration; + }; + image.Loaded += UpdatePlayback; + image.Unloaded += OnUnloaded; + image.IsVisibleChanged += OnIsVisibleChanged; + UpdatePlayback(image, null); + } + + private void UpdatePlayback(object sender, RoutedEventArgs args) + { + if (_image.IsLoaded && _image.IsVisible) + { + _timer.Start(); + } + else + { + _timer.Stop(); + } + } + + private void OnUnloaded(object sender, RoutedEventArgs args) => _timer.Stop(); + private void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs args) => UpdatePlayback(sender, null); + + public void Dispose() + { + _timer.Stop(); + _image.Loaded -= UpdatePlayback; + _image.Unloaded -= OnUnloaded; + _image.IsVisibleChanged -= OnIsVisibleChanged; + } + } +} diff --git a/FModel/Views/Resources/Converters/FileToGeometryConverter.cs b/FModel/Views/Resources/Converters/FileToGeometryConverter.cs index 64789c23..dc6e0535 100644 --- a/FModel/Views/Resources/Converters/FileToGeometryConverter.cs +++ b/FModel/Views/Resources/Converters/FileToGeometryConverter.cs @@ -28,7 +28,7 @@ public class FileToGeometryConverter : IMultiValueConverter EAssetCategory.UserDefinedStruct => ("BlueprintIcon", "UserDefinedStructBrush"), EAssetCategory.CookedMetaData => ("BlueprintIcon", "CookedMetaDataBrush"), - EAssetCategory.Texture => ("TextureIconAlt", "TextureBrush"), + EAssetCategory.Texture or EAssetCategory.AnimatedTexture => ("TextureIconAlt", "TextureBrush"), EAssetCategory.StaticMesh => ("StaticMeshIconAlt", "NeutralBrush"), EAssetCategory.SkeletalMesh => ("SkeletalMeshIconAlt", "NeutralBrush"), diff --git a/FModel/Views/Resources/Resources.xaml b/FModel/Views/Resources/Resources.xaml index cf1fb7ca..3b90dc3c 100644 --- a/FModel/Views/Resources/Resources.xaml +++ b/FModel/Views/Resources/Resources.xaml @@ -528,6 +528,7 @@ @@ -535,8 +536,7 @@ - - + @@ -547,7 +547,7 @@ - + @@ -556,7 +556,7 @@ - + @@ -565,6 +565,9 @@ + + diff --git a/Snooper b/Snooper index 526a2be7..e59c8966 160000 --- a/Snooper +++ b/Snooper @@ -1 +1 @@ -Subproject commit 526a2be78db6b49341dd05a6a48246c50a8b944f +Subproject commit e59c8966e375830ccdd42adee4b9bf7ac0702124