Example #1
0
    public void UpdateRatingAndLevel(Profile profile, bool showChange = false)
    {
        rating.text = $"{"PROFILE_WIDGET_RATING".Get()} {profile.Rating:N2}";
        level.text  = $"{"PROFILE_WIDGET_LEVEL".Get()} {profile.Exp.CurrentLevel}";

        if (showChange && lastProfile != null)
        {
            var lastRating    = Math.Floor(lastProfile.Rating * 100) / 100;
            var currentRating = Math.Floor(profile.Rating * 100) / 100;
            var rtDifference  = currentRating - lastRating;
            if (rtDifference >= 0.01)
            {
                rating.text += $" <color=#9BC53D>(+{Math.Round(rtDifference, 2)})</color>";
            }

            /*else if (rtDifference <= -0.01)
             * {
             *  rating.text += $" <color=#E55934>({Math.Round(rtDifference, 2)})</color>";
             * }*/

            var levelDifference = profile.Exp.CurrentLevel - lastProfile.Exp.CurrentLevel;
            if (levelDifference > 0)
            {
                level.text += $" <color=#9BC53D>(+{levelDifference})</color>";
            }
        }

        lastProfile = profile;
        if (layoutGroup != null)
        {
            LayoutFixer.Fix(layoutGroup.transform);
        }
    }
Example #2
0
    protected override async void OnRendered()
    {
        base.OnRendered();

        toggleOfflineButton.GetComponentInChildren <Text>().text = Context.IsOnline() ? "OFFLINE_GO_OFFLINE".Get() : "OFFLINE_GO_ONLINE".Get();
        LayoutFixer.Fix(toggleOfflineButton.transform);
        profileTab.characterTransitionElement.Enter();
        profileTab.changeCharacterButton.gameObject.SetActive(LoadedPayload.IsPlayer);
        contentTabs.gameObject.SetActive(LoadedPayload.IsPlayer);
        topRightColumn.gameObject.SetActive(LoadedPayload.IsPlayer);
        // Always use local character if local player
        if (LoadedPayload.Profile.User.Uid == Context.Player.Id)
        {
            profileTab.characterDisplay.Load(CharacterAsset.GetTachieBundleId(Context.CharacterManager.SelectedCharacterId));
        }
        else if (LoadedPayload.Profile.Character != null)
        {
            profileTab.characterDisplay.Load(CharacterAsset.GetTachieBundleId(LoadedPayload.Profile.Character.AssetId));
        }
        contentTabs.Select(LoadedPayload.TabIndex);
        await UniTask.DelayFrame(2);

        if (LoadedPayload.ProfileScrollPosition > -1)
        {
            profileTab.scrollRect.verticalNormalizedPosition = LoadedPayload.ProfileScrollPosition;
        }
    }
Example #3
0
    public async void SetSignedIn(Profile profile)
    {
        name.text = profile.User.Uid;
        name.DOKill();
        name.DOFade(1, 0.2f);
        infoLayoutGroup.gameObject.SetActive(true);
        LayoutFixer.Fix(layoutGroup.transform);
        if (avatarImage.sprite == null)
        {
            spinner.IsSpinning = true;
            var url = profile.User.Avatar.LargeUrl;
            print("Avatar URL: " + url);
            var sprite = await Context.AssetMemory.LoadAsset <Sprite>(
                url,
                AssetTag.PlayerAvatar,
                useFileCacheOnly : Context.IsOffline()
                );

            spinner.IsSpinning = false;
            if (sprite != null)
            {
                SetAvatarSprite(sprite);
            }
            else
            {
                if (Context.IsOnline())
                {
                    Toast.Enqueue(Toast.Status.Failure, "TOAST_COULD_NOT_DOWNLOAD_AVATAR".Get());
                }
            }
        }
        UpdateRatingAndLevel(profile);
    }
Example #4
0
    public void SetModel(string levelId, LevelRating data)
    {
        if (data.total > 0)
        {
            averageRatingText.text = ((data.average ?? 0) / 2.0).ToString("0.00");
            numRatingsText.text    = $"{data.total} " + (data.total > 1 ? "GAME_PREP_RATINGS_UNIT_RATINGS" : "GAME_PREP_RATINGS_UNIT_RATING").Get();
        }
        else
        {
            averageRatingText.text = "N/A";
            numRatingsText.text    = "0 " + "GAME_PREP_RATINGS_UNIT_RATINGS".Get();
        }

        if (Context.OnlinePlayer.IsAuthenticated && Context.LevelManager.LoadedLocalLevels.ContainsKey(levelId))
        {
            messageText.text = data.rating > 0
                ? "GAME_PREP_RATINGS_YOU_RATED_X".Get($"{data.rating / 2.0:0.#}")
                : (data.total > 0 ? "GAME_PREP_RATINGS_YOU_HAVENT_RATED" : "GAME_PREP_RATINGS_BE_THE_FIRST").Get();
            rateButton.gameObject.SetActive(true);
        }
        else
        {
            messageText.text = "";
            rateButton.gameObject.SetActive(false);
        }
        LayoutFixer.Fix(transform);
    }
Example #5
0
 public override void SetModel(TierRankingEntry entry)
 {
     Model           = entry;
     completion.text = $"{(Mathf.FloorToInt((float) (entry.completion * 100 * 100)) / 100f):0.00}%";
     completionGradient.SetGradient(ScoreGrades.FromTierCompletion(entry.completion).GetGradient());
     accuracy.text = (Math.Floor(entry.averageAccuracy * 100 * 100) / 100).ToString("0.00") + "%";
     LayoutFixer.Fix(transform as RectTransform);
 }
