Exemplo n.º 1
0
        public static void Import([NotNull] string carId)
        {
            if (carId == null)
            {
                throw new ArgumentNullException(nameof(carId));
            }

            var cmDistance = PlayerStatsManager.Instance.GetDistanceDrivenByCar(carId);

            if (cmDistance <= 0d)
            {
                return;
            }

            var filename = Path.Combine(AcPaths.GetPythonAppsDirectory(AcRootDirectory.Instance.RequireValue), OdometerAppId, DataFileName);

            if (!File.Exists(filename))
            {
                return;
            }

            var ini = new IniFile(filename);

            ImportIfNeeded(carId, ini["Cars"].GetDouble(carId, 0d) * ini["Adjustments"].GetDouble(carId, 1d));
        }
Exemplo n.º 2
0
        public void Wrapper()
        {
            var rulesSet = Path.Combine(TestDir, "analyzer", "rules.txt");
            var storage  = Path.Combine(TestDir, "analyzer", "storage.data");
            var ids      = AcKunosContent.GetKunosCarIds(AcRoot).ToArray();

            var wrapper = RulesWrapper.FromFile(AcRoot, rulesSet, storage, ids);

            wrapper.EnsureActual();

            var d = ids.Where(x => Directory.Exists(AcPaths.GetCarDirectory(AcRoot, x)))
                    .Select(x => new { Id = x, Data = DataWrapper.FromCarDirectory(AcRoot, x) })
                    .ToList();

            var w = Stopwatch.StartNew();
            var j = 0;

            foreach (var car in d)
            {
                foreach (var s in wrapper.FindSimular(car.Data, "aero", false, 0.85))
                {
                    AcToolsLogging.Write($"{car.Id} is similar to {s.CarId} by {s.Value * 100:F1}%");
                    j++;
                }
            }

            AcToolsLogging.Write($"Check time: {w.Elapsed.TotalMilliseconds / j:F2} ms");
        }
Exemplo n.º 3
0
            protected override IEnumerable PackOverride(CarObject t)
            {
                yield return(Add("data/ambient_shadows.ini", "data/cameras.ini", "data/dash_cam.ini", "data/driver3d.ini",
                                 "data/extra_animations.ini", "data/lights.ini", "data/mirrors.ini"));

                yield return(Add("animations/*.ksanim"));

                yield return(Add("body_shadow.png", "tyre_*_shadow.png"));

                var mainModel = AcPaths.GetMainCarFilename(t.Location, false);

                if (mainModel == null)
                {
                    throw new Exception("Failed to find main car model");
                }
                yield return(AddFile("model.kn5", mainModel));

                var textureNames = Kn5.FromFile(AcPaths.GetMainCarFilename(t.Location, t.AcdData, false) ?? throw new Exception(),
                                                SkippingTextureLoader.Instance, SkippingMaterialLoader.Instance, SkippingNodeLoader.Instance).TexturesData.Keys.ToList();

                foreach (var skin in _skins)
                {
                    foreach (var name in textureNames)
                    {
                        yield return(Add($"skins/{skin.Id}/{name}"));
                    }
                }
            }
Exemplo n.º 4
0
        public void Run()
        {
            SteamRunningHelper.EnsureSteamIsRunning(RunSteamIfNeeded, false);

            _acLauncher       = AcPaths.GetAcLauncherFilename(AcRoot);
            _acLauncherBackup = _acLauncher.ApartFromLast(".exe", StringComparison.OrdinalIgnoreCase) + "_backup_ts.exe";

            if (File.Exists(_acLauncherBackup) && new FileInfo(_acLauncher).Length > ApproximateAcstarterSize)
            {
                File.Move(_acLauncherBackup, _acLauncherBackup.ApartFromLast(".exe", StringComparison.OrdinalIgnoreCase) + "_" + DateTime.Now.Ticks + ".exe");
            }

            if (!File.Exists(_acLauncherBackup))
            {
                File.Move(_acLauncher, _acLauncherBackup);
            }

            if (!File.Exists(_acLauncher))
            {
                File.WriteAllBytes(_acLauncher, Resources.AcStarter);
            }

            PreviewRun?.Invoke(this, new AcsRunEventArgs(Path.Combine(AcRoot, AcsName), Use32BitVersion));
            _launcherProcess = Process.Start(new ProcessStartInfo {
                WorkingDirectory = AcRoot,
                FileName         = Path.GetFileName(_acLauncher),
                Arguments        = $"--first-stage {AcsName}"
            });
        }
