Skip to content

Commit

Permalink
Added deserialization
Browse files Browse the repository at this point in the history
  • Loading branch information
spacehamster committed Dec 1, 2018
1 parent 12599a1 commit 561990a
Show file tree
Hide file tree
Showing 13 changed files with 194 additions and 114 deletions.
50 changes: 1 addition & 49 deletions CustomRaces/AssetsDump.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,58 +84,10 @@ public static void DumpEquipmentEntities()
JsonBlueprints.Dump(resource, kv.Key);
}
}
public static void Validate()
public static void DumpList()
{
Directory.CreateDirectory($"Blueprints/");
var names = new Dictionary<string, List<BlueprintScriptableObject>>();
var qualifiedNames = new Dictionary<string, List<BlueprintScriptableObject>>();
var blueprints = ResourcesLibrary.GetBlueprints<BlueprintScriptableObject>();
foreach (var blueprint in blueprints)
{
if (names.ContainsKey(blueprint.name))
{
names[blueprint.name].Add(blueprint);
}
else
{
names[blueprint.name] = new List<BlueprintScriptableObject>() { blueprint };
}
var qualifiedName = blueprint.GetType().ToString() + "." + blueprint.name;
if (qualifiedNames.ContainsKey(qualifiedName))
{
qualifiedNames[qualifiedName].Add(blueprint);
}
else
{
qualifiedNames[qualifiedName] = new List<BlueprintScriptableObject>() { blueprint };
}
}
using (var file = new StreamWriter("Blueprints/Duplicates.txt"))
{
foreach (var kv in names)
{
if (kv.Value.Count > 1)
{
foreach (var blueprint in kv.Value)
{
file.WriteLine($"{blueprint.name}\t{blueprint.AssetGuid}\t{blueprint.GetType()}\t");
}
}
}
}
using (var file = new StreamWriter("Blueprints/QualifiedDuplicates.txt"))
{
foreach (var kv in qualifiedNames)
{
if (kv.Value.Count > 1)
{
foreach (var blueprint in kv.Value)
{
file.WriteLine($"{blueprint.name}\t{blueprint.AssetGuid}\t{blueprint.GetType()}\t");
}
}
}
}
using (var file = new StreamWriter("Blueprints/Blueprints.txt"))
{
foreach (var blueprint in blueprints)
Expand Down
3 changes: 3 additions & 0 deletions CustomRaces/CustomRaces.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>libs\Newtonsoft.Json.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
Expand Down Expand Up @@ -91,9 +92,11 @@
</Reference>
<Reference Include="UnityEngine.Networking">
<HintPath>libs\UnityEngine.Networking.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="UnityEngine.UNETModule">
<HintPath>libs\UnityEngine.UNETModule.dll</HintPath>
<Private>False</Private>
</Reference>
</ItemGroup>
<ItemGroup>
Expand Down
23 changes: 22 additions & 1 deletion CustomRaces/JSON/BlueprintAssetIdConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,28 @@ public override object ReadJson(
JsonSerializer serializer
)
{
throw new NotImplementedException();
string text = (string)reader.Value;
Main.DebugLog($"Reading blueprint: {text}");
if (text == null || text == "null")
{
return null;
}
if (text.StartsWith("Blueprint"))
{
var parts = text.Split(':');
BlueprintScriptableObject blueprintScriptableObject = ResourcesLibrary.TryGetBlueprint(parts[1]);
if (blueprintScriptableObject == null)
{
throw new JsonSerializationException(string.Format("Failed to load blueprint by guid {0}", text));
}
return blueprintScriptableObject;
}
if (text.StartsWith("File"))
{
var parts = text.Split(':');
return JsonBlueprints.Load<BlueprintScriptableObject>($"customraces/mods/data/{parts[1]}");
}
throw new JsonSerializationException(string.Format("Invalid blueprint format {0}", text));
}

// ReSharper disable once IdentifierTypo
Expand Down
8 changes: 1 addition & 7 deletions CustomRaces/JSON/BlueprintComponentConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,8 @@ public override void WriteJson(JsonWriter w, object o, JsonSerializer szr)
j.WriteTo(w);
}

public override object ReadJson(
JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer
)
public override object ReadJson(JsonReader reader, Type type, object existing, JsonSerializer serializer)
{
//JToken token = JToken.Load(reader);
throw new NotImplementedException();
}
List<MemberInfo> GetSerializableMembers(Type objectType)
Expand Down
10 changes: 3 additions & 7 deletions CustomRaces/JSON/BlueprintContractResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ private static readonly BlueprintAssetIdConverter BlueprintAssetIdConverter
new XmlNodeConverter(),
new VersionConverter(),
new RegexConverter(),
//new BlueprintComponentConverter(true),
new LocalizedStringConverter(true),
new WeakResourceLinkConverter(true),
new UnityJsonConverter(true),
Expand All @@ -75,7 +74,6 @@ protected override JsonConverter ResolveContractConverter(Type objectType)
if (BlueprintScriptableObjectType.IsAssignableFrom(objectType))
if (objectType != RootBlueprintType)
{
//Main.DebugLog($"Using {BlueprintAssetIdConverter.GetType()} for {objectType}");
return BlueprintAssetIdConverter;
}
var prefCnv = PreferredConverters.FirstOrDefault(cnv => cnv.CanConvert(objectType));
Expand All @@ -96,7 +94,6 @@ protected override JsonConverter ResolveContractConverter(Type objectType)
converter = base.ResolveContractConverter(objectType);
if (converter == null) break;
}
//Main.DebugLog($"Found converter {converter?.GetType().ToString() ?? "NULL"} for {objectType}");
return null;
}