Example #6
0
    protected override void Render()
    {
        foreach (Transform child in sectionHolder.transform)
        {
            Destroy(child.gameObject);
        }

        foreach (var section in LoadedPayload.Layout.Sections)
        {
            switch (section)
            {
            case Layout.LevelSection levelSection:
            {
                var sectionGameObject = Instantiate(levelSectionPrefab, sectionHolder.transform);
                var sectionBehavior   = sectionGameObject.GetComponent <LevelSection>();
                sectionBehavior.titleText.text = levelSection.TitleKey.Get();
                foreach (var onlineLevel in levelSection.Levels)
                {
                    var levelCardGameObject = Instantiate(levelCardPrefab, sectionBehavior.levelCardHolder.transform);
                    var levelCard           = levelCardGameObject.GetComponent <LevelCard>();
                    levelCard.SetModel(new LevelView {
                            Level = onlineLevel.ToLevel(LevelType.User), DisplayOwner = true
                        });
                }
                sectionBehavior.viewMoreButton.GetComponentInChildren <Text>().text =
                    "COMMUNITY_HOME_VIEW_ALL".Get();
                sectionBehavior.viewMoreButton.onPointerClick.AddListener(_ =>
                    {
                        Context.ScreenManager.ChangeScreen(CommunityLevelSelectionScreen.Id, ScreenTransition.In, 0.4f,
                                                           transitionFocus: ((RectTransform)sectionBehavior.viewMoreButton.transform).GetScreenSpaceCenter(),
                                                           payload: new CommunityLevelSelectionScreen.Payload {
                            Query = levelSection.Query.JsonDeepCopy()
                        });
                    });
                break;
            }

            case Layout.CollectionSection collectionSection:
            {
                var sectionGameObject = Instantiate(collectionSectionPrefab, sectionHolder.transform);
                var sectionBehavior   = sectionGameObject.GetComponent <CollectionSection>();
                foreach (var collection in collectionSection.Collections)
                {
                    var collectionGameObject = Instantiate(collectionCardPrefab, sectionBehavior.collectionCardHolder.transform);
                    var collectionCard       = collectionGameObject.GetComponent <CollectionCard>();
                    collectionCard.SetModel(collection);
                    collectionCard.titleOverride  = collection.title;
                    collectionCard.sloganOverride = collection.slogan;
                }
                break;
            }
            }
        }

        LayoutFixer.Fix(contentHolder.transform);
        base.Render();
    }
Example #7
0
    public override void SetModel(RankingEntry entry)
    {
        Model = entry;
        var scoreGrade = ScoreGrades.From(entry.score);

        grade.text = scoreGrade.ToString();
        gradeGradient.SetGradient(scoreGrade.GetGradient());
        score.text    = entry.score.ToString("D6");
        accuracy.text = (Math.Floor(entry.accuracy * 100 * 100) / 100).ToString("0.00") + "%";
        LayoutFixer.Fix(transform as RectTransform);
    }
Example #8
0
    public void SetModel(LevelMeta.ChartSection section)
    {
        this.section = section;
        Difficulty   = Difficulty.Parse(section.type);

        gradientMesh.SetGradient(Difficulty.Gradient);
        name.text  = !section.name.IsNullOrEmptyTrimmed() ? section.name : Difficulty.Name;
        level.text = "LV." + Difficulty.ConvertToDisplayLevel(section.difficulty);

        LayoutFixer.Fix(transform);
    }
Example #9
0
    private void Update()
    {
        var profileRect = profileRectTransform.rect;

        if (profileRectTransform != null && !Mathf.Approximately(lastProfileRectWidth, profileRect.width))
        {
            lastProfileRectWidth = profileRect.width;
            // Set padding based on profile
            horizontalLayoutGroup.padding.right = (int)profileRect.width - 24;
            LayoutFixer.Fix(horizontalLayoutGroup.transform);
        }
    }
Example #10
0
    private async void RebuildLayout()
    {
        LayoutStaticizer.Activate(transform);
        LayoutFixer.Fix(transform);
        await UniTask.DelayFrame(5);

        if (this == null || transform == null)
        {
            return;
        }
        LayoutStaticizer.Staticize(transform);
    }
Example #11
0
    public static async UniTask <bool> Show(string text, float duration = 0.8f, Action onFullyShown = null, Action onFullyHidden = null)
    {
        if (isTransitioning)
        {
            await UniTask.WaitUntil(() => !isTransitioning);
        }
        isTransitioning = true;
        var hasResult = false;
        var result    = false;
        var it        = Instance;

        it.canvas.enabled             = true;
        it.canvas.overrideSorting     = true;
        it.canvas.sortingOrder        = NavigationSortingOrder.TermsOverlay;
        it.canvasGroup.enabled        = true;
        it.canvasGroup.blocksRaycasts = true;
        it.canvasGroup.interactable   = true;
        LayoutFixer.Fix(it.agreeButton.transform.parent);
        await UniTask.DelayFrame(5);

        it.canvasGroup.DOKill();
        it.canvasGroup.DOFade(1, duration).SetEase(Ease.OutCubic);
        Context.SetMajorCanvasBlockRaycasts(false);
        it.text.text = $"\n\n\n\n{text}\n\n\n\n";
        if (((Language)Context.Player.Settings.Language).ShouldUseNonBreakingSpaces())
        {
            it.text.text = it.text.text.Replace(" ", "\u00A0");
        }
        it.scrollRect.verticalNormalizedPosition = 1;
        it.scheduledPulse.StartPulsing();
        it.agreeButton.onPointerClick.AddListener(_ =>
        {
            hasResult = true;
            result    = true;
        });
        it.disagreeButton.onPointerClick.AddListener(_ =>
        {
            hasResult = true;
            result    = false;
        });
        if (onFullyShown != null)
        {
            await UniTask.Delay(TimeSpan.FromSeconds(duration));

            onFullyShown();
        }
        await UniTask.WaitUntil(() => hasResult);

        isTransitioning = false;
        Hide(duration, onFullyHidden);
        return(result);
    }