Exemplo n.º 5
0
        private static void LaunchReport(string filename)
        {
            try {
                using (var stream = File.OpenRead(Path.Combine(Path.GetDirectoryName(filename) ?? "", Path.GetFileNameWithoutExtension(filename) + ".zip")))
                    using (var archive = new ZipArchive(stream)) {
                        // Apply video config
                        var currentVideo  = new IniFile(AcPaths.GetCfgVideoFilename());
                        var currentWidth  = currentVideo["VIDEO"].GetInt("WIDTH", 1920);
                        var currentHeight = currentVideo["VIDEO"].GetInt("HEIGHT", 1080);
                        var newVideo      =
                            IniFile.Parse((archive.GetEntry("video.ini") ?? throw new Exception("Video config is missing")).Open().ReadAsStringAndDispose());
                        newVideo["VIDEO"].Set("WIDTH", Math.Min(currentWidth, newVideo["VIDEO"].GetInt("WIDTH", 1920)));
                        newVideo["VIDEO"].Set("HEIGHT", Math.Min(currentHeight, newVideo["VIDEO"].GetInt("HEIGHT", 1080)));
                        File.WriteAllText(AcPaths.GetCfgVideoFilename(), newVideo.ToString());

                        // Apply CSP config
                        PatchSettingsModel.Create().ImportFromPresetData(archive.GetEntry("csp.ini")?.Open().ReadAsStringAndDispose() ?? string.Empty);

                        // Apply race config
                        File.WriteAllText(AcPaths.GetRaceIniFilename(),
                                          (archive.GetEntry("race.ini") ?? throw new Exception("Race config is missing")).Open().ReadAsStringAndDispose());

                        Process.Start(new ProcessStartInfo {
                            FileName         = Path.Combine(AcRootDirectory.Instance.Value ?? "", "acs.exe"),
                            WorkingDirectory = AcRootDirectory.Instance.Value ?? ""
                        });
                    }
            } catch (Exception e) {
                NonfatalError.Notify("Failed to launch report race", e);
            }
        }
Exemplo n.º 6
0
        public static void Start(ShowroomProperties properties)
        {
            if (_busy)
            {
                return;
            }
            _busy = true;

            try {
                var filename             = AcPaths.GetCfgShowroomFilename();
                var originalShowroomFile = File.ReadAllText(filename);

                var iniFile = IniFile.Parse(originalShowroomFile);
                iniFile["SHOWROOM"].Set("CAR", (properties.CarId ?? "").ToLowerInvariant());
                iniFile["SHOWROOM"].Set("SKIN", (properties.CarSkinId ?? "").ToLowerInvariant());
                iniFile["SHOWROOM"].Set("TRACK", (properties.ShowroomId ?? "").ToLowerInvariant());
                iniFile["SETTINGS"].Set("CAMERA_FOV", properties.CameraFov);
                iniFile.Save(filename);

                using (properties.UseBmp ? new ScreenshotFormatChange(properties.AcRoot, "BMP") : null)
                    using (properties.DisableWatermark ? new DisableShowroomWatermarkChange(properties.AcRoot) : null)
                        using (properties.DisableSweetFx ? new DisableSweetFxChange(properties.AcRoot) : null)
                            using (properties.Filter != null ? new VideoIniChange(properties.VideoPresetFilename, properties.Filter) : null) {
                                var process = Process.Start(new ProcessStartInfo {
                                    WorkingDirectory = properties.AcRoot,
                                    FileName         = "acShowroom.exe"
                                });

                                process?.WaitForExit();
                            }
            } finally {
                _busy = false;
            }
        }
