示例#1
0
        protected override IEnumerable <UpdateOption> GetUpdateOptions()
        {
            bool UiFilter(string x)
            {
                return(!FileUtils.ArePathsEqual(x, @"ui_skin.json"));
            }

            bool PreviewFilter(string x)
            {
                return(!FileUtils.ArePathsEqual(x, @"preview.jpg") && !FileUtils.ArePathsEqual(x, @"preview.png"));
            }

            return(base.GetUpdateOptions().Union(new[] {
                new UpdateOption(ToolsStrings.ContentInstallation_KeepUiInformation, false)
                {
                    Filter = UiFilter
                },
                new UpdateOption("Update over existing files, keep preview", false)
                {
                    Filter = PreviewFilter
                },
                new UpdateOption("Update over existing files, keep UI information & preview", false)
                {
                    Filter = x => UiFilter(x) && PreviewFilter(x)
                }
            }));
        }
示例#2
0
        public static void RescanCategory([NotNull] PresetsCategory category, bool reloadPresets)
        {
            foreach (var c in Instances.Values.SelectMany(x => x))
            {
                if (c != null && Equals(c._presetable?.PresetableCategory, category))
                {
                    c.UpdateSavedPresets();

                    if (reloadPresets && c._selectedPresetFilename != null)
                    {
                        var entry = c.SavedPresets.FirstOrDefault(x => FileUtils.ArePathsEqual(x.VirtualFilename, c._selectedPresetFilename));
                        if (entry == null)
                        {
                            Logging.Warning($@"Can’t set preset to “{c._selectedPresetFilename}”, entry not found");
                        }
                        else if (!ReferenceEquals(c.CurrentUserPreset, entry))
                        {
                            c.CurrentUserPreset = entry;
                        }
                        else
                        {
                            c.SelectionChanged(entry);
                        }
                    }
                }
            }
        }
示例#3
0
        protected override ICopyCallback GetCopyCallback(string destination)
        {
            var path = EntryPath;

            return(string.IsNullOrWhiteSpace(path) ? new CopyCallback(null) :
                   new CopyCallback(info => FileUtils.ArePathsEqual(info.Key, path) ? _destination : null));
        }
示例#4
0
        public static bool LoadPreset(string key, string filename, string serialized, bool changed)
        {
            ValuesStorage.Set("__userpresets_p_" + key, filename);
            ValuesStorage.Set("__userpresets_c_" + key, changed);

            var r = false;

            foreach (var c in GetInstance(key))
            {
                c.UpdateSavedPresets();

                var entry = c.SavedPresets.FirstOrDefault(x => FileUtils.ArePathsEqual(x.VirtualFilename, filename));
                c.CurrentUserPreset = entry;

                try {
                    c.UserPresetable?.ImportFromPresetData(serialized);
                } catch (Exception e) {
                    NonfatalError.Notify("Can’t load preset", e);
                }

                c.SetChanged(changed);
                r = true;
            }

            return(r);
        }
示例#5
0
        private void ScanMods(bool force, params string[] filenames)
        {
            void Scan()
            {
                var directories = Directory.GetDirectories(ModsDirectory).Where(x => Path.GetFileName(x)?.StartsWith("!") == false).ToList();
                var replaceMods = force || !directories.SequenceEqual(Mods.Select(x => x.ModDirectory));

                if (replaceMods)
                {
                    Mods.ReplaceEverythingBy_Direct(Directory.GetDirectories(ModsDirectory).Where(x => Path.GetFileName(x)?.StartsWith("!") == false).Select(x => new GenericMod(this, x)));
                }
                else
                {
                    foreach (var changed in filenames.Where(x => x?.EndsWith(GenericMod.DescriptionExtension, StringComparison.OrdinalIgnoreCase) == true))
                    {
                        Mods.FirstOrDefault(x => FileUtils.IsAffectedBy(changed, x.ModDirectory))?.Description.Reset();
                    }
                }

                if (replaceMods || filenames.Any(x => x == null || FileUtils.ArePathsEqual(x, ConfigFilename)))
                {
                    var state = new FileInfo(ConfigFileName);
                    if (!_lastSaved.HasValue || !state.Exists || state.LastWriteTime > _lastSaved)
                    {
                        LoadState();
                    }
                }
            }

            _operationBusy.Do(Scan);
        }
示例#6
0
        public static IDisposable WatchFile(string filename, Action reloadAction)
        {
            var reloading = false;

            return(SetWatcher(Path.GetDirectoryName(filename), async s => {
                if (reloading || !FileUtils.ArePathsEqual(s, filename))
                {
                    return;
                }
                reloading = true;

                try {
                    for (var i = 0; i < 3; i++)
                    {
                        try {
                            await Task.Delay(300);
                            reloadAction();
                            break;
                        } catch (IOException e) {
                            AcToolsLogging.Write(e);
                        }
                    }
                } finally {
                    reloading = false;
                }
            }));
        }
示例#7
0
        private void ComboBox_SelectionChanged(object sender, SelectedItemChangedEventArgs e)
        {
            var entry = _comboBox?.SelectedItem as ISavedPresetEntry;

            if (entry == null)
            {
                return;
            }

            if (!ReferenceEquals(CurrentUserPreset, entry))
            {
                CurrentUserPreset = entry;
                foreach (var c in GetInstance(_presetable.PresetableKey).ApartFrom(this))
                {
                    var en = c.SavedPresets.FirstOrDefault(x => FileUtils.ArePathsEqual(x.Filename, entry.Filename));
                    if (en == null)
                    {
                        Logging.Warning($@"Can’t set preset to “{entry.Filename}”, entry not found");
                    }
                    else if (!ReferenceEquals(c.CurrentUserPreset, en))
                    {
                        c.CurrentUserPreset = en;
                    }
                    else
                    {
                        c.SelectionChanged(en);
                    }
                }
            }
            else
            {
                SelectionChanged(entry);
            }
        }
