public override void CounterInit() { try { _logger.Debug("Attempting to Initialize FPS Counter"); _targetFramerate = (int)XRDevice.refreshRate; _logger.Debug($"Target framerate = {_targetFramerate}"); _counterText = CanvasUtility.CreateTextFromSettings(Settings); _counterText.color = Color.white; _counterText.fontSize = 2.5f; _counterText.lineSpacing = -50f; if (!_config.ShowRing) { return; } var canvas = CanvasUtility.GetCanvasFromID(Settings.CanvasID); if (canvas == null) { return; } _ringImage = _fpsCounterUtils.CreateRing(canvas); _ringImage.rectTransform.anchoredPosition = _counterText.rectTransform.anchoredPosition; _ringImage.transform.localScale = _ringSize / 10; } catch (Exception ex) { _logger.Error("FPS Counter Done"); _logger.Error(ex); } }
public async void Initialize() { if (_config.EnabledIntroSounds.Count > 0 && !_didPlay) { _didPlay = true; var ourLuckyIntro = _config.EnabledIntroSounds[_random.Next(0, _config.EnabledIntroSounds.Count)]; try { Stopwatch stopwatch = Stopwatch.StartNew(); _siraLog.Debug($"Loading {ourLuckyIntro.FullName}"); AudioClip audioClip = await _audioClipAsyncLoader.LoadAudioClipAsync(ourLuckyIntro.FullName, _cancellationTokenSource.Token); stopwatch.Stop(); _siraLog.Debug($"Finished Loading Intro in {stopwatch.Elapsed} seconds"); await SiraUtil.Utilities.AwaitSleep(1000); _audioSourcer.clip = audioClip; _audioSourcer.Play(); await SiraUtil.Utilities.AwaitSleep((int)(audioClip.length * 1000)); if (_audioSourcer.clip == audioClip) { _audioSourcer.clip = null; } } catch (Exception e) { _siraLog.Error(e.Message); _config.EnabledIntroSounds.Remove(ourLuckyIntro); } } }
internal async Task <Beatmap> Vote(Beatmap beatmap, bool upvote, CancellationToken token) { try { bool steam = false; if (_platformUserModel is SteamPlatformUserModel) { steam = true; } else if (!(_platformUserModel is OculusPlatformUserModel)) { _siraLog.Debug("Current platform cannot vote."); return(beatmap); } var info = await _platformUserModel.GetUserInfo(); var authToken = await _platformUserModel.GetUserAuthToken(); var ticket = authToken.token; _siraLog.Debug("Starting Vote..."); if (steam) { ticket = ticket.Replace("-", ""); } else { ticket = authToken.token; } var response = await beatmap.LatestVersion.Vote(upvote?BeatSaverSharp.Models.Vote.Type.Upvote : BeatSaverSharp.Models.Vote.Type.Downvote, steam?BeatSaverSharp.Models.Vote.Platform.Steam : BeatSaverSharp.Models.Vote.Platform.Oculus, info.platformUserId, ticket, token); _siraLog.Info(response.Successful); _siraLog.Info(response.Error ?? "good"); if (response.Successful) { await beatmap.Refresh(); } _siraLog.Debug($"Voted. Upvote? ({upvote})"); } catch (Exception e) { _siraLog.Error(e.Message); } return(beatmap); }
public override void InstallBindings() { if ((!_gameplayCoreSceneSetupData?.playerSpecificSettings.noTextsAndHuds ?? false) && !Container.Resolve <PluginUtils>().IsCountersPlusPresent) { _logger.Debug($"Binding {nameof(FPSCounter)}"); Container.BindInterfacesAndSelfTo <FpsCounter>().AsSingle().NonLazy(); _logger.Debug($"Finished binding {nameof(FPSCounter)}"); } else { _logger.Debug($"Either Counters+ is present or No Text and HUD enabled in PlayerSettings - Not constructing FpsCounter"); } }
/// <summary> /// Reads all saved platform descriptors from the cache file /// </summary> private IEnumerable <CustomPlatform> EnumeratePlatformDescriptorsFromFile() { using FileStream stream = new(_cacheFilePath, FileMode.Open, FileAccess.Read); using BinaryReader reader = new(stream, Encoding.UTF8); if (reader.ReadByte() != kCacheFileVersion) { yield break; } int count = reader.ReadInt32(); for (int i = 0; i < count; i++) { CustomPlatform platform = new GameObject().AddComponent <CustomPlatform>(); platform.platName = reader.ReadString(); platform.platAuthor = reader.ReadString(); platform.platHash = reader.ReadString(); platform.fullPath = reader.ReadString(); platform.icon = reader.ReadNullableSprite(); if (!File.Exists(platform.fullPath)) { _siraLog.Debug($"File {platform.fullPath} no longer exists; skipped"); Object.Destroy(platform.gameObject); continue; } platform.name = $"{platform.platName} by {platform.platAuthor}"; platform.transform.SetParent(_anchor); LastSelectedPlatform(platform); yield return(platform); } }
/// <summary> /// Changes to a specific <see cref="CustomPlatform"/> /// </summary> /// <param name="platform">The <see cref="CustomPlatform"/> to change to</param> public async Task ChangeToPlatformAsync(CustomPlatform platform) { if (platform == _platformManager.ActivePlatform) { return; } _cancellationTokenSource?.Cancel(); _cancellationTokenSource?.Dispose(); _cancellationTokenSource = new CancellationTokenSource(); CancellationToken token = _cancellationTokenSource.Token; DestroyPlatform(_platformManager.ActivePlatform.gameObject); if (platform == _platformManager.RandomPlatform) { platform = RandomPlatform; } _platformManager.ActivePlatform = platform; if (platform.isDescriptor) { platform = await ReplaceDescriptorAsync(platform); } if (token.IsCancellationRequested) { return; } _platformManager.ActivePlatform = platform; _siraLog.Debug($"Switching to {platform.name}"); _environmentHider.HideObjectsForPlatform(platform); SpawnPlatform(platform.gameObject); }
public void Init(SaberType type, VRControllersInputManager vrControllersInputManager) { OVRInput.Controller oculusController; XRNode node; if (type == SaberType.SaberA) { oculusController = OVRInput.Controller.LTouch; node = XRNode.LeftHand; } else { oculusController = OVRInput.Controller.RTouch; node = XRNode.RightHand; } var controllerInputDevice = InputDevices.GetDeviceAtXRNode(node); var vrSystem = OVRInput.IsControllerConnected(oculusController) ? VRSystem.Oculus : VRSystem.SteamVR; var dir = _config.ThumstickDirection; var triggerHandler = new TriggerHandler(node, _config.TriggerThreshold, _config.ReverseTrigger); var gripHandler = new GripHandler(vrSystem, oculusController, controllerInputDevice, _config.GripThreshold, _config.ReverseGrip); var thumbstickAction = new ThumbstickHandler(node, _config.ThumbstickThreshold, dir, _config.ReverseThumbstick); _trickInputHandler.Add(_config.TriggerAction, triggerHandler); _trickInputHandler.Add(_config.GripAction, gripHandler); _trickInputHandler.Add(_config.ThumbstickAction, thumbstickAction); _logger.Debug("Started Input Manager using " + vrSystem); }
public void Initialize() { siraLog.Debug("Initializing Presence Controller"); if (didInstantiateUserManagerProperly) { userManager.OnCurrentUserUpdate += CurrentUserUpdated; } }
public void Initialize() { try { _logger.Debug("Attempting to Initialize FPS Counter"); _targetFramerate = (int)XRDevice.refreshRate; _logger.Debug($"Target framerate = {_targetFramerate}"); var gameObject = new GameObject("FPS Counter"); var canvas = gameObject.AddComponent <Canvas>(); canvas.renderMode = RenderMode.WorldSpace; gameObject.transform.localScale = Vector3.one / 10; gameObject.transform.position = new Vector3(0, 3.5f, 8f); gameObject.transform.rotation = Quaternion.identity; gameObject.AddComponent <CurvedCanvasSettings>().SetRadius(0f); var canvasTransform = canvas.transform as RectTransform; _counter = BeatSaberUI.CreateText(canvasTransform, string.Empty, Vector3.zero); _counter.alignment = TextAlignmentOptions.Center; _counter.fontSize = 2.5f; _counter.color = Color.white; _counter.lineSpacing = -50f; _counter.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 2f); _counter.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 2f); _counter.enableWordWrapping = false; _counter.overflowMode = TextOverflowModes.Overflow; if (!_config.ShowRing) { return; } _image = _fpsCounterUtils.CreateRing(canvas); var imageTransform = _image.rectTransform; imageTransform.anchoredPosition = _counter.rectTransform.anchoredPosition; imageTransform.localScale *= 0.1f; } catch (Exception ex) { _logger.Error("FPS Counter Done"); _logger.Error(ex); } }
private async Task Init() { _siraLog.Debug("Loading music."); var badMusic = new List <FileInfo>(); var stopwatch = Stopwatch.StartNew(); var loadedCustoms = new List <AudioContainer>(); foreach (var musicPath in _config.EnabledMusicFiles) { if (!musicPath.Exists || musicPath.Extension != ".ogg") { badMusic.Add(musicPath); continue; } try { _siraLog.Debug($"Loading {musicPath.FullName}"); AudioClip audioClip = await _cachedMediaAsyncLoader.LoadAudioClipAsync(musicPath.FullName, _cancellationTokenSource.Token); var name = musicPath.Name.Remove(musicPath.Name.IndexOf(musicPath.Extension)); var maybeImage = musicPath.Directory.EnumerateFiles().FirstOrDefault(ef => ef.Name.Remove(ef.Name.IndexOf(ef.Extension)) == name && (ef.Extension == ".png" || ef.Extension == ".jpg")); Texture2D?texHolder = null; if (maybeImage != null && maybeImage.Exists) { texHolder = (await _cachedMediaAsyncLoader.LoadSpriteAsync(maybeImage !.FullName, _cancellationTokenSource.Token)).texture; } loadedCustoms.Add(new AudioContainer(name, audioClip, texHolder)); } catch (Exception e) { _siraLog.Error(e.Message); badMusic.Add(musicPath); } } foreach (var bad in badMusic) { // If any of the music files failed to load or do not exist, remove them. _config.EnabledMusicFiles.Remove(bad); } stopwatch.Stop(); _siraLog.Debug($"Finished Loading Music in {stopwatch.Elapsed} seconds"); _randomObjectPicker = new RandomObjectPicker <AudioContainer>(loadedCustoms.ToArray(), 0.07f); Loaded?.Invoke(); }
public async void Init(GlobalTrickManager globalTrickManager) { _globalTrickManager = globalTrickManager; _logger.Debug($"Instantiated on {gameObject.name}"); if (!_vrController) { _logger.Error("Controller not present"); Cleanup(); return; } if (IsLeftSaber) { _globalTrickManager.LeftSaberTrickManager = this; } else { _globalTrickManager.RightSaberTrickManager = this; } _movementController.Init(_vrController, this); _inputManager.Init(_saber.saberType, _vrController.GetField <VRControllersInputManager, VRController>("_vrControllersInputManager")); _inputManager.TrickActivated += OnTrickActivated; _inputManager.TrickDeactivated += OnTrickDeactivated; var success = await SaberTrickModel.Init(_saber); if (success) { _logger.Info($"Got saber model"); } else { _logger.Error("Couldn't get saber model"); Cleanup(); return; } _movementController.enabled = true; AddTrick <SpinTrick>(); AddTrick <ThrowTrick>(); _logger.Info($"{Tricks.Count} tricks initialized"); if (_pauseController) { _pauseController.didResumeEvent += EndAllTricks; } _logger.Info("Trick Manager initialized"); }
private void MainMenu_Activated(bool firstActivation, bool _, bool __) { if (firstActivation) { _siraLog.Debug("Menu Activating"); var mainView = _mainMenuViewController; var view = mainView as ViewController; var quitButton = Quit(ref mainView); var binder = Bind(ref view); _siraLog.Debug("Replacing Binder"); quitButton.onClick.RemoveAllListeners(); var list = BindingList(ref binder).ToList(); var quitBinding = list.First(b => b.Item1 == quitButton); list.Remove(quitBinding); binder.AddBinding(quitButton, LoadThenPlayOutroThenQuit); BindingList(ref binder) = list; } }
/// <summary> /// Loads all platforms or their descriptors if a cache file exists /// </summary> private async Task LoadPlatformsAsync(CancellationToken cancellationToken) { Stopwatch sw = Stopwatch.StartNew(); try { foreach (CustomPlatform platform in EnumeratePlatformDescriptorsFromFile()) { AllPlatforms.AddSorted(BuildInPlatformsCount, AllPlatforms.Count - BuildInPlatformsCount, platform); } } catch (Exception e) { _siraLog.Debug($"Failed to read cache file:\n{e}"); try { File.Delete(_cacheFilePath); } catch { /* Ignored */ } } // Load all remaining platforms, or all if no cache file is found foreach (string path in Directory.EnumerateFiles(DirectoryPath, "*.plat").Where(x => AllPlatforms.All(y => y.fullPath != x))) { if (cancellationToken.IsCancellationRequested) { return; } CustomPlatform?platform = await CreatePlatformAsync(path); if (platform is null) { continue; } AllPlatforms.AddSorted(BuildInPlatformsCount, AllPlatforms.Count - BuildInPlatformsCount, platform); } sw.Stop(); _siraLog.Debug($"Loaded {AllPlatforms.Count.ToString(NumberFormatInfo.InvariantInfo)} platforms in {sw.ElapsedMilliseconds.ToString(NumberFormatInfo.InvariantInfo)}ms"); }
private void OnDescriptionLinkPressed(string url, string title) { siraLog.Debug($"Link to {url} ({title}) has been clicked"); OpenLink(url, title); }
public void Initialize() { _siraLog.Debug("Initializing Presence Controller"); _userManager.OnCurrentUserUpdate += CurrentUserUpdated; }
public void QueueChange(PluginInformation plugin, string type, IEnumerable <string> lines, Action <bool> completion) { siraLog.Debug($"Change queued: {plugin.Plugin.Name} {type} {string.Join(",", lines)}"); changeQueue.Enqueue(new ChangeQueueItem(plugin, type, lines, completion)); TryProcessNextChange(); }
public void Initialize() { var is360Level = _beatmapData.spawnRotationEventsCount > 0; var pos = is360Level ? _config.Chart360LevelPosition : _config.ChartStandardLevelPosition; var rot = is360Level ? Quaternion.Euler(_config.Chart360LevelRotation) : Quaternion.Euler(_config.ChartStandardLevelRotation); _floatingScreen = FloatingScreen.CreateFloatingScreen(_config.ChartSize, false, pos, rot, curvatureRadius: 0f, hasBackground: _config.HasBackground); _floatingScreen.SetRootViewController(this, AnimationType.None); _floatingScreen.name = nameof(SongChartVisualizer); if (_config.HasBackground) { var imageView = _floatingScreen.GetComponentInChildren <ImageView>(); imageView.material = _assetLoader.UINoGlowMaterial; imageView.color = _config.CombinedBackgroundColor; transform.SetParent(imageView.transform); } if (_audioTimeSyncController.songLength < 0) { _shouldNotRunTick = true; return; } // _siraLog.Debug($"There are {_beatmapData.beatmapObjectsData.Count(x => x.beatmapObjectType == BeatmapObjectType.Note)} notes"); // _siraLog.Debug($"There are {_beatmapData.beatmapLinesData.Count} lines"); _npsSections = GetNpsSections(_beatmapData); #if DEBUG for (var i = 0; i < _npsSections.Count; i++) { var npsInfos = _npsSections[i]; _siraLog.Debug($"Nps at section {i + 1}: {npsInfos.Nps} (from [{npsInfos.FromTime}] to [{npsInfos.ToTime}])"); } #endif _siraLog.Debug("Loading assetbundle.."); var assembly = Assembly.GetExecutingAssembly(); using (var stream = assembly.GetManifestResourceStream("SongChartVisualizer.UI.linegraph")) { _assetBundle = AssetBundle.LoadFromStream(stream); } if (!_assetBundle) { _siraLog.Warn("Failed to load AssetBundle! The chart will not work properly.."); } else { var prefab = _assetBundle.LoadAsset <GameObject>("LineGraph"); var sprite = _assetBundle.LoadAsset <Sprite>("Circle"); var go = Instantiate(prefab, transform); go.transform.Translate(0.04f, 0, 0); _windowGraph = go.AddComponent <WindowGraph>(); _windowGraph.circleSprite = sprite; _windowGraph.transform.localScale /= 10; var npsValues = _npsSections.Select(info => info.Nps).ToList(); _windowGraph.ShowGraph(npsValues, false, linkColor: _config.LineColor); _currentSectionIdx = 0; _currentSection = _npsSections[_currentSectionIdx]; CreateSelfCursor(_config.PointerColor); if (_config.PeakWarning) { var highestValue = _npsSections.Max(info => info.Nps); _hardestSectionIdx = _npsSections.FindIndex(info => Math.Abs(info.Nps - highestValue) < 0.001f); PrepareWarningText(); FadeInTextIfNeeded(); } } }
private async Task Parse(StandardLevelDetailViewController standardLevelDetailViewController) { if (!_didParse) { var info = await _platformUserModel.GetUserInfo(); CanVote = true; _siraLog.Debug("Doing Initial BSML Parsing of the Detail View"); _siraLog.Debug("Getting Manifest Stream"); using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("DiTails.Views.detail-view.bsml")) using (var reader = new StreamReader(stream)) { _siraLog.Debug("Reading Manifest Stream"); _bsmlContent = await reader.ReadToEndAsync(); } if (!string.IsNullOrWhiteSpace(_bsmlContent)) { _siraLog.Debug("Parsing Details"); try { BSMLParser.instance.Parse(_bsmlContent, standardLevelDetailViewController.gameObject, this); } catch (Exception e) { _siraLog.Critical(e); } if (rootTransform != null && mainModalTransform != null) { rootTransform.gameObject.name = "DiTailsDetailView"; mainModalTransform.gameObject.name = "DiTailsMainModal"; } if (descriptionModalTransform != null && artworkModalTransform != null) { descriptionModalTransform.gameObject.name = "DiTailsDescriptionModal"; artworkModalTransform.gameObject.name = "DiTailsArtworkModal"; } if (panel1Transform != null && mainOkButton != null) { var buttons = panel1Transform.GetComponentsInChildren <UnityEngine.UI.Button>(true).ToList(); buttons.Add(mainOkButton); foreach (var button in buttons) { foreach (var image in button.GetComponentsInChildren <ImageView>(true)) { var view = image; IMAGESKEW(ref view) = 0f; image.SetVerticesDirty(); } foreach (var text in button.GetComponentsInChildren <TMP_Text>(true)) { text.alignment = TextAlignmentOptions.Center; if (text.fontStyle.HasFlag(FontStyles.Italic)) { text.fontStyle -= FontStyles.Italic; } } } } _siraLog.Debug("Parsing Complete"); _didParse = true; } } }