Exemplo n.º 7
0
        private void UpdateDirectories() {
            CarsDirectories?.Obsolete();
            TracksDirectories?.Obsolete();
            ShowroomsDirectories?.Obsolete();
            WeatherDirectories?.Obsolete();
            PpFiltersDirectories?.Obsolete();
            DriverModelsDirectories?.Obsolete();
            PythonAppsDirectories?.Obsolete();

            CarsDirectories = Value == null ? null : new AcDirectories(AcPaths.GetCarsDirectory(Value));
            TracksDirectories = Value == null ? null : new AcDirectories(AcPaths.GetTracksDirectory(Value));
            ShowroomsDirectories = Value == null ? null : new AcDirectories(AcPaths.GetShowroomsDirectory(Value));
            WeatherDirectories = Value == null ? null : new AcDirectories(AcPaths.GetWeatherDirectory(Value));
            PpFiltersDirectories = Value == null ? null : new AcDirectories(AcPaths.GetPpFiltersDirectory(Value));
            DriverModelsDirectories = Value == null ? null : new AcDirectories(AcPaths.GetDriverModelsDirectory(Value));
            PythonAppsDirectories = Value == null ? null : new AcDirectories(AcPaths.GetPythonAppsDirectory(Value));
            FontsDirectories = Value == null ? null : new AcDirectories(AcPaths.GetFontsDirectory(Value));
            KunosCareerDirectories = Value == null ? null : new AcDirectories(AcPaths.GetKunosCareerDirectory(Value));

            FileUtils.EnsureDirectoryExists(AcPaths.GetReplaysDirectory());
            ReplaysDirectories = ReplaysDirectories ?? new MultiDirectories(AcPaths.GetReplaysDirectory(), null);
            UserChampionshipsDirectories = UserChampionshipsDirectories ?? new AcDirectories(Path.Combine(AcPaths.GetDocumentsDirectory(), "champs"));

            CarsDirectories?.CreateIfMissing();
            TracksDirectories?.CreateIfMissing();
            ShowroomsDirectories?.CreateIfMissing();
            WeatherDirectories?.CreateIfMissing();
            PpFiltersDirectories?.CreateIfMissing();
            DriverModelsDirectories?.CreateIfMissing();
            PythonAppsDirectories?.CreateIfMissing();
            UserChampionshipsDirectories?.CreateIfMissing();
        }
Exemplo n.º 8
0
        public bool Test(string carId, string key, ITestEntry value)
        {
            switch (key)
            {
            case null:
                return(value.Test(carId));

            case "l":
            case "len":
            case "length":
                return(value.Test(carId.Length));

            case "k":
            case "kunos": {
                return(value.Test(TestIfKunosUsingGuids(carId)));
            }

            case "a":
            case "age": {
                var directory = AcPaths.GetCarDirectory(_acRoot, carId);
                var age       = File.GetCreationTime(directory);
                return(value.Test(DateTime.Now - age));
            }

            case "n":
            case "new": {
                var directory = AcPaths.GetCarDirectory(_acRoot, carId);
                var age       = File.GetCreationTime(directory);
                return(value.Test((DateTime.Now - age).TotalDays < 7d));
            }

            default:
                return(false);
            }
        }
            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);
                }
            }
            private void ImportCsv(string filename)
            {
                try {
                    if (_wrapper == null)
                    {
                        throw new InformativeException("Can’t import CSV-file",
                                                       "LUTLibrary.dll missing or can’t be loaded.");
                    }

                    var 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";
                    }

                    var lutData = new LutDataFile();
                    var lut     = _wrapper.ToLut(filename);
                    if (lut == null)
                    {
                        throw new Exception(@"Expected field or method is missing");
                    }

                    lutData.Values.AddRange(lut);
                    lutData.Save(Path.Combine(AcPaths.GetDocumentsCfgDirectory(), name));
                    SwitchFfPostProcessLutName(name);
                } catch (Exception e) {
                    NonfatalError.Notify("Can’t import CSV-file", e);
                }
            }
