Skip to content

Commit

Permalink
feat: Make RxProps to use SHR from renderer
Browse files Browse the repository at this point in the history
  • Loading branch information
OnedgeLee committed Jun 13, 2024
1 parent 361d0cf commit 02e70ee
Show file tree
Hide file tree
Showing 14 changed files with 69 additions and 43 deletions.
15 changes: 8 additions & 7 deletions nekoyume/Assets/_Scripts/Blockchain/ActionRenderHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -754,7 +754,7 @@ private void ResponseCreateAvatar(
{
await UpdateAgentStateAsync(eval);
await UpdateAvatarState(eval, eval.Action.index);
await RxProps.SelectAvatarAsync(eval.Action.index);
await RxProps.SelectAvatarAsync(eval.Action.index, eval.OutputState);
}).ToObservable()
.ObserveOnMainThread()
.Subscribe(x =>
Expand Down Expand Up @@ -2115,7 +2115,7 @@ private ActionEvaluation<EventDungeonBattle> PrepareEventDungeonBattle(
var task = UniTask.RunOnThreadPool(() =>
{
UpdateCurrentAvatarStateAsync(eval).Forget();
RxProps.EventDungeonInfo.UpdateAsync().Forget();
RxProps.EventDungeonInfo.UpdateAsync(eval.OutputState).Forget();
_disposableForBattleEnd = null;
Game.Game.instance.Stage.IsAvatarStateUpdatedAfterBattle = true;
}, configureAwait: false);
Expand Down Expand Up @@ -2602,12 +2602,12 @@ private static async UniTaskVoid ResponseJoinArenaAsync(
eval.Action.round == currentRound.Round)
{
await UniTask.WhenAll(
RxProps.ArenaInfoTuple.UpdateAsync(),
RxProps.ArenaInformationOrderedWithScore.UpdateAsync());
RxProps.ArenaInfoTuple.UpdateAsync(eval.OutputState),
RxProps.ArenaInformationOrderedWithScore.UpdateAsync(eval.OutputState));
}
else
{
await RxProps.ArenaInfoTuple.UpdateAsync();
await RxProps.ArenaInfoTuple.UpdateAsync(eval.OutputState);
}

if (arenaJoin && arenaJoin.IsActive())
Expand Down Expand Up @@ -2646,8 +2646,8 @@ private async void ResponseBattleArenaAsync(ActionEvaluation<BattleArena> eval)
}

// NOTE: Start cache some arena info which will be used after battle ends.
await UniTask.WhenAll(RxProps.ArenaInfoTuple.UpdateAsync(),
RxProps.ArenaInformationOrderedWithScore.UpdateAsync());
await UniTask.WhenAll(RxProps.ArenaInfoTuple.UpdateAsync(eval.OutputState),
RxProps.ArenaInformationOrderedWithScore.UpdateAsync(eval.OutputState));

