Skip to content

Commit 93a31ab

Browse files
authored
Merge pull request #8 from IntoTheDev/vlad/messagepack/webgl
WebGL support and minor changes
2 parents eedcba2 + a5c9d53 commit 93a31ab

File tree

7 files changed

+176
-134
lines changed

7 files changed

+176
-134
lines changed

Runtime/AssetsContainer.cs

Lines changed: 40 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -11,43 +11,52 @@ namespace ToolBox.Serialization
1111
{
1212
internal sealed class AssetsContainer : ScriptableObject
1313
{
14-
[SerializeField] private AssetEntry[] _savedAssets = Array.Empty<AssetEntry>();
14+
[SerializeField] private AssetEntry[] _savedAssets;
1515
[SerializeField] private string[] _paths;
1616

17-
public bool TryResolveId(object value, out string id)
17+
public bool TryResolveId(Object value, out string id)
1818
{
1919
id = null;
2020

21-
if (value is not Object obj || !TryGetValue(obj, out var entry))
21+
if (!TryGetByObject(value, out var entry))
22+
{
2223
return false;
23-
24+
}
25+
2426
id = entry.Guid;
2527
return true;
2628
}
2729

28-
public bool TryResolveReference(string id, out object value)
30+
public bool TryResolveReference(string id, out Object value)
2931
{
3032
value = null;
31-
32-
if (id == null)
33+
34+
if (!TryGetById(id, out var entry))
35+
{
3336
return false;
37+
}
3438

35-
var contains = TryGetValue(id, out var entry);
3639
value = entry.Asset;
37-
38-
return contains;
40+
return true;
3941
}
4042

4143
#if UNITY_EDITOR
4244
public void LoadAssets()
4345
{
4446
if (_paths == null)
47+
{
4548
return;
49+
}
4650

4751
_paths = _paths.Where(x => !string.IsNullOrEmpty(x) && AssetDatabase.IsValidFolder(x)).ToArray();
4852

4953
if (_paths.Length == 0)
54+
{
5055
return;
56+
}
57+
58+
// ReSharper disable once UseArrayEmptyMethod
59+
_savedAssets ??= new AssetEntry[0];
5160

5261
var assets = AssetDatabase
5362
.FindAssets("t:Object", _paths)
@@ -65,21 +74,21 @@ public void LoadAssets()
6574

6675
foreach (var asset in assets)
6776
{
68-
var path = AssetDatabase.GetAssetPath(asset);
69-
var guid = AssetDatabase.AssetPathToGUID(path);
70-
71-
if (!TryGetValue(asset, out _))
72-
newEntries.Add(new AssetEntry(guid, asset));
77+
if (!TryGetByObject(asset, out _))
78+
{
79+
newEntries.Add(new AssetEntry(Guid.NewGuid().ToString(), asset));
80+
}
7381

74-
var childAssets = AssetDatabase.LoadAllAssetRepresentationsAtPath(AssetDatabase.GetAssetPath(asset));
82+
var children = AssetDatabase.LoadAllAssetRepresentationsAtPath(AssetDatabase.GetAssetPath(asset));
7583

76-
foreach (var child in childAssets)
84+
foreach (var child in children)
7785
{
78-
if (TryGetValue(child, out _))
86+
if (TryGetByObject(child, out _))
87+
{
7988
continue;
89+
}
8090

81-
var childGuid = Guid.NewGuid().ToString();
82-
newEntries.Add(new AssetEntry(childGuid, child));
91+
newEntries.Add(new AssetEntry(Guid.NewGuid().ToString(), child));
8392
}
8493
}
8594

@@ -89,18 +98,20 @@ public void LoadAssets()
8998

9099
public void Clear()
91100
{
92-
_savedAssets = Array.Empty<AssetEntry>();
101+
_savedAssets = null;
93102
EditorUtility.SetDirty(this);
94103
}
95104
#endif
96105

97-
private bool TryGetValue(string guid, out AssetEntry entry)
106+
private bool TryGetById(string guid, out AssetEntry entry)
98107
{
99108
foreach (var asset in _savedAssets)
100109
{
101-
if (asset.Guid != guid)
110+
if (asset.Guid != guid)
111+
{
102112
continue;
103-
113+
}
114+
104115
entry = asset;
105116
return true;
106117
}
@@ -109,13 +120,15 @@ private bool TryGetValue(string guid, out AssetEntry entry)
109120
return false;
110121
}
111122

112-
private bool TryGetValue(Object obj, out AssetEntry entry)
123+
private bool TryGetByObject(Object value, out AssetEntry entry)
113124
{
114125
foreach (var asset in _savedAssets)
115126
{
116-
if (asset.Asset != obj)
127+
if (asset.Asset != value)
128+
{
117129
continue;
118-
130+
}
131+
119132
entry = asset;
120133
return true;
121134
}

Runtime/AssetsContainerEditor.cs

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,10 @@ private void OnEnable()
2323
private void OnGUI()
2424
{
2525
var obj = new SerializedObject(_provider);
26-
obj.Update();
2726
var objectsProperty = obj.FindProperty("_savedAssets");
2827
var pathsProperty = obj.FindProperty("_paths");
28+
29+
obj.Update();
2930

3031
DrawPaths(pathsProperty);
3132
DrawButtons();
@@ -39,7 +40,7 @@ private void DrawPaths(SerializedProperty pathsProperty)
3940
var selectContent = new GUIContent("Select Path");
4041
var removeContent = new GUIContent("x");
4142

42-
for (int i = 0; i < pathsProperty.arraySize; i++)
43+
for (var i = 0; i < pathsProperty.arraySize; i++)
4344
{
4445
EditorGUILayout.BeginHorizontal();
4546

@@ -48,40 +49,54 @@ private void DrawPaths(SerializedProperty pathsProperty)
4849

4950
if (GUILayout.Button(selectContent, EditorStyles.miniButtonLeft, GUILayout.Width(75f)))
5051
{
51-
string path = EditorUtility.OpenFolderPanel("Select path", "Assets", "");
52+
var path = EditorUtility.OpenFolderPanel("Select path", "Assets", "");
5253

5354
if (path != "Assets" || path.Length != 0)
55+
{
5456
path = path.Substring(path.IndexOf("Assets"));
57+
}
5558

5659
if (AssetDatabase.IsValidFolder(path))
60+
{
5761
element.stringValue = path;
62+
}
5863
else
64+
{
5965
pathsProperty.DeleteArrayElementAtIndex(i);
66+
}
6067
}
6168

6269
if (GUILayout.Button(removeContent, EditorStyles.miniButtonLeft, GUILayout.Width(30f)))
70+
{
6371
pathsProperty.DeleteArrayElementAtIndex(i);
72+
}
6473

6574
EditorGUILayout.EndHorizontal();
6675
}
6776

6877
GUILayout.Space(10f);
6978

7079
if (GUILayout.Button("Add Path", GUILayout.Height(30f)))
80+
{
7181
pathsProperty.InsertArrayElementAtIndex(pathsProperty.arraySize);
82+
}
7283
}
7384

7485
private void DrawButtons()
7586
{
7687
EditorGUILayout.BeginHorizontal();
7788

7889
if (GUILayout.Button("Load assets at paths"))
90+
{
7991
_provider.LoadAssets();
92+
}
8093

8194
if (GUILayout.Button("Remove assets from container"))
8295
{
8396
if (EditorUtility.DisplayDialog("Clear", "Do you really want to remove all referenced assets?", "Yes", "No"))
97+
{
8498
_provider.Clear();
99+
}
85100
}
86101

87102
EditorGUILayout.EndHorizontal();

Runtime/DataSerializer.cs

Lines changed: 47 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System.Threading;
44
using System.Threading.Tasks;
55
using MessagePack;
6+
using MessagePack.Resolvers;
67
using UnityEngine;
78

89
namespace ToolBox.Serialization
@@ -14,21 +15,18 @@ public static class DataSerializer
1415

1516
internal static AssetsContainer Container { get; private set; }
1617

17-
public static MessagePackSerializerOptions Options { get; set; } =
18-
MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate.Options;
18+
public static MessagePackSerializerOptions Options { get; set; } = ContractlessStandardResolverAllowPrivate.Options;
1919

2020
public static void Save<T>(string key, T data)
2121
{
2222
var bytes = Serialize(data);
2323

24-
if (_data.ContainsKey(key))
24+
if (_data.TryAdd(key, bytes))
2525
{
26-
_data[key] = bytes;
27-
}
28-
else
29-
{
30-
_data.Add(key, bytes);
26+
return;
3127
}
28+
29+
_data[key] = bytes;
3230
}
3331

3432
public static T Load<T>(string key)
@@ -69,75 +67,83 @@ public static void DeleteAll()
6967
_data.Clear();
7068
}
7169

72-
public static byte[] Serialize<T>(T data)
73-
{
74-
return MessagePackSerializer.Serialize(data, Options);
75-
}
76-
77-
public static T Deserialize<T>(byte[] bytes)
78-
{
79-
return MessagePackSerializer.Deserialize<T>(bytes, Options);
80-
}
81-
8270
public static void SaveFile(string fileName)
8371
{
84-
var path = CreatePath(fileName);
72+
var path = GetPath(fileName);
8573
var bytes = Serialize(_data);
8674

8775
File.WriteAllBytes(path, bytes);
76+
77+
#if UNITY_WEBGL
78+
Application.ExternalEval("_JS_FileSystem_Sync();");
79+
#endif
8880
}
89-
81+
9082
public static async Task SaveFileAsync(string fileName, CancellationToken token = default)
9183
{
92-
var path = CreatePath(fileName);
84+
var path = GetPath(fileName);
9385
var bytes = Serialize(_data);
9486

9587
await File.WriteAllBytesAsync(path, bytes, token);
88+
89+
#if UNITY_WEBGL
90+
Application.ExternalEval("_JS_FileSystem_Sync();");
91+
#endif
9692
}
9793

9894
public static void LoadFile(string fileName)
9995
{
100-
var path = CreatePath(fileName);
96+
var path = GetPath(fileName);
10197
var bytes = File.ReadAllBytes(path);
10298

103-
if (TryDeserializeData(bytes, out var data))
104-
_data = data;
99+
if (bytes.Length == 0)
100+
{
101+
return;
102+
}
103+
104+
_data = Deserialize<Dictionary<string, byte[]>>(bytes);
105105
}
106-
106+
107107
public static async Task LoadFileAsync(string fileName, CancellationToken token = default)
108108
{
109-
var path = CreatePath(fileName);
109+
var path = GetPath(fileName);
110110
var bytes = await File.ReadAllBytesAsync(path, token);
111111

112-
if (TryDeserializeData(bytes, out var data))
113-
_data = data;
112+
if (bytes.Length == 0)
113+
{
114+
return;
115+
}
116+
117+
_data = Deserialize<Dictionary<string, byte[]>>(bytes);
118+
}
119+
120+
public static byte[] Serialize<T>(T data)
121+
{
122+
return MessagePackSerializer.Serialize(data, Options);
123+
}
124+
125+
public static T Deserialize<T>(byte[] bytes)
126+
{
127+
return MessagePackSerializer.Deserialize<T>(bytes, Options);
114128
}
115129

130+
// Should we get rid of Setup and let user configure DataSerializer (there's only Container lol) themselves?
116131
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
117132
private static void Setup()
118133
{
119134
Container = Resources.Load<AssetsContainer>("ToolBoxAssetsContainer");
120135
}
121136

122-
private static string CreatePath(string fileName)
137+
private static string GetPath(string fileName)
123138
{
124139
var path = Path.Combine(_persistentDataPath, fileName);
125140

126141
if (!File.Exists(path))
142+
{
127143
File.Create(path).Close();
144+
}
128145

129146
return path;
130147
}
131-
132-
private static bool TryDeserializeData(byte[] bytes, out Dictionary<string, byte[]> data)
133-
{
134-
data = null;
135-
136-
if (bytes.Length == 0)
137-
return false;
138-
139-
data = Deserialize<Dictionary<string, byte[]>>(bytes);
140-
return true;
141-
}
142148
}
143-
}
149+
}

0 commit comments

Comments
 (0)