Exemplo n.º 11
0
        private CarDescription GetCarDescription([NotNull] string carId, [CanBeNull] DataWrapper carData)
        {
            var carDirectory = AcPaths.GetCarDirectory(_acRoot, carId);
            var carKn5       = carData == null?AcPaths.GetMainCarFilename(carDirectory) : AcPaths.GetMainCarFilename(carDirectory, carData);

            return(new CarDescription(carKn5, carDirectory));
        }
Exemplo n.º 12
0
        private static async Task <ArgumentHandleResult> ProcessInputFile(string filename)
        {
            bool isDirectory;

            try {
                if (!FileUtils.Exists(filename))
                {
                    return(ArgumentHandleResult.Failed);
                }
                isDirectory = FileUtils.IsDirectory(filename);
            } catch (Exception) {
                return(ArgumentHandleResult.Failed);
            }

            if (!isDirectory && filename.EndsWith(@".acreplay", StringComparison.OrdinalIgnoreCase) ||
                Path.GetDirectoryName(filename)?.Equals(AcPaths.GetReplaysDirectory(), StringComparison.OrdinalIgnoreCase) == true)
            {
                await GameWrapper.StartReplayAsync(new Game.StartProperties(new Game.ReplayProperties {
                    Filename = filename
                }));

                return(ArgumentHandleResult.Successful);
            }

            if (!isDirectory && filename.EndsWith(@".kn5", StringComparison.OrdinalIgnoreCase))
            {
                await CustomShowroomWrapper.StartAsync(filename);

                return(ArgumentHandleResult.Successful);
            }

            return(ArgumentHandleResult.FailedShow);
        }
Exemplo n.º 13
0
        public static void UpdateSidekickDatabase([NotNull] CarObject car, bool?separateFiles = null)
        {
            try {
                var directory = Path.Combine(AcPaths.GetPythonAppsDirectory(AcRootDirectory.Instance.RequireValue), SidekickAppId);
                if (!Directory.Exists(directory))
                {
                    return;
                }

                if (!AcSettingsHolder.Python.IsActivated(SidekickAppId))
                {
                    Logging.Write("App is not active");
                    return;
                }

                if (car.AcdData?.IsEmpty != false)
                {
                    Logging.Write("Data is damaged");
                    return;
                }

                var kunosCar            = car.Author == AcCommonObject.AuthorKunos;
                var separateFilesActual = separateFiles ?? !kunosCar;
                var updateIfChanged     = kunosCar ? SettingsHolder.Drive.SidekickUpdateExistingKunos :
                                          SettingsHolder.Drive.SidekickUpdateExistingMods;

                UpdateSidekickCompounds(directory, car.AcdData, car.Id, separateFilesActual, updateIfChanged);
                UpdateSidekickBrakes(directory, car.AcdData, car.Id, separateFilesActual, updateIfChanged);
            } catch (Exception e) {
                Logging.Error(e);
            }
        }
Exemplo n.º 14
0
        private static async Task PrepareReplay(Game.StartProperties properties, IGameUi ui, CancellationToken cancellation)
        {
            var replayProperties = properties.ReplayProperties;

            if (replayProperties != null)
            {
                var replayFilename = replayProperties.Filename ?? Path.Combine(AcPaths.GetReplaysDirectory(), replayProperties.Name);
                ui.OnProgress("Checking replay for fake cars…");

                var fakes = await FakeCarsHelper.GetFakeCarsIds(replayFilename);

                if (fakes.Count > 0)
                {
                    Logging.Debug("Fakes found: " + fakes.Select(x => $"{x.FakeId} ({x.SourceId})").JoinToString(", "));
                    foreach (var fake in fakes)
                    {
                        var car = CarsManager.Instance.GetById(fake.SourceId);
                        if (car != null)
                        {
                            FakeCarsHelper.CreateFakeCar(car, fake.FakeId, null);
                        }
                        else
                        {
                            Logging.Warning("Original not found: " + fake.SourceId);
                        }
                    }
                }
            }
        }