示例#8
0
        public static bool LoadPreset(string key, string filename)
        {
            ValuesStorage.Set("__userpresets_p_" + key, filename);
            ValuesStorage.Set("__userpresets_c_" + key, false);

            var r = false;

            foreach (var c in GetInstance(key))
            {
                c.UpdateSavedPresets();

                var entry = c.SavedPresets.FirstOrDefault(x => FileUtils.ArePathsEqual(x.VirtualFilename, filename));
                if (entry == null)
                {
                    Logging.Warning($@"Can’t set preset to “{filename}”, entry not found");
                }
                else if (!ReferenceEquals(c.CurrentUserPreset, entry))
                {
                    c.CurrentUserPreset = entry;
                }
                else
                {
                    c.SelectionChanged(entry);
                }

                r = true;
            }

            return(r);
        }
            private void ImportLut(string filename)
            {
                try {
                    string name;
                    if (!FileUtils.ArePathsEqual(Path.GetDirectoryName(filename), AcPaths.GetDocumentsCfgDirectory()))
                    {
                        name = Prompt.Show("Choose a name for the new LUT setting:", "New LUT",
                                           Path.GetFileNameWithoutExtension(filename) + ".lut", "?", required: true, maxLength: 120);
                        if (string.IsNullOrWhiteSpace(name))
                        {
                            return;
                        }

                        if (!name.EndsWith(".lut", StringComparison.OrdinalIgnoreCase))
                        {
                            name += ".lut";
                        }

                        File.Copy(filename, Path.Combine(AcPaths.GetDocumentsCfgDirectory(), name), true);
                    }
                    else
                    {
                        name = Path.GetFileName(filename);
                    }

                    SwitchFfPostProcessLutName(name);
                } catch (Exception e) {
                    NonfatalError.Notify("Can’t import LUT-file", e);
                }
            }
