From a71ba41770e93c00c0de0cc84a209d8a21f182d4 Mon Sep 17 00:00:00 2001 From: Masusder <59669685+Masusder@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:55:58 +0100 Subject: [PATCH] Mesh/Material thumbnail preview / Reworked preview resolver / Fixed filters resolve / Improved preview settings section --- CUE4Parse | 2 +- FModel/Enums.cs | 10 + FModel/Framework/SnooperHost.cs | 75 +- FModel/MainWindow.xaml | 1 - FModel/MainWindow.xaml.cs | 30 +- .../Services/AssetExplorerPreviewResolver.cs | 359 ++++++++++ FModel/Settings/UserSettings.cs | 14 + FModel/ViewModels/AssetsFolderViewModel.cs | 72 +- FModel/ViewModels/CUE4ParseViewModel.cs | 1 + FModel/ViewModels/GameFileViewModel.cs | 642 +++++++++--------- FModel/ViewModels/SettingsViewModel.cs | 21 + FModel/ViewModels/SnooperViewModel.cs | 8 + .../Explorer/ListExplorer/FileRow.xaml | 16 +- .../Explorer/TiledExplorer/FileButton.xaml | 16 +- FModel/Views/SettingsView.xaml | 82 ++- Snooper | 2 +- 16 files changed, 966 insertions(+), 385 deletions(-) create mode 100644 FModel/Services/AssetExplorerPreviewResolver.cs diff --git a/CUE4Parse b/CUE4Parse index c95dd9b5..ff2068ca 160000 --- a/CUE4Parse +++ b/CUE4Parse @@ -1 +1 @@ -Subproject commit c95dd9b587a6fb8cbf030d6b84d37cd0c7512b7d +Subproject commit ff2068caf456c4fe86f846d770526b2479295c7d diff --git a/FModel/Enums.cs b/FModel/Enums.cs index 9b5a79b7..eedc0f36 100644 --- a/FModel/Enums.cs +++ b/FModel/Enums.cs @@ -199,3 +199,13 @@ public enum EExplorerViewMode Grid, List } + +public enum EMeshPreviewMode +{ + [Description("Automatic")] + Automatic, + [Description("On-Hover")] + OnHover, + [Description("None")] + None +} diff --git a/FModel/Framework/SnooperHost.cs b/FModel/Framework/SnooperHost.cs index 30e49a86..8f799926 100644 --- a/FModel/Framework/SnooperHost.cs +++ b/FModel/Framework/SnooperHost.cs @@ -1,10 +1,16 @@ using System; +using System.Collections.Concurrent; using System.Threading; +using System.Threading.Tasks; +using CUE4Parse.FileProvider; +using CUE4Parse.FileProvider.Objects; +using CUE4Parse.UE4.Assets.Exports.Texture; using Editor; using FModel.Views.Resources.Controls; using OpenTK.Windowing.Desktop; using Serilog; using Serilog.Context; +using Snooper.Rendering; namespace FModel.Framework; @@ -20,10 +26,13 @@ namespace FModel.Framework; public sealed class SnooperHost(Func build, Action onStartupFailure) : IDisposable { private readonly Lock _lock = new(); - private readonly SemaphoreSlim _wanted = new(0); + private readonly AutoResetEvent _wanted = new(false); private readonly ManualResetEventSlim _ready = new(); + private readonly ConcurrentQueue _renderRequests = new(); + private readonly MeshPreviewRenderer _meshPreviews = new(); private volatile EditorWindow? _window; + private volatile bool _openRequested; private Exception? _failure; private Thread? _thread; @@ -36,7 +45,8 @@ public sealed class SnooperHost(Func build, Action onSt _thread ??= StartThread(); _ready.Reset(); - _wanted.Release(); + _openRequested = true; + _wanted.Set(); _ready.Wait(); if (_window is { } window) return window; @@ -48,6 +58,55 @@ public sealed class SnooperHost(Func build, Action onSt return null; } + public Task RenderMeshPreviewAsync(IFileProvider provider, GameFile file, ETexturePlatform platform) + { + if (_meshPreviews.IsReady) + return _meshPreviews.RenderAsync(provider, file, platform); + + var completion = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously); + QueueGraphicsWork(() => + { + try + { + _meshPreviews.Initialize(loadBindings: _window == null); + completion.SetResult(_meshPreviews.RenderAsync(provider, file, platform)); + } + catch (Exception exception) + { + completion.SetException(exception); + } + }); + + return completion.Task.Unwrap(); + } + + public void CloseMeshPreviews() + { + if (_thread is not null) + QueueGraphicsWork(_meshPreviews.Dispose); + } + + private void QueueGraphicsWork(Action action) + { + lock (_lock) + { + _thread ??= StartThread(); + _renderRequests.Enqueue(action); + if (_window is { } window) + window.Invoke(RunGraphicsWork); + else + _wanted.Set(); + } + } + + private void RunGraphicsWork() + { + if (_renderRequests.TryDequeue(out var action)) + action(); + if (!_renderRequests.IsEmpty && _window is { } window) + window.Invoke(RunGraphicsWork); + } + private Thread StartThread() { // this thread must never die until fmodel closes @@ -66,12 +125,22 @@ public sealed class SnooperHost(Func build, Action onSt while (true) { - _wanted.Wait(); + if (!_openRequested && _renderRequests.IsEmpty) + _wanted.WaitOne(); + + if (!_openRequested) + { + RunGraphicsWork(); + continue; + } + _openRequested = false; try { _failure = null; _window = build(); + if (!_renderRequests.IsEmpty) + _window.Invoke(RunGraphicsWork); } catch (Exception e) { diff --git a/FModel/MainWindow.xaml b/FModel/MainWindow.xaml index c79a0f23..224aebfb 100644 --- a/FModel/MainWindow.xaml +++ b/FModel/MainWindow.xaml @@ -650,7 +650,6 @@ diff --git a/FModel/MainWindow.xaml.cs b/FModel/MainWindow.xaml.cs index 179b9f61..c2b0c47d 100644 --- a/FModel/MainWindow.xaml.cs +++ b/FModel/MainWindow.xaml.cs @@ -1,7 +1,6 @@ using System; using System.Collections; using System.ComponentModel; -using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows; @@ -27,6 +26,7 @@ public partial class MainWindow private ThreadWorkerViewModel _threadWorkerView => ApplicationService.ThreadWorkerView; private ApplicationViewModel _applicationView => ApplicationService.ApplicationView; private DiscordHandler _discordHandler => DiscordService.DiscordHandler; + private readonly AssetExplorerPreviewResolver _previewResolver; public MainWindow() { @@ -55,9 +55,8 @@ public partial class MainWindow DataContext = _applicationView; InitializeComponent(); - AssetsExplorer.ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged; - AssetsListExplorer.ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged; - AssetsListName.ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged; + _previewResolver = new AssetExplorerPreviewResolver(_applicationView, AssetsExplorer, AssetsListExplorer, AssetsListName); + AssetsExplorer.SelectionChanged += (_, e) => SyncSelection(AssetsListName, e); AssetsListExplorer.SelectionChanged += (_, e) => SyncSelection(AssetsListName, e); AssetsListName.SelectionChanged += (_, e) => SyncSelection(AssetsExplorer, e); @@ -83,6 +82,7 @@ public partial class MainWindow private void OnClosing(object sender, CancelEventArgs e) { + _previewResolver.Dispose(); _discordHandler.Dispose(); } @@ -274,28 +274,6 @@ public partial class MainWindow private void OnFolderOpenAssets(object sender, EventArgs e) => _applicationView.SelectedLeftTabIndex = 2; - private void OnPreviewTexturesToggled(object sender, RoutedEventArgs e) => ItemContainerGenerator_StatusChanged(AssetsExplorer.ItemContainerGenerator, EventArgs.Empty); - private void ItemContainerGenerator_StatusChanged(object sender, EventArgs e) - { - if (sender is not ItemContainerGenerator { Status: GeneratorStatus.ContainersGenerated } generator) - return; - - var list = ReferenceEquals(generator, AssetsExplorer.ItemContainerGenerator) ? AssetsExplorer - : ReferenceEquals(generator, AssetsListExplorer.ItemContainerGenerator) ? AssetsListExplorer - : AssetsListName; - - if (!list.IsVisible || list.FindVisualChild() is not { } panel) - return; - - foreach (var container in panel.Children.OfType()) - { - if (container is FrameworkElement { IsVisible: true, DataContext: GameFileViewModel file }) - { - file.OnIsVisible(); - } - } - } - private void OnAssetsTreeSelectedItemChanged(object sender, SelectionChangedEventArgs e) { if (sender is not ListBox { SelectedItem: TreeItem }) diff --git a/FModel/Services/AssetExplorerPreviewResolver.cs b/FModel/Services/AssetExplorerPreviewResolver.cs new file mode 100644 index 00000000..06daf4a9 --- /dev/null +++ b/FModel/Services/AssetExplorerPreviewResolver.cs @@ -0,0 +1,359 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Threading; +using FModel.Extensions; +using FModel.Settings; +using FModel.ViewModels; +using OpenTK.Windowing.GraphicsLibraryFramework; +using Serilog; +using Snooper.Rendering; + +namespace FModel.Services; + +public sealed class AssetExplorerPreviewResolver : IDisposable +{ + private readonly ApplicationViewModel _applicationView; + private readonly (ListBox Grid, ListBox List, ListBox Packages) _views; + private readonly UserSettings _settings = UserSettings.Default; + + private ListBox Explorer => _views.Grid.IsVisible ? _views.Grid : _views.List; + private readonly DispatcherTimer _resolutionTimer = new(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(100) }; + private int _assetResolutionVersion; + private int _startedAssetResolutionVersion; + private bool _resolvingAssets; + private bool _closing; + private GameFileViewModel _hoveredMeshPreview; + private CancellationTokenSource _meshPreviewRequest; + private bool _meshPreviewsPending; + private bool _meshPreviewsUnavailable; + + public AssetExplorerPreviewResolver(ApplicationViewModel applicationView, ListBox grid, ListBox list, ListBox packages) + { + _applicationView = applicationView; + _views = (grid, list, packages); + + _resolutionTimer.Tick += OnResolutionTick; + _settings.PropertyChanged += OnSettingsChanged; + foreach (var view in new[] { grid, list, packages }) + { + view.ItemContainerGenerator.StatusChanged += OnContainersGenerated; + view.IsVisibleChanged += OnVisibilityChanged; + view.AddHandler(ScrollViewer.ScrollChangedEvent, new ScrollChangedEventHandler(OnScrollChanged)); + + if (view == packages) + continue; + + view.MouseMove += OnHoverChanged; + view.MouseLeave += OnHoverChanged; + } + + ScheduleAssetResolution(); + ScheduleMeshPreviews(); + } + + public void Dispose() + { + if (_closing) + return; + + _closing = true; + Interlocked.Increment(ref _assetResolutionVersion); + _resolutionTimer.Stop(); + _resolutionTimer.Tick -= OnResolutionTick; + _settings.PropertyChanged -= OnSettingsChanged; + foreach (var view in new[] { _views.Grid, _views.List, _views.Packages }) + { + view.ItemContainerGenerator.StatusChanged -= OnContainersGenerated; + view.IsVisibleChanged -= OnVisibilityChanged; + view.RemoveHandler(ScrollViewer.ScrollChangedEvent, new ScrollChangedEventHandler(OnScrollChanged)); + if (view == _views.Packages) + continue; + + view.MouseMove -= OnHoverChanged; + view.MouseLeave -= OnHoverChanged; + } + + _meshPreviewsUnavailable = true; + _meshPreviewRequest?.Cancel(); + SnooperViewModel.Instance.CloseMeshPreviews(); + } + + private void OnVisibilityChanged(object sender, DependencyPropertyChangedEventArgs e) + { + ScheduleAssetResolution(); + if (!ReferenceEquals(sender, _views.Packages)) + ScheduleMeshPreviews(); + } + + private void OnContainersGenerated(object sender, EventArgs e) + { + if (sender is not ItemContainerGenerator { Status: GeneratorStatus.ContainersGenerated } generator) + return; + + var (grid, list, packages) = _views; + var view = packages; + if (ReferenceEquals(generator, grid.ItemContainerGenerator)) + { + view = grid; + } + else if (ReferenceEquals(generator, list.ItemContainerGenerator)) + { + view = list; + } + + if (!view.IsVisible) + return; + + ScheduleAssetResolution(); + if (view != packages) + ScheduleMeshPreviews(); + } + + private void ScheduleAssetResolution() + { + if (_closing) + return; + + Interlocked.Increment(ref _assetResolutionVersion); + RestartResolutionTimer(); + } + + private void RestartResolutionTimer() + { + _resolutionTimer.Stop(); + _resolutionTimer.Start(); + } + + private void OnResolutionTick(object sender, EventArgs e) + { + _resolutionTimer.Stop(); + if (_closing) + return; + + if (!_resolvingAssets && _startedAssetResolutionVersion != _assetResolutionVersion) + ResolveVisibleAssets(); + if (_meshPreviewsPending && _meshPreviewRequest == null) + _ = ResolveMeshPreviewsAsync(); + } + + private void ResolveVisibleAssets() + { + var version = _startedAssetResolutionVersion = _assetResolutionVersion; + var explorer = Explorer; + var previewMode = _settings.MeshPreviewMode; + var hovered = previewMode is EMeshPreviewMode.OnHover ? GetHoveredAsset(explorer) : null; + var resolve = explorer.IsVisible && _settings.PreviewTexturesAssetExplorer ? EResolveCompute.All : EResolveCompute.Category; + + var requests = GetVisibleAssets(explorer, file => file.NeedsResolution(resolve)) + .Select(file => (File: file, Resolve: resolve)) + .Concat(GetVisibleAssets(_views.Packages, file => file.NeedsResolution(EResolveCompute.Category)) + .Select(file => (File: file, Resolve: EResolveCompute.Category))) + .DistinctBy(request => request.File); + + var visible = (hovered == null ? requests : requests.OrderByDescending(request => ReferenceEquals(request.File, hovered))).ToArray(); + if (visible.Length == 0) + return; + + var provider = _applicationView.CUE4Parse?.Provider; + var dispatcher = explorer.Dispatcher; + _resolvingAssets = true; + _ = Task.Run(() => + { + var foundMesh = false; + var previewScheduled = false; + try + { + foreach (var (file, flags) in visible) + { + if (Volatile.Read(ref _assetResolutionVersion) != version) + break; + + var categoryPending = file.NeedsResolution(EResolveCompute.Category); + file.Resolve(flags, provider); + if (!categoryPending || !file.CanResolveMeshPreview) + continue; + + foundMesh = true; + if (previewScheduled || (previewMode != EMeshPreviewMode.Automatic && !ReferenceEquals(file, hovered))) + continue; + + previewScheduled = true; + dispatcher.InvokeAsync(() => + { + if (!_closing && version == _assetResolutionVersion) + ScheduleMeshPreviews(cancelRunning: false, debounce: false); + }, DispatcherPriority.Background); + } + } + finally + { + dispatcher.InvokeAsync(() => + { + _resolvingAssets = false; + if (_closing) + return; + + if (foundMesh) + ScheduleMeshPreviews(cancelRunning: false, debounce: version != _assetResolutionVersion); + if (version != _assetResolutionVersion && !_resolutionTimer.IsEnabled) + _resolutionTimer.Start(); + }, DispatcherPriority.Background); + } + }); + } + + private static IEnumerable GetVisibleAssets(ListBox list, Predicate include) + { + if (!list.IsVisible || list.FindVisualChild() is not { } viewport || viewport.FindVisualChild() is not { } panel) + yield break; + + var viewportBounds = new Rect(viewport.RenderSize); + foreach (var child in panel.Children) + { + if (child is not ListBoxItem { IsVisible: true, DataContext: GameFileViewModel file } container || !include(file)) + continue; + + var bounds = container.TransformToAncestor(viewport).TransformBounds(new Rect(container.RenderSize)); + bounds.Intersect(viewportBounds); + if (bounds.Width > 0 && bounds.Height > 0) + yield return file; + } + } + + private void OnSettingsChanged(object sender, PropertyChangedEventArgs e) + { + if (e.PropertyName is nameof(UserSettings.MeshPreviewMode) or nameof(UserSettings.PreviewMaterialThumbnails)) + { + ScheduleMeshPreviews(); + } + else if (e.PropertyName == nameof(UserSettings.PreviewTexturesAssetExplorer)) + { + ScheduleAssetResolution(); + } + } + + private void OnScrollChanged(object sender, ScrollChangedEventArgs e) + { + if (sender is ListBox { IsVisible: true } list && (e.VerticalChange != 0 || e.HorizontalChange != 0 || e.ViewportHeightChange != 0 || e.ViewportWidthChange != 0)) + { + ScheduleAssetResolution(); + if (!ReferenceEquals(list, _views.Packages)) + ScheduleMeshPreviews(); + } + } + + private void OnHoverChanged(object sender, MouseEventArgs e) + { + if (_settings.MeshPreviewMode is not EMeshPreviewMode.OnHover || sender is not ListBox list) + return; + + var file = e.RoutedEvent == Mouse.MouseLeaveEvent ? null : GetHoveredMeshPreview(list); + if (ReferenceEquals(_hoveredMeshPreview, file)) + return; + + _hoveredMeshPreview = file; + ScheduleMeshPreviews(); + } + + private static GameFileViewModel GetHoveredAsset(ListBox list) => list.IsMouseOver && Mouse.DirectlyOver is DependencyObject element && + ItemsControl.ContainerFromElement(list, element) is ListBoxItem { DataContext: GameFileViewModel file } + ? file + : null; + + private static GameFileViewModel GetHoveredMeshPreview(ListBox list) => GetHoveredAsset(list) is { CanResolveMeshPreview: true } file ? file : null; + + private void ScheduleMeshPreviews(bool cancelRunning = true, bool debounce = true) + { + if (cancelRunning) + _meshPreviewRequest?.Cancel(); + + _meshPreviewsPending = !_closing && !_meshPreviewsUnavailable && _applicationView.IsAssetsExplorerVisible && _settings.MeshPreviewMode is not EMeshPreviewMode.None; + if (_meshPreviewsPending && _meshPreviewRequest == null) + { + if (debounce) + { + RestartResolutionTimer(); + } + else + { + _ = ResolveMeshPreviewsAsync(); + } + } + } + + private async Task ResolveMeshPreviewsAsync() + { + _meshPreviewsPending = false; + + var list = Explorer; + if (_settings.MeshPreviewMode is EMeshPreviewMode.None || !list.IsVisible || !_applicationView.IsAssetsExplorerVisible || _applicationView.CUE4Parse?.Provider is not { } provider) + return; + + GameFileViewModel[] assets; + if (_settings.MeshPreviewMode is EMeshPreviewMode.OnHover) + { + _hoveredMeshPreview = GetHoveredMeshPreview(list); + assets = _hoveredMeshPreview is { } hovered ? [hovered] : []; + } + else + { + assets = [.. GetVisibleAssets(list, file => file.CanResolveMeshPreview)]; + } + + if (assets.Length == 0) + return; + + using var request = new CancellationTokenSource(); + _meshPreviewRequest = request; + try + { + var platform = _settings.CurrentDir.TexturePlatform; + foreach (var file in assets) + { + if (request.IsCancellationRequested) + break; + if (!file.TryBeginMeshPreview()) + continue; + + try + { + var pixels = await SnooperViewModel.Instance.RenderMeshPreviewAsync(provider, file.Asset, platform); + if (pixels == null || _closing) + continue; + + const int size = MeshPreviewRenderer.MaxPreviewSize; + var image = BitmapSource.Create(size, size, 96, 96, PixelFormats.Pbgra32, null, pixels, size * 4); + image.Freeze(); + file.MeshPreviewImage = image; + } + catch (GLFWException exception) + { + _meshPreviewsUnavailable = true; + _meshPreviewsPending = false; + Log.Warning(exception, "Could not start the Snooper mesh preview context"); + break; + } + catch (Exception exception) + { + Log.Debug(exception, "Could not render the mesh preview for {Asset}", file.Asset.Path); + } + } + } + finally + { + _meshPreviewRequest = null; + if (_meshPreviewsPending && !_closing && !_resolutionTimer.IsEnabled) + _resolutionTimer.Start(); + } + } +} diff --git a/FModel/Settings/UserSettings.cs b/FModel/Settings/UserSettings.cs index fa385d54..0b5f731f 100644 --- a/FModel/Settings/UserSettings.cs +++ b/FModel/Settings/UserSettings.cs @@ -698,6 +698,20 @@ public sealed class UserSettings : ViewModel set => SetProperty(ref _previewTexturesAssetExplorer, value); } + private EMeshPreviewMode _meshPreviewMode = EMeshPreviewMode.Automatic; + public EMeshPreviewMode MeshPreviewMode + { + get => _meshPreviewMode; + set => SetProperty(ref _meshPreviewMode, value); + } + + private bool _previewMaterialThumbnails = true; + public bool PreviewMaterialThumbnails + { + get => _previewMaterialThumbnails; + set => SetProperty(ref _previewMaterialThumbnails, value); + } + private EExplorerViewMode _explorerViewMode = EExplorerViewMode.Grid; public EExplorerViewMode ExplorerViewMode diff --git a/FModel/ViewModels/AssetsFolderViewModel.cs b/FModel/ViewModels/AssetsFolderViewModel.cs index db0f3181..2aeb8754 100644 --- a/FModel/ViewModels/AssetsFolderViewModel.cs +++ b/FModel/ViewModels/AssetsFolderViewModel.cs @@ -88,7 +88,7 @@ public class TreeItem : ViewModel } else { - _ = OnSelectedCategoryChanged(); + ResolveCategoryFilter(); } } } @@ -106,7 +106,7 @@ public class TreeItem : ViewModel // BulkPopulate sorts Folders before this view is created _filteredFoldersView ??= new ListCollectionView(Folders) { - Filter = ItemFilter + Filter = HasFilter ? ItemFilter : null }; return _filteredFoldersView; } @@ -133,14 +133,27 @@ public class TreeItem : ViewModel Version = vfsEntry.Vfs.Ver; } PathAtThisPoint = pathHere; - - AssetsList.AssetsView.Filter = ItemFilter; } + private bool HasFilter => SelectedCategory != EAssetCategory.All || _searchTerms.Length != 0; + private void RefreshFilters() { - AssetsList.AssetsView.Refresh(); - FilteredFoldersView?.Refresh(); + Predicate filter = HasFilter ? ItemFilter : null; + UpdateFilter(AssetsList.AssetsView, filter); + if (_filteredFoldersView != null) UpdateFilter(_filteredFoldersView, filter); + } + + private static void UpdateFilter(ICollectionView view, Predicate filter) + { + if (view.Filter != filter) + { + view.Filter = filter; + } + else if (filter != null) + { + view.Refresh(); + } } private bool ItemFilter(object item) => item switch @@ -161,10 +174,51 @@ public class TreeItem : ViewModel return true; } - private async Task OnSelectedCategoryChanged() + private bool _resolvingCategory; + + private void ResolveCategoryFilter() { - await Task.WhenAll(AssetsList.Assets.Select(asset => asset.ResolveAsync(EResolveCompute.Category))); - RefreshFilters(); + if (_resolvingCategory) + return; + + var assets = AssetsList.Assets.Where(file => file.NeedsResolution(EResolveCompute.Category)).ToArray(); + if (assets.Length == 0) + { + RefreshFilters(); + return; + } + + _resolvingCategory = true; + var provider = ApplicationService.ApplicationView.CUE4Parse?.Provider; + _ = Task.Run(() => + { + var interrupted = false; + foreach (var asset in assets) + { + if (_selectedCategory is EAssetCategory.All) + { + interrupted = true; + break; + } + asset.Resolve(EResolveCompute.Category, provider); + } + + Application.Current.Dispatcher.InvokeAsync(() => + { + _resolvingCategory = false; + if (SelectedCategory is EAssetCategory.All) + return; + + if (interrupted) + { + ResolveCategoryFilter(); + } + else + { + RefreshFilters(); + } + }); + }); } public override string ToString() => $"{Header} | {Folders.Count} Folders | {AssetsList.Assets.Count} Files"; diff --git a/FModel/ViewModels/CUE4ParseViewModel.cs b/FModel/ViewModels/CUE4ParseViewModel.cs index f128c654..5fa52bb7 100644 --- a/FModel/ViewModels/CUE4ParseViewModel.cs +++ b/FModel/ViewModels/CUE4ParseViewModel.cs @@ -184,6 +184,7 @@ public class CUE4ParseViewModel : ViewModel Provider.ReadScriptData = UserSettings.Default.ReadScriptData; Provider.ReadShaderMaps = UserSettings.Default.ReadShaderMaps; Provider.ReadNaniteData = true; + Provider.CachePackages = true; PropertyUtil.SearchPropertyInTemplate = true; // search template properties when looking for a prop via GetOrDefault and cie GameDirectory = new GameDirectoryViewModel(); diff --git a/FModel/ViewModels/GameFileViewModel.cs b/FModel/ViewModels/GameFileViewModel.cs index 9b26fe42..2614f7d7 100644 --- a/FModel/ViewModels/GameFileViewModel.cs +++ b/FModel/ViewModels/GameFileViewModel.cs @@ -6,9 +6,11 @@ using System.Threading.Tasks; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; +using System.Windows.Threading; using CUE4Parse_Conversion.Textures; using CUE4Parse_Conversion.Textures.Paper2D; using CUE4Parse_Conversion.Dto; +using CUE4Parse.FileProvider; using CUE4Parse.FileProvider.Objects; using CUE4Parse.GameTypes.Borderlands3.Assets.Exports; using CUE4Parse.GameTypes.Borderlands4.Assets.Exports; @@ -64,6 +66,7 @@ using CUE4Parse.UE4.Objects.UObject.Editor; using CUE4Parse.UE4.Versions; using CUE4Parse.Utils; using FModel.Framework; +using FModel.Extensions; using FModel.Services; using FModel.Settings; using FModel.Views.Resources.Controls; @@ -80,7 +83,12 @@ public class GameFileViewModel(GameFile asset) : ViewModel private ApplicationViewModel _applicationView => ApplicationService.ApplicationView; private EGame? GameVersion => _applicationView.CUE4Parse?.Provider.Versions.Game; - public EResolveCompute Resolved { get; private set; } = EResolveCompute.None; + private volatile EResolveCompute _resolved; + public EResolveCompute Resolved + { + get => _resolved; + private set => _resolved = value; + } public GameFile Asset { get; } = asset; private string _resolvedAssetType = asset.Extension; @@ -146,12 +154,35 @@ public class GameFileViewModel(GameFile asset) : ViewModel private set { if (SetProperty(ref _previewImage, value)) - { - Resolved |= EResolveCompute.Preview; - } + RaisePropertyChanged(nameof(DisplayPreviewImage)); } } + private BitmapSource _meshPreviewImage; + public BitmapSource MeshPreviewImage + { + get => _meshPreviewImage; + set + { + if (SetProperty(ref _meshPreviewImage, value)) + RaisePropertyChanged(nameof(DisplayPreviewImage)); + } + } + + public ImageSource DisplayPreviewImage => MeshPreviewImage ?? PreviewImage; + + private volatile bool _canResolveMeshPreview; + public bool CanResolveMeshPreview => _canResolveMeshPreview && (!AssetCategory.IsOfCategory(EAssetCategory.Materials) || UserSettings.Default.PreviewMaterialThumbnails); + + public bool TryBeginMeshPreview() + { + if (!CanResolveMeshPreview) + return false; + + _canResolveMeshPreview = false; + return true; + } + private int _numTextures = 0; public int NumTextures { @@ -159,43 +190,46 @@ public class GameFileViewModel(GameFile asset) : ViewModel private set => SetProperty(ref _numTextures, value); } - public Task ExtractAsync() - => ApplicationService.ThreadWorkerView.Begin(cancellationToken => - _applicationView.CUE4Parse.ExtractSelected(cancellationToken, [Asset])); + public Task ExtractAsync() => ApplicationService.ThreadWorkerView.Begin(cancellationToken => _applicationView.CUE4Parse.ExtractSelected(cancellationToken, [Asset])); - public Task ResolveAsync(EResolveCompute resolve) + private Lock _resolveLock; + + public bool NeedsResolution(EResolveCompute resolve) => (resolve & ~Resolved) != EResolveCompute.None; + + public void Resolve(EResolveCompute resolve, IFileProvider provider) { - try - { - return ResolveInternalAsync(resolve); - } - catch (Exception e) - { - Log.Error(e, "Failed to resolve asset {AssetName} ({Resolver})", Asset.Path, resolve.ToStringBitfield()); + if (!NeedsResolution(resolve)) + return; - Resolved = EResolveCompute.All; - return Task.CompletedTask; + lock (LazyInitializer.EnsureInitialized(ref _resolveLock)) + { + resolve &= ~Resolved; + if (resolve is EResolveCompute.None) + return; + + try + { + if (!Asset.IsUePackage || provider is null) + { + ResolveByExtension(resolve, provider); + } + else + { + ResolveByPackage(resolve, provider); + } + } + catch (Exception e) + { + Log.Error(e, "Failed to resolve asset {AssetName} ({Resolver})", Asset.Path, resolve.ToStringBitfield()); + } + finally + { + Resolved |= resolve; + } } } - private Task ResolveInternalAsync(EResolveCompute resolve) - { - if (!_applicationView.IsAssetsExplorerVisible || !UserSettings.Default.PreviewTexturesAssetExplorer) - { - resolve &= ~EResolveCompute.Preview; - } - - resolve &= ~Resolved; - if (resolve == EResolveCompute.None) - return Task.CompletedTask; - - if (!Asset.IsUePackage || _applicationView.CUE4Parse is null) - return ResolveByExtensionAsync(resolve); - - return ResolveByPackageAsync(resolve); - } - - private Task ResolveByPackageAsync(EResolveCompute resolve) + private void ResolveByPackage(EResolveCompute resolve, IFileProvider provider) { if (Asset.Extension is "umap") { @@ -203,7 +237,7 @@ public class GameFileViewModel(GameFile asset) : ViewModel AssetActions = EBulkType.Worlds | EBulkType.Textures | EBulkType.Audio | EBulkType.Code; ResolvedAssetType = "World"; Resolved |= EResolveCompute.Preview; - return Task.CompletedTask; + return; } if (Asset.NameWithoutExtension.EndsWith("_BuiltData")) @@ -212,231 +246,229 @@ public class GameFileViewModel(GameFile asset) : ViewModel AssetActions = EBulkType.Textures; ResolvedAssetType = "MapBuildDataRegistry"; Resolved |= EResolveCompute.Preview; - return Task.CompletedTask; + return; } - return Task.Run(() => + var pkg = provider.LoadPackage(Asset); + + var pointer = FindMainExport(pkg); + if (pointer?.Object is not { } export) + return; + + if ((resolve & EResolveCompute.Category) != 0) + ResolveCategory((AbstractUePackage) pkg, pointer, export); + + if (AssetCategory is not (EAssetCategory.Texture or EAssetCategory.AnimatedTexture or EAssetCategory.ItemDefinitionBase)) { - // TODO: cache and reuse packages - var pkg = _applicationView.CUE4Parse?.Provider.LoadPackage(Asset); - if (pkg is null) - throw new InvalidOperationException($"Failed to load {Asset.Path} as UE package."); - - var mainIndex = pkg.GetExportIndex(Asset.NameWithoutExtension, StringComparison.OrdinalIgnoreCase); - if (mainIndex < 0) mainIndex = pkg.GetExportIndex($"{Asset.NameWithoutExtension}_C", StringComparison.OrdinalIgnoreCase); - if (mainIndex < 0) mainIndex = 0; - - var pointer = new FPackageIndex(pkg, mainIndex + 1).ResolvedObject; - if (pointer?.Object is null) - return; - - var dummy = ((AbstractUePackage) pkg).ConstructObject(pointer.Class, pkg); - ResolvedAssetType = dummy.ExportType; - - AssetFamily = dummy switch - { - UAtomSoundBase or UAtomSoundBank or USoundAtomCue or USoundAtomCueSheet - or USoundAtomConfig or UAtomDspBusSetting or UAtomRackBase => EAssetFamily.Criware, - - UAkAudioType or UAkAssetData or UAkAssetPlatformData or UAkMediaAssetData - or UAkMediaAsset or UWwiseAssetLibrary or UWwiseAssetLibraryGroup or UExternalSource or UExternalSourceBank => EAssetFamily.Wwise, - - UFMODEvent or UFMODBank or UFMODBankLookup or UFMODBus - or UFMODSnapshot or UFMODSnapshotReverb or UFMODVCA => EAssetFamily.FMod, - - UHoudiniAsset or UHoudiniStaticMesh => EAssetFamily.Houdini, - - UPaperTileMap or UPaperTileLayer or UPaperTileSet or UPaperSprite or UPaperFlipbook => EAssetFamily.Paper2D, - - _ => EAssetFamily.None, - }; - - (AssetCategory, AssetActions) = dummy switch - { - URigVMBlueprintGeneratedClass => (EAssetCategory.RigVMBlueprintGeneratedClass, EBulkType.Code), - UAnimBlueprintGeneratedClass => (EAssetCategory.AnimBlueprintGeneratedClass, EBulkType.Code), - UWidgetBlueprintGeneratedClass => (EAssetCategory.WidgetBlueprintGeneratedClass, EBulkType.Code), - UFunction => (EAssetCategory.BlueprintGeneratedClass, EBulkType.Code), - UBlueprintGeneratedClass => (EAssetCategory.BlueprintGeneratedClass, EBulkType.Code | EBulkType.Worlds), - - UUserDefinedEnum => (EAssetCategory.UserDefinedEnum, EBulkType.None), - UUserDefinedStruct => (EAssetCategory.UserDefinedStruct, EBulkType.Code), - UBlueprintCore => (EAssetCategory.Blueprint, EBulkType.Code), - UClassCookedMetaData or UStructCookedMetaData or UEnumCookedMetaData => (EAssetCategory.CookedMetaData, EBulkType.None), - - UStaticMesh => (EAssetCategory.StaticMesh, EBulkType.Meshes), - UHoudiniStaticMesh => (EAssetCategory.StaticMesh, EBulkType.Meshes), - USkeletalMesh => (EAssetCategory.SkeletalMesh, EBulkType.Meshes), - UChaosClothAsset => (EAssetCategory.ChaosClothAsset, EBulkType.Meshes), - UCustomizableObject => (EAssetCategory.CustomizableObject, EBulkType.None), // TODO: Add support - UNaniteDisplacedMesh => (EAssetCategory.NaniteDisplacedMesh, EBulkType.None), - UGeometryCollection => (EAssetCategory.GeometryCollection, EBulkType.Meshes), - UGroomAsset => (EAssetCategory.GroomAsset, EBulkType.Meshes), // TODO: Add full support - UGroomBindingAsset => (EAssetCategory.GroomAsset, EBulkType.None), // TODO: Add support - - UHoudiniAsset => (EAssetCategory.Data, EBulkType.None), - - UTexture or UPaperSprite => (EAssetCategory.Texture, EBulkType.Textures), - UPaperFlipbook => (EAssetCategory.AnimatedTexture, EBulkType.Textures), - - UMaterialInterface => (EAssetCategory.Material, EBulkType.None), - UMaterialInterfaceEditorOnlyData => (EAssetCategory.MaterialEditorData, EBulkType.None), - UMaterialFunction => (EAssetCategory.MaterialFunction, EBulkType.None), - UMaterialFunctionEditorOnlyData => (EAssetCategory.MaterialFunctionEditorData, EBulkType.None), - UMaterialParameterCollection => (EAssetCategory.MaterialParameterCollection, EBulkType.None), - - UAnimationAsset => (EAssetCategory.Animation, EBulkType.Animations), - USkeleton => (EAssetCategory.Skeleton, EBulkType.Meshes), - URig => (EAssetCategory.Rig, EBulkType.None), - - UWorld => (EAssetCategory.World, EBulkType.Meshes | EBulkType.Textures | EBulkType.Audio | EBulkType.Code), - UMapBuildDataRegistry => (EAssetCategory.BuildData, EBulkType.Textures), - ULevelSequence => (EAssetCategory.LevelSequence, EBulkType.Code), - UFoliageType => (EAssetCategory.Foliage, EBulkType.None), - - UItemDefinitionBase => (EAssetCategory.ItemDefinitionBase, EBulkType.Textures), - UDataAsset or UDataTable or UCurveTable or UStringTable => (EAssetCategory.Data, EBulkType.None), - UCurveBase => (EAssetCategory.CurveBase, EBulkType.None), - UPhysicsAsset => (EAssetCategory.PhysicsAsset, EBulkType.None), - UObjectRedirector => (EAssetCategory.ObjectRedirector, EBulkType.None), - UPhysicalMaterial => (EAssetCategory.PhysicalMaterial, EBulkType.None), - - USoundAtomCue or UAtomSoundCue or UAkAudioEvent or USoundCue or UFMODEvent - or UAkAssetData or UAkAssetPlatformData => (EAssetCategory.AudioEvent, EBulkType.Audio), - - UFileManaMovie => (EAssetCategory.Video, EBulkType.None), - - UFMODBankLookup or USoundAtomConfig or UFMODSnapshotReverb or UFMODBus or UFMODSnapshot - or UFMODVCA or UAtomDspBusSetting => (EAssetCategory.Data, EBulkType.None), - - USQEXSEADSoundAttenuation => (EAssetCategory.Audio, EBulkType.None), - - UFMODBank or UAkAudioBank or UAtomSoundBank or USoundAtomCueSheet - or UAkInitBank or USQEXSEADSoundBank => (EAssetCategory.SoundBank, EBulkType.Audio), - - UWwiseAssetLibrary or UWwiseAssetLibraryGroup or UAtomSoundBase or USoundBase or UAkMediaAssetData - or UExternalSource or UExternalSourceBank or UAkMediaAsset => (EAssetCategory.Audio, EBulkType.Audio), - - UAkAudioType => (EAssetCategory.Data, EBulkType.None), - - UFileMediaSource => (EAssetCategory.Video, EBulkType.None), - UFont or UFontFace or USMGLocaleFontUMG => (EAssetCategory.Font, EBulkType.None), - - UNiagaraSystem or UNiagaraScriptBase or UParticleSystem => (EAssetCategory.Particle, EBulkType.None), - - USwfMovie => (EAssetCategory.Flash, EBulkType.None), - - // Game specific assets below - UBorderlandsDialogObject when GameVersion is EGame.GAME_Borderlands3 => (EAssetCategory.Borderlands, EBulkType.None), // Borderlands 3; - UGbxGraphAsset or UDialogScriptData or UDialogPerformanceData when GameVersion is EGame.GAME_Borderlands4 or EGame.GAME_Borderlands3 => (EAssetCategory.Borderlands, EBulkType.Audio), // Borderlands 4; Borderlands 3; - UFaceFXAnimSet when GameVersion is EGame.GAME_Borderlands4 => (EAssetCategory.Borderlands, EBulkType.Audio), // Borderlands 4; - UWubAudioEvent or UWubDialogueEvent when GameVersion is EGame.GAME_LEGOBatmanLegacyoftheDarkKnight => (EAssetCategory.LegoBatman, EBulkType.Audio), // Lego Batman: Legacy of the Dark Knight; - UREDBinaryObject => (EAssetCategory.ArcSys, EBulkType.None), // Arc System Works games; - UOrpheusBank or UOrpheusEvent => (EAssetCategory.GothamKnights, EBulkType.Audio), // Gotham Knights; - UIRMesh => (EAssetCategory.Nascar, EBulkType.Meshes), // iRacing games; - UPaperTileMap when GameVersion is EGame.GAME_DeadByDaylight => (EAssetCategory.DeadByDaylight, EBulkType.Worlds), // DBD; UPaperTileMap isn't game specific, its use is just non typical - - _ => (EAssetCategory.All, EBulkType.None), - }; - - var obj = pointer.Object.Value; - IconStyle = obj switch - { - UGroomBindingAsset => (null, "GroomBindingAssetBrush"), - USkeletalMesh mesh when mesh.AssetUserData?.Any(data => data?.ResolvedObject is { } reference && - (reference.IsA() || reference.Class?.Name.Text == "DNAAssetUserData")) == true => ("MetaHumanIcon", null), // Way to detect MetaHumans, for >UE 5.8 DNAAssetUserData is needed since DNAAsset can be standalone asset - _ => default - }; - - if (EmbeddedFilesDto.Supports(dummy)) - { - 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; - } - - switch (AssetCategory) - { - case EAssetCategory.Texture: - { - if (!resolve.HasFlag(EResolveCompute.Preview)) - break; - - if (obj is UTexture2DArray textureArray && textureArray.GetFirstMip() is { SizeZ: > 1 } firstMip) - NumTextures = firstMip.SizeZ; - - 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 (obj is UItemDefinitionBase itemDef) - { - if (LookupPreview(itemDef.DataList)) break; - - if (itemDef is UAthenaPickaxeItemDefinition pickaxe && pickaxe.WeaponDefinition.TryLoad(out UItemDefinitionBase weaponDef)) - { - LookupPreview(weaponDef.DataList); - } - - bool LookupPreview(FInstancedStruct[] dataList) - { - foreach (var data in dataList) - { - if (!data.NonConstStruct.TryGetValue(out FSoftObjectPath icon, "Icon", "LargeIcon") || - !icon.TryLoad(out var texture)) - continue; - - var img = texture.Decode(MaxPreviewSize, UserSettings.GetExportOptions()); - if (img == null) return false; - - using var bitmap = img.ToSkBitmap(); - using var image = bitmap.Encode(SKEncodedImageFormat.Png, 100); - SetPreviewImage(image); - return true; - } - return false; - } - } - break; - default: - Resolved |= EResolveCompute.Preview; - break; - } - }); + Resolved |= EResolveCompute.Preview; + } + else if ((resolve & EResolveCompute.Preview) != 0) + { + ResolvePackagePreview(export.Value); + } } - private Task ResolveByExtensionAsync(EResolveCompute resolve) + private void ResolveCategory(AbstractUePackage pkg, ResolvedObject pointer, Lazy export) + { + var dummy = pkg.ConstructObject(pointer.Class, pkg); + ResolvedAssetType = dummy.ExportType; + + AssetFamily = dummy switch + { + UAtomSoundBase or UAtomSoundBank or USoundAtomCue or USoundAtomCueSheet + or USoundAtomConfig or UAtomDspBusSetting or UAtomRackBase => EAssetFamily.Criware, + + UAkAudioType or UAkAssetData or UAkAssetPlatformData or UAkMediaAssetData + or UAkMediaAsset or UWwiseAssetLibrary or UWwiseAssetLibraryGroup or UExternalSource or UExternalSourceBank => EAssetFamily.Wwise, + + UFMODEvent or UFMODBank or UFMODBankLookup or UFMODBus + or UFMODSnapshot or UFMODSnapshotReverb or UFMODVCA => EAssetFamily.FMod, + + UHoudiniAsset or UHoudiniStaticMesh => EAssetFamily.Houdini, + + UPaperTileMap or UPaperTileLayer or UPaperTileSet or UPaperSprite or UPaperFlipbook => EAssetFamily.Paper2D, + + _ => EAssetFamily.None, + }; + + var (category, actions) = dummy switch + { + URigVMBlueprintGeneratedClass => (EAssetCategory.RigVMBlueprintGeneratedClass, EBulkType.Code), + UAnimBlueprintGeneratedClass => (EAssetCategory.AnimBlueprintGeneratedClass, EBulkType.Code), + UWidgetBlueprintGeneratedClass => (EAssetCategory.WidgetBlueprintGeneratedClass, EBulkType.Code), + UFunction => (EAssetCategory.BlueprintGeneratedClass, EBulkType.Code), + UBlueprintGeneratedClass => (EAssetCategory.BlueprintGeneratedClass, EBulkType.Code | EBulkType.Worlds), + + UUserDefinedEnum => (EAssetCategory.UserDefinedEnum, EBulkType.None), + UUserDefinedStruct => (EAssetCategory.UserDefinedStruct, EBulkType.Code), + UBlueprintCore => (EAssetCategory.Blueprint, EBulkType.Code), + UClassCookedMetaData or UStructCookedMetaData or UEnumCookedMetaData => (EAssetCategory.CookedMetaData, EBulkType.None), + + UStaticMesh => (EAssetCategory.StaticMesh, EBulkType.Meshes), + UHoudiniStaticMesh => (EAssetCategory.StaticMesh, EBulkType.Meshes), + USkeletalMesh => (EAssetCategory.SkeletalMesh, EBulkType.Meshes), + UChaosClothAsset => (EAssetCategory.ChaosClothAsset, EBulkType.Meshes), + UCustomizableObject => (EAssetCategory.CustomizableObject, EBulkType.None), // TODO: Add support + UNaniteDisplacedMesh => (EAssetCategory.NaniteDisplacedMesh, EBulkType.None), + UGeometryCollection => (EAssetCategory.GeometryCollection, EBulkType.Meshes), + UGroomAsset => (EAssetCategory.GroomAsset, EBulkType.Meshes), // TODO: Add full support + UGroomBindingAsset => (EAssetCategory.GroomAsset, EBulkType.None), // TODO: Add support + + UHoudiniAsset => (EAssetCategory.Data, EBulkType.None), + + UTexture or UPaperSprite => (EAssetCategory.Texture, EBulkType.Textures), + UPaperFlipbook => (EAssetCategory.AnimatedTexture, EBulkType.Textures), + + UMaterialInterface => (EAssetCategory.Material, EBulkType.None), + UMaterialInterfaceEditorOnlyData => (EAssetCategory.MaterialEditorData, EBulkType.None), + UMaterialFunction => (EAssetCategory.MaterialFunction, EBulkType.None), + UMaterialFunctionEditorOnlyData => (EAssetCategory.MaterialFunctionEditorData, EBulkType.None), + UMaterialParameterCollection => (EAssetCategory.MaterialParameterCollection, EBulkType.None), + + UAnimationAsset => (EAssetCategory.Animation, EBulkType.Animations), + USkeleton => (EAssetCategory.Skeleton, EBulkType.Meshes), + URig => (EAssetCategory.Rig, EBulkType.None), + + UWorld => (EAssetCategory.World, EBulkType.Meshes | EBulkType.Textures | EBulkType.Audio | EBulkType.Code), + UMapBuildDataRegistry => (EAssetCategory.BuildData, EBulkType.Textures), + ULevelSequence => (EAssetCategory.LevelSequence, EBulkType.Code), + UFoliageType => (EAssetCategory.Foliage, EBulkType.None), + + UItemDefinitionBase => (EAssetCategory.ItemDefinitionBase, EBulkType.Textures), + UDataAsset or UDataTable or UCurveTable or UStringTable => (EAssetCategory.Data, EBulkType.None), + UCurveBase => (EAssetCategory.CurveBase, EBulkType.None), + UPhysicsAsset => (EAssetCategory.PhysicsAsset, EBulkType.None), + UObjectRedirector => (EAssetCategory.ObjectRedirector, EBulkType.None), + UPhysicalMaterial => (EAssetCategory.PhysicalMaterial, EBulkType.None), + + USoundAtomCue or UAtomSoundCue or UAkAudioEvent or USoundCue or UFMODEvent + or UAkAssetData or UAkAssetPlatformData => (EAssetCategory.AudioEvent, EBulkType.Audio), + + UFileManaMovie => (EAssetCategory.Video, EBulkType.None), + + UFMODBankLookup or USoundAtomConfig or UFMODSnapshotReverb or UFMODBus or UFMODSnapshot + or UFMODVCA or UAtomDspBusSetting => (EAssetCategory.Data, EBulkType.None), + + USQEXSEADSoundAttenuation => (EAssetCategory.Audio, EBulkType.None), + + UFMODBank or UAkAudioBank or UAtomSoundBank or USoundAtomCueSheet + or UAkInitBank or USQEXSEADSoundBank => (EAssetCategory.SoundBank, EBulkType.Audio), + + UWwiseAssetLibrary or UWwiseAssetLibraryGroup or UAtomSoundBase or USoundBase or UAkMediaAssetData + or UExternalSource or UExternalSourceBank or UAkMediaAsset => (EAssetCategory.Audio, EBulkType.Audio), + + UAkAudioType => (EAssetCategory.Data, EBulkType.None), + + UFileMediaSource => (EAssetCategory.Video, EBulkType.None), + UFont or UFontFace or USMGLocaleFontUMG => (EAssetCategory.Font, EBulkType.None), + + UNiagaraSystem or UNiagaraScriptBase or UParticleSystem => (EAssetCategory.Particle, EBulkType.None), + + USwfMovie => (EAssetCategory.Flash, EBulkType.None), + + // Game specific assets below + UBorderlandsDialogObject when GameVersion is EGame.GAME_Borderlands3 => (EAssetCategory.Borderlands, EBulkType.None), // Borderlands 3; + UGbxGraphAsset or UDialogScriptData or UDialogPerformanceData when GameVersion is EGame.GAME_Borderlands4 or EGame.GAME_Borderlands3 => (EAssetCategory.Borderlands, EBulkType.Audio), // Borderlands 4; Borderlands 3; + UFaceFXAnimSet when GameVersion is EGame.GAME_Borderlands4 => (EAssetCategory.Borderlands, EBulkType.Audio), // Borderlands 4; + UWubAudioEvent or UWubDialogueEvent when GameVersion is EGame.GAME_LEGOBatmanLegacyoftheDarkKnight => (EAssetCategory.LegoBatman, EBulkType.Audio), // Lego Batman: Legacy of the Dark Knight; + UREDBinaryObject => (EAssetCategory.ArcSys, EBulkType.None), // Arc System Works games; + UOrpheusBank or UOrpheusEvent => (EAssetCategory.GothamKnights, EBulkType.Audio), // Gotham Knights; + UIRMesh => (EAssetCategory.Nascar, EBulkType.Meshes), // iRacing games; + UPaperTileMap when GameVersion is EGame.GAME_DeadByDaylight => (EAssetCategory.DeadByDaylight, EBulkType.Worlds), // DBD; UPaperTileMap isn't game specific, its use is just non typical + + _ => (EAssetCategory.All, EBulkType.None), + }; + + (AssetCategory, AssetActions) = (category, actions); + + _canResolveMeshPreview = category.IsOfCategory(EAssetCategory.Mesh) || (category.IsOfCategory(EAssetCategory.Materials) && dummy is UMaterialInterface) || dummy is UIRMesh; + + IconStyle = dummy switch + { + UGroomBindingAsset => (null, "GroomBindingAssetBrush"), + USkeletalMesh when export.Value is USkeletalMesh mesh && mesh.AssetUserData?.Any(data => data?.ResolvedObject is { } reference && (reference.IsA() || reference.Class?.Name.Text == "DNAAssetUserData")) == true => ("MetaHumanIcon", null), // Way to detect MetaHumans, for >UE 5.8 DNAAssetUserData is needed since DNAAsset can be standalone asset + _ => default + }; + + if (EmbeddedFilesDto.Supports(dummy)) + { + var files = new EmbeddedFilesDto(export.Value).Files; + EmbeddedFileExtensions = string.Join(", ", files.Select(file => "." + file.Extension).Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(extension => extension, StringComparer.OrdinalIgnoreCase)); + if (files.Count > 0) + AssetActions |= EBulkType.EmbeddedFiles; + } + + } + + private void ResolvePackagePreview(UObject export) + { + var options = UserSettings.GetExportOptions(); + switch (export) + { + case UTexture or UPaperSprite: + { + if (export is UTexture2DArray textureArray && textureArray.GetFirstMip() is { SizeZ: > 1 } firstMip) + NumTextures = firstMip.SizeZ; + + var img = export switch + { + UTexture texture => texture.Decode(MaxPreviewSize, options), + UPaperSprite sprite => sprite.Decode(options), + _ => null + }; + if (img != null) + { + using var bitmap = img.ToSkBitmap(); + SetPreviewImage(bitmap); + } + break; + } + case UPaperFlipbook flipbook: + { + var preview = ImageAnimation.CreateThumbnail(flipbook, options, MaxPreviewSize); + if (preview != null) + PublishPreview(preview); + + break; + } + case UItemDefinitionBase itemDef: + { + if (LookupPreview(itemDef.DataList)) + break; + + if (itemDef is UAthenaPickaxeItemDefinition pickaxe && pickaxe.WeaponDefinition.TryLoad(out UItemDefinitionBase weaponDef)) + LookupPreview(weaponDef.DataList); + + break; + + bool LookupPreview(FInstancedStruct[] dataList) + { + foreach (var data in dataList) + { + if (!data.NonConstStruct.TryGetValue(out FSoftObjectPath icon, "Icon", "LargeIcon") || !icon.TryLoad(out var texture)) + continue; + + var img = texture.Decode(MaxPreviewSize, options); + if (img == null) return false; + + using var bitmap = img.ToSkBitmap(); + SetPreviewImage(bitmap); + return true; + } + return false; + } + } + } + } + + private ResolvedObject FindMainExport(IPackage package) + { + var index = package.GetExportIndex(Asset.NameWithoutExtension, StringComparison.OrdinalIgnoreCase); + if (index < 0) index = package.GetExportIndex($"{Asset.NameWithoutExtension}_C", StringComparison.OrdinalIgnoreCase); + return new FPackageIndex(package, Math.Max(0, index) + 1).ResolvedObject; + } + + private void ResolveByExtension(EResolveCompute resolve, IFileProvider provider) { var lowercaseExtension = Asset.Extension.ToLowerInvariant(); @@ -525,41 +557,41 @@ public class GameFileViewModel(GameFile asset) : ViewModel AssetCategory = EAssetCategory.Texture; AssetActions = EBulkType.Textures; if (!resolve.HasFlag(EResolveCompute.Preview)) - return Task.CompletedTask; + return; - return Task.Run(() => + if (provider == null) return; + var data = provider.SaveAsset(Asset); + using var stream = new MemoryStream(data); + stream.Position = 0; + + SKBitmap bitmap; + if (lowercaseExtension == "svg") { - var data = _applicationView.CUE4Parse.Provider.SaveAsset(Asset); - using var stream = new MemoryStream(data); - stream.Position = 0; + var svg = new SKSvg(); + svg.Load(stream); + if (svg.Picture == null) + return; - SKBitmap bitmap; - if (lowercaseExtension == "svg") - { - var svg = new SKSvg(); - svg.Load(stream); - if (svg.Picture == null) - return; + bitmap = new SKBitmap(MaxPreviewSize, MaxPreviewSize); + using var canvas = new SKCanvas(bitmap); + canvas.Clear(SKColors.Transparent); - bitmap = new SKBitmap(MaxPreviewSize, MaxPreviewSize); - using var canvas = new SKCanvas(bitmap); - canvas.Clear(SKColors.Transparent); + var bounds = svg.Picture.CullRect; + float scale = Math.Min(MaxPreviewSize / bounds.Width, MaxPreviewSize / bounds.Height); + canvas.Scale(scale); + canvas.Translate(-bounds.Left, -bounds.Top); + canvas.DrawPicture(svg.Picture); + } + else + { + bitmap = SKBitmap.Decode(stream); + } - var bounds = svg.Picture.CullRect; - float scale = Math.Min(MaxPreviewSize / bounds.Width, MaxPreviewSize / bounds.Height); - canvas.Scale(scale); - canvas.Translate(-bounds.Left, -bounds.Top); - canvas.DrawPicture(svg.Picture); - } - else - { - bitmap = SKBitmap.Decode(stream); - } - - using var image = bitmap.Encode(lowercaseExtension == "jpg" ? SKEncodedImageFormat.Jpeg : SKEncodedImageFormat.Png, 100); - SetPreviewImage(image); - bitmap.Dispose(); - }); + using (bitmap) + { + if (bitmap != null) SetPreviewImage(bitmap); + } + return; } case "swf": AssetCategory = EAssetCategory.Flash; @@ -586,37 +618,25 @@ public class GameFileViewModel(GameFile asset) : ViewModel } Resolved |= EResolveCompute.Preview; - return Task.CompletedTask; } - private void SetPreviewImage(SKData data) + private void SetPreviewImage(SKBitmap bitmap) { - 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); - } - - private CancellationTokenSource _previewCts; - public void OnIsVisible() - { - if (Resolved == EResolveCompute.All) + if (bitmap.Width <= 0 || bitmap.Height <= 0) return; - _previewCts?.Cancel(); - _previewCts = new CancellationTokenSource(); - var token = _previewCts.Token; - Task.Delay(100, token).ContinueWith(t => - { - if (t.IsCanceled) return; - ResolveAsync(EResolveCompute.All); - }, TaskScheduler.FromCurrentSynchronizationContext()); + var scale = Math.Min(1, (double) MaxPreviewSize / Math.Max(bitmap.Width, bitmap.Height)); + using var pixels = new SKBitmap(new SKImageInfo(Math.Max(1, (int) (bitmap.Width * scale)), Math.Max(1, (int) (bitmap.Height * scale)), SKColorType.Bgra8888, SKAlphaType.Premul)); + + if (!bitmap.ScalePixels(pixels, SKFilterQuality.Low)) + return; + + var image = BitmapSource.Create(pixels.Width, pixels.Height, 96, 96, PixelFormats.Pbgra32, null, pixels.GetPixels(), pixels.ByteCount, pixels.RowBytes); + image.Freeze(); + PublishPreview(image); } + + private void PublishPreview(ImageSource image) => Application.Current.Dispatcher.InvokeAsync(() => PreviewImage = image, DispatcherPriority.Background); } [Flags] diff --git a/FModel/ViewModels/SettingsViewModel.cs b/FModel/ViewModels/SettingsViewModel.cs index cf262915..7c96b998 100644 --- a/FModel/ViewModels/SettingsViewModel.cs +++ b/FModel/ViewModels/SettingsViewModel.cs @@ -106,6 +106,20 @@ public class SettingsViewModel : ViewModel set => SetProperty(ref _selectedDiscordRpc, value); } + private EMeshPreviewMode _selectedMeshPreviewMode; + public EMeshPreviewMode SelectedMeshPreviewMode + { + get => _selectedMeshPreviewMode; + set => SetProperty(ref _selectedMeshPreviewMode, value); + } + + private bool _previewMaterialThumbnails; + public bool PreviewMaterialThumbnails + { + get => _previewMaterialThumbnails; + set => SetProperty(ref _previewMaterialThumbnails, value); + } + private ECompressedAudio _selectedCompressedAudio; public ECompressedAudio SelectedCompressedAudio { @@ -147,6 +161,7 @@ public class SettingsViewModel : ViewModel public ReadOnlyObservableCollection AssetLanguages { get; private set; } public ReadOnlyObservableCollection AesReloads { get; private set; } public ReadOnlyObservableCollection DiscordRpcs { get; private set; } + public ReadOnlyObservableCollection MeshPreviewModes { get; private set; } public ReadOnlyObservableCollection CompressedAudios { get; private set; } public ReadOnlyObservableCollection MappingCompressions { get; private set; } public ReadOnlyObservableCollection CosmeticStyles { get; private set; } @@ -190,11 +205,14 @@ public class SettingsViewModel : ViewModel SelectedJsonHighlightTheme = UserSettings.Default.JsonHighlightTheme; SelectedAesReload = UserSettings.Default.AesReload; SelectedDiscordRpc = UserSettings.Default.DiscordRpc; + SelectedMeshPreviewMode = UserSettings.Default.MeshPreviewMode; + PreviewMaterialThumbnails = UserSettings.Default.PreviewMaterialThumbnails; UeGames = new ReadOnlyObservableCollection(new ObservableCollection(EnumerateUeGames())); AssetLanguages = new ReadOnlyObservableCollection(new ObservableCollection(EnumerateAssetLanguages())); AesReloads = new ReadOnlyObservableCollection(new ObservableCollection(EnumerateAesReloads())); DiscordRpcs = new ReadOnlyObservableCollection(new ObservableCollection(EnumerateDiscordRpcs())); + MeshPreviewModes = new ReadOnlyObservableCollection(new ObservableCollection(EnumerateMeshPreviewModes())); CompressedAudios = new ReadOnlyObservableCollection(new ObservableCollection(EnumerateCompressedAudios())); MappingCompressions = new ReadOnlyObservableCollection(new ObservableCollection(EnumerateMappingCompressions())); CosmeticStyles = new ReadOnlyObservableCollection(new ObservableCollection(EnumerateCosmeticStyles())); @@ -229,6 +247,8 @@ public class SettingsViewModel : ViewModel UserSettings.Default.AesReload = SelectedAesReload; UserSettings.Default.DiscordRpc = SelectedDiscordRpc; UserSettings.Default.JsonHighlightTheme = SelectedJsonHighlightTheme; + UserSettings.Default.MeshPreviewMode = SelectedMeshPreviewMode; + UserSettings.Default.PreviewMaterialThumbnails = PreviewMaterialThumbnails; Options.SaveAsUserDefaults(); @@ -246,6 +266,7 @@ public class SettingsViewModel : ViewModel private IEnumerable EnumerateAssetLanguages() => Enum.GetValues(); private IEnumerable EnumerateAesReloads() => Enum.GetValues(); private IEnumerable EnumerateDiscordRpcs() => Enum.GetValues(); + private IEnumerable EnumerateMeshPreviewModes() => Enum.GetValues(); private IEnumerable EnumerateCompressedAudios() => Enum.GetValues(); private IEnumerable EnumerateMappingCompressions() => Enum.GetValues() .Where(value => value is not (EUsmapCompressionMethod.Oodle or EUsmapCompressionMethod.Unknown)) diff --git a/FModel/ViewModels/SnooperViewModel.cs b/FModel/ViewModels/SnooperViewModel.cs index 140737f4..5f0a719b 100644 --- a/FModel/ViewModels/SnooperViewModel.cs +++ b/FModel/ViewModels/SnooperViewModel.cs @@ -2,9 +2,12 @@ using System; using System.Numerics; using System.Runtime.InteropServices; using System.Threading; +using System.Threading.Tasks; using System.Windows; using System.Windows.Forms; using CUE4Parse.GameTypes.Nascar.Assets.Exports; +using CUE4Parse.FileProvider; +using CUE4Parse.FileProvider.Objects; using CUE4Parse.UE4.Assets.Exports; using CUE4Parse.UE4.Assets.Exports.Animation; using CUE4Parse.UE4.Assets.Exports.Engine; @@ -13,6 +16,7 @@ using CUE4Parse.UE4.Assets.Exports.Houdini; using CUE4Parse.UE4.Assets.Exports.Material; using CUE4Parse.UE4.Assets.Exports.Paper2D; using CUE4Parse.UE4.Assets.Exports.StaticMesh; +using CUE4Parse.UE4.Assets.Exports.Texture; using CUE4Parse.UE4.Objects.Engine; using CUE4Parse.UE4.Versions; using CUE4Parse_Conversion.Options; @@ -75,6 +79,10 @@ public class SnooperViewModel : ViewModel, IDisposable _environment = new EnvironmentActor(); } + public Task RenderMeshPreviewAsync(IFileProvider provider, GameFile asset, ETexturePlatform platform) => _host.RenderMeshPreviewAsync(provider, asset, platform); + + public void CloseMeshPreviews() => _host.CloseMeshPreviews(); + public void Load(UObject obj, CancellationToken ct = default) { if (!CanOpenSnooper) diff --git a/FModel/Views/Resources/Controls/Explorer/ListExplorer/FileRow.xaml b/FModel/Views/Resources/Controls/Explorer/ListExplorer/FileRow.xaml index 5e40d0ca..45252052 100644 --- a/FModel/Views/Resources/Controls/Explorer/ListExplorer/FileRow.xaml +++ b/FModel/Views/Resources/Controls/Explorer/ListExplorer/FileRow.xaml @@ -24,21 +24,27 @@ - + + Stretch="Uniform" IsHitTestVisible="False"> diff --git a/FModel/Views/Resources/Controls/Explorer/TiledExplorer/FileButton.xaml b/FModel/Views/Resources/Controls/Explorer/TiledExplorer/FileButton.xaml index e5e01eb9..2bf4f17f 100644 --- a/FModel/Views/Resources/Controls/Explorer/TiledExplorer/FileButton.xaml +++ b/FModel/Views/Resources/Controls/Explorer/TiledExplorer/FileButton.xaml @@ -20,15 +20,25 @@ - - + + diff --git a/FModel/Views/SettingsView.xaml b/FModel/Views/SettingsView.xaml index a9522933..5ab6b1df 100644 --- a/FModel/Views/SettingsView.xaml +++ b/FModel/Views/SettingsView.xaml @@ -433,49 +433,81 @@ + + + + - + - - - - + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + Style="{DynamicResource {x:Static adonisUi:Styles.ToggleSwitch}}" Margin="0 5 0 10" /> - - + + Style="{DynamicResource {x:Static adonisUi:Styles.ToggleSwitch}}" Margin="0 5 0 10" /> - - + + Style="{DynamicResource {x:Static adonisUi:Styles.ToggleSwitch}}" Margin="0 5 0 10" /> - - + + Style="{DynamicResource {x:Static adonisUi:Styles.ToggleSwitch}}" Margin="0 5 0 10" /> - - + + Style="{DynamicResource {x:Static adonisUi:Styles.ToggleSwitch}}" Margin="0 5 0 10" /> - - + + Style="{DynamicResource {x:Static adonisUi:Styles.ToggleSwitch}}" Margin="0 5 0 10" /> diff --git a/Snooper b/Snooper index d3d4ce01..f45e6376 160000 --- a/Snooper +++ b/Snooper @@ -1 +1 @@ -Subproject commit d3d4ce01f3b37e30adb0f76db4285fe727f8b95a +Subproject commit f45e637610a66b599bf5b943575202b70bc8ea41