Exemplo n.º 15
0
        private static bool InstallModule()
        {
            try {
                var ini       = new IniFile(Path.Combine(AcPaths.GetDocumentsCfgDirectory(), "launcher.ini"));
                var theme     = ini["WINDOW"].GetNonEmpty("theme");
                var directory = Path.Combine(AcRootDirectory.Instance.RequireValue, @"launcher", @"themes", theme ?? @"default", @"modules", ModuleId);

                var installed = false;
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);

                    using (var stream = new MemoryStream(BinaryResources.ModuleCmHelper))
                        using (var archive = new ZipArchive(stream)) {
                            archive.ExtractToDirectory(directory);
                        }

                    installed = true;
                }

                var active = ini["MODULES"].GetStrings("ACTIVE");
                if (!active.ArrayContains(ModuleId))
                {
                    ini["MODULES"].Set("ACTIVE", active.Append(@"CmHelper").Distinct());
                    ini.Save();
                    installed = true;
                }

                return(installed);
            } catch (Exception e) {
                throw new InformativeException("Can’t install UI module", e);
            }
        }
Exemplo n.º 16
0
        private void ShotInner([NotNull] string carId, [NotNull] string skinId, [CanBeNull] string destination,
                               [CanBeNull] ImageUtils.ImageInformation information, [CanBeNull] Action callback)
        {
            if (destination == null)
            {
                destination = Path.Combine(AcPaths.GetCarSkinDirectory(_acRoot, carId, skinId), _options.PreviewName);
            }

            var shotStream = new MemoryStream(_approximateSize ?? 100000);

            _renderer.Shot(_renderer.Width, _renderer.Height, _options.SoftwareDownsize ? 1d : 1d / _options.SsaaMultiplier, 1d, shotStream,
                           RendererShotFormat.Png);
            if (!_approximateSize.HasValue || _approximateSize < shotStream.Position)
            {
                _approximateSize = (int)(shotStream.Position * 1.2);
            }

            shotStream.Position = 0;
            ProcessConvertation(() => {
                using (var stream = File.Open(destination, FileMode.Create, FileAccess.ReadWrite)) {
                    ImageUtils.Convert(shotStream, stream,
                                       _options.SoftwareDownsize ? new Size(_options.PreviewWidth, _options.PreviewHeight) : (Size?)null, exif: information,
                                       format: destination.EndsWith(".png") ? ImageFormat.Png : ImageFormat.Jpeg);
                    callback?.Invoke();
                }
            }, DisposeCallback(shotStream));
        }
Exemplo n.º 17
0
        private static ArgumentHandleResult ProcessSharedCarSetup(SharedEntry shared, byte[] data)
        {
            var content  = data.ToUtf8String();
            var metadata = SharingHelper.GetMetadata(SharedEntryType.CarSetup, content, out content);

            var carId   = metadata.GetValueOrDefault("car");
            var trackId = metadata.GetValueOrDefault("track") ?? CarSetupObject.GenericDirectory;

            if (carId == null)
            {
                throw new InformativeException(AppStrings.Arguments_CannotInstallCarSetup, AppStrings.Arguments_MetadataIsMissing);
            }

            var result = ShowDialog(shared, applyable: false,
                                    additionalButton: trackId == CarSetupObject.GenericDirectory ? null : AppStrings.Arguments_SaveAsGeneric);

            switch (result)
            {
            case Choise.Save:
            case Choise.Extra:
                var filename = FileUtils.EnsureUnique(Path.Combine(AcPaths.GetCarSetupsDirectory(carId),
                                                                   result == Choise.Save ? trackId : CarSetupObject.GenericDirectory, shared.GetFileName()));
                Directory.CreateDirectory(Path.GetDirectoryName(filename) ?? "");
                File.WriteAllText(filename, content);
                return(ArgumentHandleResult.SuccessfulShow);

            default:
                return(ArgumentHandleResult.Failed);
            }
        }
