public async Task Load() { if (IsInitialized) { return; } _logger.Info("Initializing"); await _prefabLoader.LoadAsync(); if (!await LoadTextures()) { return; } if (!await LoadConstellation()) { return; } _logger.Info("Mod content loaded"); _pillowSpawner.CanSpawn = true; _pillowSpawner.Refresh(); _logger.Info("Initialized"); IsInitialized = 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"); }
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); }
private Sprite?LoadSpriteFromResources(Assembly assembly, string resourcePath, float pixelsPerUnit = 256.0f) { using var stream = assembly.GetManifestResourceStream(resourcePath); if (stream == null) { _siraLog.Warning($"Couldn't find embedded resource {resourcePath}"); return(null); } byte[] imageData = new byte[stream.Length]; stream.Read(imageData, 0, (int)stream.Length); if (imageData.Length == 0) { return(null); } var texture = new Texture2D(2, 2, TextureFormat.RGBA32, false, false); texture.LoadImage(imageData); var rect = new Rect(0, 0, texture.width, texture.height); var sprite = Sprite.Create(texture, rect, Vector2.zero, pixelsPerUnit); _siraLog.Info($"Successfully loaded sprite {resourcePath}, w={texture.width}, h={texture.height}"); return(sprite); }
public override async void Init(Transform parent, Saber saber) { await _gameSaberSetup.SetupTask; transform.SetParent(parent, false); var saberModel = saber.saberType == SaberType.SaberA ? _saberSet.LeftSaber : _saberSet.RightSaber; _saberInstance = _saberInstanceFactory.Create(saberModel); _saberInstance.SetParent(transform); _saberInstance.CreateTrail(_saberTrail); SetColor(_saberColor ?? _colorManager.ColorForSaberType(_saberInstance.Model.SaberSlot.ToSaberType())); if (_afHandler != null && AFHandler.IsValid && AFHandler.ShouldFire) { await Task.Delay(4000); await _afHandler.Shoot(this, saber.saberType); } else { _eventPlayer?.SetPartEventList(_saberInstance.Events, saber.saberType); } _logger.Info("Instantiated Saber"); }
/// <summary> /// Loads all platforms or their descriptors if a cache file exists /// </summary> private async Task LoadPlatformsAsync() { Stopwatch sw = Stopwatch.StartNew(); CancellationToken cancellationToken = _cancellationTokenSource.Token; if (File.Exists(_cacheFilePath)) { foreach (CustomPlatform platform in EnumeratePlatformDescriptorsFromFile()) { AllPlatforms.AddSorted(1, AllPlatforms.Count - 1, platform); } } // Load all remaining platforms, or all if no cache file is found foreach (string path in Directory.EnumerateFiles(DirectoryPath, "*.plat")) { cancellationToken.ThrowIfCancellationRequested(); if (AllPlatforms.Any(x => x.fullPath == path)) { continue; } CustomPlatform?platform = await CreatePlatformAsync(path); if (platform is null) { continue; } AllPlatforms.AddSorted(1, AllPlatforms.Count - 1, platform); } sw.Stop(); _siraLog.Info($"Loaded {AllPlatforms.Count.ToString(NumberFormatInfo.InvariantInfo)} platforms in {sw.ElapsedMilliseconds.ToString(NumberFormatInfo.InvariantInfo)}ms"); }
private void RegisterAll(BSMLParser parser) { if (Registered) { return; } foreach (var tag in InstantiateOfType <BSMLTag>()) { parser.RegisterTag(tag); } foreach (var macro in InstantiateOfType <BSMLMacro>()) { parser.RegisterMacro(macro); } foreach (var handler in InstantiateOfType <TypeHandler>()) { parser.RegisterTypeHandler(handler); } RegisterCustomComponents(parser); #if false DocCustoms(parser); #endif _logger.Info("Registered Custom Components"); Registered = true; }
public void SetModelComposition(ModelComposition composition) { CurrentModelComposition?.DestroyAdditionalInstances(); CurrentModelComposition = composition; _saberSet.SetModelComposition(CurrentModelComposition); OnModelCompositionSet?.Invoke(CurrentModelComposition); _logger.Info($"Selected Saber: {composition.ListName}"); }
private void HandleSelectPlugin(PluginInformation?plugin) { if (plugin != null) { siraLog.Info($"Mod list selected plugin {plugin.Plugin} ({plugin.State})"); } modInfoViewController.SetPlugin(plugin); modControlsViewController.SetPlugin(plugin); }
public async Task PlayRandomAudio(UnityEngine.AudioClip fallback, LevelCompletionResults results, bool highScore) { await SiraUtil.Utilities.AwaitSleep(250); if (results.levelEndStateType == LevelCompletionResults.LevelEndStateType.Failed && _config.ResultFailedSoundsEnabled) { var hasAudio = _config.EnabledResultFailedSounds.Count != 0; if (!hasAudio) { return; } var randomAudioFile = _config.EnabledResultFailedSounds[_random.Next(0, _config.EnabledResultFailedSounds.Count)]; _siraLog.Info($"Loading Audio File: {randomAudioFile.FullName}"); var clip = await _audioClipAsyncLoader.LoadAudioClipAsync(randomAudioFile.FullName, CancellationToken.None); Play(clip); } else if (results.levelEndStateType == LevelCompletionResults.LevelEndStateType.Cleared && _config.ResultSoundsEnabled) { var info = results.fullCombo ? (_config.EnabledResultFCSounds.Count == 0 ? _config.EnabledResultSounds : _config.EnabledResultFCSounds) : _config.EnabledResultSounds; var hasAudio = info.Count != 0; if (!hasAudio) { if (highScore) { _songPreviewPlayer.CrossfadeTo(fallback, 0f, fallback.length); } return; } var randomAudioFile = info[_random.Next(0, info.Count)]; _siraLog.Info($"Loading Audio File: {randomAudioFile.FullName}"); var clip = await _audioClipAsyncLoader.LoadAudioClipAsync(randomAudioFile.FullName, CancellationToken.None); if (highScore) { Play(clip); } } }
public void Initialize() { RegisterPluginChangeListeners(); _logger.Info("Checking for Counters+"); var pluginMetaData = PluginManager.EnabledPlugins.FirstOrDefault(x => x.Id == COUNTERS_PLUS_MOD_ID); if (pluginMetaData == null) { return; } if (pluginMetaData.HVersion.Major < 2) { _logger.Warning($"Version {pluginMetaData.HVersion} of Counters+ has been found, but is deemed incompatible with FPS Counter. NOT INTEGRATING!"); return; } IsCountersPlusPresent = true; _logger.Info("Found Counters+"); }
/// <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); } }
public override void Init(Transform parent, Saber saber) { var saberModel = saber.saberType == SaberType.SaberA ? _saberSet.LeftSaber : _saberSet.RightSaber; _saberInstance = _saberInstanceFactory.Create(saberModel); _saberInstance.SetParent(parent); _saberInstance.CreateTrail(_saberTrail.GetField <SaberTrailRenderer, SaberTrail>("_trailRendererPrefab")); SetColor(_saberColor ?? _colorManager.ColorForSaberType(_saberInstance.Model.SaberSlot.ToSaberType())); _eventPlayer?.SetPartEventList(_saberInstance.Events, saber.saberType); _logger.Info("Instantiated Saber"); }
/// <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) { try { if (platform == _platformManager.ActivePlatform) { return; } _cancellationTokenSource?.Cancel(); _cancellationTokenSource?.Dispose(); _cancellationTokenSource = new CancellationTokenSource(); CancellationToken cancellationToken = _cancellationTokenSource.Token; DestroyCustomObjects(); _platformManager.ActivePlatform.gameObject.SetActive(false); _platformManager.ActivePlatform = platform; if (platform.isDescriptor) { CustomPlatform?newPlatform = await _platformManager.CreatePlatformAsync(platform.fullPath); if (newPlatform is not null) { _platformManager.AllPlatforms.Replace(platform, newPlatform); UnityEngine.Object.Destroy(platform.gameObject); } cancellationToken.ThrowIfCancellationRequested(); if (newPlatform is null) { _ = ChangeToPlatformAsync(_platformManager.DefaultPlatform); return; } _platformManager.ActivePlatform = newPlatform; } _siraLog.Info($"Switching to {_platformManager.ActivePlatform.name}"); _environmentHider.HideObjectsForPlatform(_platformManager.ActivePlatform); _platformManager.ActivePlatform.gameObject.SetActive(true); SpawnCustomObjects(); } catch (OperationCanceledException) { } }
public void SetModelComposition(ModelComposition composition, bool lazyInit = true) { if (CurrentModelComposition != null) { CurrentModelComposition.SaveAdditionalData(); CurrentModelComposition.DestroyAdditionalInstances(); } if (lazyInit && CurrentModelComposition != composition) { composition?.LazyInit(); } CurrentModelComposition = composition; _saberSet.SetModelComposition(CurrentModelComposition); OnModelCompositionSet?.Invoke(CurrentModelComposition); _logger.Info($"Selected Saber: {composition?.ListName}"); }
private async Task LoadAllMetaDataForLoader(AssetBundleLoader loader, bool createIfNotExisting = false) { var sw = Stopwatch.StartNew(); await Task.Run(async() => { foreach (var assetMetaPath in await _customSaberAssetLoader.CollectFiles()) { var relativePath = PathTools.ToRelativePath(assetMetaPath.MetaDataPath); if (_metaData.TryGetValue(relativePath, out _)) { continue; } if (!assetMetaPath.HasMetaData) { if (createIfNotExisting) { var comp = await await UnityMainThreadTaskScheduler.Factory.StartNew(() => this[PathTools.ToRelativePath(assetMetaPath.Path)]); if (comp == null) { continue; } var metaData = new PreloadMetaData(assetMetaPath, comp, comp.AssetTypeDefinition); await metaData.SaveToFile(); _metaData.Add(relativePath, metaData); } } else { var metaData = new PreloadMetaData(assetMetaPath); await metaData.LoadFromFile(); metaData.IsFavorite = _config.IsFavorite(PathTools.ToRelativePath(assetMetaPath.Path)); _metaData.Add(relativePath, metaData); } } }); sw.Stop(); _logger.Info($"Loaded Metadata in {sw.Elapsed.Seconds}.{sw.Elapsed.Milliseconds}s"); }
public async Task LoadAllCustomSabersAsync(bool fireEvent) { var sw = Stopwatch.StartNew(); foreach (var path in _customSaberAssetLoader.CollectFiles()) { var relativePath = PathTools.ToRelativePath(path); if (_modelCompositions.ContainsKey(relativePath)) { continue; } await LoadComposition(relativePath); } sw.Stop(); _logger.Info($"Loaded in {sw.Elapsed.Seconds} Seconds"); if (fireEvent) { NotifyLoadingFinished(); } }
/// <summary> /// Changes to a specific <see cref="CustomPlatform"/> /// </summary> /// <param name="index">The index of the new <see cref="CustomPlatform"/> in the list <see cref="AllPlatforms"/></param> internal void ChangeToPlatform(int index) { if (!_platformManager.allPlatforms[index].requirements.All(x => _platformManager.allPluginNames.Contains(x))) { _siraLog.Warning("Missing requirement for platform " + _platformManager.allPlatforms[index].name); ChangeToPlatform(0); return; } _siraLog.Info("Switching to " + _platformManager.allPlatforms[index].name); _platformManager.activePlatform?.gameObject.SetActive(false); DestroyCustomObjects(); _platformManager.activePlatform = _platformManager.allPlatforms[index]; SharedCoroutineStarter.instance.StartCoroutine(WaitAndSpawn()); IEnumerator WaitAndSpawn() { if (_platformManager.activePlatform.transform.childCount == 0 && index != 0) { yield return(SharedCoroutineStarter.instance.StartCoroutine(_platformLoader.LoadFromFileAsync(_platformManager.activePlatform.fullPath, _platformManager.HandlePlatformLoaded))); } yield return(new WaitForEndOfFrame()); if (index != 0) { _platformManager.activePlatform.gameObject.SetActive(true); AddManagers(_platformManager.activePlatform); SpawnCustomObjects(); } else { _platformManager.activePlatform = null; } _hider.HideObjectsForPlatform(_platformManager.allPlatforms[index]); } }
public void Initialize() { _canvasGO = new GameObject("SliceVisualizerCanvas", typeof(Canvas), typeof(CanvasScaler), typeof(GraphicRaycaster)); var canvas = _canvasGO.GetComponent <Canvas>(); canvas.renderMode = RenderMode.WorldSpace; _canvasGO.transform.localScale = Vector3.one * _config.CanvasScale; _canvasGO.transform.localPosition = _config.CanvasOffset; _beatmapObjectManager.noteWasCutEvent += OnNoteCut; for (var i = 0; i < MaxItems; i++) { _slicedBlockPool[i] = _blockFactory.Create(); _slicedBlockPool[i].Init(_canvasGO.transform); } try { CreateCheckbox(); } catch (Exception err) { _logger.Info(string.Format("Cannot create checkbox: {0}", err)); } }
public void Print(SiraLog logger) { logger.Info(GetString()); }
/// <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)); } } } }