_disposableForBattleEnd?.Dispose();
_disposableForBattleEnd = Game.Game.instance.Arena.OnArenaEnd
Expand Down Expand Up @@ -3165,6 +3165,7 @@ private void ManipulateState()
{
RxProps.SelectAvatarAsync(
States.Instance.CurrentAvatarKey,
eval.OutputState,
forceNewSelection: true).Forget();
NotificationSystem.Push(
MailType.System,
Expand Down
2 changes: 2 additions & 0 deletions nekoyume/Assets/_Scripts/Blockchain/Agent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ public class Agent : MonoBehaviour, IDisposable, IAgent
public int AppProtocolVersion { get; private set; }
public BlockHash BlockTipHash => blocks.Tip.Hash;

public HashDigest<SHA256> BlockTipStateRootHash => blocks.Tip.StateRootHash;

private readonly Subject<(NCTx tx, List<ActionBase> actions)> _onMakeTransactionSubject =
new Subject<(NCTx tx, List<ActionBase> actions)>();

Expand Down
2 changes: 2 additions & 0 deletions nekoyume/Assets/_Scripts/Blockchain/IAgent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ public interface IAgent

BlockHash BlockTipHash { get; }

HashDigest<SHA256> BlockTipStateRootHash { get; }

IObservable<(Transaction tx, List<ActionBase> actions)>
OnMakeTransaction { get; }

Expand Down
10 changes: 8 additions & 2 deletions nekoyume/Assets/_Scripts/Blockchain/RPCAgent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ public class RPCAgent : MonoBehaviour, IAgent, IActionEvaluationHubReceiver

public BlockHash BlockTipHash { get; private set; }

public HashDigest<SHA256> BlockTipStateRootHash { get; private set; }

private readonly Subject<(NCTx tx, List<ActionBase> actions)> _onMakeTransactionSubject =
new Subject<(NCTx tx, List<ActionBase> actions)>();

Expand Down Expand Up @@ -950,17 +952,21 @@ public void OnUnrender(byte[] evaluation)

public void OnRenderBlock(byte[] oldTip, byte[] newTip)
{
UniTask.RunOnThreadPool<(long, BlockHash)>(() =>
UniTask.RunOnThreadPool<(long, BlockHash, HashDigest<SHA256>)>(() =>
{
var dict = (Dictionary) _codec.Decode(newTip);
var newTipBlock = BlockMarshaler.UnmarshalBlock(dict);
return (newTipBlock.Index, new BlockHash(newTipBlock.Hash.ToByteArray()));
return (
newTipBlock.Index,
newTipBlock.Hash,
newTipBlock.StateRootHash);
}).ToObservable().ObserveOnMainThread().Subscribe(tuple =>
{
_blockHashCache.Add(tuple.Item1, tuple.Item2);
BlockIndex = tuple.Item1;
BlockIndexSubject.OnNext(BlockIndex);
BlockTipHash = tuple.Item2;
BlockTipStateRootHash = tuple.Item3;
BlockTipHashSubject.OnNext(BlockTipHash);
_lastTipChangedAt = DateTimeOffset.UtcNow;
Expand Down
6 changes: 3 additions & 3 deletions nekoyume/Assets/_Scripts/Game/Game.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1314,7 +1314,7 @@ public static IDictionary<string, string> GetTableCsvAssets()
return container.tableCsvAssets.ToDictionary(asset => asset.name, asset => asset.text);
}

private static async void EnterNext()
private async void EnterNext()
{
NcDebug.Log("[Game] EnterNext() invoked");
if (!GameConfig.IsEditor)
Expand All @@ -1330,7 +1330,7 @@ private static async void EnterNext()
var sw = new Stopwatch();
sw.Reset();
sw.Start();
await RxProps.SelectAvatarAsync(slotIndex, true);
await RxProps.SelectAvatarAsync(slotIndex, Agent.BlockTipStateRootHash, true);
sw.Stop();
NcDebug.Log("[Game] EnterNext()... SelectAvatarAsync() finished in" +
$" {sw.ElapsedMilliseconds}ms.(elapsed)");
Expand Down Expand Up @@ -1362,7 +1362,7 @@ private static async void EnterNext()
var sw = new Stopwatch();
sw.Reset();
sw.Start();
await RxProps.SelectAvatarAsync(slotIndex, true);
await RxProps.SelectAvatarAsync(slotIndex, Agent.BlockTipStateRootHash, true);
sw.Stop();
NcDebug.Log("[Game] EnterNext()... SelectAvatarAsync() finished in" +
$" {sw.ElapsedMilliseconds}ms.(elapsed)");
Expand Down
32 changes: 18 additions & 14 deletions nekoyume/Assets/_Scripts/State/AsyncUpdatableRxProp.cs
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
using System;
using System;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;

namespace Nekoyume.State
{
using Libplanet.Common;
using System.Security.Cryptography;
using UniRx;

public interface IReadOnlyAsyncUpdatableRxProp<T> : IReadOnlyReactiveProperty<T>
{
bool IsUpdating { get; }

UniTask<T> UpdateAsync(bool forceNotify = false);
UniTask<T> UpdateAsync(HashDigest<SHA256> stateRootHash, bool forceNotify = false);

IObservable<T> UpdateAsObservable(bool forceNotify = false);
IObservable<T> UpdateAsObservable(HashDigest<SHA256> stateRootHash, bool forceNotify = false);

IDisposable SubscribeWithUpdateOnce(Action<T> onNext, bool forceNotify = false);
IDisposable SubscribeWithUpdateOnce(Action<T> onNext, HashDigest<SHA256> stateRootHash, bool forceNotify = false);

IDisposable SubscribeOnMainThreadWithUpdateOnce(
Action<T> onNext,
HashDigest<SHA256> stateRootHash,
bool forceNotify = false);
}

Expand All @@ -30,27 +33,27 @@ public class AsyncUpdatableRxProp<T> :
ReactiveProperty<T>,
IAsyncUpdatableRxProp<T>
{
private readonly Func<T, Task<T>> _updateAsyncFunc;
private readonly Func<T, HashDigest<SHA256>, Task<T>> _updateAsyncFunc;

public bool IsUpdating { get; private set; } = false;

public AsyncUpdatableRxProp(Func<T, Task<T>> updateAsyncFunc) :
public AsyncUpdatableRxProp(Func<T, HashDigest<SHA256>, Task<T>> updateAsyncFunc) :
this(default, updateAsyncFunc)
{
}

public AsyncUpdatableRxProp(T defaultValue, Func<T, Task<T>> updateAsyncFunc)
public AsyncUpdatableRxProp(T defaultValue, Func<T, HashDigest<SHA256>, Task<T>> updateAsyncFunc)
{
Value = defaultValue;
_updateAsyncFunc = updateAsyncFunc
?? throw new ArgumentNullException(nameof(updateAsyncFunc));
}

public async UniTask<T> UpdateAsync(bool forceNotify = false)
public async UniTask<T> UpdateAsync(HashDigest<SHA256> stateRootHash, bool forceNotify = false)
{
IsUpdating = true;
var t = await Task.Run(async () =>
await _updateAsyncFunc(Value));
await _updateAsyncFunc(Value, stateRootHash));
IsUpdating = false;
if (forceNotify)
{
Expand All @@ -64,20 +67,21 @@ public async UniTask<T> UpdateAsync(bool forceNotify = false)
return t;
}

public IObservable<T> UpdateAsObservable(bool forceNotify = false) =>
UpdateAsync(forceNotify).ToObservable();
public IObservable<T> UpdateAsObservable(HashDigest<SHA256> stateRootHash, bool forceNotify = false) =>
UpdateAsync(stateRootHash, forceNotify).ToObservable();

public IDisposable SubscribeWithUpdateOnce(Action<T> onNext, bool forceNotify = false)
public IDisposable SubscribeWithUpdateOnce(Action<T> onNext, HashDigest<SHA256> stateRootHash, bool forceNotify = false)
{
UpdateAsync(forceNotify).Forget();
UpdateAsync(stateRootHash, forceNotify).Forget();
return this.Subscribe(onNext);
}

public IDisposable SubscribeOnMainThreadWithUpdateOnce(
Action<T> onNext,
HashDigest<SHA256> stateRootHash,
bool forceNotify = false)
{
UpdateAsync(forceNotify).Forget();
UpdateAsync(stateRootHash, forceNotify).Forget();
return this
.SubscribeOnMainThread()
.Subscribe(onNext);
Expand Down
10 changes: 7 additions & 3 deletions nekoyume/Assets/_Scripts/State/RxProps.Arena.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@

namespace Nekoyume.State
{
using Libplanet.Common;
using System.Security.Cryptography;
using UniRx;

public static partial class RxProps
Expand Down Expand Up @@ -143,7 +145,7 @@ private static void UpdateArenaTicketProgress(long blockIndex)

private static async Task<(ArenaInformation current, ArenaInformation next)>
UpdateArenaInfoTupleAsync(
(ArenaInformation current, ArenaInformation next) previous)
(ArenaInformation current, ArenaInformation next) previous, HashDigest<SHA256> stateRootHash)
{
var avatarAddress = _states.CurrentAvatarState?.address;
if (!avatarAddress.HasValue)
Expand Down Expand Up @@ -177,6 +179,7 @@ private static void UpdateArenaTicketProgress(long blockIndex)
nextRoundData.Round)
: default;
var dict = await _agent.GetStateBulkAsync(
stateRootHash,
ReservedAddresses.LegacyAccount,
new[]
{
Expand All @@ -196,7 +199,8 @@ dict[nextArenaInfoAddress] is List nextList
}

private static async Task<List<ArenaParticipantModel>>
UpdateArenaInformationOrderedWithScoreAsync(List<ArenaParticipantModel> previous)
UpdateArenaInformationOrderedWithScoreAsync(
List<ArenaParticipantModel> previous, HashDigest<SHA256> stateRootHash)
{
var avatarAddress = _states.CurrentAvatarState?.address;
List<ArenaParticipantModel> avatarAddrAndScoresWithRank =
Expand Down Expand Up @@ -239,7 +243,7 @@ private static async Task<List<ArenaParticipantModel>>
playerScoreAddr
};
var stateBulk =
await agent.GetStateBulkAsync(ReservedAddresses.LegacyAccount, addrBulk);
await agent.GetStateBulkAsync(stateRootHash, ReservedAddresses.LegacyAccount, addrBulk);
var purchasedCountDuringInterval = stateBulk[purchasedCountAddress] is Integer iValue
? (int)iValue
: 0;
Expand Down
10 changes: 6 additions & 4 deletions nekoyume/Assets/_Scripts/State/RxProps.Event.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Collections.Generic;
using System.Collections.Generic;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;
using Libplanet.Action.State;
Expand All @@ -9,6 +9,8 @@

namespace Nekoyume.State
{
using Libplanet.Common;
using System.Security.Cryptography;
using UniRx;

public static partial class RxProps
Expand Down Expand Up @@ -111,7 +113,7 @@ private static void OnBlockIndexEvent(long blockIndex)

private static void OnAvatarChangedEvent()
{
_eventDungeonInfo.UpdateAsync().Forget();
_eventDungeonInfo.UpdateAsync(_agent.BlockTipStateRootHash).Forget();
}

private static void UpdateEventDungeonSheetData(long blockIndex)
Expand Down Expand Up @@ -204,7 +206,7 @@ private static void UpdateEventDungeonRemainingTimeText(long blockIndex)
}

private static async Task<EventDungeonInfo>
UpdateEventDungeonInfoAsync(EventDungeonInfo previous)
UpdateEventDungeonInfoAsync(EventDungeonInfo previous, HashDigest<SHA256> stateRootHash)
{
if (_eventDungeonInfoUpdatedBlockIndex == _agent.BlockIndex)
{
Expand All @@ -220,7 +222,7 @@ private static async Task<EventDungeonInfo>
var addr = Nekoyume.Model.Event.EventDungeonInfo.DeriveAddress(
_currentAvatarAddr.Value,
EventDungeonRow.Id);
return await _agent.GetStateAsync(ReservedAddresses.LegacyAccount, addr)
return await _agent.GetStateAsync(stateRootHash, ReservedAddresses.LegacyAccount, addr)
is Bencodex.Types.List serialized
? new EventDungeonInfo(serialized)
: null;
Expand Down
7 changes: 5 additions & 2 deletions nekoyume/Assets/_Scripts/State/RxProps.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@

namespace Nekoyume.State
{
using Libplanet.Common;
using System.Security.Cryptography;
using UniRx;

public static partial class RxProps
Expand Down Expand Up @@ -69,14 +71,15 @@ public static void Stop()

public static async UniTask SelectAvatarAsync(
int avatarIndexToSelect,
HashDigest<SHA256> stateRootHash,
bool forceNewSelection = false)
{
await States.Instance.SelectAvatarAsync(
avatarIndexToSelect,
forceNewSelection: forceNewSelection);
await UniTask.WhenAll(
ArenaInfoTuple.UpdateAsync(),
EventDungeonInfo.UpdateAsync(),
ArenaInfoTuple.UpdateAsync(stateRootHash),
EventDungeonInfo.UpdateAsync(stateRootHash),
WorldBossStates.Set(States.Instance.CurrentAvatarState.address),
UniTask.RunOnThreadPool(States.Instance.InitAvatarBalancesAsync).ToObservable().ObserveOnMainThread().ToUniTask(),
States.Instance.InitItemSlotStates());
Expand Down
7 changes: 4 additions & 3 deletions nekoyume/Assets/_Scripts/UI/Widget/ArenaBoard.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Collections.Generic;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Cysharp.Threading.Tasks;
Expand Down Expand Up @@ -64,8 +64,9 @@ public async UniTaskVoid ShowAsync(bool ignoreShowAnimation = false)
loading.Show(LoadingScreen.LoadingType.Arena);
var sw = new Stopwatch();
sw.Start();
await UniTask.WhenAll(RxProps.ArenaInformationOrderedWithScore.UpdateAsync(),
RxProps.ArenaInfoTuple.UpdateAsync());
await UniTask.WhenAll(
RxProps.ArenaInformationOrderedWithScore.UpdateAsync(Game.Game.instance.Agent.BlockTipStateRootHash),
RxProps.ArenaInfoTuple.UpdateAsync(Game.Game.instance.Agent.BlockTipStateRootHash));
loading.Close();
Show(RxProps.ArenaInformationOrderedWithScore.Value,
ignoreShowAnimation);
Expand Down
5 changes: 3 additions & 2 deletions nekoyume/Assets/_Scripts/UI/Widget/ArenaJoin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,9 @@ public async UniTaskVoid ShowAsync(
sw.Start();
var loading = Find<LoadingScreen>();
loading.Show(LoadingScreen.LoadingType.Arena);
await UniTask.WhenAll(RxProps.ArenaInfoTuple.UpdateAsync(),
RxProps.ArenaInformationOrderedWithScore.UpdateAsync());
await UniTask.WhenAll(
RxProps.ArenaInfoTuple.UpdateAsync(Game.Game.instance.Agent.BlockTipStateRootHash),
RxProps.ArenaInformationOrderedWithScore.UpdateAsync(Game.Game.instance.Agent.BlockTipStateRootHash));
loading.Close();
sw.Stop();
NcDebug.Log($"[Arena] Loading Complete. {sw.Elapsed}");
Expand Down
2 changes: 1 addition & 1 deletion nekoyume/Assets/_Scripts/UI/Widget/LoginDetail.cs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ public async void LoginClick()
var loadingScreen = Find<LoadingScreen>();
loadingScreen.Show(
LoadingScreen.LoadingType.Entering, L10nManager.Localize("UI_IN_MINING_A_BLOCK"));
await RxProps.SelectAvatarAsync(_selectedIndex);
await RxProps.SelectAvatarAsync(_selectedIndex, Game.Game.instance.Agent.BlockTipStateRootHash);
loadingScreen.Close();
OnDidAvatarStateLoaded(States.Instance.CurrentAvatarState);
}
Expand Down
2 changes: 1 addition & 1 deletion nekoyume/Assets/_Scripts/UI/Widget/Screen/RewardScreen.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections;
using Nekoyume.Game.Controller;
using UnityEngine;
Expand Down
2 changes: 1 addition & 1 deletion nekoyume/Assets/_Scripts/UI/Widget/Synopsis.cs
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,7 @@ private async Task End()
loadingScreen.Show(
LoadingScreen.LoadingType.Entering,
L10nManager.Localize("UI_LOADING_BOOTSTRAP_START"));
await RxProps.SelectAvatarAsync(slotIndex);
await RxProps.SelectAvatarAsync(slotIndex, Game.Game.instance.Agent.BlockTipStateRootHash);
loadingScreen.Close();
Game.Event.OnRoomEnter.Invoke(false);
Game.Event.OnUpdateAddresses.Invoke();
Expand Down

0 comments on commit 02e70ee

Please sign in to comment.