Expand All @@ -117,13 +114,11 @@ void Allow()
}
if (member is FieldInfo field)
{
//Main.DebugLog($"Serializing field {field.ReflectedType}.{field.Name}");
jsonProp.Readable = true;
jsonProp.Writable = true;
//Readonly field
if (field.IsInitOnly)
{
//Main.DebugLog($"Skipping readonly field {field.ReflectedType}.{field.Name}");
Skip();
return null;
}
Expand All @@ -132,11 +127,12 @@ void Allow()
Skip();
return null;
}
// ReSharper disable once InvertIf
if (field.FieldType.IsSubclassOf(BlueprintScriptableObjectType))
{
//MemberConverter required to deserialize see
//https://stackoverflow.com/questions/24946362/custom-jsonconverter-is-ignored-for-deserialization-when-using-custom-contract-r
jsonProp.MemberConverter = BlueprintAssetIdConverter;
jsonProp.Converter = BlueprintAssetIdConverter;
jsonProp.IsReference = false;
Allow();
}
}
Expand Down
7 changes: 1 addition & 6 deletions CustomRaces/JSON/GameObjectAssetIdConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,7 @@ public override void WriteJson(JsonWriter w, object o, JsonSerializer szr)
j.WriteTo(w);
}

public override object ReadJson(
JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer
)
public override object ReadJson(JsonReader reader, Type type, object existing, JsonSerializer serializer)
{
throw new NotImplementedException();
}
Expand Down
22 changes: 6 additions & 16 deletions CustomRaces/JSON/JsonBlueprints.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
using Kingmaker.Blueprints;
using Kingmaker.Blueprints.CharGen;
using Kingmaker.Blueprints.Classes;
using Kingmaker.Blueprints.Classes.Spells;
using Kingmaker.Blueprints.Items.Weapons;
using Kingmaker.Visual.CharacterSystem;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.IO;
Expand Down Expand Up @@ -82,24 +77,21 @@ public static T Load<T>(string filepath)
{
var type = typeof(BlueprintScriptableObject).IsAssignableFrom(typeof(T)) ? typeof(T) : null;
var settings = CreateSettings(type);
var text = File.ReadAllText(filepath);
return JsonConvert.DeserializeObject<T>(text, settings);
}
public class RaceConverter : CustomCreationConverter<BlueprintRace>
{
public override BlueprintRace Create(Type objectType)
var serializer = JsonSerializer.Create(settings);

using (StreamReader sr = new StreamReader(filepath))
using (JsonReader jsonReader = new JsonTextReader(sr))
{
return new BlueprintRace();
return serializer.Deserialize<T>(jsonReader);
}
}
public static T Loads<T>(string text)
{
var type = typeof(BlueprintScriptableObject).IsAssignableFrom(typeof(T)) ? typeof(T) : null;
var settings = CreateSettings(type);
var serializer = JsonSerializer.Create(settings);
var jsonReader = new JsonTextReader(new StringReader(text));
using (StringReader sr = new StringReader(text))
using (JsonReader writer = new JsonTextReader(sr))
using (JsonReader jsonReader = new JsonTextReader(sr))
{
return serializer.Deserialize<T>(jsonReader);
}
Expand All @@ -108,7 +100,6 @@ public static void Dump(BlueprintScriptableObject blueprint)
{
Directory.CreateDirectory($"Blueprints/{blueprint.GetType()}");
JsonSerializer serializer = JsonSerializer.Create(CreateSettings(blueprint.GetType()));
//using (StreamWriter sw = new StreamWriter(Console.OpenStandardOutput()))
using (StreamWriter sw = new StreamWriter($"Blueprints/{blueprint.GetType()}/{blueprint.name}.{blueprint.AssetGuid}.json"))
using (JsonWriter writer = new JsonTextWriter(sw))
{
Expand All @@ -120,7 +111,6 @@ public static void Dump(EquipmentEntity ee, string assetId)
Directory.CreateDirectory($"Blueprints/{ee.GetType()}");
JsonSerializer serializer
= JsonSerializer.Create(CreateSettings(null));
//using (StreamWriter sw = new StreamWriter(Console.OpenStandardOutput()))
using (StreamWriter sw = new StreamWriter($"Blueprints/{ee.GetType()}/{ee.name}.json"))
using (JsonWriter writer = new JsonTextWriter(sw))
{
Expand Down
10 changes: 3 additions & 7 deletions CustomRaces/JSON/LocalizedStringConverter.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using JetBrains.Annotations;
using Kingmaker.Blueprints;
using Kingmaker.Localization;
using Newtonsoft.Json;
using System;
Expand Down Expand Up @@ -34,14 +35,9 @@ public override void WriteJson(JsonWriter w, object o, JsonSerializer szr)
w.WriteValue(string.Format($"LocalizedString:{ls.Key}:{text}"));
}

public override object ReadJson(
JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer
)
public override object ReadJson(JsonReader reader, Type type, object existing, JsonSerializer serializer)
{
throw new NotImplementedException();
return RaceUtil.MakeLocalized("Test string");
}

// ReSharper disable once IdentifierTypo
Expand Down
6 changes: 4 additions & 2 deletions CustomRaces/JSON/UnityJsonConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -171,9 +171,11 @@ public override void WriteJson(JsonWriter w, object value, JsonSerializer szr)
}
}

public override object ReadJson(JsonReader r, Type type, object value, JsonSerializer szr)
public override object ReadJson(JsonReader reader, Type type, object existing, JsonSerializer serializer)
{
throw new NotImplementedException();
JToken token = JToken.Load(reader);
return null;
//throw new NotImplementedException($"Not implemented for type {type}");
}

public override bool CanConvert(Type objectType) => Enabled && SupportedTypes.Contains(objectType);
Expand Down
21 changes: 14 additions & 7 deletions CustomRaces/JSON/WeakResourceLinkConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,21 @@ public override void WriteJson(JsonWriter w, object o, JsonSerializer szr)
w.WriteValue(string.Format($"Resource:{resource.AssetId}:{path ?? "NULL"}"));
}

