public override string AcApiRequest(string url) { url = url.SubstringExt(AcApiHandlerFactory.AcSchemeName.Length + 3); Logging.Debug(url); var index = url.IndexOf('?'); var pieces = (index == -1 ? url : url.Substring(0, index)).Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); switch (pieces[0]) { case "getguid": return(SteamIdHelper.Instance.Value); case "setsetting": switch (pieces.ArrayElementAtOrDefault(1)) { case "race": foreach (var parameter in GetParameters()) { var p = parameter.Key.Split('/'); if (p.Length != 2) { Logging.Warning($"Invalid key: {parameter.Key}"); } else { Logging.Debug($"Parameter: {parameter.Key}={parameter.Value}"); _raceConfig[p[0]].Set(p[1], parameter.Value); } } break; default: Logging.Warning($"Unknown setting: {pieces.ArrayElementAtOrDefault(1)}"); break; } return(string.Empty); case "start": ActionExtension.InvokeInMainThread(() => { GameWrapper.StartAsync(new Game.StartProperties { PreparedConfig = _raceConfig }); }); return(string.Empty); default: Logging.Warning($"Unknown request: {pieces[0]} (“{url}”)"); return(null); } Dictionary <string, string> GetParameters() { return((index == -1 ? "" : url.Substring(index + 1)) .Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Split(new[] { '=' }, 2)).ToDictionary( x => Uri.UnescapeDataString(x[0]), x => Uri.UnescapeDataString(x.ArrayElementAtOrDefault(1) ?? ""))); } }
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); }
private async Task <ArgumentHandleResult> ProcessInputFile(string filename) { var isDirectory = FileUtils.IsDirectory(filename); if (!isDirectory && filename.EndsWith(@".acreplay", StringComparison.OrdinalIgnoreCase) || Path.GetDirectoryName(filename)?.Equals(FileUtils.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); } try { new InstallAdditionalContentDialog(filename).ShowDialog(); } catch (Exception e) { NonfatalError.Notify(AppStrings.Arguments_CannotInstallAdditionalContent, e); return(ArgumentHandleResult.Failed); } return(ArgumentHandleResult.Successful); }
public MainWindow() { GameWrapper.RegisterFactory(this); DataContext = new ViewModel(); InitializeComponent(); RenderOptions.SetBitmapScalingMode(Scene, _bestQuality ? BitmapScalingMode.HighQuality : BitmapScalingMode.LowQuality); }
public void startOnlineRace(string ip, int port, int httpPort, IJavascriptCallback callback = null) { if (_car == null) { throw new Exception("Car is not set"); } if (_track == null) { throw new Exception("Track is not set"); } ActionExtension.InvokeInMainThread(async() => { var result = await GameWrapper.StartAsync(new Game.StartProperties { BasicProperties = new Game.BasicProperties { CarId = _car.Id, TrackId = _track.MainTrackObject.Id, TrackConfigurationId = _track.LayoutId, CarSkinId = _carSkin?.Id ?? _car.SelectedSkin?.Id ?? "" }, ModeProperties = new Game.OnlineProperties { Guid = SteamIdHelper.Instance.Value, ServerIp = ip, ServerPort = port, ServerHttpPort = httpPort, Password = InternalUtils.GetRaceUPassword(_track.IdWithLayout, ip, port), RequestedCar = _car.Id } }); callback?.ExecuteAsync(result?.IsNotCancelled); }).Ignore(); }
public async Task <Lobby> CreateLobby(GameWrapper game, LobbyConnection host, string name) { using (var alock = await Data.Synchronizer.SetStateAsync(ModuleState.Writing)) { log.Debug("creating new lobby '" + name + "' for host " + host); var lobby = new Lobby(name) { Host = host, Backend = new LobbyBackendWrapper(game) }; await SetGameMode(lobby, lobby.Backend.DefaultGameMode); Data.AddLobby(lobby); try { await Broadcast(Messages.LobbyCreated(lobby)); await JoinLobby(host, lobby); } catch { Data.RemoveLobby(lobby); throw; } return(lobby); } }
public override void initController(System.Action <string> printFunc, System.Action <object, int, short> sendMsgFunc, System.Action shutdownGameServer, GameWrapper wrapper, List <string> preGamePlayers) { controller.updater = updater; controller.gameLogic = gameLogic; controller.init(printFunc, sendMsgFunc, shutdownGameServer, wrapper, preGamePlayers); }
public EnemyManager(GameWrapper i_Game) : base(i_Game) { m_AlienManager = new AlienManager(i_Game); m_AlienManager.AliensReachedBottom += alienManager_AliensReachedBottom; m_AlienManager.AllAliensAreDead += alienManager_AllAliensAreDead; m_MothershipManager = new MothershipManager(i_Game); }
public ScoreLabel(GameWrapper i_Game, PlayerShip i_Player) : base(i_Game) { m_PlayerIndex = 0; m_Player = i_Player; m_Player.ScoreChanged += player_ScoreChanged; m_Label = new CalibriLabel(i_Game); }
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); }
public MenuItem(string i_Text, GameWrapper i_Game) : base(i_Game) { m_SpriteFontManager = new SpriteFontManager(i_Game); m_SpriteFontManager.TexturePath = @"Fonts/Calibri"; Text = i_Text; m_Game = i_Game; Visible = true; }
internal void AddModule(IServerGameFactory game) { if (_games.Values.ToArray().Where(g => g.Factory.Name == game.Name).Any()) { throw new ArgumentException("Game with name " + game.Name + " already exists!"); } var wrapper = new GameWrapper(game); _games.Add(wrapper.Id, wrapper); }
public WrapBot(string botName, int botTeam, int botIndex) : base(botName, botTeam, botIndex) { State = BotState.Kickoff; Action = BotAction.Default; Controller = new Controller(); Field = new FieldService(botTeam); Ball = new BallWrapper(); Info = new PlayerWrapper(); Game = new GameWrapper(); DesiredState = null; }
public AnimatedMenuItem(string i_Text, GameWrapper i_Game) : base(i_Text, i_Game) { if (m_PulseAnimator == null) { m_PulseAnimator = new PulseAnimator(k_PulseAnimatorName, 0.997f); } m_PulseAnimator.BoundSprite = m_SpriteFontManager; m_PulseAnimator.Initialize(); }
public Player2(GameWrapper i_Game) : base(i_Game) { m_FrameOffset = 0; this.SourceRectangle = new Rectangle(m_FrameOffset * k_FrameWidth, 0, k_FrameWidth, k_FrameHeight); this.IsMouseControled = false; this.KeyMoveLeft.Add(Keys.A); this.KeyMoveRight.Add(Keys.D); this.KeyShoot.Add(Keys.W); }
public LobbyBackendWrapper(GameWrapper game) { Game = game; var provider = Game.Factory.CreateLobbySettingsProvider(); var builder = new SettingsBuilder(); provider.ProvideSettings(builder); GameModes = builder.CreateGameModeDic(); }
protected override void OnItemDoubleClick(AcObjectNew obj) { if (obj is ReplayObject replay) { GameWrapper.StartReplayAsync(new Game.StartProperties(new Game.ReplayProperties { Name = replay.Id, TrackId = replay.TrackId, TrackConfiguration = replay.TrackConfiguration, WeatherId = replay.WeatherId })); } }
public Player1(GameWrapper i_Game) : base(i_Game) { m_FrameOffset = 1; this.SourceRectangle = new Rectangle(m_FrameOffset * k_FrameWidth, 0, k_FrameWidth, k_FrameHeight); this.Position = new Vector2(k_InitialLeftMargin, Game.GraphicsDevice.Viewport.Height - this.Height - k_BottomMargin); this.IsMouseControled = true; this.KeyMoveLeft.Add(Keys.Left); this.KeyMoveRight.Add(Keys.Right); this.KeyShoot.Add(Keys.LeftControl); this.KeyShoot.Add(Keys.RightControl); }
protected override void OnItemDoubleClick(AcObjectNew obj) { var replay = obj as ReplayObject; if (replay == null) { return; } GameWrapper.StartReplayAsync(new Game.StartProperties(new Game.ReplayProperties { Name = replay.Id, TrackId = replay.TrackId, TrackConfiguration = replay.TrackConfiguration, WeatherId = replay.WeatherId })); }
private static async Task <ArgumentHandleResult> ProcessRaceConfig(CustomUriRequest custom) { var config = GetSettings(custom.Params, @"config") ?? throw new Exception(@"Settings are not specified"); var assists = GetSettings(custom.Params, @"assists"); if (assists != null && !UserPresetsControl.LoadSerializedPreset(AssistsViewModel.Instance.PresetableKey, assists)) { AssistsViewModel.Instance.ImportFromPresetData(assists); } await GameWrapper.StartAsync(new Game.StartProperties { PreparedConfig = IniFile.Parse(config) }); return(ArgumentHandleResult.Successful); }
public async Task <bool> Go() { if (Server?.Ip == null || Player == null || CarId == null) { return(false); } try { if (Car == null) { throw new InformativeException(string.Format(ToolsStrings.AcError_CarIsMissing, CarId), AppStrings.Srs_CarIsMissing_Commentary); } var anyTrack = TracksManager.Instance.GetDefault(); Logging.Debug(CarSkinId); await GameWrapper.StartAsync(new Game.StartProperties { BasicProperties = new Game.BasicProperties { CarId = CarId, CarSkinId = CarSkinId, TrackId = anyTrack?.Id, TrackConfigurationId = anyTrack?.LayoutId }, ModeProperties = new Game.OnlineProperties { ServerName = Server.DisplayName, ServerIp = Server.Ip, ServerPort = Server.Port ?? 9615, ServerHttpPort = Server.PortHttp, Password = Server.Password, Penalties = true, }, AdditionalPropertieses = { new SrsMark { Name = Player.DisplayName ?? SrsMark.GetName(), Team = Player.Team ?? "", Nationality = Player.Nationality ?? "" } } }); return(true); } catch (Exception e) { NonfatalError.Notify(AppStrings.Common_CannotStartRace, e); return(false); } }
public void init(Action <string> printFunc, Action <object, int, short> sendMsgFunc, Action shutdownGameServer, GameWrapper wrapper, List <string> preGamePlayers) { print = printFunc; initProtocol(sendMsgFunc); this.wrapper = wrapper; this.shutdownGameServer = shutdownGameServer; this.preGamePlayers = preGamePlayers; gameLog.init(spectatorModule); spectatorModule.init(gameLog); print("Amount of Players : " + preGamePlayers.Count); foreach (string s in preGamePlayers) { print("Player: " + s); } }
/* Loads the approriate gamelogic. The gameMaster file should be located in the "GameLibrariesFolder/ *GameName* /main.dll" * Important that the namespace is "Main" & The class name "GameMaster" */ public static void loadServerGameLogic(ref GameWrapper wrapper, ref GameMaster gameController, ref GameType gameType, List <string> preGamePlayers) { if (!Msf.Args.IsProvided(Msf.Args.LoadScene)) { Debug.LogError("A scene to load was not provided"); return; } //Go to the correct folder and get dll! Should be located in "GameLibraries/*GameName*/main.dll" string dllFolder = Application.dataPath.Substring(0, Application.dataPath.Length - 15); dllFolder += "GameLibraries/" + Msf.Args.LoadScene + "/"; string filePath = dllFolder + "Main.dll"; FileInfo dllFile = new FileInfo(filePath); if (dllFile.Exists == false) { Debug.LogError("Could not find approprate dll file!\n " + filePath); return; } //Create an instance. Must be named "GameMaster" and in "Main" namespace Assembly loadedFile = Assembly.LoadFile(dllFile.FullName); Type testType = loadedFile.GetType("Main.GameMaster"); object testInstance = Activator.CreateInstance(testType, null); //This is where the magic happens! We call getInstance wich returns a GameMaster object. MethodInfo useFunc = testType.GetMethod("getInstance"); gameController = (Game.GameMaster)useFunc.Invoke(testInstance, null); wrapper.init(gameController.getProtocol(), gameController); gameType = gameController.getGameType(); //Debug.LogError ("CurrentGame: " + gameType); //We give the Dll some functions so that it can interact with server Action <string> printFunc = printMsg; Action <object, int, short> networkMsg = wrapper.sendMsg; gameController.init(printFunc, networkMsg, AlbotNetworkManager.shutdownGameServer, wrapper, preGamePlayers); AlbotNetworkManager.onClientLeft += wrapper.clientLeft; }
public GameOverScreen(GameWrapper i_Game, GameOverEventArgs i_GameInfo) : base(i_Game) { this.IsModal = true; this.BlendState = BlendState.NonPremultiplied; m_GameInfo = i_GameInfo; m_Score = new CalibriLabel(i_Game); m_Instructions = new CalibriLabel(i_Game); m_GameInfoLabel = new CalibriLabel(i_Game, eFontSize.Large); Add(m_Score); Add(m_GameInfoLabel); Add(m_Instructions); updateGameInfo(); defineInstructionsMessage(); }
public void _startOnlineRace(string jsonParams, IJavascriptCallback callback = null) { var args = JObject.Parse(jsonParams); if (_car == null) { throw new Exception("Car is not set"); } if (_track == null) { throw new Exception("Track is not set"); } var ip = args.GetStringValueOnly("ip") ?? throw new Exception("“ip” parameter is missing"); var port = args.GetIntValueOnly("port") ?? throw new Exception("“port” parameter is missing"); var properties = new Game.StartProperties { BasicProperties = new Game.BasicProperties { CarId = _car.Id, TrackId = _track.MainTrackObject.Id, TrackConfigurationId = _track.LayoutId, CarSkinId = _carSkin?.Id ?? _car.SelectedSkin?.Id ?? "" }, ModeProperties = new Game.OnlineProperties { Guid = SteamIdHelper.Instance.Value, ServerIp = ip, ServerPort = port, ServerHttpPort = args.GetIntValueOnly("httpPort") ?? throw new Exception("“httpPort” parameter is missing"), Password = args.GetStringValueOnly("password") ?? InternalUtils.GetRaceUPassword(_track.IdWithLayout, ip, port), RequestedCar = _car.Id, CspFeaturesList = args.GetStringValueOnly("cspFeatures"), CspReplayClipUploadUrl = args.GetStringValueOnly("cspReplayClipUploadUrl"), } }; ActionExtension.InvokeInMainThread(async() => { var result = await GameWrapper.StartAsync(properties); callback?.ExecuteAsync(result?.IsNotCancelled); }).Ignore(); }
public LoadingScreen(GameWrapper i_Game, int i_LevelNumber) : base(i_Game) { m_Game = i_Game; m_TimeCount = k_NumOfSecondsToCount; m_LevelNumber = new CalibriLabel(i_Game, eFontSize.Large); m_LevelNumber.Initialize(); m_LevelNumber.Text = "Level " + i_LevelNumber.ToString(); //m_LevelNumber.Position = new Vector2((Game.GraphicsDevice.Viewport.Width / 2) - (m_LevelNumber.Bounds.Width / 2), // (Game.GraphicsDevice.Viewport.Height / 2) - (m_LevelNumber.Bounds.Height)); m_LevelNumber.CenterToViewPort(); Add(m_LevelNumber); m_Countdown = new CalibriLabel(i_Game, eFontSize.Large); m_Countdown.Initialize(); m_Countdown.Color = Color.White; m_Countdown.Position = new Vector2((Game.GraphicsDevice.Viewport.Width / 2) - (m_Countdown.Bounds.Width / 2), m_LevelNumber.Bounds.Y + m_LevelNumber.Bounds.Height + 10); Add(m_Countdown); }
public PlayerShip(GameWrapper i_Game) : base(i_Game) { m_Keys = new List<KeyManager>(); m_ShootKey = new KeyManager(Game); m_Keys.Add(m_ShootKey); m_MoveRightKey = new KeyManager(Game); m_Keys.Add(m_MoveRightKey); m_MoveLeftKey = new KeyManager(Game); m_Keys.Add(m_MoveLeftKey); m_BulletManager = new BulletManager(Game); m_BulletManager.MaxActiveBullets = k_MaxShotsFired; m_BulletManager.BulletHit += BulletManager_BulletHit; Lives = k_InitNumOfLives; this.Color = Color.White; m_PlayerScore = 0; m_ShootKey.KeyWasPressed += ShootKey_KeyWasPressed; m_IsAlive = true; TexturePath = @"Sprites/Ships_32x32"; this.IsPartOfTexture = true; }
internal static GameWrapper AIHandler; //this is not particularly good architecture, but it will work for now. //static constructor. It gets called on first reference to static class. static Chess() { /* * PlayerWhite = new GameObject[] * { * Create(Chessman.Colours.White, Chessman.Types.Bishop, 2, 0), * }; */ //RefreshBoard(); moveSounds = GameObject.Find("Board").GetComponent <AudioSwitch>(); AIHandler = GameObject.Find("Game Controller").GetComponent <GameWrapper>(); toMove = Chessman.Colours.White; GameOver = false; PieceSquareTables = new int[, ][, ] { { KingTableWhite, KingTableBlack }, { QueenTableWhite, QueenTableBlack }, { RookTableWhite, RookTableBlack }, { BishopTableWhite, BishopTableBlack }, { KnightTableWhite, KnightTableBlack }, { PawnTableWhite, PawnTableBlack }, }; ConstructPieceSquareTables(); }
private static async Task <ArgumentHandleResult> ProcessUriRequestObsolete(string request) { string key, param; NameValueCollection query; { var splitted = request.Split(new[] { '/' }, 2); if (splitted.Length != 2) { return(ArgumentHandleResult.FailedShow); } key = splitted[0]; param = splitted[1]; var index = param.IndexOf('?'); if (index != -1) { query = HttpUtility.ParseQueryString(param.SubstringExt(index + 1)); param = param.Substring(0, index); } else { query = null; } } switch (key) { case "quickdrive": var preset = Convert.FromBase64String(param).ToUtf8String(); if (!await QuickDrive.RunAsync(serializedPreset: preset)) { NonfatalError.Notify(AppStrings.Common_CannotStartRace, AppStrings.Arguments_CannotStartRace_Commentary); return(ArgumentHandleResult.Failed); } break; case "race": var raceIni = Convert.FromBase64String(param).ToUtf8String(); await GameWrapper.StartAsync(new Game.StartProperties { PreparedConfig = IniFile.Parse(raceIni) }); break; case "open": var address = Convert.FromBase64String(param).ToUtf8String(); try { return(await ProcessInputFile(await LoadRemoveFile(address, query?.Get(@"name")))); } catch (Exception e) when(e.IsCancelled()) { return(ArgumentHandleResult.Failed); } catch (Exception e) { Logging.Warning(e); return(ArgumentHandleResult.FailedShow); } case "install": return(await ContentInstallationManager.Instance.InstallAsync(param, new ContentInstallationParams(true)) ? ArgumentHandleResult.Successful : ArgumentHandleResult.Failed); } return(ArgumentHandleResult.Successful); }
private App() { if (AppArguments.GetBool(AppFlag.IgnoreHttps)) { ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true; } AppArguments.Set(AppFlag.SyncNavigation, ref ModernFrame.OptionUseSyncNavigation); AppArguments.Set(AppFlag.DisableTransitionAnimation, ref ModernFrame.OptionDisableTransitionAnimation); AppArguments.Set(AppFlag.RecentlyClosedQueueSize, ref LinkGroupFilterable.OptionRecentlyClosedQueueSize); AppArguments.Set(AppFlag.NoProxy, ref KunosApiProvider.OptionNoProxy); var proxy = AppArguments.Get(AppFlag.Proxy); if (!string.IsNullOrWhiteSpace(proxy)) { try { var s = proxy.Split(':'); WebRequest.DefaultWebProxy = new WebProxy(s[0], FlexibleParser.ParseInt(s.ArrayElementAtOrDefault(1), 1080)); } catch (Exception e) { Logging.Error(e); } } // TODO: AppArguments.Set(AppFlag.ScanPingTimeout, ref RecentManagerOld.OptionScanPingTimeout); AppArguments.Set(AppFlag.LanSocketTimeout, ref KunosApiProvider.OptionLanSocketTimeout); AppArguments.Set(AppFlag.LanPollTimeout, ref KunosApiProvider.OptionLanPollTimeout); AppArguments.Set(AppFlag.WebRequestTimeout, ref KunosApiProvider.OptionWebRequestTimeout); AppArguments.Set(AppFlag.DirectRequestTimeout, ref KunosApiProvider.OptionDirectRequestTimeout); AppArguments.Set(AppFlag.CommandTimeout, ref GameCommandExecutorBase.OptionCommandTimeout); AppArguments.Set(AppFlag.DisableAcRootChecking, ref AcPaths.OptionEaseAcRootCheck); AppArguments.Set(AppFlag.AcObjectsLoadingConcurrency, ref BaseAcManagerNew.OptionAcObjectsLoadingConcurrency); AppArguments.Set(AppFlag.SkinsLoadingConcurrency, ref CarObject.OptionSkinsLoadingConcurrency); AppArguments.Set(AppFlag.KunosCareerIgnoreSkippedEvents, ref KunosCareerEventsManager.OptionIgnoreSkippedEvents); AppArguments.Set(AppFlag.IgnoreMissingSkinsInKunosEvents, ref KunosEventObjectBase.OptionIgnoreMissingSkins); AppArguments.Set(AppFlag.CanPack, ref AcCommonObject.OptionCanBePackedFilter); AppArguments.Set(AppFlag.CanPackCars, ref CarObject.OptionCanBePackedFilter); AppArguments.Set(AppFlag.ForceToastFallbackMode, ref Toast.OptionFallbackMode); AppArguments.Set(AppFlag.SmartPresetsChangedHandling, ref UserPresetsControl.OptionSmartChangedHandling); AppArguments.Set(AppFlag.EnableRaceIniRestoration, ref Game.OptionEnableRaceIniRestoration); AppArguments.Set(AppFlag.EnableRaceIniTestMode, ref Game.OptionRaceIniTestMode); AppArguments.Set(AppFlag.RaceOutDebug, ref Game.OptionDebugMode); AppArguments.Set(AppFlag.NfsPorscheTribute, ref RaceGridViewModel.OptionNfsPorscheNames); AppArguments.Set(AppFlag.KeepIniComments, ref IniFile.OptionKeepComments); AppArguments.Set(AppFlag.AutoConnectPeriod, ref OnlineServer.OptionAutoConnectPeriod); AppArguments.Set(AppFlag.GenericModsLogging, ref GenericModsEnabler.OptionLoggingEnabled); AppArguments.Set(AppFlag.SidekickOptimalRangeThreshold, ref SidekickHelper.OptionRangeThreshold); AppArguments.Set(AppFlag.GoogleDriveLoaderDebugMode, ref GoogleDriveLoader.OptionDebugMode); AppArguments.Set(AppFlag.GoogleDriveLoaderManualRedirect, ref GoogleDriveLoader.OptionManualRedirect); AppArguments.Set(AppFlag.DebugPing, ref ServerEntry.OptionDebugPing); AppArguments.Set(AppFlag.DebugContentId, ref AcObjectNew.OptionDebugLoading); AppArguments.Set(AppFlag.JpegQuality, ref ImageUtilsOptions.JpegQuality); AppArguments.Set(AppFlag.FbxMultiMaterial, ref Kn5.OptionJoinToMultiMaterial); Acd.Factory = new AcdFactory(); Lazier.SyncAction = ActionExtension.InvokeInMainThreadAsync; KeyboardListenerFactory.Register <KeyboardListener>(); LimitedSpace.Initialize(); DataProvider.Initialize(); SteamIdHelper.Initialize(AppArguments.Get(AppFlag.ForceSteamId)); TestKey(); AppDomain.CurrentDomain.ProcessExit += OnProcessExit; if (!AppArguments.GetBool(AppFlag.PreventDisableWebBrowserEmulationMode) && ( ValuesStorage.Get <int>(WebBrowserEmulationModeDisabledKey) < WebBrowserHelper.EmulationModeDisablingVersion || AppArguments.GetBool(AppFlag.ForceDisableWebBrowserEmulationMode))) { try { WebBrowserHelper.DisableBrowserEmulationMode(); ValuesStorage.Set(WebBrowserEmulationModeDisabledKey, WebBrowserHelper.EmulationModeDisablingVersion); } catch (Exception e) { Logging.Warning("Can’t disable emulation mode: " + e); } } JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.None, NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Include, Culture = CultureInfo.InvariantCulture }; AcToolsLogging.Logger = (s, m, p, l) => Logging.Write($"{s} (AcTools)", m, p, l); AcToolsLogging.NonFatalErrorHandler = (s, c, e, b) => { if (b) { NonfatalError.NotifyBackground(s, c, e); } else { NonfatalError.Notify(s, c, e); } }; AppArguments.Set(AppFlag.ControlsDebugMode, ref ControlsSettings.OptionDebugControlles); AppArguments.Set(AppFlag.ControlsRescanPeriod, ref DirectInputScanner.OptionMinRescanPeriod); var ignoreControls = AppArguments.Get(AppFlag.IgnoreControls); if (!string.IsNullOrWhiteSpace(ignoreControls)) { ControlsSettings.OptionIgnoreControlsFilter = Filter.Create(new StringTester(), ignoreControls); } var sseStart = AppArguments.Get(AppFlag.SseName); if (!string.IsNullOrWhiteSpace(sseStart)) { SseStarter.OptionStartName = sseStart; } AppArguments.Set(AppFlag.SseLogging, ref SseStarter.OptionLogging); FancyBackgroundManager.Initialize(); if (AppArguments.Has(AppFlag.UiScale)) { AppearanceManager.Instance.AppScale = AppArguments.GetDouble(AppFlag.UiScale, 1d); } if (AppArguments.Has(AppFlag.WindowsLocationManagement)) { AppearanceManager.Instance.ManageWindowsLocation = AppArguments.GetBool(AppFlag.WindowsLocationManagement, true); } if (!InternalUtils.IsAllRight) { AppAppearanceManager.OptionCustomThemes = false; } else { AppArguments.Set(AppFlag.CustomThemes, ref AppAppearanceManager.OptionCustomThemes); } AppArguments.Set(AppFlag.FancyHintsDebugMode, ref FancyHint.OptionDebugMode); AppArguments.Set(AppFlag.FancyHintsMinimumDelay, ref FancyHint.OptionMinimumDelay); AppArguments.Set(AppFlag.WindowsVerbose, ref DpiAwareWindow.OptionVerboseMode); AppArguments.Set(AppFlag.ShowroomUiVerbose, ref LiteShowroomFormWrapperWithTools.OptionAttachedToolsVerboseMode); AppArguments.Set(AppFlag.BenchmarkReplays, ref GameDialog.OptionBenchmarkReplays); // Shared memory, now as an app flag SettingsHolder.Drive.WatchForSharedMemory = !AppArguments.GetBool(AppFlag.DisableSharedMemory); /*AppAppearanceManager.OptionIdealFormattingModeDefaultValue = AppArguments.GetBool(AppFlag.IdealFormattingMode, * !Equals(DpiAwareWindow.OptionScale, 1d));*/ NonfatalErrorSolution.IconsDictionary = new Uri("/AcManager.Controls;component/Assets/IconData.xaml", UriKind.Relative); AppearanceManager.DefaultValuesSource = new Uri("/AcManager.Controls;component/Assets/ModernUI.Default.xaml", UriKind.Relative); AppAppearanceManager.Initialize(Pages.Windows.MainWindow.GetTitleLinksEntries()); VisualExtension.RegisterInput <WebBlock>(); ContentUtils.Register("AppStrings", AppStrings.ResourceManager); ContentUtils.Register("ControlsStrings", ControlsStrings.ResourceManager); ContentUtils.Register("ToolsStrings", ToolsStrings.ResourceManager); ContentUtils.Register("UiStrings", UiStrings.ResourceManager); AcObjectsUriManager.Register(new UriProvider()); { var uiFactory = new GameWrapperUiFactory(); GameWrapper.RegisterFactory(uiFactory); ServerEntry.RegisterFactory(uiFactory); } GameWrapper.RegisterFactory(new DefaultAssistsFactory()); LapTimesManager.Instance.SetListener(); RaceResultsStorage.Instance.SetListener(); AcError.RegisterFixer(new AcErrorFixer()); AcError.RegisterSolutionsFactory(new SolutionsFactory()); InitializePresets(); SharingHelper.Initialize(); SharingUiHelper.Initialize(AppArguments.GetBool(AppFlag.ModernSharing) ? new Win10SharingUiHelper() : null); { var addonsDir = FilesStorage.Instance.GetFilename("Addons"); var pluginsDir = FilesStorage.Instance.GetFilename("Plugins"); if (Directory.Exists(addonsDir) && !Directory.Exists(pluginsDir)) { Directory.Move(addonsDir, pluginsDir); } else { pluginsDir = FilesStorage.Instance.GetDirectory("Plugins"); } PluginsManager.Initialize(pluginsDir); PluginsWrappers.Initialize( new AssemblyResolvingWrapper(KnownPlugins.Fmod, FmodResolverService.Resolver), new AssemblyResolvingWrapper(KnownPlugins.Fann, FannResolverService.Resolver), new AssemblyResolvingWrapper(KnownPlugins.Magick, ImageUtils.MagickResolver), new AssemblyResolvingWrapper(KnownPlugins.CefSharp, CefSharpResolverService.Resolver)); } { var onlineMainListFile = FilesStorage.Instance.GetFilename("Online Servers", "Main List.txt"); var onlineFavouritesFile = FilesStorage.Instance.GetFilename("Online Servers", "Favourites.txt"); if (File.Exists(onlineMainListFile) && !File.Exists(onlineFavouritesFile)) { Directory.Move(onlineMainListFile, onlineFavouritesFile); } } CupClient.Initialize(); Superintendent.Initialize(); ModsWebBrowser.Initialize(); AppArguments.Set(AppFlag.OfflineMode, ref AppKeyDialog.OptionOfflineMode); WebBlock.DefaultDownloadListener = new WebDownloadListener(); FlexibleLoader.CmRequestHandler = new CmRequestHandler(); ContextMenus.ContextMenusProvider = new ContextMenusProvider(); PrepareUi(); AppShortcut.Initialize("Content Manager", "Content Manager"); // If shortcut exists, make sure it has a proper app ID set for notifications if (File.Exists(AppShortcut.ShortcutLocation)) { AppShortcut.CreateShortcut(); } AppIconService.Initialize(new AppIconProvider()); Toast.SetDefaultAction(() => (Current.Windows.OfType <ModernWindow>().FirstOrDefault(x => x.IsActive) ?? Current.MainWindow as ModernWindow)?.BringToFront()); BbCodeBlock.ImageClicked += OnBbImageClick; BbCodeBlock.OptionEmojiProvider = new EmojiProvider(); BbCodeBlock.OptionImageCacheDirectory = FilesStorage.Instance.GetTemporaryFilename("Images"); BbCodeBlock.OptionEmojiCacheDirectory = FilesStorage.Instance.GetTemporaryFilename("Emoji"); BbCodeBlock.AddLinkCommand(new Uri("cmd://findMissing/car"), new DelegateCommand <string>( id => { WindowsHelper.ViewInBrowser(SettingsHolder.Content.MissingContentSearch.GetUri(id, SettingsHolder.MissingContentType.Car)); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://findMissing/track"), new DelegateCommand <string>( id => { WindowsHelper.ViewInBrowser(SettingsHolder.Content.MissingContentSearch.GetUri(id, SettingsHolder.MissingContentType.Track)); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://downloadMissing/car"), new DelegateCommand <string>(id => { var s = id.Split('|'); IndexDirectDownloader.DownloadCarAsync(s[0], s.ArrayElementAtOrDefault(1)).Forget(); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://downloadMissing/track"), new DelegateCommand <string>(id => { var s = id.Split('|'); IndexDirectDownloader.DownloadTrackAsync(s[0], s.ArrayElementAtOrDefault(1)).Forget(); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://createNeutralLut"), new DelegateCommand <string>(id => NeutralColorGradingLut.CreateNeutralLut(id.As(16)))); BbCodeBlock.DefaultLinkNavigator.PreviewNavigate += (sender, args) => { if (args.Uri.IsAbsoluteUri && args.Uri.Scheme == "acmanager") { ArgumentsHandler.ProcessArguments(new[] { args.Uri.ToString() }, true).Forget(); args.Cancel = true; } }; AppArguments.SetSize(AppFlag.ImagesCacheLimit, ref BetterImage.OptionCacheTotalSize); AppArguments.Set(AppFlag.ImagesMarkCached, ref BetterImage.OptionMarkCached); BetterImage.RemoteUserAgent = CmApiProvider.UserAgent; BetterImage.RemoteCacheDirectory = BbCodeBlock.OptionImageCacheDirectory; GameWrapper.Started += (sender, args) => { BetterImage.CleanUpCache(); GCHelper.CleanUp(); }; AppArguments.Set(AppFlag.UseVlcForAnimatedBackground, ref DynamicBackground.OptionUseVlc); Filter.OptionSimpleMatching = true; GameResultExtension.RegisterNameProvider(new GameSessionNameProvider()); CarBlock.CustomShowroomWrapper = new CustomShowroomWrapper(); CarBlock.CarSetupsView = new CarSetupsView(); SettingsHolder.Content.OldLayout = AppArguments.GetBool(AppFlag.CarsOldLayout); var acRootIsFine = Superintendent.Instance.IsReady && !AcRootDirectorySelector.IsReviewNeeded(); if (acRootIsFine && SteamStarter.Initialize(AcRootDirectory.Instance.Value)) { if (SettingsHolder.Drive.SelectedStarterType != SettingsHolder.DriveSettings.SteamStarterType) { SettingsHolder.Drive.SelectedStarterType = SettingsHolder.DriveSettings.SteamStarterType; Toast.Show("Starter changed to replacement", "Enjoy Steam being included into CM"); } } else if (SettingsHolder.Drive.SelectedStarterType == SettingsHolder.DriveSettings.SteamStarterType) { SettingsHolder.Drive.SelectedStarterType = SettingsHolder.DriveSettings.DefaultStarterType; Toast.Show($"Starter changed to {SettingsHolder.Drive.SelectedStarterType.DisplayName}", "Steam Starter is unavailable", () => { ModernDialog.ShowMessage( "To use Steam Starter, please make sure CM is taken place of the official launcher and AC root directory is valid.", "Steam Starter is unavailable", MessageBoxButton.OK); }); } InitializeUpdatableStuff(); BackgroundInitialization(); ExtraProgressRings.Initialize(); FatalErrorMessage.Register(new AppRestartHelper()); ImageUtils.SafeMagickWrapper = fn => { try { return(fn()); } catch (OutOfMemoryException e) { NonfatalError.Notify(ToolsStrings.MagickNet_CannotLoad, ToolsStrings.MagickNet_CannotLoad_Commentary, e); } catch (Exception e) { NonfatalError.Notify(ToolsStrings.MagickNet_CannotLoad, e); } return(null); }; DataFileBase.ErrorsCatcher = new DataSyntaxErrorCatcher(); AppArguments.Set(AppFlag.SharedMemoryLiveReadingInterval, ref AcSharedMemory.OptionLiveReadingInterval); AcSharedMemory.Initialize(); AppArguments.Set(AppFlag.RunRaceInformationWebserver, ref PlayerStatsManager.OptionRunStatsWebserver); AppArguments.Set(AppFlag.RaceInformationWebserverFile, ref PlayerStatsManager.OptionWebserverFilename); PlayerStatsManager.Instance.SetListener(); RhmService.Instance.SetListener(); WheelOptionsBase.SetStorage(new WheelAnglesStorage()); _hibernator = new AppHibernator(); _hibernator.SetListener(); VisualCppTool.Initialize(FilesStorage.Instance.GetDirectory("Plugins", "NativeLibs")); try { SetRenderersOptions(); } catch (Exception e) { VisualCppTool.OnException(e, null); } CommonFixes.Initialize(); CmPreviewsTools.MissingShowroomHelper = new CarUpdatePreviewsDialog.MissingShowroomHelper(); // Paint shop+livery generator? LiteShowroomTools.LiveryGenerator = new LiveryGenerator(); // Discord if (AppArguments.Has(AppFlag.DiscordCmd)) { // Do not show main window and wait for futher instructions? } if (SettingsHolder.Integrated.DiscordIntegration) { AppArguments.Set(AppFlag.DiscordVerbose, ref DiscordConnector.OptionVerboseMode); DiscordConnector.Initialize(AppArguments.Get(AppFlag.DiscordClientId) ?? InternalUtils.GetDiscordClientId(), new DiscordHandler()); DiscordImage.OptionDefaultImage = @"track_ks_brands_hatch"; GameWrapper.Started += (sender, args) => args.StartProperties.SetAdditional(new GameDiscordPresence(args.StartProperties, args.Mode)); } // Reshade? var loadReShade = AppArguments.GetBool(AppFlag.ForceReshade); if (!loadReShade && string.Equals(AppArguments.Get(AppFlag.ForceReshade), "kn5only", StringComparison.OrdinalIgnoreCase)) { loadReShade = AppArguments.Values.Any(x => x.EndsWith(".kn5", StringComparison.OrdinalIgnoreCase)); } if (loadReShade) { var reshade = Path.Combine(MainExecutingFile.Directory, "dxgi.dll"); if (File.Exists(reshade)) { Kernel32.LoadLibrary(reshade); } } // Auto-show that thing InstallAdditionalContentDialog.Initialize(); // Let’s roll ShutdownMode = ShutdownMode.OnExplicitShutdown; new AppUi(this).Run(); }
private async Task <ArgumentHandleResult> ProcessUriRequestObsolete(string request) { string key, param; NameValueCollection query; { var splitted = request.Split(new[] { '/' }, 2); if (splitted.Length != 2) { return(ArgumentHandleResult.FailedShow); } key = splitted[0]; param = splitted[1]; var index = param.IndexOf('?'); if (index != -1) { query = HttpUtility.ParseQueryString(param.SubstringExt(index + 1)); param = param.Substring(0, index); } else { query = null; } } switch (key) { case "quickdrive": var preset = Convert.FromBase64String(param).ToUtf8String(); if (!QuickDrive.RunSerializedPreset(preset)) { NonfatalError.Notify(AppStrings.Common_CannotStartRace, AppStrings.Arguments_CannotStartRace_Commentary); return(ArgumentHandleResult.Failed); } break; case "race": var raceIni = Convert.FromBase64String(param).ToUtf8String(); await GameWrapper.StartAsync(new Game.StartProperties { PreparedConfig = IniFile.Parse(raceIni) }); break; case "open": case "install": var address = Convert.FromBase64String(param).ToUtf8String(); var path = await LoadRemoveFile(address, query?.Get(@"name")); if (string.IsNullOrWhiteSpace(path)) { return(ArgumentHandleResult.FailedShow); } try { if (!FileUtils.Exists(path)) { return(ArgumentHandleResult.FailedShow); } } catch (Exception) { return(ArgumentHandleResult.FailedShow); } return(await ProcessInputFile(path)); } return(ArgumentHandleResult.Successful); }
private static async Task MainAsync(Options options) { var sunAngle = MathUtils.Random(-70d, 70d); var seconds = Game.ConditionProperties.GetSeconds(sunAngle); var weather = WeatherManager.Instance.GetById(options.WeatherId); var track = options.TrackId.Split('/'); switch (options.Starter) { case Starter.Official: SettingsHolder.Drive.SelectedStarterType = SettingsHolder.Drive.StarterTypes.GetById("Official"); break; case Starter.Tricky: SettingsHolder.Drive.SelectedStarterType = SettingsHolder.Drive.StarterTypes.GetById("Tricky"); break; case Starter.UiModule: SettingsHolder.Drive.SelectedStarterType = SettingsHolder.Drive.StarterTypes.GetById("UI Module"); break; case Starter.Sse: PluginsManager.Initialize(options.PluginsDir); SettingsHolder.Drive.SelectedStarterType = SettingsHolder.Drive.StarterTypes.GetById("SSE"); break; default: throw new ArgumentOutOfRangeException(); } var result = await GameWrapper.StartAsync(new Game.StartProperties(new Game.BasicProperties { CarId = options.CarId, CarSkinId = options.CarSkinId, TrackId = track[0], TrackConfigurationId = track.ElementAtOrDefault(1), DriverName = options.DriverName }, GetAssistsProperties(options.Assist), new Game.ConditionProperties { AmbientTemperature = options.AmbientTemperature, CloudSpeed = 2d, SunAngle = sunAngle, RoadTemperature = Game.ConditionProperties.GetRoadTemperature(seconds, options.AmbientTemperature, weather.TemperatureCoefficient), TimeMultipler = 1d, WeatherName = weather.Id }, Game.DefaultTrackPropertiesPresets.First().Properties, GetModeProperties(options))); if (result == null) { Console.WriteLine("Race cancelled"); return; } switch (options.Mode) { case Mode.Practice: return; case Mode.HotLap: var bestLap = result.GetExtraByType <Game.ResultExtraBestLap>()?.Time; if (bestLap.HasValue) { Console.WriteLine(bestLap); } else { Console.WriteLine("Time has not been set"); } return; case Mode.Race: var position = result.Sessions.LastOrDefault(x => x.BestLaps.Any())?.CarPerTakenPlace?.IndexOf(0); if (position.HasValue) { Console.WriteLine(position); } else { Console.WriteLine("Position has not been taken"); } return; case Mode.Drift: var points = result.GetExtraByType <Game.ResultExtraDrift>()?.Points; if (points.HasValue) { Console.WriteLine(points); } else { Console.WriteLine("Score has not been set"); } return; default: throw new ArgumentOutOfRangeException(); } }
void IGameUi.OnResult(Game.Result result, ReplayHelper replayHelper) { if (result != null && result.NumberOfSessions == 1 && result.Sessions.Length == 1 && result.Sessions[0].Type == Game.SessionType.Practice && SettingsHolder.Drive.SkipPracticeResults || _properties?.ReplayProperties != null || _properties?.BenchmarkProperties != null) { Close(); return; } /* save replay button * / * Func<string> buttonText = () => replayHelper?.IsReplayRenamed == true ? * AppStrings.RaceResult_UnsaveReplay : AppStrings.RaceResult_SaveReplay; * * var saveReplayButton = CreateExtraDialogButton(buttonText(), () => { * if (replayHelper == null) { * Logging.Warning("ReplayHelper=<NULL>"); * return; * } * * replayHelper.IsReplayRenamed = !replayHelper.IsReplayRenamed; * }); * * if (replayHelper == null) { * saveReplayButton.IsEnabled = false; * } else { * replayHelper.PropertyChanged += (sender, args) => { * if (args.PropertyName == nameof(ReplayHelper.IsReplayRenamed)) { * saveReplayButton.Content = buttonText(); * } * }; * } * * /* save replay alt button */ ButtonWithComboBox saveReplayButton; if (replayHelper != null) { Func <string> buttonText = () => replayHelper.IsRenamed ? AppStrings.RaceResult_UnsaveReplay : AppStrings.RaceResult_SaveReplay; Func <string> saveAsText = () => string.Format(replayHelper.IsRenamed ? "Saved as “{0}”" : "Save as “{0}”", replayHelper.Name); saveReplayButton = new ButtonWithComboBox { Margin = new Thickness(4, 0, 0, 0), MinHeight = 21, MinWidth = 65, Content = ToolsStrings.Shared_Replay, Command = new AsyncCommand(replayHelper.Play), MenuItems = { new MenuItem { Header = saveAsText(), Command = new DelegateCommand(() =>{ var newName = Prompt.Show("Save replay as:", "Replay Name", replayHelper.Name, "?", required: true); if (!string.IsNullOrWhiteSpace(newName)) { replayHelper.Name = newName; } replayHelper.IsRenamed = true; }) }, new MenuItem { Header = buttonText(), Command = new DelegateCommand(replayHelper.Rename) }, new Separator(), new MenuItem { Header = "Share Replay", Command = new AsyncCommand(() =>{ var car = _properties?.BasicProperties?.CarId == null ? null : CarsManager.Instance.GetById(_properties.BasicProperties.CarId); var track = _properties?.BasicProperties?.TrackId == null ? null : TracksManager.Instance.GetById(_properties.BasicProperties.TrackId); return(SelectedReplayPage.ShareReplay(replayHelper.Name, replayHelper.Filename, car, track)); }) }, } }; replayHelper.PropertyChanged += (sender, args) => { if (args.PropertyName == nameof(ReplayHelper.IsRenamed)) { ((MenuItem)saveReplayButton.MenuItems[0]).Header = saveAsText(); ((MenuItem)saveReplayButton.MenuItems[1]).Header = buttonText(); } }; } else { saveReplayButton = null; } var tryAgainButton = CreateExtraDialogButton(AppStrings.RaceResult_TryAgain, () => { CloseWithResult(MessageBoxResult.None); GameWrapper.StartAsync(_properties).Forget(); }); Button fixButton = null; if (result == null || !result.IsNotCancelled) { Model.CurrentState = ViewModel.State.Cancelled; var whatsGoingOn = _properties?.GetAdditional <WhatsGoingOn>(); fixButton = this.CreateFixItButton(whatsGoingOn?.Solution); Model.ErrorMessage = whatsGoingOn?.GetDescription(); } else { try { Model.CurrentState = ViewModel.State.Finished; Model.FinishedData = GetFinishedData(_properties, result); } catch (Exception e) { Logging.Warning(e); Model.CurrentState = ViewModel.State.Error; Model.ErrorMessage = AppStrings.RaceResult_ResultProcessingError; Buttons = new[] { CloseButton }; return; } } Buttons = new[] { fixButton, fixButton == null ? saveReplayButton : null, fixButton == null ? tryAgainButton : null, CloseButton }; }
public ScoreBoard(GameWrapper i_Game) : base(i_Game) { m_ScoreLabels = new List<ScoreLabel>(); Position = new Vector2(15, 15); }
protected Task StartAsync(Game.StartProperties properties) { return(GameWrapper.StartAsync(properties)); }
public SingleActionMenuItem(string i_Text, GameWrapper i_Game) : base(i_Text, i_Game) { }
public LivesDisplay(GameWrapper i_Game) : base(i_Game) { m_Players = new List<PlayerShip>(); }
public ScreenOptionsScreen(GameWrapper i_Game) : base(i_Game) { m_FullScreen = false; }
private static async Task <ArgumentHandleResult> ProcessRaceOnline(NameValueCollection p) { // Required arguments var ip = p.Get(@"ip"); var port = FlexibleParser.TryParseInt(p.Get(@"port")); var httpPort = FlexibleParser.TryParseInt(p.Get(@"httpPort")); var carId = p.Get(@"car"); // Optional arguments var allowWithoutSteamId = p.GetFlag("allowWithoutSteamId"); var carSkinId = p.Get(@"skin"); var trackId = p.Get(@"track"); var name = p.Get(@"name"); var nationality = p.Get(@"nationality"); var password = p.Get(@"plainPassword"); var encryptedPassword = p.Get(@"password"); if (string.IsNullOrWhiteSpace(ip)) { throw new InformativeException("IP is missing"); } if (!port.HasValue) { throw new InformativeException("Port is missing or is in invalid format"); } if (!httpPort.HasValue) { throw new InformativeException("HTTP port is missing or is in invalid format"); } if (string.IsNullOrWhiteSpace(password) && !string.IsNullOrWhiteSpace(encryptedPassword)) { password = OnlineServer.DecryptSharedPassword(ip, httpPort.Value, encryptedPassword); } if (string.IsNullOrWhiteSpace(carId)) { throw new InformativeException("Car ID is missing"); } var car = CarsManager.Instance.GetById(carId); if (car == null) { throw new InformativeException("Car is missing"); } if (!string.IsNullOrWhiteSpace(carSkinId) && car.GetSkinById(carSkinId) == null) { throw new InformativeException("Car skin is missing"); } var track = string.IsNullOrWhiteSpace(trackId) ? null : TracksManager.Instance.GetLayoutByKunosId(trackId); if (!string.IsNullOrWhiteSpace(trackId) && track == null) { throw new InformativeException("Track is missing"); } if (!SteamIdHelper.Instance.IsReady && !allowWithoutSteamId) { throw new InformativeException(ToolsStrings.Common_SteamIdIsMissing); } await GameWrapper.StartAsync(new Game.StartProperties { BasicProperties = new Game.BasicProperties { CarId = carId, TrackId = track?.MainTrackObject.Id ?? @"imola", TrackConfigurationId = track?.LayoutId, CarSkinId = carSkinId, DriverName = name, DriverNationality = nationality }, ModeProperties = new Game.OnlineProperties { Guid = SteamIdHelper.Instance.Value, ServerIp = ip, ServerPort = port.Value, ServerHttpPort = httpPort.Value, Password = password, RequestedCar = carId } }); return(ArgumentHandleResult.Successful); }
public override void initController(Action <string> printFunc, Action <object, int, short> sendMsgFunc, Action shutdownGameServer, GameWrapper wrapper, List <string> preGamePlayers) { daGame.init(printFunc, sendMsgFunc, shutdownGameServer, wrapper, preGamePlayers); }
public ToggleValueMenuItem(string i_ValueLabel, string i_DefaultValue, GameWrapper i_Game) : base(i_ValueLabel, i_Game) { m_ValueLabel = i_ValueLabel; Value = i_DefaultValue; }
public async Task <bool> Go() { if (EventId == null) { return(false); } try { var app = PythonAppsManager.Instance.GetById(RsrMark.AppId); if (app == null) { throw new InformativeException(AppStrings.Rsr_AppIsMissing, AppStrings.Rsr_AppIsMissing_Commentary); } if (!app.Enabled) { app.ToggleCommand.Execute(null); await Task.Delay(500); } if (!app.Enabled) { throw new InformativeException(AppStrings.Rsr_AppIsDisabled, AppStrings.Rsr_AppIsDisabled_Commentary); } var ids = await LoadData(); if (ids == null) { throw new InformativeException(AppStrings.Rsr_InvalidParameters, AppStrings.Rsr_InvalidParameters_Commentary); } if (Car == null) { throw new InformativeException(string.Format(ToolsStrings.AcError_CarIsMissing, ids.Item1), AppStrings.Rsr_ContentIsMissing_Commentary); } if (Track == null) { throw new InformativeException(string.Format(ToolsStrings.AcError_TrackIsMissing, ids.Item2), AppStrings.Rsr_ContentIsMissing_Commentary); } await GameWrapper.StartAsync(new Game.StartProperties { BasicProperties = new Game.BasicProperties { CarId = Car.Id, TrackId = Track.Id, TrackConfigurationId = Track.LayoutId, CarSkinId = CarSkin?.Id, }, AssistsProperties = Assists.ToGameProperties(), ConditionProperties = new Game.ConditionProperties { AmbientTemperature = 26d, RoadTemperature = 32d, CloudSpeed = 1d, SunAngle = 0, TimeMultipler = 1d, WeatherName = WeatherManager.Instance.GetDefault()?.Id }, TrackProperties = Game.GetDefaultTrackPropertiesPreset().Properties, ModeProperties = new Game.HotlapProperties { SessionName = AppStrings.Rsr_SessionName, Penalties = true, GhostCar = GhostCar, GhostCarAdvantage = 0d }, AdditionalPropertieses = { new RsrMark() } }); return(true); } catch (Exception e) { NonfatalError.Notify(AppStrings.Common_CannotStartRace, e); return(false); } }
private async Task Join(object o) { var carEntry = SelectedCarEntry; if (carEntry == null || Cars == null) { return; } var correctId = GetCorrectId(carEntry.Id); if (correctId == null) { Logging.Error("Can’t find correct ID"); return; } if (!IsBookedForPlayer && BookingMode && !ReferenceEquals(o, ActualJoin) && !ReferenceEquals(o, ForceJoin)) { if (_factory == null) { Logging.Error("Booking: UI factory is missing"); return; } PrepareBookingUi(); ProcessBookingResponse(await Task.Run(() => KunosApiProvider.TryToBook(Ip, PortHttp, Password, correctId, carEntry.AvailableSkin?.Id, DriverName.GetOnline(), ""))); return; } DisposeHelper.Dispose(ref _ui); IsBooked = false; BookingErrorMessage = null; var properties = new Game.StartProperties(new Game.BasicProperties { CarId = carEntry.Id, CarSkinId = carEntry.AvailableSkin?.Id, TrackId = Track?.Id, TrackConfigurationId = Track?.LayoutId }, null, null, null, new Game.OnlineProperties { RequestedCar = correctId, ServerIp = Ip, ServerName = DisplayName, ServerPort = PortRace, ServerHttpPort = PortHttp, Guid = SteamIdHelper.Instance.Value, Password = Password }); var now = DateTime.Now; await GameWrapper.StartAsync(properties); var whatsGoingOn = properties.GetAdditional <WhatsGoingOn>(); WrongPassword = whatsGoingOn?.Type == WhatsGoingOnType.OnlineWrongPassword; if (whatsGoingOn == null) { LastConnected = now; FileBasedOnlineSources.AddRecent(this).Forget(); UpdateStats(); } }
public MainMenuScreen(GameWrapper i_Game) : base(i_Game) { }
public MothershipManager(GameWrapper i_Game) { m_Game = i_Game; }
public MenuScreen(GameWrapper i_Game) : base(i_Game) { m_Menu = new Menu.Menu(i_Game); this.Add(m_Menu); }
public SpriteFontManager(GameWrapper i_Game) : base(i_Game) { m_IsSpriteFont = true; m_Text = string.Empty; }
private App() { AppArguments.Set(AppFlag.SyncNavigation, ref ModernFrame.OptionUseSyncNavigation); AppArguments.Set(AppFlag.DisableTransitionAnimation, ref ModernFrame.OptionDisableTransitionAnimation); AppArguments.Set(AppFlag.RecentlyClosedQueueSize, ref LinkGroupFilterable.OptionRecentlyClosedQueueSize); AppArguments.Set(AppFlag.ForceSteamId, ref SteamIdHelper.OptionForceValue); AppArguments.Set(AppFlag.NoProxy, ref KunosApiProvider.OptionNoProxy); var proxy = AppArguments.Get(AppFlag.Proxy); if (!string.IsNullOrWhiteSpace(proxy)) { try { var s = proxy.Split(':'); WebRequest.DefaultWebProxy = new WebProxy(s[0], FlexibleParser.ParseInt(s.ElementAtOrDefault(1), 1080)); } catch (Exception e) { Logging.Error(e); } } // TODO: AppArguments.Set(AppFlag.ScanPingTimeout, ref RecentManagerOld.OptionScanPingTimeout); AppArguments.Set(AppFlag.LanSocketTimeout, ref KunosApiProvider.OptionLanSocketTimeout); AppArguments.Set(AppFlag.LanPollTimeout, ref KunosApiProvider.OptionLanPollTimeout); AppArguments.Set(AppFlag.WebRequestTimeout, ref KunosApiProvider.OptionWebRequestTimeout); AppArguments.Set(AppFlag.DirectRequestTimeout, ref KunosApiProvider.OptionDirectRequestTimeout); AppArguments.Set(AppFlag.CommandTimeout, ref GameCommandExecutorBase.OptionCommandTimeout); AppArguments.Set(AppFlag.DisableAcRootChecking, ref AcRootDirectory.OptionDisableChecking); AppArguments.Set(AppFlag.AcObjectsLoadingConcurrency, ref BaseAcManagerNew.OptionAcObjectsLoadingConcurrency); AppArguments.Set(AppFlag.SkinsLoadingConcurrency, ref CarObject.OptionSkinsLoadingConcurrency); AppArguments.Set(AppFlag.KunosCareerIgnoreSkippedEvents, ref KunosCareerEventsManager.OptionIgnoreSkippedEvents); AppArguments.Set(AppFlag.IgnoreMissingSkinsInKunosEvents, ref KunosEventObjectBase.OptionIgnoreMissingSkins); AppArguments.Set(AppFlag.ForceToastFallbackMode, ref Toast.OptionFallbackMode); AppArguments.Set(AppFlag.SmartPresetsChangedHandling, ref UserPresetsControl.OptionSmartChangedHandling); AppArguments.Set(AppFlag.EnableRaceIniRestoration, ref Game.OptionEnableRaceIniRestoration); AppArguments.Set(AppFlag.EnableRaceIniTestMode, ref Game.OptionRaceIniTestMode); AppArguments.Set(AppFlag.RaceOutDebug, ref Game.OptionDebugMode); AppArguments.Set(AppFlag.LiteStartupModeSupported, ref Pages.Windows.MainWindow.OptionLiteModeSupported); AppArguments.Set(AppFlag.NfsPorscheTribute, ref RaceGridViewModel.OptionNfsPorscheNames); AppArguments.Set(AppFlag.KeepIniComments, ref IniFile.OptionKeepComments); AppArguments.Set(AppFlag.AutoConnectPeriod, ref OnlineServer.OptionAutoConnectPeriod); LimitedSpace.Initialize(); LimitedStorage.Initialize(); DataProvider.Initialize(); CountryIdToImageConverter.Initialize( FilesStorage.Instance.GetDirectory(FilesStorage.DataDirName, ContentCategory.CountryFlags), FilesStorage.Instance.GetDirectory(FilesStorage.DataUserDirName, ContentCategory.CountryFlags)); FilesStorage.Instance.Watcher(ContentCategory.CountryFlags).Update += (sender, args) => { CountryIdToImageConverter.ResetCache(); }; TestKey(); AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; if (!AppArguments.GetBool(AppFlag.PreventDisableWebBrowserEmulationMode) && ( ValuesStorage.GetInt(WebBrowserEmulationModeDisabledKey) < WebBrowserHelper.EmulationModeDisablingVersion || AppArguments.GetBool(AppFlag.ForceDisableWebBrowserEmulationMode))) { try { WebBrowserHelper.DisableBrowserEmulationMode(); ValuesStorage.Set(WebBrowserEmulationModeDisabledKey, WebBrowserHelper.EmulationModeDisablingVersion); } catch (Exception e) { Logging.Warning("Can’t disable emulation mode: " + e); } } JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.None, NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Include, Culture = CultureInfo.InvariantCulture }; AcToolsLogging.Logger = (s, m, p, l) => Logging.Write($"{s} (AcTools)", m, p, l); var ignoreControls = AppArguments.Get(AppFlag.IgnoreControls); if (!string.IsNullOrWhiteSpace(ignoreControls)) { ControlsSettings.OptionIgnoreControlsFilter = Filter.Create(new StringTester(), ignoreControls); } var sseStart = AppArguments.Get(AppFlag.SseName); if (!string.IsNullOrWhiteSpace(sseStart)) { SseStarter.OptionStartName = sseStart; } FancyBackgroundManager.Initialize(); DpiAwareWindow.OptionScale = AppArguments.GetDouble(AppFlag.UiScale, 1d); if (!AppKeyHolder.IsAllRight) { AppAppearanceManager.OptionCustomThemes = false; } else { AppArguments.Set(AppFlag.CustomThemes, ref AppAppearanceManager.OptionCustomThemes); } AppAppearanceManager.OptionIdealFormattingModeDefaultValue = AppArguments.GetBool(AppFlag.IdealFormattingMode, !Equals(DpiAwareWindow.OptionScale, 1d)); AppAppearanceManager.Initialize(); AcObjectsUriManager.Register(new UriProvider()); { var uiFactory = new GameWrapperUiFactory(); GameWrapper.RegisterFactory(uiFactory); ServerEntry.RegisterFactory(uiFactory); } GameWrapper.RegisterFactory(new DefaultAssistsFactory()); LapTimesManager.Instance.SetListener(); AcError.RegisterFixer(new AcErrorFixer()); AcError.RegisterSolutionsFactory(new SolutionsFactory()); InitializePresets(); SharingHelper.Initialize(); SharingUiHelper.Initialize(); { var addonsDir = FilesStorage.Instance.GetFilename("Addons"); var pluginsDir = FilesStorage.Instance.GetFilename("Plugins"); if (Directory.Exists(addonsDir) && !Directory.Exists(pluginsDir)) { Directory.Move(addonsDir, pluginsDir); } else { pluginsDir = FilesStorage.Instance.GetDirectory("Plugins"); } PluginsManager.Initialize(pluginsDir); PluginsWrappers.Initialize( new MagickPluginWrapper(), new AwesomiumPluginWrapper(), new CefSharpPluginWrapper(), new StarterPlus()); } { var onlineMainListFile = FilesStorage.Instance.GetFilename("Online Servers", "Main List.txt"); var onlineFavouritesFile = FilesStorage.Instance.GetFilename("Online Servers", "Favourites.txt"); if (File.Exists(onlineMainListFile) && !File.Exists(onlineFavouritesFile)) { Directory.Move(onlineMainListFile, onlineFavouritesFile); } } SteamIdHelper.Initialize(AppArguments.Get(AppFlag.ForceSteamId)); Superintendent.Initialize(); AppArguments.Set(AppFlag.OfflineMode, ref AppKeyDialog.OptionOfflineMode); PrepareUi(); AppIconService.Initialize(this); Toast.SetDefaultAction(() => (Current.Windows.OfType <ModernWindow>().FirstOrDefault(x => x.IsActive) ?? Current.MainWindow as ModernWindow)?.BringToFront()); BbCodeBlock.ImageClicked += BbCodeBlock_ImageClicked; BbCodeBlock.OptionEmojiProvider = InternalUtils.GetEmojiProvider(); BbCodeBlock.OptionImageCacheDirectory = FilesStorage.Instance.GetTemporaryFilename("Images"); BbCodeBlock.OptionEmojiCacheDirectory = FilesStorage.Instance.GetTemporaryFilename("Emoji"); AppArguments.SetSize(AppFlag.ImagesCacheLimit, ref BetterImage.OptionCacheTotalSize); AppArguments.Set(AppFlag.ImagesMarkCached, ref BetterImage.OptionMarkCached); AppArguments.Set(AppFlag.UseVlcForAnimatedBackground, ref DynamicBackground.OptionUseVlc); Filter.OptionSimpleMatching = SettingsHolder.Content.SimpleFiltering; StartupUri = new Uri(!Superintendent.Instance.IsReady || AcRootDirectorySelector.IsReviewNeeded() ? @"Pages/Dialogs/AcRootDirectorySelector.xaml" : @"Pages/Windows/MainWindow.xaml", UriKind.Relative); InitializeUpdatableStuff(); BackgroundInitialization(); FatalErrorMessage.Register(this); ImageUtils.SafeMagickWrapper = fn => { try { return(fn()); } catch (OutOfMemoryException e) { NonfatalError.Notify(ToolsStrings.MagickNet_CannotLoad, ToolsStrings.MagickNet_CannotLoad_Commentary, e); } catch (Exception e) { NonfatalError.Notify(ToolsStrings.MagickNet_CannotLoad, e); } return(null); }; AbstractDataFile.ErrorsCatcher = new DataSyntaxErrorCatcher(); AppArguments.Set(AppFlag.SharedMemoryLiveReadingInterval, ref AcSharedMemory.OptionLiveReadingInterval); AcSharedMemory.Initialize(); AppArguments.Set(AppFlag.RunRaceInformationWebserver, ref PlayerStatsManager.OptionRunStatsWebserver); AppArguments.Set(AppFlag.RaceInformationWebserverFile, ref PlayerStatsManager.OptionWebserverFilename); PlayerStatsManager.Instance.SetListener(); AppArguments.Set(AppFlag.RhmKeepAlive, ref RhmService.OptionKeepRunning); RhmService.Instance.SetListener(); _hibernator = new AppHibernator(); _hibernator.SetListener(); AppArguments.Set(AppFlag.TrackMapGeneratorMaxSize, ref TrackMapRenderer.OptionMaxSize); CommonFixes.Initialize(); // TODO: rearrange code! CmPreviewsSettings.SelectCarDialog = SelectCarDialog.Show; CmPreviewsTools.MissingShowroomHelper = new CarUpdatePreviewsDialog.MissingShowroomHelper(); }