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); } }
private async Task <bool> LoadBundle() { var data = await Readers.ReadResourceAsync(BUNDLE_PATH); if (data == null) { _logger.Error($"Resource at {BUNDLE_PATH} doesn't exist"); return(false); } _assetBundle = await Readers.LoadAssetBundleAsync(data); if (_assetBundle == null) { _logger.Error("Couldn't load embedded AssetBundle"); return(false); } #if false foreach (var assetName in _assetBundle.GetAllAssetNames()) { var obj = _assetBundle.LoadAsset(assetName); Debug.LogWarning($"{assetName}: {obj.GetType().Name}"); } #endif return(true); }
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"); }
/// <summary> /// Reads all saved platform descriptors out of the cache file /// </summary> private void LoadPlatformInfosFromFile() { try { using FileStream stream = new FileStream(customPlatformsInfoCacheFilePath, FileMode.Open, FileAccess.Read); using BinaryReader reader = new BinaryReader(stream, Encoding.UTF8); if (reader.ReadByte() != kCacheFileVersion) { return; } 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(); Texture2D tex = reader.ReadTexture2D(); int reqCount = reader.ReadInt32(); for (int j = 0; j < reqCount; j++) { platform.requirements.Add(reader.ReadString()); } int sugCount = reader.ReadInt32(); for (int j = 0; j < sugCount; j++) { platform.suggestions.Add(reader.ReadString()); } platform.icon = Sprite.Create(tex, new Rect(0f, 0f, tex.width, tex.height), Vector2.zero); platform.name = platform.platName + " by " + platform.platAuthor; platform.transform.parent = transform; if (!File.Exists(platform.fullPath)) { _siraLog.Info($"File {platform.fullPath} no longer exists; skipped"); continue; } CheckLastSelectedPlatform(ref platform); _platformLoader.platformFilePaths.Add(platform.fullPath, platform); allPlatforms.Add(platform); } } catch (Exception e) { _siraLog.Error("Failed to load cached platform info:\n" + e); } }
private async Task LoadThenPlayOutroThenQuitAsync() { if (!_config.OutroSoundsEnabled || _config.EnabledOutroSounds.Count == 0) { _siraLog.Debug("No Outro Audio Set. Quitting Immediately"); _fadeInOutController.FadeOutInstant(); Application.Quit(); return; } try { var outro = _config.EnabledOutroSounds[_random.Next(0, _config.EnabledOutroSounds.Count)]; _siraLog.Debug($"Loading {outro.FullName}"); var audioClip = await _audioClipAsyncLoader.LoadAudioClipAsync(outro.FullName, CancellationToken.None); _audioSourcer.clip = audioClip; _audioSourcer.Play(); _fadeInOutController.FadeOut(audioClip.length); await SiraUtil.Utilities.AwaitSleep((int)(audioClip.length * 1000)); if (_audioSourcer.clip == audioClip) { _audioSourcer.clip = null; } Application.Quit(); } catch (Exception e) { _siraLog.Error(e.Message); // If anything goes wrong, we do not want an SAO incident. Application.Quit(); } }
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); } } }
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); } }
/// <summary> /// Loads the platform's AssetBundle located at <param name="fullPath"></param><br/> /// If the loading process for this path is already started, the corresponding Task is awaited and the result returned /// </summary> /// <param name="fullPath">The path to the platform's AssetBundle</param> /// <returns>The loaded <see cref="CustomPlatform"/>, or null if an error occurs</returns> internal async Task <CustomPlatform?> LoadPlatformFromFileAsync(string fullPath) { if (!File.Exists(fullPath)) { _siraLog.Error($"File could not be found:\n{fullPath}"); return(null); } if (_pathTaskPairs.TryGetValue(fullPath, out Task <CustomPlatform?> task)) { return(await task); } task = LoadPlatformFromFileAsyncImpl(fullPath); _pathTaskPairs.Add(fullPath, task); CustomPlatform?platform = await task; _pathTaskPairs.Remove(fullPath); return(platform); }
public async Task FromJson(JObject obj, Serializer serializer) { try { await LeftSaber.FromJson((JObject)obj[nameof(LeftSaber)], serializer); await RightSaber.FromJson((JObject)obj[nameof(RightSaber)], serializer); } catch (Exception e) { _logger.Error("Saber loading error:\n" + e); throw; } }
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); }
protected override void DidActivate(bool firstActivation, bool addedToHierarchy, bool screenSystemEnabling) { try { if (firstActivation) { SetTitle(modName); showBackButton = true; SetViewControllersToNavigationController(navigationController, modListViewController, modInfoViewController); ProvideInitialViewControllers(navigationController); modalPopupViewController.SetData(navigationController.gameObject); } modListViewController.DidSelectPlugin += HandleSelectPlugin; modControlsViewController.OnListNeedsRefresh += HandleListNeedsRefresh; modControlsViewController.OnChangeNeedsConfirmation += modalPopupViewController.QueueChange; } catch (Exception ex) { siraLog.Error(ex); } modControlsViewController.PresentFloatingScreen(); }
private async Task <bool> CheckLoaded() { if (_assetBundle) { return(true); } var data = await Readers.ReadResourceAsync(BUNDLE_PATH); if (data == null) { _logger.Error($"Resource at {BUNDLE_PATH} doesn't exist"); return(false); } _assetBundle = await Readers.LoadAssetBundleAsync(data); if (_assetBundle == null) { _logger.Error("Couldn't load embedded AssetBundle"); return(false); } return(true); }
protected override void DidActivate(bool firstActivation, bool addedToHierarchy, bool screenSystemEnabling) { try { if (firstActivation) { SetTitle(Plugin.Name); showBackButton = true; ProvideInitialViewControllers(_configSelectorViewController); } } catch (Exception ex) { _siraLog.Error(ex); } }
private GameObject GetSaber(InjectContext ctx) { var saberManager = ctx.Container.Resolve <SaberManager>(); if (!saberManager) { _logger.Error("Couldn't resolve SaberManager"); return(null); } var saberType = (SaberType)ctx.Identifier; return(saberType == SaberType.SaberA ? saberManager.leftSaber.gameObject : saberManager.rightSaber.gameObject); }
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(); }
/// <summary> /// Handles when a song is selected, downloading a <see cref="CustomPlatform"/> from modelsaber if needed /// </summary> /// <param name="usePlatform">Wether the selected song requests a platform or not</param> /// <param name="name">The name of the requested platform</param> /// <param name="hash">The hash of the requested platform</param> /// <param name="level">The song the platform was requested for</param> /// <returns></returns> private IEnumerator <UnityWebRequestAsyncOperation> HandleSongSelected(bool usePlatform, string name, string hash, IPreviewBeatmapLevel level) { // No platform is requested, abort if (!usePlatform) { _platformManager.apiRequestIndex = -1; _platformManager.apiRequestedLevelId = null; yield break; } _platformManager.apiRequestedLevelId = level.levelID; // Test if the requested platform is already downloaded for (int i = 0; i < _platformManager.allPlatforms.Count; i++) { if (_platformManager.allPlatforms[i].platHash == hash || _platformManager.allPlatforms[i].platName.StartsWith(name)) { _platformManager.apiRequestIndex = i; yield break; } } if (hash != null) { using UnityWebRequest www = UnityWebRequest.Get("https://modelsaber.com/api/v2/get.php?type=platform&filter=hash:" + hash); yield return(www.SendWebRequest()); if (www.isNetworkError || www.isHttpError) { _siraLog.Error("Error downloading a platform: \n" + www.error); } else { Dictionary <string, PlatformDownloadData> downloadData = JsonConvert.DeserializeObject <Dictionary <string, PlatformDownloadData> >(www.downloadHandler.text); PlatformDownloadData data = downloadData.FirstOrDefault().Value; if (data != null) { SharedCoroutineStarter.instance.StartCoroutine(DownloadSavePlatform(data)); } } } else if (name != null) { using UnityWebRequest www = UnityWebRequest.Get("https://modelsaber.com/api/v2/get.php?type=platform&filter=name:" + name); yield return(www.SendWebRequest()); if (www.isNetworkError || www.isHttpError) { _siraLog.Info("Error downloading a platform: \n" + www.error); } else { Dictionary <string, PlatformDownloadData> downloadData = JsonConvert.DeserializeObject <Dictionary <string, PlatformDownloadData> >(www.downloadHandler.text); PlatformDownloadData data = downloadData.FirstOrDefault().Value; if (data != null) { SharedCoroutineStarter.instance.StartCoroutine(DownloadSavePlatform(data)); } } } }
/// <summary> /// Asynchronously loads a <see cref="CustomPlatform"/> from a specified file path /// </summary> private async Task <CustomPlatform?> LoadPlatformFromFileAsyncCore(string fullPath) { byte[] bundleData = await Task.Run(() => File.ReadAllBytes(fullPath)); AssetBundle?assetBundle = await LoadAssetBundleFromBytesAsync(bundleData); if (assetBundle is null) { _siraLog.Error($"File could not be loaded:\n{fullPath}"); return(null); } GameObject?platformPrefab = await LoadAssetFromAssetBundleAsync <GameObject>(assetBundle, "_CustomPlatform"); if (platformPrefab is null) { assetBundle.Unload(true); _siraLog.Error($"Platform GameObject could not be loaded:\n{fullPath}"); return(null); } assetBundle.Unload(false); CustomPlatform?customPlatform = platformPrefab.GetComponent <CustomPlatform>(); if (customPlatform is null) { // Check for old platform global::CustomPlatform?legacyPlatform = platformPrefab.GetComponent <global::CustomPlatform>(); if (legacyPlatform is not null) { // Replace legacy platform component with up to date one customPlatform = platformPrefab.AddComponent <CustomPlatform>(); customPlatform.platName = legacyPlatform.platName; customPlatform.platAuthor = legacyPlatform.platAuthor; customPlatform.hideDefaultPlatform = true; // Remove old platform data UnityEngine.Object.Destroy(legacyPlatform); } else { // No CustomPlatform component, abort UnityEngine.Object.Destroy(platformPrefab); _siraLog.Error($"AssetBundle does not contain a CustomPlatform:\n{fullPath}"); return(null); } } Camera[] cameras = platformPrefab.GetComponentsInChildren <Camera>(true); foreach (Camera camera in cameras) { BloomPrePass bloomPrePass = camera.gameObject.AddComponent <BloomPrePass>(); _bloomPrepassRendererAccessor(ref bloomPrePass) = _bloomPrepassRenderer; _bloomPrePassEffectContainerAccessor(ref bloomPrePass) = _bloomPrePassEffectContainer; } customPlatform.platHash = await Task.Run(() => ComputeHash(bundleData)); customPlatform.fullPath = fullPath; customPlatform.name = $"{customPlatform.platName} by {customPlatform.platAuthor}"; return(customPlatform); }