Example #12
0
    public async void OnContentLoaded(Content content)
    {
        scrollRect.ClearCells();

        scrollRect.totalCount = content.Season.tiers.Count + 1;
        var tiers = new List <TierData>(content.Season.tiers)
        {
            new TierData {
                isScrollRectFix = true
            }
        };

        for (var i = 0; i < tiers.Count - 1; i++)
        {
            var tier = tiers[i];
            tier.index = i;
            if (tier.Meta.parsedCriteria == default)
            {
                tier.Meta.parsedCriteria = tier.Meta.criteria.Select(Criterion.Parse).ToList();
            }
            if (tier.Meta.parsedStages == default)
            {
                tier.Meta.parsedStages = new List <Level>();
                tier.Meta.validStages  = new List <bool>();
                for (var stage = 0; stage < Math.Min(tier.Meta.stages.Count, 3); stage++)
                {
                    var level = tier.Meta.stages[stage].ToLevel(LevelType.Tier);
                    tier.Meta.parsedStages.Add(level);
                    tier.Meta.validStages.Add(level.IsLocal && level.Type == LevelType.Tier &&
                                              level.Meta.version == tier.Meta.stages[stage].Version);
                }
            }
        }

        scrollRect.objectsToFill = tiers.Cast <object>().ToArray();
        scrollRect.RefillCells();
        scrollRect.GetComponent <TransitionElement>().Apply(it =>
        {
            it.Leave(false, true);
            it.Enter();
        });
        LayoutFixer.Fix(scrollRect.content, count: 6);

        if (lastScrollPosition > -1)
        {
            await UniTask.DelayFrame(5);

            LayoutFixer.Fix(scrollRect.content, count: 6);
            scrollRect.SetVerticalNormalizedPositionFix(lastScrollPosition);
        }
        StartCoroutine(SnapCoroutine());
    }
Example #13
0
 public void SetSignedOut()
 {
     name.text = "PROFILE_WIDGET_NOT_SIGNED_IN".Get();
     name.DOKill();
     name.DOFade(1, 0.2f);
     infoLayoutGroup.gameObject.SetActive(false);
     LayoutFixer.Fix(layoutGroup.transform);
     background.color = Color.white;
     spinner.defaultIcon.GetComponent <Image>().color = Color.white;
     spinner.IsSpinning = false;
     avatarImage.sprite = null;
     avatarImage.color  = Color.clear;
 }
Example #14
0
    public virtual void SetData(IEnumerable <T> data)
    {
        Clear();
        if (canvasGroup == null)
        {
            return;
        }
        canvasGroup.alpha = 0;
        foreach (var datum in data)
        {
            var entryElement = Instantiate(entryPrefab, transform).GetComponent <TE>();
            Entries.Add(entryElement);
            entryElement.SetModel(datum);
            LayoutFixer.Fix(entryElement.transform);
        }

        LayoutFixer.Fix(transform);
        canvasGroup.DOFade(1, 0.4f).SetDelay(0.1f).SetEase(Ease.OutCubic);
    }
Example #15
0
    public void Load(Level level)
    {
        if (level == null)
        {
            return;
        }
        foreach (Transform child in transform)
        {
            Destroy(child.gameObject);
        }
        difficultyPills.Clear();

        var meta = level.Meta;
        var hasPreferredDifficulty = false;

        foreach (var section in meta.charts)
        {
            var difficultyPill = Instantiate(difficultyPillPrefab, transform).GetComponent <DifficultyPill>();
            difficultyPill.SetModel(section);
            difficultyPills.Add(difficultyPill);

            if (Context.PreferredDifficulty == difficultyPill.Difficulty)
            {
                hasPreferredDifficulty = true;
                difficultyPill.Select(false);
            }
        }

        if (!hasPreferredDifficulty)
        {
            if (Context.PreferredDifficulty == Difficulty.Extreme)
            {
                difficultyPills.Last().Select(false);
            }
            else
            {
                difficultyPills.First().Select(false);
            }
        }

        LayoutFixer.Fix(transform);
    }
Example #16
0
    private void InstantiateSettings()
    {
        SettingsFactory.InstantiateGeneralSettings(generalTab, true);
        SettingsFactory.InstantiateGameplaySettings(gameplayTab);
        SettingsFactory.InstantiateVisualSettings(visualTab);
        SettingsFactory.InstantiateAdvancedSettings(advancedTab, true);

        async void Fix(Transform transform)
        {
            LayoutStaticizer.Activate(transform);
            LayoutFixer.Fix(transform);
            await UniTask.DelayFrame(5);

            LayoutStaticizer.Staticize(transform);
        }

        Fix(generalTab.parent);
        Fix(gameplayTab.parent);
        Fix(visualTab.parent);
        Fix(advancedTab.parent);
    }
