diff --git a/CUE4Parse b/CUE4Parse index 858ecc7d..7f3a0ccf 160000 --- a/CUE4Parse +++ b/CUE4Parse @@ -1 +1 @@ -Subproject commit 858ecc7dae30b5a99e9bb2dbb77cb65c527c7f32 +Subproject commit 7f3a0ccf121d538b1cceb3c81278189b2161d0cc diff --git a/FModel/App.xaml.cs b/FModel/App.xaml.cs index 93c06aff..225143b3 100644 --- a/FModel/App.xaml.cs +++ b/FModel/App.xaml.cs @@ -74,47 +74,48 @@ public partial class App if (!Directory.Exists(UserSettings.Default.RawDataDirectory)) { createMe = true; - UserSettings.Default.RawDataDirectory = Path.Combine(UserSettings.Default.OutputDirectory, "Exports"); + UserSettings.Default.RawDataDirectory = UserSettings.Default.ExportsDirectory; } if (!Directory.Exists(UserSettings.Default.PropertiesDirectory)) { createMe = true; - UserSettings.Default.PropertiesDirectory = Path.Combine(UserSettings.Default.OutputDirectory, "Exports"); + UserSettings.Default.PropertiesDirectory = UserSettings.Default.ExportsDirectory; } if (!Directory.Exists(UserSettings.Default.TextureDirectory)) { createMe = true; - UserSettings.Default.TextureDirectory = Path.Combine(UserSettings.Default.OutputDirectory, "Exports"); + UserSettings.Default.TextureDirectory = UserSettings.Default.ExportsDirectory; } if (!Directory.Exists(UserSettings.Default.AudioDirectory)) { createMe = true; - UserSettings.Default.AudioDirectory = Path.Combine(UserSettings.Default.OutputDirectory, "Exports"); + UserSettings.Default.AudioDirectory = UserSettings.Default.ExportsDirectory; } if (!Directory.Exists(UserSettings.Default.CodeDirectory)) { createMe = true; - UserSettings.Default.CodeDirectory = Path.Combine(UserSettings.Default.OutputDirectory, "Exports"); + UserSettings.Default.CodeDirectory = UserSettings.Default.ExportsDirectory; } if (!Directory.Exists(UserSettings.Default.ModelDirectory)) { createMe = true; - UserSettings.Default.ModelDirectory = Path.Combine(UserSettings.Default.OutputDirectory, "Exports"); + UserSettings.Default.ModelDirectory = UserSettings.Default.ExportsDirectory; } Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "FModel")); - Directory.CreateDirectory(Path.Combine(UserSettings.Default.OutputDirectory, "Backups")); - if (createMe) Directory.CreateDirectory(Path.Combine(UserSettings.Default.OutputDirectory, "Exports")); - Directory.CreateDirectory(Path.Combine(UserSettings.Default.OutputDirectory, "Logs")); + Directory.CreateDirectory(UserSettings.Default.BackupsDirectory); + if (createMe) Directory.CreateDirectory(UserSettings.Default.ExportsDirectory); + Directory.CreateDirectory(UserSettings.Default.LogsDirectory); + Directory.CreateDirectory(UserSettings.Default.MappingsDirectory); CacheManager.EnsureDirectories(); #if DEBUG - var filePath = Path.Combine(UserSettings.Default.OutputDirectory, "Logs", $"FModel-Debug-Log-{DateTime.Now:yyyy-MM-dd}.log"); + var filePath = Path.Combine(UserSettings.Default.LogsDirectory, $"FModel-Debug-Log-{DateTime.Now:yyyy-MM-dd}.log"); var viewerContexts = typeof(Snooper.Hosting.Bridge).Assembly.GetTypes() .Concat(typeof(EditorWindow).Assembly.GetTypes()) @@ -122,7 +123,7 @@ public partial class App .Append("Snooper") .ToHashSet(StringComparer.Ordinal); #else - var filePath = Path.Combine(UserSettings.Default.OutputDirectory, "Logs", $"FModel-Log-{DateTime.Now:yyyy-MM-dd}.log"); + var filePath = Path.Combine(UserSettings.Default.LogsDirectory, $"FModel-Log-{DateTime.Now:yyyy-MM-dd}.log"); #endif const string template1 = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u3}] {SourceContext}: {Message:lj}{NewLine}{Exception}"; const string template2 = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u3}] [{ClassName}] {ObjectPath}: {Message:lj}{NewLine}{Exception}"; @@ -150,6 +151,7 @@ public partial class App .MinimumLevel.Override("CUE4Parse_Conversion", LogEventLevel.Verbose) .WriteTo.Sink(ImGuiSink.Instance) .CreateLogger(); + CUE4Parse.CUE4ParseLog.UseLogger(Log.Logger); CacheManager.MigrateLegacyFiles(); Log.Information("Version {Version} ({CommitId})", Constants.APP_VERSION, Constants.APP_COMMIT_ID); diff --git a/FModel/Framework/CacheManager.cs b/FModel/Framework/CacheManager.cs index 55b55478..a59566af 100644 --- a/FModel/Framework/CacheManager.cs +++ b/FModel/Framework/CacheManager.cs @@ -9,7 +9,7 @@ namespace FModel.Framework; public static class CacheManager { public static string DataDirectory => - Directory.CreateDirectory(Path.Combine(UserSettings.Default.OutputDirectory, ".data")).FullName; + Directory.CreateDirectory(UserSettings.Default.CacheDirectory).FullName; public static string ChunksDirectory => Directory.CreateDirectory(Path.Combine(DataDirectory, "chunks")).FullName; diff --git a/FModel/Framework/FModelBridgeHost.cs b/FModel/Framework/FModelBridgeHost.cs index 792c8c1b..d4b75a10 100644 --- a/FModel/Framework/FModelBridgeHost.cs +++ b/FModel/Framework/FModelBridgeHost.cs @@ -12,7 +12,7 @@ namespace FModel.Framework; public sealed class FModelBridgeHost : IBridgeHost { public string Name => "FModel"; - public string ImGuiIniPath => Path.Combine(UserSettings.Default.OutputDirectory, ".data", "snooper.ini"); + public string ImGuiIniPath => Path.Combine(UserSettings.Default.CacheDirectory, "snooper.ini"); public bool CanBrowseAssets => true; diff --git a/FModel/Framework/StaticMappingGenerator.cs b/FModel/Framework/StaticMappingGenerator.cs new file mode 100644 index 00000000..1bdb442a --- /dev/null +++ b/FModel/Framework/StaticMappingGenerator.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using System.IO; +using CUE4Parse.MappingsProvider.Usmap; +using CUE4Parse.UE4.Versions; +using Serilog; + +namespace FModel.Framework; + +public static class StaticMappingGenerator +{ + public static string Generate(string executable, string mappingsDirectory, EGame game, EUsmapCompressionMethod compression, string gameDisplayName = null) + { + if (game < EGame.GAME_UE4_18) + throw new NotSupportedException("Static mapping generation requires Unreal Engine 4.18 or later."); + + var directory = Directory.CreateDirectory(mappingsDirectory).FullName; + var pendingOutput = Path.Combine(directory, $"{Guid.NewGuid():N}.usmap"); + + try + { + if (!UsmapGenerator.Generate(executable, pendingOutput, compression)) + throw new InvalidOperationException("UsmapGen could not create the mapping."); + + using var stream = File.OpenRead(pendingOutput); + var engineVersion = new UsmapParser(stream, comparer: StringComparer.Ordinal).EngineVersion; + + var major = engineVersion?.Major ?? ((int) game >> 24); + var minor = engineVersion?.Minor ?? (((int) game >> 16) & 0xFF); + var suffix = compression == EUsmapCompressionMethod.None ? "" : $"_{compression}"; + var name = gameDisplayName == null ? null : string.Join("_", gameDisplayName.Split(Path.GetInvalidFileNameChars(), StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)); + if (string.IsNullOrEmpty(name) || string.Equals(name, "Unknown", StringComparison.OrdinalIgnoreCase)) + name = Path.GetFileNameWithoutExtension(executable); + + // Example: 501_GameName_22-11-2026_ZStandard.usmap (Engine version without using "." is intentional) + var fileName = FormattableString.Invariant($"{major}{minor:D2}_{name}_{DateTime.Today:dd-MM-yyyy}{suffix}.usmap"); + var output = Path.Combine(directory, fileName); + File.Move(pendingOutput, output, overwrite: true); + return output; + } + finally + { + try + { + File.Delete(pendingOutput); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning(ex, "Could not remove temporary mapping {Path}", pendingOutput); + } + } + } + + public static string FindShippingExe(string archiveDirectory) + { + if (!Directory.Exists(archiveDirectory)) + throw new DirectoryNotFoundException("Static mapping generation requires a local archive directory."); + + var archive = new DirectoryInfo(archiveDirectory); + for (var directory = archive; directory.Parent != null; directory = directory.Parent) + { + if (Search(directory) is { } executable) + return executable; + } + + var options = new EnumerationOptions { AttributesToSkip = FileAttributes.ReparsePoint }; + string match = null; + foreach (var project in FindProjects(archive)) + { + if (Search(project) is not { } executable) + continue; + + if (match != null) + throw new FileNotFoundException($"Found multiple Win64 shipping executables under '{archiveDirectory}'."); + + match = executable; + } + + return match ?? throw new FileNotFoundException($"No Win64 shipping executable was found near '{archiveDirectory}'."); + + IEnumerable FindProjects(DirectoryInfo directory) + { + foreach (var child in directory.EnumerateDirectories("*", options)) + { + if (child.Name.Equals("Engine", StringComparison.OrdinalIgnoreCase)) + continue; + + if (Directory.Exists(Path.Combine(child.FullName, "Content", "Paks"))) + { + yield return child; + continue; + } + + foreach (var project in FindProjects(child)) + yield return project; + } + } + + static string Search(DirectoryInfo project) + { + var binaries = Path.Combine(project.FullName, "Binaries", "Win64"); + if (!Directory.Exists(binaries)) + return null; + + var preferred = Path.Combine(binaries, $"{project.Name}-Win64-Shipping.exe"); + if (File.Exists(preferred)) + return preferred; + + var projectExecutable = Path.Combine(binaries, $"{project.Name}.exe"); + if (File.Exists(projectExecutable)) + return projectExecutable; + + using var candidates = Directory.EnumerateFiles(binaries, "*-Shipping.exe").GetEnumerator(); + if (!candidates.MoveNext()) + return null; + + var executable = candidates.Current; + if (candidates.MoveNext()) + throw new FileNotFoundException($"Found multiple shipping executables in '{binaries}'."); + + return executable; + } + } +} diff --git a/FModel/Settings/UserSettings.cs b/FModel/Settings/UserSettings.cs index 991e9e9c..fa385d54 100644 --- a/FModel/Settings/UserSettings.cs +++ b/FModel/Settings/UserSettings.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.IO; using System.Windows; using System.Windows.Input; +using CUE4Parse.MappingsProvider.Usmap; using CUE4Parse.UE4.Assets.Exports.Material; using CUE4Parse.UE4.Versions; using CUE4Parse_Conversion.Options; @@ -92,6 +93,12 @@ public sealed class UserSettings : ViewModel set => SetProperty(ref _outputDirectory, value); } + [JsonIgnore] public string ExportsDirectory => Path.Combine(OutputDirectory, "Exports"); + [JsonIgnore] public string BackupsDirectory => Path.Combine(OutputDirectory, "Backups"); + [JsonIgnore] public string LogsDirectory => Path.Combine(OutputDirectory, "Logs"); + [JsonIgnore] public string MappingsDirectory => Path.Combine(OutputDirectory, "Mappings"); + [JsonIgnore] public string CacheDirectory => Path.Combine(OutputDirectory, ".data"); + private string _rawDataDirectory; public string RawDataDirectory { @@ -148,6 +155,16 @@ public sealed class UserSettings : ViewModel set => SetProperty(ref _lastOpenedSettingTab, value); } + // Without Oodle + private EUsmapCompressionMethod _mappingCompression = EUsmapCompressionMethod.ZStandard; + public EUsmapCompressionMethod MappingCompression + { + get => _mappingCompression; + set => SetProperty(ref _mappingCompression, value is not (EUsmapCompressionMethod.Oodle or EUsmapCompressionMethod.Unknown) && Enum.IsDefined(value) + ? value + : EUsmapCompressionMethod.ZStandard); + } + private bool _isLoggerExpanded = true; public bool IsLoggerExpanded { diff --git a/FModel/ViewModels/ApplicationViewModel.cs b/FModel/ViewModels/ApplicationViewModel.cs index 4e3c7ad1..235bdacb 100644 --- a/FModel/ViewModels/ApplicationViewModel.cs +++ b/FModel/ViewModels/ApplicationViewModel.cs @@ -261,7 +261,7 @@ public class ApplicationViewModel : ViewModel public static async Task InitVgmStream() { - var vgmZipFilePath = Path.Combine(UserSettings.Default.OutputDirectory, ".data", "vgmstream-win.zip"); + var vgmZipFilePath = Path.Combine(UserSettings.Default.CacheDirectory, "vgmstream-win.zip"); var vgmFileInfo = new FileInfo(vgmZipFilePath); if (!vgmFileInfo.Exists || vgmFileInfo.LastWriteTimeUtc < DateTime.UtcNow.AddMonths(-4)) @@ -288,10 +288,10 @@ public class ApplicationViewModel : ViewModel if (!Avx2.IsSupported) return; - var oodlePath = Path.Combine(UserSettings.Default.OutputDirectory, ".data", OodleHelper.OODLE_NAME_OLD); + var oodlePath = Path.Combine(UserSettings.Default.CacheDirectory, OodleHelper.OODLE_NAME_OLD); if (!File.Exists(oodlePath)) { - oodlePath = Path.Combine(UserSettings.Default.OutputDirectory, ".data", OodleHelper.OODLE_NAME_CURRENT); + oodlePath = Path.Combine(UserSettings.Default.CacheDirectory, OodleHelper.OODLE_NAME_CURRENT); } await OodleHelper.InitializeAsync(oodlePath); @@ -299,7 +299,7 @@ public class ApplicationViewModel : ViewModel public static async Task InitZlib() { - var zlibPath = Path.Combine(UserSettings.Default.OutputDirectory, ".data", ZlibHelper.DLL_NAME); + var zlibPath = Path.Combine(UserSettings.Default.CacheDirectory, ZlibHelper.DLL_NAME); var zlibFileInfo = new FileInfo(zlibPath); if (!zlibFileInfo.Exists || zlibFileInfo.LastWriteTimeUtc < DateTime.UtcNow.AddMonths(-4)) @@ -316,7 +316,7 @@ public class ApplicationViewModel : ViewModel public static async Task InitUnluac() { - var unluacPath = Path.Combine(UserSettings.Default.OutputDirectory, ".data", UnluacHelper.DllName); + var unluacPath = Path.Combine(UserSettings.Default.CacheDirectory, UnluacHelper.DllName); await UnluacHelper.InitializeAsync(unluacPath).ConfigureAwait(false); if (UnluacHelper.Instance is null) FLogger.Append(ELog.Error, () => FLogger.Text("Failed to download unluac", Constants.WHITE, true)); diff --git a/FModel/ViewModels/AudioPlayerViewModel.cs b/FModel/ViewModels/AudioPlayerViewModel.cs index 43757288..fef6f49f 100644 --- a/FModel/ViewModels/AudioPlayerViewModel.cs +++ b/FModel/ViewModels/AudioPlayerViewModel.cs @@ -710,7 +710,7 @@ public class AudioPlayerViewModel : ViewModel, ISource, IDisposable private static bool TryConvertRada(string inputFilePath, byte[] inputFileData, string extension, out string rawFilePath, bool updateUi = false) { rawFilePath = string.Empty; - var decoderPath = Path.Combine(UserSettings.Default.OutputDirectory, ".data", $"{extension}dec.exe"); + var decoderPath = Path.Combine(UserSettings.Default.CacheDirectory, $"{extension}dec.exe"); if (!File.Exists(decoderPath)) { Log.Error("Failed to convert {FilePath}, {Extension} decoder is missing", inputFilePath, extension); @@ -763,10 +763,10 @@ public class AudioPlayerViewModel : ViewModel, ISource, IDisposable private static string TryGetVgmstreamPath() { - var vgmFilePath = Path.Combine(UserSettings.Default.OutputDirectory, ".data", "test.exe"); + var vgmFilePath = Path.Combine(UserSettings.Default.CacheDirectory, "test.exe"); if (!File.Exists(vgmFilePath)) { - vgmFilePath = Path.Combine(UserSettings.Default.OutputDirectory, ".data", "vgmstream-cli.exe"); + vgmFilePath = Path.Combine(UserSettings.Default.CacheDirectory, "vgmstream-cli.exe"); if (!File.Exists(vgmFilePath)) { Log.Error("Failed to convert audio, vgmstream is missing"); diff --git a/FModel/ViewModels/BackupManagerViewModel.cs b/FModel/ViewModels/BackupManagerViewModel.cs index ce2c0356..5699117b 100644 --- a/FModel/ViewModels/BackupManagerViewModel.cs +++ b/FModel/ViewModels/BackupManagerViewModel.cs @@ -63,7 +63,7 @@ public class BackupManagerViewModel : ViewModel { await _threadWorkerView.Begin(_ => { - var backupFolder = Path.Combine(UserSettings.Default.OutputDirectory, "Backups"); + var backupFolder = UserSettings.Default.BackupsDirectory; var fileName = $"{_gameName}_{DateTime.Now:MM'_'dd'_'yyyy}.fbkp"; var fullPath = Path.Combine(backupFolder, fileName); var func = new Func(x => !x.IsUePackagePayload); @@ -92,7 +92,7 @@ public class BackupManagerViewModel : ViewModel if (SelectedBackup == null) return; await _threadWorkerView.Begin(_ => { - var fullPath = Path.Combine(Path.Combine(UserSettings.Default.OutputDirectory, "Backups"), SelectedBackup.FileName); + var fullPath = Path.Combine(UserSettings.Default.BackupsDirectory, SelectedBackup.FileName); _apiEndpointView.DownloadFile(SelectedBackup.Url, fullPath); SaveCheck(fullPath, SelectedBackup.FileName, "downloaded", "download"); }); diff --git a/FModel/ViewModels/CUE4ParseViewModel.cs b/FModel/ViewModels/CUE4ParseViewModel.cs index f1dae55e..f128c654 100644 --- a/FModel/ViewModels/CUE4ParseViewModel.cs +++ b/FModel/ViewModels/CUE4ParseViewModel.cs @@ -108,6 +108,7 @@ public class CUE4ParseViewModel : ViewModel RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); private static readonly HttpClient _chunkClient = ManifestParseOptions.CreateDefaultClient(); + private string _appliedLocalMappingPath; public AbstractVfsFileProvider Provider { get; } public GameDirectoryViewModel GameDirectory { get; } @@ -406,69 +407,101 @@ public class CUE4ParseViewModel : ViewModel return new FileUsmapTypeMappingsProvider(path, StringComparer.Ordinal); } + public void ApplyMappingFile(string path) + { + var mappings = SelectMappingsProvider(path); + var endpoint = UserSettings.Default.CurrentDir.Endpoints[(int) EEndpointType.Mapping]; + Provider.MappingsContainer = mappings; + endpoint.FilePath = path; + endpoint.Overwrite = true; + _appliedLocalMappingPath = path; + LogLoadedMappings(ELog.Information); + } + + public bool HasMappingSettingsChanged() + { + var endpoint = UserSettings.Default.CurrentDir.Endpoints[(int) EEndpointType.Mapping]; + return !string.Equals(_appliedLocalMappingPath, GetLocalMappingPath(endpoint), StringComparison.OrdinalIgnoreCase); + } + + private static string GetLocalMappingPath(EndpointSettings endpoint) => endpoint.Overwrite && File.Exists(endpoint.FilePath) ? endpoint.FilePath : null; + public Task InitMappings(bool force = false) { - if (!UserSettings.IsEndpointValid(EEndpointType.Mapping, out var endpoint)) + var endpoint = UserSettings.Default.CurrentDir.Endpoints[(int) EEndpointType.Mapping]; + if (GetLocalMappingPath(endpoint) is { } path) + { + ApplyMappingFile(path); + return Task.CompletedTask; + } + + if (!endpoint.IsValid) { Provider.MappingsContainer = null; + _appliedLocalMappingPath = null; return Task.CompletedTask; } return Task.Run(() => { var l = ELog.Information; - if (endpoint.Overwrite && File.Exists(endpoint.FilePath)) + var mappingsProvider = _appliedLocalMappingPath == null ? Provider.MappingsContainer : null; + + // deprecated values + if (endpoint.Path == "$.[?(@.meta.compressionMethod=='Oodle')].['url','fileName']") endpoint.Path = "$.[0].['url','fileName']"; + if (endpoint.Url == "https://fortnitecentral.genxgames.gg/api/v1/mappings") { - Provider.MappingsContainer = SelectMappingsProvider(endpoint.FilePath); + endpoint.Url = "https://uedb.dev/svc/api/v1/fortnite/mappings"; + endpoint.Path = "$.mappings.ZStandard"; } - else if (endpoint.IsValid) + + var mappingsFolder = CacheManager.MappingsDirectory; + var mappings = _apiEndpointView.DynamicApi.GetMappings(CancellationToken.None, endpoint.Url, endpoint.Path); + if (mappings is { Length: > 0 }) { - // deprecated values - if (endpoint.Path == "$.[?(@.meta.compressionMethod=='Oodle')].['url','fileName']") endpoint.Path = "$.[0].['url','fileName']"; - if (endpoint.Url == "https://fortnitecentral.genxgames.gg/api/v1/mappings") + foreach (var mapping in mappings) { - endpoint.Url = "https://uedb.dev/svc/api/v1/fortnite/mappings"; - endpoint.Path = "$.mappings.ZStandard"; - } + if (!mapping.IsValid) continue; - var mappingsFolder = CacheManager.MappingsDirectory; - var mappings = _apiEndpointView.DynamicApi.GetMappings(CancellationToken.None, endpoint.Url, endpoint.Path); - if (mappings is { Length: > 0 }) - { - foreach (var mapping in mappings) + var mappingPath = Path.Combine(mappingsFolder, mapping.FileName); + if (force || !File.Exists(mappingPath) || new FileInfo(mappingPath).Length == 0) { - if (!mapping.IsValid) continue; - - var mappingPath = Path.Combine(mappingsFolder, mapping.FileName); - if (force || !File.Exists(mappingPath) || new FileInfo(mappingPath).Length == 0) - { - _apiEndpointView.DownloadFile(mapping.Url, mappingPath); - } - - Provider.MappingsContainer = SelectMappingsProvider(mappingPath); - break; + _apiEndpointView.DownloadFile(mapping.Url, mappingPath); } + + mappingsProvider = SelectMappingsProvider(mappingPath); + break; } + } - if (Provider.MappingsContainer == null) + if (mappingsProvider == null) + { + var latestUsmaps = new DirectoryInfo(mappingsFolder).GetFiles("*_oo.usmap"); + if (latestUsmaps.Length > 0) { - var latestUsmaps = new DirectoryInfo(mappingsFolder).GetFiles("*_oo.usmap"); - if (latestUsmaps.Length <= 0) return; - var latestUsmapInfo = latestUsmaps.OrderBy(f => f.LastWriteTime).Last(); - Provider.MappingsContainer = new FileUsmapTypeMappingsProvider(latestUsmapInfo.FullName, StringComparer.Ordinal); + mappingsProvider = new FileUsmapTypeMappingsProvider(latestUsmapInfo.FullName, StringComparer.Ordinal); l = ELog.Warning; } } - if (Provider.MappingsContainer is FileUsmapTypeMappingsProvider m) - { - Log.Information($"Mappings pulled from '{m.FileName}'"); - FLogger.Append(l, () => FLogger.Text($"Mappings pulled from '{m.FileName}'", Constants.WHITE, true)); - } + if (GetLocalMappingPath(endpoint) != null) return; + + Provider.MappingsContainer = mappingsProvider; + _appliedLocalMappingPath = null; + LogLoadedMappings(l); }); } + private void LogLoadedMappings(ELog level) + { + if (Provider.MappingsContainer is FileUsmapTypeMappingsProvider m) + { + Log.Information($"Mappings pulled from '{m.FileName}'"); + FLogger.Append(level, () => FLogger.Text($"Mappings pulled from '{m.FileName}'", Constants.WHITE, true)); + } + } + public Task VerifyConsoleVariables() { if (Provider.Versions["StripAdditiveRefPose"]) diff --git a/FModel/ViewModels/Commands/LoadCommand.cs b/FModel/ViewModels/Commands/LoadCommand.cs index db2392f9..d22bf1fc 100644 --- a/FModel/ViewModels/Commands/LoadCommand.cs +++ b/FModel/ViewModels/Commands/LoadCommand.cs @@ -168,7 +168,7 @@ public class LoadCommand : ViewModelCommand var openFileDialog = new OpenFileDialog { Title = "Select a backup file older than your current game version", - InitialDirectory = Path.Combine(UserSettings.Default.OutputDirectory, "Backups"), + InitialDirectory = UserSettings.Default.BackupsDirectory, Filter = "FBKP Files (*.fbkp)|*.fbkp|All Files (*.*)|*.*", Multiselect = false }; diff --git a/FModel/ViewModels/SettingsViewModel.cs b/FModel/ViewModels/SettingsViewModel.cs index 0b91ff26..cf262915 100644 --- a/FModel/ViewModels/SettingsViewModel.cs +++ b/FModel/ViewModels/SettingsViewModel.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using CUE4Parse.MappingsProvider.Usmap; using CUE4Parse.UE4.Assets.Exports.Texture; using CUE4Parse.UE4.Objects.Core.Serialization; using CUE4Parse.UE4.Versions; @@ -33,6 +34,8 @@ public class SettingsViewModel : ViewModel set => SetProperty(ref _selectedUeGame, value); } + public bool CanGenerateMapping => UserSettings.Default.CurrentDir?.UeVersion >= EGame.GAME_UE4_18; + private IList _selectedCustomVersions; public IList SelectedCustomVersions { @@ -68,6 +71,20 @@ public class SettingsViewModel : ViewModel set => SetProperty(ref _mappingEndpoint, value); } + private EUsmapCompressionMethod _selectedMappingCompression; + public EUsmapCompressionMethod SelectedMappingCompression + { + get => _selectedMappingCompression; + set => SetProperty(ref _selectedMappingCompression, value); + } + + private bool _isGeneratingMapping; + public bool IsGeneratingMapping + { + get => _isGeneratingMapping; + set => SetProperty(ref _isGeneratingMapping, value); + } + private ELanguage _selectedAssetLanguage; public ELanguage SelectedAssetLanguage { @@ -131,27 +148,16 @@ public class SettingsViewModel : ViewModel public ReadOnlyObservableCollection AesReloads { get; private set; } public ReadOnlyObservableCollection DiscordRpcs { get; private set; } public ReadOnlyObservableCollection CompressedAudios { get; private set; } + public ReadOnlyObservableCollection MappingCompressions { get; private set; } public ReadOnlyObservableCollection CosmeticStyles { get; private set; } public ReadOnlyObservableCollection JsonHighlightThemes { get; private set; } - private string _outputSnapshot; - private string _rawDataSnapshot; - private string _propertiesSnapshot; - private string _textureSnapshot; - private string _audioSnapshot; - private string _codeSnapshot; - private string _modelSnapshot; private string _gameSnapshot; private EGame _ueGameSnapshot; private IList _customVersionsSnapshot; private IDictionary _optionsSnapshot; private IDictionary> _mapStructTypesSnapshot; private ELanguage _assetLanguageSnapshot; - private ECompressedAudio _compressedAudioSnapshot; - private EIconStyle _cosmeticStyleSnapshot; - private EJsonHighlightTheme _jsonHighlightThemeSnapshot; - - private bool _mappingsUpdate = false; public SettingsViewModel() { @@ -160,44 +166,28 @@ public class SettingsViewModel : ViewModel public void Initialize() { - _outputSnapshot = UserSettings.Default.OutputDirectory; - _rawDataSnapshot = UserSettings.Default.RawDataDirectory; - _propertiesSnapshot = UserSettings.Default.PropertiesDirectory; - _textureSnapshot = UserSettings.Default.TextureDirectory; - _audioSnapshot = UserSettings.Default.AudioDirectory; - _codeSnapshot = UserSettings.Default.CodeDirectory; - _modelSnapshot = UserSettings.Default.ModelDirectory; _gameSnapshot = UserSettings.Default.GameDirectory; _ueGameSnapshot = UserSettings.Default.CurrentDir.UeVersion; _customVersionsSnapshot = UserSettings.Default.CurrentDir.Versioning.CustomVersions; _optionsSnapshot = UserSettings.Default.CurrentDir.Versioning.Options; _mapStructTypesSnapshot = UserSettings.Default.CurrentDir.Versioning.MapStructTypes; - _criwareDecryptionKey = UserSettings.Default.CurrentDir.CriwareDecryptionKey; - _unluacOpcodeMap = UserSettings.Default.CurrentDir.UnluacOpCodeMap; AesEndpoint = UserSettings.Default.CurrentDir.Endpoints[0]; MappingEndpoint = UserSettings.Default.CurrentDir.Endpoints[1]; - MappingEndpoint.PropertyChanged += (_, args) => - { - if (!_mappingsUpdate) - _mappingsUpdate = args.PropertyName is "Overwrite" or "FilePath"; - }; _assetLanguageSnapshot = UserSettings.Default.AssetLanguage; - _compressedAudioSnapshot = UserSettings.Default.CompressedAudioMode; - _cosmeticStyleSnapshot = UserSettings.Default.CosmeticStyle; - _jsonHighlightThemeSnapshot = UserSettings.Default.JsonHighlightTheme; SelectedUeGame = _ueGameSnapshot; SelectedCustomVersions = _customVersionsSnapshot; SelectedOptions = _optionsSnapshot; SelectedMapStructTypes = _mapStructTypesSnapshot; SelectedAssetLanguage = _assetLanguageSnapshot; - SelectedCompressedAudio = _compressedAudioSnapshot; - SelectedCosmeticStyle = _cosmeticStyleSnapshot; - CriwareDecryptionKey = _criwareDecryptionKey; - UnluacOpcodeMap = _unluacOpcodeMap; - SelectedJsonHighlightTheme = _jsonHighlightThemeSnapshot; + SelectedCompressedAudio = UserSettings.Default.CompressedAudioMode; + SelectedMappingCompression = UserSettings.Default.MappingCompression; + SelectedCosmeticStyle = UserSettings.Default.CosmeticStyle; + CriwareDecryptionKey = UserSettings.Default.CurrentDir.CriwareDecryptionKey; + UnluacOpcodeMap = UserSettings.Default.CurrentDir.UnluacOpCodeMap; + SelectedJsonHighlightTheme = UserSettings.Default.JsonHighlightTheme; SelectedAesReload = UserSettings.Default.AesReload; SelectedDiscordRpc = UserSettings.Default.DiscordRpc; @@ -206,6 +196,7 @@ public class SettingsViewModel : ViewModel AesReloads = new ReadOnlyObservableCollection(new ObservableCollection(EnumerateAesReloads())); DiscordRpcs = new ReadOnlyObservableCollection(new ObservableCollection(EnumerateDiscordRpcs())); CompressedAudios = new ReadOnlyObservableCollection(new ObservableCollection(EnumerateCompressedAudios())); + MappingCompressions = new ReadOnlyObservableCollection(new ObservableCollection(EnumerateMappingCompressions())); CosmeticStyles = new ReadOnlyObservableCollection(new ObservableCollection(EnumerateCosmeticStyles())); JsonHighlightThemes = new ReadOnlyObservableCollection(new ObservableCollection(EnumerateJsonHighlightThemes())); } @@ -217,8 +208,6 @@ public class SettingsViewModel : ViewModel if (_assetLanguageSnapshot != SelectedAssetLanguage) whatShouldIDo.Add(SettingsOut.ReloadLocres); - if (_mappingsUpdate) - whatShouldIDo.Add(SettingsOut.ReloadMappings); if (_ueGameSnapshot != SelectedUeGame || _customVersionsSnapshot != SelectedCustomVersions || _optionsSnapshot != SelectedOptions || // combobox @@ -234,6 +223,7 @@ public class SettingsViewModel : ViewModel UserSettings.Default.CurrentDir.UnluacOpCodeMap = UnluacOpcodeMap; UserSettings.Default.AssetLanguage = SelectedAssetLanguage; + UserSettings.Default.MappingCompression = SelectedMappingCompression; UserSettings.Default.CompressedAudioMode = SelectedCompressedAudio; UserSettings.Default.CosmeticStyle = SelectedCosmeticStyle; UserSettings.Default.AesReload = SelectedAesReload; @@ -257,6 +247,9 @@ public class SettingsViewModel : ViewModel private IEnumerable EnumerateAesReloads() => Enum.GetValues(); private IEnumerable EnumerateDiscordRpcs() => Enum.GetValues(); private IEnumerable EnumerateCompressedAudios() => Enum.GetValues(); + private IEnumerable EnumerateMappingCompressions() => Enum.GetValues() + .Where(value => value is not (EUsmapCompressionMethod.Oodle or EUsmapCompressionMethod.Unknown)) + .Reverse(); private IEnumerable EnumerateCosmeticStyles() => Enum.GetValues(); private IEnumerable EnumerateJsonHighlightThemes() => Enum.GetValues(); } diff --git a/FModel/Views/ImageMerger.xaml.cs b/FModel/Views/ImageMerger.xaml.cs index 6a3a4189..4af9f40d 100644 --- a/FModel/Views/ImageMerger.xaml.cs +++ b/FModel/Views/ImageMerger.xaml.cs @@ -142,7 +142,7 @@ public partial class ImageMerger var fileBrowser = new OpenFileDialog { Title = "Add image(s)", - InitialDirectory = Path.Combine(UserSettings.Default.OutputDirectory, "Exports"), + InitialDirectory = UserSettings.Default.ExportsDirectory, Multiselect = true, Filter = "Image Files (*.png,*.bmp,*.jpg,*.jpeg,*.jfif,*.jpe,*.tiff,*.tif)|*.png;*.bmp;*.jpg;*.jpeg;*.jfif;*.jpe;*.tiff;*.tif|All Files (*.*)|*.*" }; diff --git a/FModel/Views/Resources/Controls/DropOverlay.xaml.cs b/FModel/Views/Resources/Controls/DropOverlay.xaml.cs index faacc412..d9aea2da 100644 --- a/FModel/Views/Resources/Controls/DropOverlay.xaml.cs +++ b/FModel/Views/Resources/Controls/DropOverlay.xaml.cs @@ -6,7 +6,6 @@ using System.Windows; using System.Windows.Controls; using System.Windows.Threading; using FModel.Services; -using FModel.Settings; using FModel.ViewModels; namespace FModel.Views.Resources.Controls; @@ -97,17 +96,12 @@ public partial class DropOverlay : UserControl await Dispatcher.InvokeAsync(() => _applicationView.AddGameDirectory(_path)); break; case DragStatus.File: - UserSettings.IsEndpointValid(EEndpointType.Mapping, out var oldMappingsEndpoint); try { - var newMappingsEndpoint = new EndpointSettings() { Overwrite = true, FilePath = _path }; - UserSettings.Default.CurrentDir.Endpoints[(int) EEndpointType.Mapping] = newMappingsEndpoint; - await _applicationView.CUE4Parse.InitMappings(); - _applicationView.SettingsView.MappingEndpoint = newMappingsEndpoint; + _applicationView.CUE4Parse.ApplyMappingFile(_path); } catch (Exception ex) { - UserSettings.Default.CurrentDir.Endpoints[(int) EEndpointType.Mapping] = oldMappingsEndpoint; FLogger.Append(ELog.Error, () => { FLogger.Text($"Failed to load mapping file: {ex.Message}", Constants.WHITE, true); diff --git a/FModel/Views/SettingsView.xaml b/FModel/Views/SettingsView.xaml index ea1b49a0..a9522933 100644 --- a/FModel/Views/SettingsView.xaml +++ b/FModel/Views/SettingsView.xaml @@ -12,10 +12,16 @@ WindowStartupLocation="CenterScreen" ResizeMode="NoResize" IconVisibility="Collapsed" SizeToContent="Height" MinHeight="{Binding Source={x:Static SystemParameters.MaximizedPrimaryScreenHeight}, Converter={converters:RatioConverter}, ConverterParameter='0.10'}" Width="{Binding Source={x:Static SystemParameters.MaximizedPrimaryScreenWidth}, Converter={converters:RatioConverter}, ConverterParameter='0.45'}" - AllowDrop="True"> + Closing="OnClosing"> @@ -158,7 +164,6 @@ Content="{Binding IsChecked, RelativeSource={RelativeSource Self}, Converter={x:Static converters:BoolToToggleConverter.Instance}}" IsChecked="{Binding SettingsView.MappingEndpoint.Overwrite, Mode=TwoWay}" Style="{DynamicResource {x:Static adonisUi:Styles.ToggleSwitch}}" /> - @@ -169,10 +174,93 @@ DataContext="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:Views.SettingsView}}}" Visibility="{Binding SettingsView.MappingEndpoint.Overwrite, Converter={StaticResource BoolToVisibilityConverter}}" /> - + + + + + + + + + + - - + + + + + + + + @@ -186,10 +274,10 @@