public override object ReadJson(
JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer
)
public override object ReadJson(JsonReader reader, Type type, object existing, JsonSerializer serializer)
{
throw new NotImplementedException();
string text = (string)reader.Value;
if (text == null || text == "null")
{
return null;
}
if (text.StartsWith("Resource"))
{
var parts = text.Split(':');
var link = (WeakResourceLink)Activator.CreateInstance(type);
link.AssetId = parts[1];
return link;
}
throw new NotImplementedException($"Not implemented for type {type} with value {text}");
}

// ReSharper disable once IdentifierTypo
Expand Down
13 changes: 3 additions & 10 deletions CustomRaces/Main.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,13 @@ static void OnGUI(UnityModManager.ModEntry modEntry)
{
AssetsDump.DumpEquipmentEntities();
}
if (GUILayout.Button("ValidateBlueprints"))
if (GUILayout.Button("DumpList"))
{
AssetsDump.Validate();
AssetsDump.DumpList();
}
if (GUILayout.Button("TestLoad"))
{
var bp = JsonBlueprints.Loads<BlueprintRace>("{name : \"Test\"}");
var bp = JsonBlueprints.Load<BlueprintCharacterClass>("mods/customraces/data/rangerclass.json");
DebugLog("Loaded " + (bp?.name ?? "NULL"));
}
if (GUILayout.Button("FindObject"))
Expand All @@ -109,13 +109,6 @@ static void OnGUI(UnityModManager.ModEntry modEntry)
{
RaceManager.Reload();
}
if (GUILayout.Button("LogRace"))
{
var player = Game.Instance.Player.MainCharacter.Value;
var descriptor = player.Descriptor;
var race = descriptor.Progression.Race;
DebugLog("MainCharacter Race is " + race.name + " " + race.AssetGuid);
}
int newTorso = (int)GUILayout.HorizontalSlider(torso, -1, MeshTestRace.testAssets.Length - 1, GUILayout.Width(300));
GUILayout.Label("Torso: " + newTorso);
if(torso != newTorso)
Expand Down
5 changes: 3 additions & 2 deletions CustomRaces/RaceManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ public static void Init()
{
var blueprints = ResourcesLibrary.LibraryObject.BlueprintsByAssetId;
var goblinRace = (BlueprintRace)blueprints["9d168ca7100e9314385ce66852385451"];
races.Add(goblinRace);

/*races.Add(goblinRace);
races.Add(Drow.CreateRace());
races.Add(Dhampir.CreateRace());
#if (DEBUG)
Expand All @@ -28,7 +29,7 @@ public static void Init()
characterClasses.Add(Slayer.CreateClass());
#if(DEBUG)
characterClasses.Add(Ninja.CreateClass());
#endif
#endif*/
}
static public void Reload()
{
Expand Down
Loading

0 comments on commit 561990a

Please sign in to comment.