Example #17
0
    public void SetModel(TierData tier)
    {
        Tier            = tier;
        IsScrollRectFix = tier.isScrollRectFix;
        if (IsScrollRectFix)
        {
            foreach (Transform child in transform)
            {
                child.gameObject.SetActive(false);
            }
        }
        else
        {
            Index             = tier.index;
            canvasGroup.alpha = 1f;
            foreach (Transform child in transform)
            {
                child.gameObject.SetActive(true);
            }

            active       = true;
            screenCenter = this.GetScreenParent <TierSelectionScreen>().ScreenCenter;

            characterRoot.gameObject.SetActive(tier.Meta.character != null);
            if (tier.Meta.character != null)
            {
                characterDisplay.Load(CharacterAsset.GetTachieBundleId(tier.Meta.character.AssetId));
                characterDisplay.canvasGroup.alpha = 0;
            }

            gradientPane.SetModel(tier);

            for (var stage = 0; stage < Math.Min(3, tier.Meta.stages.Count); stage++)
            {
                stageCards[stage].SetModel(
                    tier.Meta.parsedStages[stage],
                    new ColorGradient(tier.Meta.colorPalette.stages[stage], 90f)
                    );
            }

            lockedOverlayRoot.SetActive(tier.locked || !tier.StagesValid);
            if (tier.locked)
            {
                lockedOverlayIcon.sprite = lockedIcon;
                lockedOverlayText.text   = "TIER_LOCKED".Get();
            }
            else if (!tier.StagesValid)
            {
                lockedOverlayIcon.sprite = unlockedIcon;
                lockedOverlayText.text   = "TIER_NOT_DOWNLOADED".Get();
            }

            foreach (Transform child in criteriaHolder.transform)
            {
                Destroy(child.gameObject);
            }
            foreach (var criterion in tier.Meta.parsedCriteria)
            {
                var criterionEntry = Instantiate(criterionEntryPrefab, criteriaHolder.transform);
                criterionEntry.SetModel(criterion.Description, CriterionState.Passed);
            }

            LayoutFixer.Fix(criteriaHolder.transform);
        }
    }
Example #18
0
    private async void OnOfflineModeToggled(bool offline)
    {
        SpinnerOverlay.Show();
        async void Fix(GameObject itGameObject, bool active)
        {
            // Yes, welcome to Unity.
            // Don't change, unless you are absolutely certain what I am (and you are) doing.
            itGameObject.SetActive(active);
            LayoutFixer.Fix(itGameObject.transform);
            await UniTask.DelayFrame(5);

            itGameObject.SetActive(!itGameObject.activeSelf);
            await UniTask.DelayFrame(0);

            itGameObject.SetActive(!itGameObject.activeSelf);
            await UniTask.DelayFrame(0);

            LayoutFixer.Fix(itGameObject.transform);
            if (active)
            {
                itGameObject.GetComponent <TransitionElement>()?.Apply(x => x.UseCurrentStateAsDefault());
            }
        }

        foreach (var gameObject in SceneManager.GetActiveScene().GetRootGameObjects())
        {
            gameObject.GetComponentsInChildren <OfflineElement>(true).ForEach(it =>
            {
                if (offline)
                {
                    it.targets.ForEach(x => x.SetActive(false));
                    it.gameObject.SetActive(true);
                }
                else
                {
                    it.gameObject.SetActive(false);
                    it.targets.ForEach(x => x.SetActive(true));
                }
                it.rebuildTransform.RebuildLayout();
                var o = it.rebuildTransform.gameObject;
                Fix(o, o.activeSelf);
            });
        }

        await UniTask.DelayFrame(10);

        foreach (var gameObject in SceneManager.GetActiveScene().GetRootGameObjects())
        {
            gameObject.GetComponentsInChildren <HiddenIfOfflineElement>(true).ForEach(it =>
            {
                Fix(it.gameObject, !offline);
                var rebuild = it.rebuildTransform;
                if (rebuild != null)
                {
                    rebuild.RebuildLayout();
                    var o = rebuild.gameObject;
                    Fix(o, o.activeSelf);
                }
            });
        }

        await UniTask.DelayFrame(10);

        foreach (var screen in Context.ScreenManager.createdScreens)
        {
            LayoutFixer.Fix(screen.transform);
        }

        await UniTask.DelayFrame(5);

        SpinnerOverlay.Hide();
    }