Exemplo n.º 18
0
        public static bool IsSupposedToWork()
        {
            // Loading value directly in case custom preset were applied, but VideoSettings aren’t updated yet
            var video = new IniFile(AcPaths.GetCfgVideoFilename())["VIDEO"];

            return((video.GetIntNullable("__CM_ORIGINAL_SHADOW_MAP_SIZE") ?? video.GetInt("SHADOW_MAP_SIZE", 2048)) < 1);
        }
Exemplo n.º 19
0
        public static void Revert()
        {
            foreach (var key in PatchedStorage.Keys.ToList())
            {
                var data = PatchedStorage.GetObject <CommandToPatch>(key);
                if (data.Offset > 0)
                {
                    ObjectExtension.Swap(ref data.OriginalOpCode, ref data.PatchedOpCode);
                    try {
                        PatchFile(key, data, false);
                        PatchedStorage.Remove(key);
                    } catch (PatchException e) {
                        NonfatalError.NotifyBackground("Can’t revert AC to its original state", e.Message.ToSentence());
                    } catch (Exception e) {
                        NonfatalError.NotifyBackground("Can’t revert AC to its original state", e);
                    }
                }
            }

            var ini   = new IniFile(AcPaths.GetCfgVideoFilename());
            var video = ini["VIDEO"];

            if (video.ContainsKey(@"__CM_ORIGINAL_SHADOW_MAP_SIZE"))
            {
                video.Set("SHADOW_MAP_SIZE", video.GetInt("__CM_ORIGINAL_SHADOW_MAP_SIZE", 2048));
                video.Remove(@"__CM_ORIGINAL_SHADOW_MAP_SIZE");
                ini.Save();
            }
        }
Exemplo n.º 20
0
        public static void ReplaceSound(CarObject donor, [NotNull] string target)
        {
            var guids     = donor.GuidsFilename;
            var soundbank = donor.SoundbankFilename;

            var id           = Path.GetFileName(target);
            var newGuids     = Path.Combine(target, @"sfx", @"GUIDs.txt");
            var newSoundbank = Path.Combine(target, @"sfx", $@"{id}.bank");

            FileUtils.EnsureDirectoryExists(Path.Combine(target, @"sfx"));

            using (var putGuids = FileUtils.RecycleOriginal(newGuids))
                using (var putSoundbank = FileUtils.RecycleOriginal(newSoundbank)) {
                    if (File.Exists(guids) && File.Exists(soundbank))
                    {
                        FileUtils.HardLinkOrCopy(soundbank, putSoundbank.Filename);
                        File.WriteAllText(putGuids.Filename, File.ReadAllText(guids).Replace(donor.Id, id));
                    }
                    else if (File.Exists(soundbank) && donor.Author == AuthorKunos)
                    {
                        FileUtils.HardLinkOrCopy(soundbank, putSoundbank.Filename);
                        File.WriteAllText(putGuids.Filename, File.ReadAllLines(AcPaths.GetSfxGuidsFilename(AcRootDirectory.Instance.RequireValue))
                                          .Where(x => !x.Contains(@"} bank:/") || x.Contains(@"} bank:/common") ||
                                                 x.EndsWith(@"} bank:/" + donor.Id))
                                          .Where(x => !x.Contains(@"} event:/") || x.Contains(@"} event:/cars/" + donor.Id + @"/"))
                                          .JoinToString(Environment.NewLine).Replace(donor.Id, id));
                    }
                    else
                    {
                        throw new InformativeException(ToolsStrings.Car_ReplaceSound_WrongCar, ToolsStrings.Car_ReplaceSound_WrongCar_Commentary);
                    }
                }
        }
