forked from vrchat-community/ClientSim
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClientSimPlayerObjectStorage.cs
More file actions
181 lines (150 loc) · 6.27 KB
/
ClientSimPlayerObjectStorage.cs
File metadata and controls
181 lines (150 loc) · 6.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Cysharp.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;
using VRC.SDK3.ClientSim.Interfaces;
using VRC.SDK3.Data;
using VRC.SDKBase;
using VRC.Udon;
namespace VRC.SDK3.ClientSim.Persistence
{
[AddComponentMenu("")] // hides component in Add Component menu
public class ClientSimPlayerObjectStorage : ClientSimBehaviour
{
#if VRC_ENABLE_PLAYER_PERSISTENCE
public static string PlayerObjectsFolder => Path.Combine("ClientSimStorage", "PlayerObjects");
internal static string ActiveSceneName;
internal static string PlayerDataFilePath(VRCPlayerApi player)
{
string root = Path.GetDirectoryName(Application.dataPath);
string path = Path.Combine(root, PlayerObjectsFolder);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
return path + "/PlayerObject_" + $"{player.playerId}" + $"_{ActiveSceneName}" + ".json";
}
private VRCPlayerApi _player;
private IClientSimUdonEventSender _udonEventSender;
private IClientSimEventDispatcher _eventDispatcher;
private Dictionary<int,IClientSimNetworkView> _persistentObjects = new Dictionary<int, IClientSimNetworkView>();
private DataDictionary _persistentObjectData = new DataDictionary();
private bool _isInitialized = false;
private bool _HasJoined = false;
private Coroutine _ContinuousUpdate;
private const float _updateInterval = 1 / 4f;
private bool hadUpdate = false;
public void Init(VRCPlayerApi player, IClientSimUdonEventSender udonEventSender, IClientSimEventDispatcher eventDispatcher)
{
_player = player;
_udonEventSender = udonEventSender;
_eventDispatcher = eventDispatcher;
ActiveSceneName = SceneManager.GetActiveScene().name;
_eventDispatcher.Subscribe<ClientSimOnPlayerJoinedEvent>(OnPlayerJoined);
UdonBehaviour.RequestSerializationHook += RequestSerializationHook;
_isInitialized = true;
_ContinuousUpdate = StartCoroutine(UpdateContinuous());
}
private void OnDestroy()
{
if(_eventDispatcher != null)
_eventDispatcher.Unsubscribe<ClientSimOnPlayerJoinedEvent>(OnPlayerJoined);
if(_ContinuousUpdate != null)
StopCoroutine(_ContinuousUpdate);
}
public IEnumerator UpdateContinuous()
{
while (true)
{
if (_HasJoined && _isInitialized)
{
Encode();
}
yield return new WaitForSeconds(_updateInterval);
}
}
public void RequestSerializationHook(UdonBehaviour udonBehaviour)
{
ClientSimNetworkEventSending.Instance.QueueRequest(udonBehaviour, this);
}
private void OnPlayerJoined(ClientSimOnPlayerJoinedEvent payload)
{
if (payload.player.playerId == _player.playerId)
{
_HasJoined = true;
Decode();
}
}
public void Encode(GameObject gameObject = null)
{
if (!_isInitialized || !_HasJoined) return;
if(_persistentObjectData == null)
_persistentObjectData = new DataDictionary();
foreach (var keyValuePersistentObject in _persistentObjects)
{
DataToken key = keyValuePersistentObject.Key.ToString();
if (!_persistentObjectData.ContainsKey(key))
_persistentObjectData.Add(key, new DataList());
_persistentObjectData[key] = keyValuePersistentObject.Value.Encode(gameObject);
}
hadUpdate = true;
}
private async UniTask SaveToFile(string data)
{
await UniTask.SwitchToTaskPool();
try{
await File.WriteAllTextAsync(PlayerDataFilePath(_player), data);
}
catch (Exception e)
{
this.LogError($"Error saving PlayerObjects: {e.Message}");
}
}
private void Decode()
{
string path = PlayerDataFilePath(_player);
if (!File.Exists(path))
{
File.WriteAllText(path, "{}");
}
string json = File.ReadAllText(path);
if (!VRCJson.TryDeserializeFromJson(json, out DataToken token))
{
this.LogError($"Error initializing PlayerObjects: {token.Error}");
return;
}
_persistentObjectData = token.DataDictionary;
ClientSimPlayer player = _player.GetClientSimPlayer();
foreach (GameObject persistantObject in player.PlayerPersistenceObjects)
{
if (!persistantObject) continue;
IClientSimNetworkId networkId = persistantObject.GetComponent<IClientSimNetworkId>();
if (networkId == null) continue;
int id = networkId.GetNetworkId();
IClientSimNetworkView serializer = persistantObject.GetComponent<IClientSimNetworkView>();
_persistentObjects.TryAdd(id, serializer);
if (_persistentObjectData.TryGetValue(id.ToString(), out var data))
{
_persistentObjects[id].Decode(data.DataList);
}
}
_eventDispatcher.SendEvent(new ClientSimOnPlayerObjectsDecodedEvent { player = _player });
}
public void LateUpdate()
{
if (hadUpdate)
{
hadUpdate = false;
_eventDispatcher.SendEvent(new ClientSimOnPlayerObjectUpdateEndedEvent());
VRCJson.TrySerializeToJson(_persistentObjectData, JsonExportType.Beautify, out DataToken json);
SaveToFile(json.String).Forget();
}
}
#endif
}
}