Example #19
0
    public static async UniTask Show(Story story)
    {
        var instance = Instance;

        if (instance.IsActive)
        {
            await UniTask.WaitUntil(() => !instance.IsActive);
        }
        await instance.Enter();

        var spriteSets    = new Dictionary <string, DialogueSpriteSet>();
        var animationSets = new Dictionary <string, DialogueAnimationSet>();

        if (story.globalTags != null)
        {
            story.globalTags.FindAll(it => it.Trim().StartsWith("SpriteSet:"))
            .Select(it => it.Substring(it.IndexOf(':') + 1).Trim())
            .Select(DialogueSpriteSet.Parse)
            .ForEach(it => spriteSets[it.Id] = it);
            story.globalTags.FindAll(it => it.Trim().StartsWith("AnimationSet:"))
            .Select(it => it.Substring(it.IndexOf(':') + 1).Trim())
            .Select(DialogueAnimationSet.Parse)
            .ForEach(it => animationSets[it.Id] = it);
        }

        await spriteSets.Values.Select(it => it.Initialize());

        await animationSets.Values.Select(it => it.Initialize());

        Sprite currentImageSprite     = null;
        string currentImageSpritePath = null;
        Sprite currentSprite          = null;
        string currentAnimation       = null;
        var    currentSpeaker         = "";
        var    currentPosition        = DialogueBoxPosition.Bottom;

        var                     shouldSetImageSprite = false;
        Dialogue                lastDialogue         = null;
        DialogueBox             lastDialogueBox      = null;
        DialogueHighlightTarget lastHighlightTarget  = null;

        while (story.canContinue && !TerminateCurrentStory)
        {
            var message  = ReplacePlaceholders(story.Continue());
            var duration = 0f;
            var tags     = story.currentTags;

            var doAction = TagValue(tags, "Action");
            if (doAction != null)
            {
                switch (doAction)
                {
                case "GamePreparation/ShowGameplayTab":
                    var tabs = Context.ScreenManager.GetScreen <GamePreparationScreen>().actionTabs;
                    tabs.OnAction(tabs.Actions.Find(it => it.index == 2));
                    break;
                }
            }

            var setDuration = TagValue(tags, "Duration");
            if (setDuration != null)
            {
                duration = float.Parse(setDuration);
            }

            var setOverlayOpacity = TagValue(tags, "OverlayOpacity");
            if (setOverlayOpacity != null)
            {
                setOverlayOpacity.Split('/', out var targetOpacity, out var fadeDuration, out var fadeDelay);
                SetOverlayOpacity().Forget();
                async UniTaskVoid SetOverlayOpacity()
                {
                    await UniTask.Delay(TimeSpan.FromSeconds(float.Parse(fadeDelay)));

                    instance.backdropImage.DOFade(float.Parse(targetOpacity), float.Parse(fadeDuration));
                }
            }

            var setHighlight = TagValue(tags, "Highlight");
            if (setHighlight != null)
            {
                lastHighlightTarget = await DialogueHighlightTarget.Find(setHighlight);

                if (lastHighlightTarget != null)
                {
                    lastHighlightTarget.Highlighted = true;
                }
            }

            var waitForHighlightOnClick = FlagValue(tags, "WaitForHighlightOnClick");
            if (waitForHighlightOnClick && lastHighlightTarget == null)
            {
                waitForHighlightOnClick = false;
            }

            var    setImage = TagValue(tags, "Image");
            string imageWidth = null, imageHeight = null, imageRadius = null;
            if (setImage != null)
            {
                if (setImage == "null")
                {
                    currentImageSprite = null;
                }
                else
                {
                    setImage.Split('/', out imageWidth, out imageHeight, out imageRadius, out var imageUrl);

                    imageUrl = ReplacePlaceholders(imageUrl);

                    SpinnerOverlay.Show();
                    currentImageSprite = await Context.AssetMemory.LoadAsset <Sprite>(imageUrl, AssetTag.DialogueImage);

                    currentImageSpritePath = imageUrl;
                    SpinnerOverlay.Hide();

                    shouldSetImageSprite = true;
                }
            }

            var setSprite = TagValue(tags, "Sprite");
            if (setSprite != null)
            {
                if (setSprite == "null")
                {
                    currentSprite = null;
                    DisposeImageSprite();
                }
                else
                {
                    setSprite.Split('/', out var id, out var state);

                    if (!spriteSets.ContainsKey(id))
                    {
                        throw new ArgumentOutOfRangeException();
                    }
                    currentSprite    = spriteSets[id].States[state].Sprite;
                    currentAnimation = null;
                }
            }

            var setAnimation = TagValue(tags, "Animation");
            if (setAnimation != null)
            {
                if (setAnimation == "null")
                {
                    currentAnimation = null;
                }
                else
                {
                    currentAnimation = setAnimation;
                    currentSprite    = null;
                }
            }

            var setSpeaker = TagValue(tags, "Speaker");
            if (setSpeaker != null)
            {
                currentSpeaker = setSpeaker == "null" ? null : setSpeaker;
            }

            var setPosition = TagValue(tags, "Position");
            if (setPosition != null)
            {
                currentPosition = (DialogueBoxPosition)Enum.Parse(typeof(DialogueBoxPosition), setPosition);
            }

            var dialogue = new Dialogue
            {
                Message     = message,
                SpeakerName = currentSpeaker,
                Sprite      = currentSprite,
                Position    = currentPosition,
                HasChoices  = story.currentChoices.Count > 0,
                IsBlocked   = waitForHighlightOnClick || duration > 0
            };

            // Lookup animation
            if (currentAnimation != null)
            {
                currentAnimation.Split('/', out var id, out var animationName);

                if (!animationSets.ContainsKey(id))
                {
                    throw new ArgumentOutOfRangeException();
                }
                dialogue.AnimatorController = animationSets[id].Controller;
                dialogue.AnimationName      = animationName;
            }

            DialogueBox dialogueBox;
            if (dialogue.Position == DialogueBoxPosition.Top)
            {
                dialogueBox = instance.topDialogueBox;
            }
            else if (dialogue.Sprite != null || dialogue.AnimatorController != null)
            {
                dialogueBox = instance.bottomFullDialogueBox;
            }
            else
            {
                dialogueBox = instance.bottomDialogueBox;
            }

            if (lastDialogue != null && (lastDialogueBox != dialogueBox || lastDialogue.SpeakerName != dialogue.SpeakerName))
            {
                await lastDialogueBox.SetDisplayed(false);

                dialogueBox.messageBox.SetLocalScale(1f);
            }

            // Display image
            if (currentImageSprite != null)
            {
                if (shouldSetImageSprite)
                {
                    instance.image.SetData(currentImageSprite, int.Parse(imageWidth), int.Parse(imageHeight), int.Parse(imageRadius));
                    await UniTask.Delay(TimeSpan.FromSeconds(1.5f));

                    shouldSetImageSprite = false;
                }
            }
            else
            {
                instance.image.Clear();
            }

            if (message.IsNullOrEmptyTrimmed())
            {
                await dialogueBox.SetDisplayed(false);
            }
            else
            {
                await dialogueBox.SetDisplayed(true);

                lastDialogue    = dialogue;
                lastDialogueBox = dialogueBox;

                instance.detectionArea.onPointerDown.SetListener(_ => { dialogueBox.messageBox.DOScale(0.97f, 0.2f); });
                instance.detectionArea.onPointerUp.SetListener(_ => { dialogueBox.messageBox.DOScale(1f, 0.2f); });
                instance.detectionArea.onPointerClick.SetListener(_ => { dialogueBox.WillFastForwardDialogue = true; });
                await dialogueBox.ShowDialogue(dialogue);
            }

            if (waitForHighlightOnClick)
            {
                instance.detectionArea.onPointerDown.RemoveAllListeners();
                instance.detectionArea.onPointerUp.RemoveAllListeners();
                await lastHighlightTarget.WaitForOnClick();
            }
            else if (story.currentChoices.Count > 0)
            {
                var proceed = false;
                var buttons = new List <SoftButton>();
                for (var index = 0; index < story.currentChoices.Count; index++)
                {
                    var choice       = story.currentChoices[index];
                    var choiceButton = Instantiate(instance.choiceButtonPrefab, instance.choicesRoot);
                    var closureIndex = index;
                    choiceButton.onPointerClick.SetListener(_ =>
                    {
                        if (proceed)
                        {
                            return;
                        }
                        story.ChooseChoiceIndex(closureIndex);
                        proceed = true;
                    });
                    choiceButton.Label = choice.text.Get();
                    buttons.Add(choiceButton);
                }

                LayoutFixer.Fix(instance.choicesRoot);
                await UniTask.DelayFrame(5);

                foreach (var button in buttons)
                {
                    button.transitionElement.UseCurrentStateAsDefault();
                    button.transitionElement.Enter();
                    await UniTask.Delay(TimeSpan.FromSeconds(0.2f));
                }

                await UniTask.WaitUntil(() => proceed);

                buttons.ForEach(it => Destroy(it.gameObject));
            }
            else
            {
                var proceed = false;
                instance.detectionArea.onPointerDown.SetListener(_ => { dialogueBox.messageBox.DOScale(0.95f, 0.2f); });
                instance.detectionArea.onPointerUp.SetListener(_ =>
                {
                    dialogueBox.messageBox.DOScale(1f, 0.2f);
                    proceed = true;
                });
                if (duration > 0)
                {
                    await UniTask.WhenAny(UniTask.WaitUntil(() => proceed),
                                          UniTask.Delay(TimeSpan.FromSeconds(duration)));
                }
                else
                {
                    await UniTask.WaitUntil(() => proceed);
                }
                instance.detectionArea.onPointerDown.RemoveAllListeners();
                instance.detectionArea.onPointerUp.RemoveAllListeners();
            }

            if (lastHighlightTarget != null)
            {
                lastHighlightTarget.Highlighted = false;
                lastHighlightTarget             = null;
            }
        }
        TerminateCurrentStory = false;
        if (lastDialogueBox != null)
        {
            lastDialogueBox.SetDisplayed(false);
        }

        instance.image.Clear();
        await instance.Leave();

        DisposeImageSprite();
        spriteSets.Values.ForEach(it => it.Dispose());
        animationSets.Values.ForEach(it => it.Dispose());

        string TagValue(List <string> tags, string tag)
        {
            return(tags.Find(it => it.Trim().StartsWith(tag + ":"))?.Let(it => it.Substring(it.IndexOf(':') + 1).Trim()));
        }

        bool FlagValue(List <string> tags, string tag)
        {
            return(tags.Any(it => it.Trim() == tag));
        }

        void DisposeImageSprite()
        {
            if (currentImageSprite != null)
            {
                Context.AssetMemory.DisposeAsset(currentImageSpritePath, AssetTag.DialogueImage);
                currentImageSprite     = null;
                currentImageSpritePath = null;
            }
        }

        string ReplacePlaceholders(string str)
        {
            str = str.Replace("[N/A]", "");
            str = str.Trim();
            if (str.StartsWith("[STORY_"))
            {
                str = str.Substring(1, str.Length - 2).Get();
            }
            foreach (var(placeholder, function) in PlaceholderFunctions)
            {
                if (str.Contains(placeholder))
                {
                    str = str.Replace(placeholder, function());
                }
            }
            return(str);
        }
    }