Exemplo n.º 21
0
        private async Task ReadKunosGuidsAsync()
        {
            if (_guidsRegex == null)
            {
                _guidsRegex = new Regex(@"^\{(\w{8}(?:-\w{4}){3}-\w{12})\}\s+event:/cars/(\w+)/e", RegexOptions.Compiled);
            }

            _kunosGuids = new Dictionary <string, string>();

            var filename = AcPaths.GetSfxGuidsFilename(AcRootDirectory.Instance.RequireValue);

            if (File.Exists(filename))
            {
                var lines = await FileUtils.ReadAllLinesAsync(filename).ConfigureAwait(false);

                for (var i = 0; i < lines.Length; i++)
                {
                    var m = _guidsRegex.Match(lines[i]);
                    if (m.Success)
                    {
                        _kunosGuids[m.Groups[1].Value] = m.Groups[2].Value;
                    }
                }
            }
        }
Exemplo n.º 22
0
        public void Run()
        {
            if (_watcher != null)
            {
                return;
            }

            _resultFilename = AcPaths.GetResultJsonFilename();
            FileUtils.EnsureFileDirectoryExists(_resultFilename);

            _timer = new DispatcherTimer {
                Interval = TimeSpan.FromSeconds(0.5), IsEnabled = true
            };
            _timer.Tick += OnTick;

            _watcher = new FileSystemWatcher(Path.GetDirectoryName(_resultFilename) ?? "")
            {
                NotifyFilter          = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName,
                IncludeSubdirectories = false,
                EnableRaisingEvents   = true,
            };

            _watcher.Changed += FileUpdate;
            _watcher.Created += FileUpdate;

            PreviewRun?.Invoke(this, new AcsRunEventArgs(null, null));
        }
Exemplo n.º 23
0
            public override void Shot(string skinId)
            {
                Prepare();
                PrepareIni(CarId, skinId, ShowroomId);

                _process = Process.Start(new ProcessStartInfo {
                    WorkingDirectory = AcRoot,
                    FileName         = "acShowroom.exe",
                    Arguments        = "pictureMode",
                    WindowStyle      = ProcessWindowStyle.Hidden
                });

                if (_process == null)
                {
                    throw new Exception("Cannot start showroom");
                }

                _process.WaitForExit();

                var filename = Path.Combine(AcPaths.GetCarSkinDirectory(AcRoot, CarId, skinId),
                                            "preview_original.jpg");

                if (_terminated)
                {
                    throw new ShotingCancelledException();
                }

                if (!File.Exists(filename))
                {
                    throw new ProcessExitedException();
                }

                File.Move(filename, Path.Combine(OutputDirectory, skinId + ".bmp"));
            }
Exemplo n.º 24
0
        private HashStorage CreateNew([NotNull] RulesEntry[] rulesSet, string[] carIds)
        {
            var hashStorage = new HashStorage(_rulesKeys);

            foreach (var car in carIds)
            {
                var carLocation = AcPaths.GetCarDirectory(_acRoot, car);
                if (!Directory.Exists(carLocation))
                {
                    continue;
                }

                var carData = DataWrapper.FromCarDirectory(carLocation);
                var bytes   = new byte[rulesSet.Length][];
                for (var i = 0; i < rulesSet.Length; i++)
                {
                    var set = rulesSet[i];
                    bytes[i] = set.Rules.GetHash(carData);
                }

                hashStorage.Add(car, bytes);
            }

            hashStorage.ParamsHashCode = _paramsHashCode;
            hashStorage.SaveTo(_storageLocation);
            return(hashStorage);
        }
Exemplo n.º 25
0
            protected override void Prepare()
            {
                base.Prepare();

                _logActivateChange = new LogActivateChange(AcRoot);
                _skins             = Directory.GetDirectories(AcPaths.GetCarSkinsDirectory(AcRoot, CarId))
                                     .Select(Path.GetFileName).ToArray();
            }