示例#10
0
        private void OnFileSomethingChanged(string filename)
        {
            if (IsBlocked)
            {
                return;
            }

            var directory = Path.GetDirectoryName(filename);

            if (directory == null)
            {
                return;
            }

            directory = FileUtils.NormalizePath(directory);
            if (FileUtils.IsAffectedBy(_dir, filename) || string.Equals(directory, _dir, StringComparison.OrdinalIgnoreCase))
            {
                _busyCreateConfigs.DoDelay(() => {
                    if ((DateTime.Now - _lastSaved).TotalSeconds < 3d)
                    {
                        return;
                    }
                    CreateConfigs();
                    RescanPossibleIssues();
                }, 300);
                if (FileUtils.ArePathsEqual(filename, PatchHelper.GetManifestFilename()))
                {
                    _busyUpdateVersion.DoDelay(PatchHelper.Reload, 300);
                }
            }
            else if (Configs != null)
            {
                _busyCreateConfigs.DoDelay(() => {
                    foreach (var item in Configs
                             .SelectMany(x => x.Sections)
                             .SelectMany(x => x)
                             .OfType <PythonAppConfigPluginValue>())
                    {
                        if (FileUtils.IsAffectedBy(filename, item.PluginsDirectory))
                        {
                            item.ReloadPlugins();
                        }
                    }
                }, 300);
            }

            if (FileUtils.ArePathsEqual(directory, AcRootDirectory.Instance.RequireValue))
            {
                var name = Path.GetFileName(filename);
                if (string.Equals(name, "dwrite.dll", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(name, "acs.exe", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(name, "acs.pdb", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(name, "changelog.txt", StringComparison.OrdinalIgnoreCase))
                {
                    RescanPossibleIssues();
                }
            }
        }
示例#11
0
 private void DeleteIfEmpty(string directory)
 {
     while (directory != null && !FileUtils.ArePathsEqual(directory, ModsDirectory) && !FileUtils.ArePathsEqual(directory, RootDirectory) &&
            Directory.Exists(directory) && FileUtils.IsDirectoryEmpty(directory))
     {
         Directory.Delete(directory);
         directory = Path.GetDirectoryName(directory);
     }
 }
示例#12
0
文件: Document.cs 项目: MRoc/puremp3
        private void OnPathChanged(Object sender, PropertyChangedEventArgs e)
        {
            string selectedPath = FileTreeModel.SelectedPathString();

            if (!FileUtils.ArePathsEqual(selectedPath, Editor.Path.Value))
            {
                FileTreeModel.ExpandAndSelect(Editor.Path.Value, false);
            }
        }
示例#13
0
 private void FileUpdate(object sender, FileSystemEventArgs e)
 {
     if (FileUtils.ArePathsEqual(e.FullPath, _resultFilename))
     {
         _timer.IsEnabled = false;
         _processTcs?.TrySetResult(null);
         _busy.DoDelay(() => {
             _tcs?.TrySetResult(true);
         }, 500);
     }
 }
示例#14
0
            private void ExtendWithPresets([NotNull] string processFilename)
            {
                if (processFilename == null)
                {
                    throw new ArgumentNullException(nameof(processFilename));
                }

                var presets = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Logitech", "Gaming Software");

                if (!Directory.Exists(presets))
                {
                    return;
                }

                var ns             = XNamespace.Get("http://www.logitech.com/schemas/2009/gaming/game_profile");
                var specialOptions = Directory.GetFiles(presets, "*.xml").TryToSelect(XDocument.Load)
                                     .FirstOrDefault(x => FileUtils.ArePathsEqual(
                                                         x?.Descendants(ns + "Target").FirstOrDefault()?.Element(ns + "Path")?.Value ?? "",
                                                         processFilename))?.Descendants(ns + "SpecialOptions")
                                     .FirstOrDefault();

                var forceOptions = specialOptions?.Element(ns + "ForceOptions");

                if (forceOptions != null && (forceOptions.Attribute("Enable")?.Value).As <bool>())
                {
                    OverallGainPercentage       = (forceOptions.Attribute("OverallAttenuation")?.Value).As(OverallGainPercentage);
                    SpringGainPercentage        = (forceOptions.Attribute("SpringAttenuation")?.Value).As(SpringGainPercentage);
                    DamperGainPercentage        = (forceOptions.Attribute("DamperAttenuation")?.Value).As(DamperGainPercentage);
                    PersistentSpringEnable      = (forceOptions.Attribute("DefaultSpringEnabled")?.Value).As(PersistentSpringEnable);
                    DefaultSpringGainPercentage = (forceOptions.Attribute("DefaultSpringAttenuation")?.Value).As(DefaultSpringGainPercentage);
                }

                var wheelOptions = specialOptions?.Element(ns + "WheelOptions");

                if (wheelOptions != null && (wheelOptions.Attribute("Enable")?.Value).As <bool>())
                {
                    OperatingRange       = (wheelOptions.Attribute("OperatingRange")?.Value).As(OperatingRange);
                    CombinedPedalsEnable = (wheelOptions.Attribute("CombinePedals")?.Value).As(CombinedPedalsEnable);
                }

                var gameOptions = specialOptions?.Element(ns + "GameOptions");

                if (gameOptions != null && (gameOptions.Attribute("Enable")?.Value).As <bool>())
                {
                    AllowGameSettings = (gameOptions.Attribute("AllowGameSettings")?.Value).As(AllowGameSettings);
                }
            }
示例#15
0
        public void ClearCache()
        {
            DisposeHelper.Dispose(ref _acDbStorage);
            DisposeHelper.Dispose(ref _acStorageNew);
            DisposeHelper.Dispose(ref _sidekickStorage);
            DisposeHelper.Dispose(ref _raceEssentialsStorage);

            foreach (var file in Directory.GetFiles(FilesStorage.Instance.GetDirectory("Progress"), "Lap Times (*).data"))
            {
                if (!FileUtils.ArePathsEqual(Path.GetFileName(file), _cmStorage.Filename))
                {
                    File.Delete(file);
                }
            }

            _lastUpdate = default(DateTime);
        }
示例#16
0
        protected override ICopyCallback GetCopyCallback(string destination)
        {
            var xaml = EntryPath;

            if (string.IsNullOrWhiteSpace(xaml))
            {
                return(new CopyCallback(null));
            }

            var resources = EntryPath.ApartFromLast(".xaml", StringComparison.OrdinalIgnoreCase);

            return(new CopyCallback(info => {
                var filename = info.Key;
                return FileUtils.ArePathsEqual(filename, xaml) ? Path.Combine(destination, Path.GetFileName(xaml))
                        : FileUtils.IsAffectedBy(filename, resources) ? Path.Combine(destination, FileUtils.GetRelativePath(filename, resources)) : null;
            }));
        }
示例#17
0
        protected override ICopyCallback GetCopyCallback(string destination)
        {
            var bitmapExtension = Path.GetExtension(EntryPath);
            var mainEntry       = EntryPath.ApartFromLast(bitmapExtension) + FontObject.FontExtension;

            return(new CopyCallback(info => {
                if (FileUtils.ArePathsEqual(info.Key, mainEntry))
                {
                    return destination;
                }

                if (FileUtils.ArePathsEqual(info.Key, EntryPath))
                {
                    return destination.ApartFromLast(FontObject.FontExtension) + bitmapExtension;
                }

                return null;
            }));
        }
示例#18
0
        private IEnumerable <string> GetPythonFilenames()
        {
            var main = Path.Combine(Location, Id + ".py");

            if (File.Exists(main))
            {
                yield return(main);
            }

            foreach (var file in Directory.GetFiles(Location, "*.py").Where(x => !FileUtils.ArePathsEqual(x, main)))
            {
                yield return(file);
            }

            foreach (var file in Directory.GetDirectories(Location).SelectMany(x => Directory.GetFiles(x, "*.py")))
            {
                yield return(file);
            }
        }
示例#19
0
文件: Document.cs 项目: MRoc/puremp3
        private void OnTreeNodeSelectionChanged(Object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == DocBase.PropertyName(FileTreeModel, m => m.SelectedTreeNode) &&
                !Object.ReferenceEquals(FileTreeModel.SelectedTreeNode, null))
            {
                string newPath = FileTreeModel.SelectedTreeNode.ItemPath;
                string oldPath = Editor.Path.Value;

                if (!FileUtils.ArePathsEqual(newPath, oldPath))
                {
                    History.Instance.ExecuteInTransaction(
                        delegate()
                    {
                        Editor.Path.Value = newPath;
                    },
                        Editor.Transaction.LazyId,
                        new Text("Change Folder to ") + newPath);
                }
            }
        }
示例#20
0
 public static byte[] TryReadBytes([NotNull] this ZipArchive archive, [NotNull] string entryName)
 {
     return(archive.Entries.FirstOrDefault(x => FileUtils.ArePathsEqual(x.FullName, entryName))?.Open().ReadAsBytesAndDispose());
 }
示例#21
0
 public static bool ZipContains([NotNull] this ZipArchive archive, [NotNull] string entryName)
 {
     return(archive.Entries.Any(x => FileUtils.ArePathsEqual(x.FullName, entryName)));
 }
示例#22
0
        public async Task <List <PackedEntry> > PackServerData(bool saveExecutable, ServerPresetPackMode mode, bool evbMode, CancellationToken cancellation)
        {
            var result = new List <PackedEntry>();

            // Wrapper
            if (ProvideDetails && DetailsMode == ServerPresetDetailsMode.ViaWrapper)
            {
                if (saveExecutable)
                {
                    string wrapper;
                    switch (mode)
                    {
                    case ServerPresetPackMode.Linux32:
                        wrapper = await LoadLinux32Wrapper(cancellation);

                        break;

                    case ServerPresetPackMode.Linux64:
                        wrapper = await LoadLinux64Wrapper(cancellation);

                        break;

                    case ServerPresetPackMode.Windows:
                        wrapper = await LoadWinWrapper(cancellation);

                        break;

                    default:
                        throw new ArgumentOutOfRangeException(nameof(mode), mode, null);
                    }

                    if (cancellation.IsCancellationRequested)
                    {
                        return(null);
                    }

                    if (wrapper == null)
                    {
                        throw new InformativeException("Can’t pack server", "Can’t load server wrapper.");
                    }

                    // Actual wrapper, compiled to a single exe-file
                    result.Add(PackedEntry.FromFile(
                                   mode == ServerPresetPackMode.Windows ? @"acServerWrapper.exe" : @"acServerWrapper",
                                   wrapper));

                    // For EVB
                    if (evbMode)
                    {
                        result.Add(PackedEntry.FromContent("arguments.json", new JArray {
                            @"--copy-executable-to=acServer_tmp.exe",
                        }.ToString(Formatting.Indented)));
                    }
                }

                // Params
                var wrapperParams = _wrapperParamsJson?.DeepClone() as JObject;
                SetWrapperParams(ref wrapperParams);
                result.Add(PackedEntry.FromContent(@"cfg/cm_wrapper_params.json", wrapperParams.ToString(Formatting.Indented)));

                // Content
                if (DetailsContentJObject != null)
                {
                    void ProcessPiece(JObject piece)
                    {
                        var file = (string)piece?[@"file"];

                        if (piece == null || file == null)
                        {
                            return;
                        }

                        var filename = Path.IsPathRooted(file) ? file : Path.Combine(WrapperContentDirectory, file);

                        if (!FileUtils.ArePathsEqual(WrapperContentDirectory, Path.GetDirectoryName(filename)))
                        {
                            piece[@"file"] = Path.GetFileName(filename);
                        }

                        result.Add(PackedEntry.FromFile($"cfg/cm_content/{Path.GetFileName(filename)}", filename));
                    }

                    void ProcessPieces(JToken token, string childrenKey = null)
                    {
                        if (!(token is JObject o))
                        {
                            return;
                        }
                        foreach (var t in o)
                        {
                            var b = (JObject)t.Value;
                            if (b == null)
                            {
                                continue;
                            }
                            ProcessPiece(b);
                            if (childrenKey != null)
                            {
                                ProcessPieces(b[childrenKey]);
                            }
                        }
                    }

                    var content = DetailsContentJObject.DeepClone();
                    ProcessPieces(content[@"cars"], @"skins");
                    ProcessPiece(content[@"track"] as JObject);
                    ProcessPieces(content[@"weather"]);
                    result.Add(PackedEntry.FromContent("cfg/cm_content/content.json", content.ToString(Formatting.Indented)));
                }
                else
                {
                    result.Add(PackedEntry.FromContent("cfg/cm_content/content.json", @"{}"));
                }
            }

            // Executable
            if (saveExecutable)
            {
                var serverDirectory = ServerPresetsManager.ServerDirectory;
                result.Add(PackedEntry.FromFile(
                               mode == ServerPresetPackMode.Windows ? @"acServer.exe" : @"acServer",
                               Path.Combine(serverDirectory, mode == ServerPresetPackMode.Windows ? @"acServer.exe" : @"acServer")));
            }

            // Main config file
            var serverCfg   = IniObject?.Clone() ?? new IniFile(IniFileMode.ValuesWithSemicolons);
            var dataSection = serverCfg["DATA"];

            SaveData(serverCfg);

            if (ProvideDetails)
            {
                if (DetailsMode == ServerPresetDetailsMode.ViaWrapper)
                {
                    serverCfg["SERVER"].Set("NAME", $"{Name} {ServerEntry.ExtendedSeparator}{WrapperPort}");
                }
                else
                {
                    await EnsureDetailsNameIsActualAsync(serverCfg);
                }
            }

            // Welcome message
            if (!string.IsNullOrEmpty(WelcomeMessage))
            {
                result.Add(PackedEntry.FromContent("cfg/welcome.txt", WelcomeMessage));
                serverCfg["SERVER"].Set("WELCOME_MESSAGE", "cfg/welcome.txt");
                dataSection.Set("WELCOME_PATH", "cfg/welcome.txt");
            }

            // Setups
            var setupIndex = 0;

            foreach (var key in dataSection.Keys.Where(x => x.StartsWith(@"FIXED_SETUP_")).ToList())
            {
                dataSection.Remove(key);
            }
            foreach (var item in SetupItems)
            {
                if (!File.Exists(item.Filename))
                {
                    continue;
                }
                var name = $@"cfg/setup_{setupIndex}_{item.CarId}.ini";
                result.Add(PackedEntry.FromFile(name, item.Filename));
                dataSection[@"FIXED_SETUP_" + setupIndex] = $@"{(item.IsDefault ? @"1" : @"0")}|{name}";
                setupIndex++;
            }

            result.Add(PackedEntry.FromContent("cfg/server_cfg.ini", serverCfg.Stringify()));

            // Entry list
            var entryList = EntryListIniObject?.Clone() ?? new IniFile();

            entryList.SetSections("CAR", DriverEntries, (entry, section) => entry.SaveTo(section));
            result.Add(PackedEntry.FromContent("cfg/entry_list.ini", entryList.Stringify()));

            // Cars
            var root = AcRootDirectory.Instance.RequireValue;

            for (var i = 0; i < CarIds.Length; i++)
            {
                var carId      = CarIds[i];
                var packedData = Path.Combine(AcPaths.GetCarDirectory(root, carId), "data.acd");
                if (File.Exists(packedData))
                {
                    result.Add(PackedEntry.FromFile(Path.Combine(@"content", @"cars", carId, @"data.acd"), packedData));
                }
            }

            // Track
            var localPath = TrackLayoutId != null?Path.Combine(TrackId, TrackLayoutId) : TrackId;

            foreach (var file in TrackDataToKeep)
            {
                var actualData = Path.Combine(AcPaths.GetTracksDirectory(root), localPath, @"data", file);
                if (File.Exists(actualData))
                {
                    result.Add(PackedEntry.FromFile(Path.Combine(@"content", @"tracks", localPath, @"data", file), actualData));
                }
            }

            // System
            var systemSurfaces = Path.Combine(ServerPresetsManager.ServerDirectory, "system", "data", "surfaces.ini");

            if (File.Exists(systemSurfaces))
            {
                result.Add(PackedEntry.FromFile("system/data/surfaces.ini", systemSurfaces));
            }

            return(result);
        }
示例#23
0
 public ISavedPresetEntry GetBuiltInPreset(PresetsCategory category, string filename)
 {
     return(_builtInPresets.GetValueOrDefault(category)?.FirstOrDefault(x => FileUtils.ArePathsEqual(x.VirtualFilename, filename)));
 }
示例#24
0
 public bool HasBuiltInPreset(PresetsCategory category, string filename)
 {
     return(_builtInPresets.GetValueOrDefault(category)?.Any(x => FileUtils.ArePathsEqual(x.VirtualFilename, filename)) == true);
 }
示例#25
0
 public string GetLocationByFilename(string filename, out bool inner)
 {
     inner = false;
     return(FileUtils.ArePathsEqual(Path.GetDirectoryName(Path.GetDirectoryName(filename)), _enabledDirectory) ? filename : null);
 }
示例#26
0
 public static byte[] ReadBytes([NotNull] this ZipArchive archive, [NotNull] string entryName)
 {
     return(archive.Entries.FirstOrDefault(x => FileUtils.ArePathsEqual(x.FullName, entryName))?.Open().ReadAsBytesAndDispose()
            ?? throw new InvalidOperationException("Entry not found: " + entryName));
 }
示例#27
0
        private void DrawMap(MapViewData map, MapViewData max, Matrix global)
        {
            // is the main map?
            var isMain = FileUtils.ArePathsEqual(map.Filename, CurrentMapFilename);

            // reset states
            DeviceContext.OutputMerger.BlendState = null;
            DeviceContext.Rasterizer.SetViewports(Viewport);

            // clear buffers just in case
            DeviceContext.ClearRenderTargetView(_f0Buffer.TargetView, new Color4(0f, 0f, 0f, 0f));
            DeviceContext.ClearRenderTargetView(_f1Buffer.TargetView, new Color4(0f, 0f, 0f, 0f));
            DeviceContext.ClearRenderTargetView(_a0Buffer.TargetView, new Color4(0f, 0f, 0f, 0f));
            DeviceContext.ClearRenderTargetView(_a1Buffer.TargetView, new Color4(0f, 0f, 0f, 0f));

            // set width to ai lanes
            if (UseAiLanes)
            {
                map.AiLaneWidth = 25f * ((isMain ? ExtraWidth : ExtraWidth * DimmedWidthMultipler) * 0.7f + 0.15f);
            }

            // draw map
            DeviceContext.OutputMerger.SetTargets(_f0Buffer.TargetView);
            map.Draw(DeviceContextHolder, _effect, global, max);

            // pp
            var current = _f0Buffer;

            // expand its width if needed
            if (!UseAiLanes)
            {
                var extraWidth = isMain ? ExtraWidth : ExtraWidth * DimmedWidthMultipler;
                for (var i = 0; i < extraWidth; i++)
                {
                    var next = current == _f0Buffer ? _f1Buffer : _f0Buffer;
                    DeviceContext.OutputMerger.SetTargets(next.TargetView);
                    _effect.FxInputMap.SetResource(current.View);

                    if (i < extraWidth - 1)
                    {
                        _effect.FxExtraWidth.Set(3f);
                    }
                    else
                    {
                        var last = extraWidth % 1f;
                        _effect.FxExtraWidth.Set(last < 0.0001f ? 3f : last * 3f);
                    }

                    _effect.TechExtraWidth.DrawAllPasses(DeviceContext, 6);
                    current = next;
                }
            }

            // fxaa if needed
            if (UseFxaa)
            {
                var next = current == _f0Buffer ? _f1Buffer : _f0Buffer;
                DeviceContextHolder.GetHelper <FxaaHelper>().Draw(DeviceContextHolder, current.View, next.TargetView);
                current = next;
            }

            // shadow if needed
            if (ShadowDistance > 0f && ShadowOpacity > 0f)
            {
                var next = current == _f0Buffer ? _f1Buffer : _f0Buffer;
                DeviceContext.OutputMerger.SetTargets(next.TargetView);
                _effect.FxInputMap.SetResource(current.View);
                _effect.TechShadow.DrawAllPasses(DeviceContext, 6);
                CustomBlending(_aSummBuffer, next, _a1Buffer, new Color4((isMain ? 1f : DimmedOpacity) * ShadowOpacity, 0f, 0f, 0f));
            }

            CustomBlending(_aSummBuffer, current, _a1Buffer, new Color4(isMain ? 1f : DimmedOpacity, 1f, 1f, 1f));
        }
示例#28
0
        private async Task <string> DownloadResumeSupportAsync([NotNull] CookieAwareWebClient client,
                                                               [NotNull] FlexibleLoaderGetPreferredDestinationCallback getPreferredDestination,
                                                               [CanBeNull] FlexibleLoaderReportDestinationCallback reportDestination, [CanBeNull] Func <bool> checkIfPaused,
                                                               IProgress <long> progress, CancellationToken cancellation)
        {
            // Common variables
            string filename = null, selectedDestination = null, actualFootprint = null;
            Stream remoteData = null;

            var resumeSupported = ResumeSupported;

            try {
                // Read resume-related data and remove it to avoid conflicts
                var resumeDestination             = CacheStorage.Get <string>(_keyDestination);
                var resumePartiallyLoadedFilename = CacheStorage.Get <string>(_keyPartiallyLoadedFilename);
                var resumeLastWriteDate           = CacheStorage.Get <DateTime?>(_keyLastWriteDate);
                var resumePreviousFootprint       = CacheStorage.Get <string>(_keyFootprint);
                ClearResumeData();

                // Collect known information for destination callback
                var information = FlexibleLoaderMetaInformation.FromLoader(this);

                // Opening stream to read…
                var headRequest = HeadRequestSupported && resumeDestination != null;
                using (headRequest ? client.SetMethod("HEAD") : null) {
                    Logging.Warning($"Initial request: {(headRequest ? "HEAD" : "GET")}");
                    remoteData = await client.OpenReadTaskAsync(Url);
                }

                cancellation.ThrowIfCancellationRequested();

                // Maybe we’ll be lucky enough to load the most accurate data
                if (client.ResponseHeaders != null)
                {
                    if (long.TryParse(client.ResponseHeaders[HttpResponseHeader.ContentLength] ?? "",
                                      NumberStyles.Any, CultureInfo.InvariantCulture, out var length))
                    {
                        TotalSize = information.TotalSize = length;
                    }

                    if (TryGetFileName(client.ResponseHeaders, out var fileName))
                    {
                        FileName = information.FileName = fileName;
                    }

                    // For example, Google Drive responds with “none” and yet allows to download file partially,
                    // so this header will only be checked if value is not defined.
                    if (resumeSupported == null)
                    {
                        var accept = client.ResponseHeaders[HttpResponseHeader.AcceptRanges] ?? "";
                        if (accept.Contains("bytes"))
                        {
                            resumeSupported = true;
                        }
                        else if (accept.Contains("none"))
                        {
                            resumeSupported = false;
                        }
                    }

                    client.LogResponseHeaders();
                }

                // Was the file partially loaded before?
                var partiallyLoaded = ResumeSupported != false && resumePartiallyLoadedFilename != null
                        ? new FileInfo(FileUtils.EnsureFilenameIsValid(resumePartiallyLoadedFilename)) : null;
                if (partiallyLoaded != null)
                {
                    Logging.Warning("Not finished: " + partiallyLoaded);
                }

                // Does it still exist
                if (partiallyLoaded?.Exists != true)
                {
                    Logging.Warning($"Partially downloaded file “{partiallyLoaded?.FullName}” does not exist");
                    partiallyLoaded = null;
                }

                // If so, wasn’t it changed since the last time?
                if (partiallyLoaded?.LastWriteTime > resumeLastWriteDate + TimeSpan.FromMinutes(5))
                {
                    Logging.Warning($"Partially downloaded file is newer that it should be: {partiallyLoaded.LastWriteTime}, expected: {resumeLastWriteDate}");
                    partiallyLoaded = null;
                }

                // Looks like file is partially downloaded, but let’s ensure link still leads to the same content
                actualFootprint = GetFootprint(information, client.ResponseHeaders);
                if (partiallyLoaded != null && resumePreviousFootprint != actualFootprint)
                {
                    Logging.Warning($"Footprints don’t match: {resumePreviousFootprint}≠{actualFootprint}");
                    partiallyLoaded = null;
                }

                // Let’s check where to load data, which is potentially the most actual data at this point
                var destination = getPreferredDestination(Url, information);
                selectedDestination = destination.Filename;
                if (partiallyLoaded != null && (!destination.CanResumeDownload || !FileUtils.ArePathsEqual(selectedDestination, resumeDestination)))
                {
                    Logging.Warning($"Different destination chosen: {selectedDestination} (before: {resumeDestination})");
                    partiallyLoaded = null;
                }

                // TODO: Check that header?

                // Where to write?
                // ReSharper disable once MergeConditionalExpression
                filename = partiallyLoaded != null ? partiallyLoaded.FullName : FileUtils.EnsureUnique(true, destination.Filename);
                reportDestination?.Invoke(filename);

                // Set cancellation token
                cancellation.Register(o => client.CancelAsync(), null);

                // Open write stream
                if (partiallyLoaded != null)
                {
                    var rangeFrom = partiallyLoaded.Length;
                    using (client.SetRange(new Tuple <long, long>(rangeFrom, -1))) {
                        Logging.Warning($"Trying to resume download from {rangeFrom} bytes…");

                        remoteData.Dispose();
                        remoteData = await client.OpenReadTaskAsync(Url);

                        cancellation.ThrowIfCancellationRequested();
                        client.LogResponseHeaders();

                        // It’s unknown if resume is supported or not at this point
                        if (resumeSupported == null)
                        {
                            var bytes      = new byte[16];
                            var firstBytes = await remoteData.ReadAsync(bytes, 0, bytes.Length);

                            cancellation.ThrowIfCancellationRequested();

                            if (CouldBeBeginningOfAFile(bytes))
                            {
                                using (var file = File.Create(filename)) {
                                    Logging.Warning("File beginning found, restart download");
                                    file.Write(bytes, 0, firstBytes);
                                    await CopyToAsync(remoteData, file, checkIfPaused, progress, cancellation);

                                    cancellation.ThrowIfCancellationRequested();
                                }

                                Logging.Write("Download finished");
                                return(filename);
                            }

                            rangeFrom += firstBytes;
                        }

                        using (var file = new FileStream(filename, FileMode.Append, FileAccess.Write)) {
                            await CopyToAsync(remoteData, file, checkIfPaused, new Progress <long>(v => {
                                progress?.Report(v + rangeFrom);
                            }), cancellation);

                            cancellation.ThrowIfCancellationRequested();
                        }
                    }
                }
                else
                {
                    if (headRequest)
                    {
                        Logging.Warning("Re-open request to be GET");
                        remoteData.Dispose();
                        remoteData = await client.OpenReadTaskAsync(Url);
                    }

                    using (var file = File.Create(filename)) {
                        Logging.Debug("Downloading the whole file…");
                        await CopyToAsync(remoteData, file, checkIfPaused, progress, cancellation);

                        cancellation.ThrowIfCancellationRequested();
                    }
                }

                Logging.Write("Download finished");
                return(filename);
            } catch (Exception e) when(e is WebException || e.IsCancelled())
            {
                Logging.Write("Download is interrupted! Saving details to resume later…");
                var download = filename == null ? null : new FileInfo(filename);

                if (download?.Exists == true && filename.Length > 0)
                {
                    CacheStorage.Set(_keyDestination, selectedDestination);
                    CacheStorage.Set(_keyPartiallyLoadedFilename, filename);
                    CacheStorage.Set(_keyFootprint, actualFootprint);
                    CacheStorage.Set(_keyLastWriteDate, download.LastWriteTime);
                }
                else
                {
                    ClearResumeData();
                }

                throw;
            } finally {
                remoteData?.Dispose();
            }
        }
示例#29
0
        protected override void DrawOverride()
        {
            // prepare states, clear buffers
            DeviceContext.OutputMerger.DepthStencilState = null;
            DeviceContext.Rasterizer.State = DeviceContextHolder.States.DoubleSidedState;
            DeviceContext.ClearRenderTargetView(_fSummBuffer.TargetView, new Color4(0f, 0f, 0f, 0f));
            DeviceContext.ClearRenderTargetView(_aSummBuffer.TargetView, new Color4(0f, 0f, 0f, 0f));
            DeviceContext.ClearRenderTargetView(RenderTargetView, new Color4(0f, 0f, 0f, 0f));

            // quad
            DeviceContextHolder.PrepareQuad(_effect.LayoutPT);

            // fixed values
            _effect.FxScreenSize.Set(new Vector4(Width, Height, 1f / Width, 1f / Height));
            _effect.FxDropShadowRadius.Set((float)(ShadowDistance * ResolutionMultiplier));
            // _effect.FxDropShadowOpacity.Set(ShadowOpacity);

            // find the biggest map provided
            MapViewData max;
            float       maxSize;
            {
                var maxMapSize = _maps.Select(x => new {
                    MaxSize = Math.Max(x.MapSize.X, x.MapSize.Y),
                    Entry   = x
                }).MaxEntryOrDefault(x => x.MaxSize);
                if (maxMapSize == null)
                {
                    return;
                }

                max     = maxMapSize.Entry;
                maxSize = maxMapSize.MaxSize;
            }

            // calculate basic UV transformation matrix which will be applied to all maps
            Matrix global;

            {
                // first of all fix aspect to match map.png and scale
                var mapScale = UseAiLanes ?
                               Matrix.Transformation2D(new Vector2(0.5f), 0f,
                                                       new Vector2(max.MapSize.X, max.MapSize.Y) / maxSize * Scale,
                                                       Vector2.Zero, 0f, Vector2.Zero) :
                               Matrix.Transformation2D(new Vector2(0.5f), 0f,
                                                       new Vector2(1f / max.MapSize.X, 1f / max.MapSize.Y) * maxSize / Scale,
                                                       Vector2.Zero, 0f, Vector2.Zero);

                // fix aspect (without it, maps will be stretched to Renderer dimensions)
                var minSide = (float)Math.Min(Width, Height);
                var scale   = UseAiLanes ?
                              Matrix.Transformation2D(new Vector2(0.5f), 0f, new Vector2(minSide / Width, minSide / Height), Vector2.Zero, 0f, Vector2.Zero) :
                              Matrix.Transformation2D(new Vector2(0.5f), 0f, new Vector2(Width, Height) / minSide, Vector2.Zero, 0f, Vector2.Zero);

                // rotate if needed
                var rotation = Matrix.Transformation2D(Vector2.Zero, 0f, new Vector2(1f), new Vector2(0.5f), -Rotation, Vector2.Zero);

                // optional offset
                var offset = UseAiLanes ?
                             Matrix.AffineTransformation2D(1f, Vector2.Zero, 0f, new Vector2(-OffsetX / Width, OffsetY / Height)) :
                             Matrix.AffineTransformation2D(1f, Vector2.Zero, 0f, new Vector2(OffsetX / Width, OffsetY / Height));

                global = UseAiLanes ? mapScale * rotation * scale * offset : offset * scale * rotation * mapScale;
            }

            foreach (var map in _maps.Where(x => !FileUtils.ArePathsEqual(x.Filename, CurrentMapFilename) && (_activeMaps == null ||
                                                                                                              _activeMaps.Any(y => FileUtils.ArePathsEqual(x.Filename, y)))))
            {
                DrawMap(map, max, global);
            }

            foreach (var map in _maps.Where(x => FileUtils.ArePathsEqual(x.Filename, CurrentMapFilename)))
            {
                DrawMap(map, max, global);
            }

            // output state
            DeviceContext.Rasterizer.SetViewports(OutputViewport);

            // draw result (on preview image if exists)
            DeviceContext.OutputMerger.SetTargets(RenderTargetView);
            _effect.FxInputMap.SetResource(_aSummBuffer.View);

            if (_shotMode)
            {
                _effect.TechFinal.DrawAllPasses(DeviceContext, 6);
            }
            else if (_previewView != null)
            {
                _effect.FxBgMap.SetResource(_previewView);

                var bgScale = new Vector2(ActualWidth / _previewSize.X, ActualHeight / _previewSize.Y);
                if (bgScale.X > 1f)
                {
                    bgScale /= bgScale.X;
                }
                if (bgScale.Y > 1f)
                {
                    bgScale /= bgScale.Y;
                }

                _effect.FxMatrix.SetMatrix(Matrix.Transformation2D(new Vector2(0.5f), 0f, bgScale, Vector2.Zero, 0f, Vector2.Zero));
                _effect.TechFinalBg.DrawAllPasses(DeviceContext, 6);
            }
            else
            {
                _effect.TechFinalCheckers.DrawAllPasses(DeviceContext, 6);
            }
        }
示例#30
0
        public static int Main(string[] args)
        {
            try {
                Trace.Listeners.Add(new ConsoleTraceListener());
                FileUtils.TryToDelete(Path.Combine(MainExecutingFile.Directory, "Log.txt"));
                Trace.Listeners.Add(new DefaultTraceListener {
                    LogFileName = Path.Combine(MainExecutingFile.Directory, "Log.txt")
                });

                var argsLoaded = false;
                if (args.Length > 0)
                {
                    try {
                        if (File.Exists(args[0]))
                        {
                            var extraFileArgs = Path.Combine(Path.GetDirectoryName(args[0]) ?? ".", "Baked Shadows Params.txt");
                            if (File.Exists(extraFileArgs))
                            {
                                args = File.ReadAllLines(extraFileArgs).Where(x => !string.IsNullOrWhiteSpace(x) && !x.TrimStart().StartsWith("#"))
                                       .Union(args).ToArray();
                                argsLoaded = true;
                            }
                            else
                            {
                                extraFileArgs = Path.Combine(Path.GetDirectoryName(args[0]) ?? ".", "Baked_Shadows_Params.txt");
                                if (File.Exists(extraFileArgs))
                                {
                                    args = File.ReadAllLines(extraFileArgs).Where(x => !string.IsNullOrWhiteSpace(x) && !x.TrimStart().StartsWith("#"))
                                           .Union(args).ToArray();
                                    argsLoaded = true;
                                }
                            }
                        }
                    } catch {
                        // ignored
                    }
                }

                if (!argsLoaded)
                {
                    var extraArgs = Path.Combine(MainExecutingFile.Directory, "Arguments.txt");
                    if (File.Exists(extraArgs))
                    {
                        args = File.ReadAllLines(extraArgs).Where(x => !string.IsNullOrWhiteSpace(x) && !x.TrimStart().StartsWith("#"))
                               .Union(args).ToArray();
                    }
                }

                var options = new Options();
                if (!Parser.Default.ParseArguments(args, options) || options.Items.Count == 0 || options.Help)
                {
                    Trace.WriteLine(options.GetUsage());
                    return(options.Help ? 0 : 1);
                }

                string mainKn5 = null;
                string destination;
                var    includeKn5   = new List <string>();
                var    occludersKn5 = new List <string>();

                if (options.Items[0].EndsWith(".ini"))
                {
                    var ini            = new IniFile(options.Items[0]);
                    var trackDirectory = Path.GetDirectoryName(ini.Filename) ?? ".";
                    var first          = true;
                    includeKn5.Clear();
                    occludersKn5.Clear();
                    foreach (var model in ini.GetSections("MODEL").Select(x => x.GetNonEmpty("FILE")).NonNull()
                             .Select(x => Path.Combine(trackDirectory, x)).Where(File.Exists))
                    {
                        if (first)
                        {
                            first   = false;
                            mainKn5 = model;
                        }
                        else
                        {
                            includeKn5.Add(model);
                        }
                    }

                    destination = Path.Combine(trackDirectory, Path.GetFileNameWithoutExtension(ini.Filename) + ".vao-patch");
                }
                else
                {
                    mainKn5     = options.Items[0];
                    destination = options.Destination ?? options.Items[0];
                    var trackDirectory = Path.GetDirectoryName(mainKn5) ?? ".";

                    if (!options.ModifyKn5Directly)
                    {
                        if (!string.IsNullOrWhiteSpace(options.IncludeKn5Filter))
                        {
                            var includeFilter = Filter.Create(StringTester.Instance, options.IncludeKn5Filter,
                                                              new FilterParams {
                                StringMatchMode = StringMatchMode.CompleteMatch
                            });
                            foreach (var file in Directory.GetFiles(trackDirectory, "*.kn5").Where(x =>
                                                                                                   includeFilter.Test(Path.GetFileName(x)) && !FileUtils.ArePathsEqual(x, mainKn5)))
                            {
                                includeKn5.Add(file);

                                destination = Path.Combine(trackDirectory, Path.GetFileName(trackDirectory)) + ".kn5";
                            }
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(options.OccludersKn5Filter ?? options.CommonKn5Filter))
                    {
                        var occludersFilter = Filter.Create(StringTester.Instance, options.OccludersKn5Filter ?? options.CommonKn5Filter,
                                                            new FilterParams {
                            StringMatchMode = StringMatchMode.CompleteMatch
                        });
                        foreach (var file in Directory.GetFiles(trackDirectory, "*.kn5").Where(x =>
                                                                                               occludersFilter.Test(Path.GetFileName(x)) && !FileUtils.ArePathsEqual(x, mainKn5)))
                        {
                            occludersKn5.Add(file);
                        }
                    }
                }

                if (mainKn5 == null)
                {
                    throw new Exception("Main KN5 not found");
                }

                using (var bakery = new MainBakery(mainKn5, options.Filter, options.IgnoreFilter, !options.ModifyKn5Directly)
                {
                    AoOpacity = options.AoOpacity,
                    AoMultiplier = options.AoMultiplier,
                    SaturationGain = options.SaturationGain,
                    SaturationInputMultiplier = options.SaturationInputMultiplier,
                    CameraFov = options.CameraFov,
                    CameraNear = options.CameraNear,
                    CameraFar = options.CameraFar,
                    CameraNormalOffsetUp = options.CameraNormalOffsetUp,
                    CameraOffsetAway = options.CameraOffsetAway,
                    CameraOffsetUp = options.CameraOffsetUp,
                    OccludersDistanceThreshold = options.OccludersDistanceThreshold,
                    MergeVertices = options.MergeVertices,
                    MergeThreshold = options.MergeThreshold,
                    OccludersSplitThreshold = options.OccludersSplitThreshold,
                    QueueSize = options.QueueSize,
                    SampleResolution = options.SampleResolution,
                    ExtraPassBrightnessGain = options.ExtraPassBrightnessGain,
                    HdrSamples = options.HdrSamples,
                    Ground = !options.NoGround,
                    SyncNormalsFilter = options.SyncNormals,
                    SyncNormalsPartiallyFilter = options.SyncNormalsPartially,
                    SyncNormalsPartiallyValue = options.SyncNormalsPartiallyValue,
                    ExtraPass = options.ExtraPass,
                    TreeFilter = options.TreeFilter,
                    GrassFilter = options.GrassFilter,
                    RegularObjectsFilter = options.RegularObjectsFilter,
                    SkipOccludersFilter = options.SkipOccludersFilter,
                    SpecialGrassAmbient = !options.NoSpecialGrassAmbient,
                    SurfacesFilter = options.Surfaces,
                    SurfacesAoOpacity = options.SurfacesAoOpacity,
                    SetMiltiplierForSkipped = options.SetMiltiplierForSkipped,
                }) {
                    if (!string.IsNullOrWhiteSpace(options.DebugPos))
                    {
                        bakery.DebugMode  = true;
                        bakery.DebugPoint = options.DebugPos.Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries)
                                            .Select(x => (float)FlexibleParser.ParseDouble(x))
                                            .ToArray().ToVector3();
                        bakery.DebugRadius = options.DebugRange;
                        Console.WriteLine("Debug mode: " + bakery.DebugPoint);
                    }

                    bakery.LoadExtraKn5(includeKn5, occludersKn5).Work(destination);
                }

                Trace.Listeners.Clear();
                return(0);
            } catch (Exception e) {
                Trace.WriteLine(e.ToString());
                return(2);
            } finally {
                if (ParentProcessUtilities.GetParentProcess().ProcessName == "explorer")
                {
                    Console.ReadLine();
                }
            }
        }