Example #20
0
    public void SetSigningIn()
    {
        name.text = "PROFILE_WIDGET_SIGNING_IN".Get();
        name.DOKill();
        name.color = name.color.WithAlpha(1);
        name.DOFade(0, 0.4f).SetLoops(-1, LoopType.Yoyo).SetEase(Ease.InOutFlash);
        infoLayoutGroup.gameObject.SetActive(false);
        LayoutFixer.Fix(layoutGroup.transform);
        background.color   = Color.white;
        spinner.IsSpinning = true;

        if (Context.IsOffline())
        {
            Context.OnlinePlayer.FetchProfile().Then(it =>
            {
                if (it == null)
                {
                    SetSignedOut();
                    Context.OnlinePlayer.Deauthenticate();
                }
                else
                {
                    SetSignedIn(Context.OnlinePlayer.LastProfile = it);
                    Context.OnlinePlayer.IsAuthenticated         = true;
                }
            });
            return;
        }

        Context.OnlinePlayer.AuthenticateWithJwtToken()
        .Then(profile =>
        {
            Toast.Next(Toast.Status.Success, "TOAST_SUCCESSFULLY_SIGNED_IN".Get());
            SetSignedIn(profile);
            Context.OnlinePlayer.IsAuthenticated = true;

            if (Context.IsOffline())
            {
                Context.SetOffline(false);
            }
        })
        .CatchRequestError(error =>
        {
            Context.OnlinePlayer.IsAuthenticated = false;
            if (error.IsNetworkError)
            {
                Context.Haptic(HapticTypes.Warning, true);
                var dialog                     = Dialog.Instantiate();
                dialog.Message                 = "DIALOG_USE_OFFLINE_MODE".Get();
                dialog.UseProgress             = false;
                dialog.UsePositiveButton       = true;
                dialog.UseNegativeButton       = true;
                dialog.OnPositiveButtonClicked = _ =>
                {
                    Context.SetOffline(true);
                    Context.OnlinePlayer.FetchProfile().Then(it =>
                    {
                        if (it == null)
                        {
                            SetSignedOut();
                            Context.OnlinePlayer.Deauthenticate();
                        }
                        else
                        {
                            SetSignedIn(Context.OnlinePlayer.LastProfile = it);
                            Context.OnlinePlayer.IsAuthenticated         = true;
                        }
                        dialog.Close();
                    }).Catch(exception => throw new InvalidOperationException());     // Impossible
                };
                dialog.OnNegativeButtonClicked = _ =>
                {
                    dialog.Close();
                    SetSigningIn();
                };
                dialog.Open();
            }
            else
            {
                switch (error.StatusCode)
                {
                case 401:
                    Toast.Next(Toast.Status.Failure, "TOAST_INCORRECT_ID_OR_PASSWORD".Get());
                    break;

                case 404:
                    Toast.Next(Toast.Status.Failure, "TOAST_ID_NOT_FOUND".Get());
                    break;

                default:
                    Toast.Next(Toast.Status.Failure, "TOAST_STATUS_CODE".Get(error.StatusCode));
                    break;
                }
                SetSignedOut();
            }
        });
    }