Exemplo n.º 26
0
        private static void SetCurrentFilterIni(string filter)
        {
            var filename = AcPaths.GetCfgVideoFilename();
            var iniFile  = new IniFile(filename);

            iniFile["POST_PROCESS"].Set("FILTER", filter);
            iniFile.Save();
        }
Exemplo n.º 27
0
        public IEnumerable <HashStorage.Simular> FindSimular(string carId, string setId, bool keepWorkedRules, double threshold)
        {
            var carLocation = AcPaths.GetCarDirectory(_acRoot, carId);

            return(Directory.Exists(carLocation) ?
                   FindSimular(DataWrapper.FromCarDirectory(carLocation), setId, keepWorkedRules, threshold) :
                   new HashStorage.Simular[0]);
        }
Exemplo n.º 28
0
        private static async Task <ArgumentHandleResult> ProcessInputFile(string filename)
        {
            bool isDirectory;

            try {
                if (!FileUtils.Exists(filename))
                {
                    return(ArgumentHandleResult.Failed);
                }
                isDirectory = FileUtils.IsDirectory(filename);
            } catch (Exception) {
                return(ArgumentHandleResult.Failed);
            }

            if (!isDirectory && filename.EndsWith(@".acreplay", StringComparison.OrdinalIgnoreCase) ||
                Path.GetDirectoryName(filename)?.Equals(AcPaths.GetReplaysDirectory(), StringComparison.OrdinalIgnoreCase) == true)
            {
                await GameWrapper.StartReplayAsync(new Game.StartProperties(new Game.ReplayProperties {
                    Filename = filename
                }));

                return(ArgumentHandleResult.Successful);
            }

            if (!isDirectory && filename.EndsWith(@".kn5", StringComparison.OrdinalIgnoreCase))
            {
                if ((Keyboard.Modifiers == ModifierKeys.Alt || Keyboard.Modifiers == ModifierKeys.Shift) && SettingsHolder.Common.DeveloperMode)
                {
                    try {
                        Kn5.FbxConverterLocation = PluginsManager.Instance.GetPluginFilename("FbxConverter", "FbxConverter.exe");
                        var kn5         = Kn5.FromFile(filename);
                        var destination = FileUtils.EnsureUnique(Path.Combine(Path.GetDirectoryName(filename) ?? @".",
                                                                              $"unpacked-{Path.GetFileName(filename)}"));
                        var name = kn5.RootNode.Name.StartsWith(@"FBX: ") ? kn5.RootNode.Name.Substring(5) :
                                   @"model.fbx";
                        Directory.CreateDirectory(destination);
                        await kn5.ExportFbxWithIniAsync(Path.Combine(destination, name));

                        var textures = Path.Combine(destination, "texture");
                        Directory.CreateDirectory(textures);
                        await kn5.ExportTexturesAsync(textures);

                        Process.Start(destination);
                    } catch (Exception e) {
                        Logging.Error(e);
                        return(ArgumentHandleResult.FailedShow);
                    }
                }
                else
                {
                    await CustomShowroomWrapper.StartAsync(filename);
                }

                return(ArgumentHandleResult.Successful);
            }

            return(ArgumentHandleResult.FailedShow);
        }
Exemplo n.º 29
0
 public static bool HasWithExtension()
 {
     try {
         return(Directory.GetFiles(AcPaths.GetReplaysDirectory()).Any(file => file.EndsWith(ReplayObject.ReplayExtension)));
     } catch (Exception e) {
         Logging.Error("Can’t get files with extension: " + e);
         return(false);
     }
 }
Exemplo n.º 30
0
        public ScreenshotFormatChange(string acRoot, string value)
        {
            _cfgFile = Path.Combine(AcPaths.GetSystemCfgDirectory(acRoot), "assetto_corsa.ini");
            var iniFile = new IniFile(_cfgFile);

            _originalFormat = iniFile["SCREENSHOT"].GetPossiblyEmpty("FORMAT");
            iniFile["SCREENSHOT"].Set("FORMAT", value);
            iniFile.Save();
        }