Example #21
0
    public async void SetModel(FullProfile profile)
    {
        Profile = profile;
        characterTransitionElement.Leave(false, true);
        characterTransitionElement.enterDuration = 1.2f;
        characterTransitionElement.enterDelay    = 0.4f;
        characterTransitionElement.onEnterStarted.SetListener(() =>
        {
            characterTransitionElement.enterDuration = 0.4f;
            characterTransitionElement.enterDelay    = 0;
        });

        avatar.SetModel(profile.User);
        levelProgressImage.fillAmount = (profile.Exp.TotalExp - profile.Exp.CurrentLevelExp)
                                        / (profile.Exp.NextLevelExp - profile.Exp.CurrentLevelExp);
        uidText.text = profile.User.Uid;

        void MarkOffline()
        {
            statusCircleImage.color = "#757575".ToColor();
            statusText.text         = "PROFILE_STATUS_OFFLINE".Get();
        }

        void MarkOnline()
        {
            statusCircleImage.color = "#47dc47".ToColor();
            statusText.text         = "PROFILE_STATUS_ONLINE".Get();
        }

        if (profile.User.Uid == Context.OnlinePlayer.LastProfile?.User.Uid)
        {
            if (Context.IsOffline())
            {
                MarkOffline();
            }
            else
            {
                MarkOnline();
            }
        }
        else
        {
            if (profile.LastActive == null)
            {
                MarkOffline();
            }
            else
            {
                var lastActive = profile.LastActive.Value.LocalDateTime;
                if (DateTime.Now - lastActive <= TimeSpan.FromMinutes(30))
                {
                    MarkOnline();
                }
                else
                {
                    statusCircleImage.color = "#757575".ToColor();
                    statusText.text         = "PROFILE_STATUS_LAST_SEEN_X".Get(lastActive.Humanize());
                }
            }
        }

        if (profile.Tier == null)
        {
            tierText.transform.parent.gameObject.SetActive(false);
        }
        else
        {
            tierText.transform.parent.gameObject.SetActive(true);
            tierText.text = profile.Tier.name;
            tierGradient.SetGradient(new ColorGradient(profile.Tier.colorPalette.background));
        }
        ratingText.text            = $"{"PROFILE_WIDGET_RATING".Get()} {profile.Rating:0.00}";
        levelText.text             = $"{"PROFILE_WIDGET_LEVEL".Get()} {profile.Exp.CurrentLevel}";
        expText.text               = $"{"PROFILE_WIDGET_EXP".Get()} {(int) profile.Exp.TotalExp}/{(int) profile.Exp.NextLevelExp}";
        totalRankedPlaysText.text  = profile.Activities.TotalRankedPlays.ToString("N0");
        totalClearedNotesText.text = profile.Activities.ClearedNotes.ToString("N0");
        highestMaxComboText.text   = profile.Activities.MaxCombo.ToString("N0");
        avgRankedAccuracyText.text = ((profile.Activities.AverageRankedAccuracy ?? 0) * 100).ToString("0.00") + "%";
        totalRankedScoreText.text  = (profile.Activities.TotalRankedScore ?? 0).ToString("N0");
        totalPlayTimeText.text     = TimeSpan.FromSeconds(profile.Activities.TotalPlayTime)
                                     .Let(it => it.ToString(it.Days > 0 ? @"d\d\ h\h\ m\m\ s\s" : @"h\h\ m\m\ s\s"));

        chartRadioGroup.onSelect.SetListener(type => UpdateChart((ChartType)Enum.Parse(typeof(ChartType), type, true)));
        UpdateChart(ChartType.AvgRating);

        pillRows.ForEach(it => LayoutFixer.Fix(it));
        if (Context.IsOnline())
        {
            var eventBadges = profile.GetEventBadges();
            if (eventBadges.Any())
            {
                badgeGrid.gameObject.SetActive(true);
                badgeGrid.SetModel(eventBadges);
            }
            else
            {
                badgeGrid.gameObject.SetActive(false);
            }
        }

        foreach (Transform child in recordSection.recordCardHolder)
        {
            Destroy(child.gameObject);
        }
        foreach (Transform child in levelSection.levelCardHolder)
        {
            Destroy(child.gameObject);
        }
        foreach (Transform child in collectionSection.collectionCardHolder)
        {
            Destroy(child.gameObject);
        }

        if (profile.RecentRecords.Count > 0)
        {
            recordSection.gameObject.SetActive(true);
            foreach (var record in profile.RecentRecords.Take(6))
            {
                var recordCard = Instantiate(recordCardPrefab, recordSection.recordCardHolder);
                recordCard.SetModel(new RecordView {
                    DisplayOwner = false, Record = record
                });
            }
        }
        else
        {
            recordSection.gameObject.SetActive(false);
        }

        if (profile.LevelCount > 0)
        {
            levelSection.gameObject.SetActive(true);
            foreach (var level in profile.Levels.Take(6))
            {
                var levelCard = Instantiate(levelCardPrefab, levelSection.levelCardHolder);
                levelCard.SetModel(new LevelView {
                    DisplayOwner = false, Level = level.ToLevel(LevelType.User)
                });
            }

            viewAllLevelsButton.GetComponentInChildren <Text>().text = "PROFILE_VIEW_ALL_X".Get(profile.LevelCount);
            viewAllLevelsButton.onPointerClick.SetListener(_ =>
            {
                Context.ScreenManager.ChangeScreen(CommunityLevelSelectionScreen.Id, ScreenTransition.In, 0.4f,
                                                   transitionFocus: ((RectTransform)viewAllLevelsButton.transform).GetScreenSpaceCenter(),
                                                   payload: new CommunityLevelSelectionScreen.Payload
                {
                    Query = new OnlineLevelQuery {
                        owner = profile.User.Uid, category = "all", sort = "creation_date", order = "desc"
                    },
                });
            });
            if (profile.FeaturedLevelCount > 0)
            {
                viewAllFeaturedLevelsButton.gameObject.SetActive(true);
                viewAllFeaturedLevelsButton.GetComponentInChildren <Text>().text =
                    "PROFILE_VIEW_FEATURED_X".Get(profile.FeaturedLevelCount);
                viewAllFeaturedLevelsButton.onPointerClick.SetListener(_ =>
                {
                    Context.ScreenManager.ChangeScreen(CommunityLevelSelectionScreen.Id, ScreenTransition.In, 0.4f,
                                                       transitionFocus: ((RectTransform)viewAllFeaturedLevelsButton.transform).GetScreenSpaceCenter(),
                                                       payload: new CommunityLevelSelectionScreen.Payload
                    {
                        Query = new OnlineLevelQuery {
                            owner = profile.User.Uid, category = "featured", sort = "creation_date", order = "desc"
                        },
                    });
                });
            }
            else
            {
                viewAllFeaturedLevelsButton.gameObject.SetActive(false);
            }

            viewAllLevelsButton.transform.parent.RebuildLayout();
        }
        else
        {
            levelSection.gameObject.SetActive(false);
        }

        if (profile.CollectionCount > 0)
        {
            collectionSection.gameObject.SetActive(true);
            foreach (var collection in profile.Collections.Take(6))
            {
                var collectionCard = Instantiate(collectionCardPrefab, collectionSection.collectionCardHolder);
                collectionCard.SetModel(collection);
            }
        }
        else
        {
            collectionSection.gameObject.SetActive(false);
        }

        LayoutFixer.Fix(sectionParent);

        await UniTask.DelayFrame(5);

        transform.RebuildLayout();

        await UniTask.DelayFrame(0);

        characterTransitionElement.Enter();
    }