Database Improvements

Brought in all the myriad improvements to the database tools from the Stream Pixels project
Added configurable nested entry grouping
This commit is contained in:
Reinier Vens 2021-04-07 01:27:35 +01:00
commit 968783bf9c
37 changed files with 865 additions and 580 deletions

View file

@ -5,7 +5,7 @@
"MessagePack",
"Unity.Mathematics",
"UniRx",
"CultCache"
"RethinkDB"
],
"includePlatforms": [],
"excludePlatforms": [],

View file

@ -4,26 +4,6 @@
using System;
public class NameAttribute : Attribute
{
public string Name;
public NameAttribute(string name)
{
Name = name;
}
}
public class OrderAttribute : Attribute
{
public int Order;
public OrderAttribute(int order)
{
Order = order;
}
}
[AttributeUsage(AttributeTargets.Class)]
public class EntityTypeRestrictionAttribute : Attribute
{

View file

@ -178,8 +178,8 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior
public override void Activate()
{
// if(CanFire)
// Trigger();
// base.Activate();
if(CanFire)
Trigger();
base.Activate();
}
}

View file

@ -15,8 +15,8 @@ public class SensorData : BehaviorData
[Inspectable, JsonProperty("sensitivity"), Key(3), RuntimeInspectable]
public PerformanceStat Sensitivity = new PerformanceStat();
[InspectableAnimationCurve, JsonProperty("sensitivityCurve"), Key(4), RuntimeInspectable]
public float4[] SensitivityCurve;
[InspectableAnimationCurve, JsonProperty("sensCurve"), Key(4), RuntimeInspectable]
public BezierCurve SensitivityCurve;
[Inspectable, JsonProperty("pingBoost"), Key(5), RuntimeInspectable]
public PerformanceStat PingBoost;

View file

@ -23,10 +23,10 @@ public abstract class WeaponData : BehaviorData
[Inspectable, JsonProperty("damage"), Key(2), RuntimeInspectable]
public PerformanceStat Damage = new PerformanceStat();
[RangedFloatInspectable(0,1), JsonProperty("penetration"), Key(3), RuntimeInspectable]
[InspectableRangedFloat(0,1), JsonProperty("penetration"), Key(3), RuntimeInspectable]
public PerformanceStat Penetration = new PerformanceStat();
[RangedFloatInspectable(0,1), JsonProperty("damageSpread"), Key(4)]
[InspectableRangedFloat(0,1), JsonProperty("damageSpread"), Key(4)]
public PerformanceStat DamageSpread = new PerformanceStat();
[Inspectable, JsonProperty("minRange"), Key(5), RuntimeInspectable]
@ -35,8 +35,8 @@ public abstract class WeaponData : BehaviorData
[Inspectable, JsonProperty("range"), Key(6), RuntimeInspectable]
public PerformanceStat Range = new PerformanceStat();
[InspectableAnimationCurve, JsonProperty("damageRange"), Key(7), RuntimeInspectable]
public float4[] DamageCurve;
[InspectableAnimationCurve, JsonProperty("damageCurve"), Key(7), RuntimeInspectable]
public BezierCurve DamageCurve;
[InspectablePrefab, JsonProperty("effect"), Key(8)]
public string EffectPrefab;

View file

@ -0,0 +1,123 @@
using System;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class BezierCurve
{
[JsonProperty("keys"), Key(0)] public float4[] Keys;
[IgnoreMember] private int2 _cachedIndices;
// Integrate area under curve between start and end time
public float IntegrateCurve(float startTime, float endTime, int steps)
{
return Integrate(Evaluate, startTime, endTime, steps);
}
// Integrate function f(x) using the trapezoidal rule between x=x_low..x_high
public static float Integrate(Func<float, float> f, float x_low, float x_high, int N_steps)
{
float h = (x_high - x_low) / N_steps;
float res = (f(x_low) + f(x_high)) / 2;
for (int i = 1; i < N_steps; i++)
{
res += f(x_low + i * h);
}
return h * res;
}
// public static float Screen(float a, float b)
// {
// return 1 - (1 - a)*(1 - b);
// }
public float Evaluate(float time)
{
// Clamp time
time = clamp(time, Keys[0].x, Keys[Keys.Length - 1].x);
FindSurroundingKeyframes(time, Keys);
return HermiteInterpolate(time, Keys[_cachedIndices.x], Keys[_cachedIndices.y]);
}
void FindSurroundingKeyframes(float time, float4[] curve)
{
// Check that time is within cached keyframe time
if (time >= curve[_cachedIndices.x].x &&
time <= curve[_cachedIndices.y].x)
{
return;
}
// Fall back to using dichotomic search.
var length = curve.Length;
int half;
int middle;
int first = 0;
while (length > 0)
{
half = length >> 1;
middle = first + half;
if (time < curve[middle].x)
{
length = half;
}
else
{
first = middle + 1;
length = length - half - 1;
}
}
// If not within range, we pick the last element twice.
var indices = int2(first - 1, min(curve.Length - 1, first));
_cachedIndices = indices;
}
float HermiteInterpolate(float time, in float4 leftKeyframe, in float4 rightKeyframe)
{
// Handle stepped curve.
if (isinf(leftKeyframe.w) || isinf(rightKeyframe.z))
{
return leftKeyframe.y;
}
float dx = rightKeyframe.x - leftKeyframe.x;
float m0;
float m1;
float t;
if (dx != 0.0f)
{
t = (time - leftKeyframe.x) / dx;
m0 = leftKeyframe.w * dx;
m1 = rightKeyframe.z * dx;
}
else
{
t = 0.0f;
m0 = 0;
m1 = 0;
}
return HermiteInterpolate(t, leftKeyframe.y, m0, m1, rightKeyframe.y);
}
static float HermiteInterpolate(float t, float p0, float m0, float m1, float p1)
{
// Unrolled the equations to avoid precision issue.
// (2 * t^3 -3 * t^2 +1) * p0 + (t^3 - 2 * t^2 + t) * m0 + (-2 * t^3 + 3 * t^2) * p1 + (t^3 - t^2) * m1
var a = 2.0f * p0 + m0 - 2.0f * p1 + m1;
var b = -3.0f * p0 - 2.0f * m0 + 3.0f * p1 - m1;
var c = m0;
var d = p0;
return t * (t * (a * t + b) + c) + d;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: cdb4803cfcd147f40a7dbb0343aebedf
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,5 +1,8 @@
using System;
[AttributeUsage(AttributeTargets.Class)]
public class GlobalSettingsAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Class)]
public class ExternalEntryAttribute : Attribute { }
@ -8,15 +11,6 @@ public class InspectableAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Field)]
public abstract class PreferredInspectorAttribute : InspectableAttribute { }
public class InspectableUnityObjectAttribute : PreferredInspectorAttribute
{
public Type ObjectType;
public InspectableUnityObjectAttribute(Type type)
{
ObjectType = type;
}
}
public class InspectableTextAttribute : PreferredInspectorAttribute { }
public class InspectablePrefabAttribute : PreferredInspectorAttribute { }
public class InspectableTextureAttribute : PreferredInspectorAttribute { }
@ -25,6 +19,16 @@ public class InspectableTemperatureAttribute : PreferredInspectorAttribute { }
public class InspectableAnimationCurveAttribute : PreferredInspectorAttribute { }
public class InspectableColorAttribute : PreferredInspectorAttribute { }
public class InspectableEnumValuesAttribute : PreferredInspectorAttribute
{
public Type EnumType;
public InspectableEnumValuesAttribute(Type enumType)
{
EnumType = enumType;
}
}
public class InspectableDatabaseLinkAttribute : PreferredInspectorAttribute
{
public readonly Type EntryType;
@ -35,22 +39,22 @@ public class InspectableDatabaseLinkAttribute : PreferredInspectorAttribute
}
}
public class RangedFloatInspectableAttribute : PreferredInspectorAttribute
public class InspectableRangedFloatAttribute : PreferredInspectorAttribute
{
public readonly float Min, Max;
public RangedFloatInspectableAttribute(float min, float max)
public InspectableRangedFloatAttribute(float min, float max)
{
Min = min;
Max = max;
}
}
public class RangedIntInspectableAttribute : PreferredInspectorAttribute
public class InspectableRangedIntAttribute : PreferredInspectorAttribute
{
public readonly int Min, Max;
public RangedIntInspectableAttribute(int min, int max)
public InspectableRangedIntAttribute(int min, int max)
{
Min = min;
Max = max;
@ -107,4 +111,24 @@ public class RethinkTableAttribute : Attribute
{
TableName = tableName;
}
}
public class NameAttribute : Attribute
{
public string Name;
public NameAttribute(string name)
{
Name = name;
}
}
public class OrderAttribute : Attribute
{
public int Order;
public OrderAttribute(int order)
{
Order = order;
}
}

View file

@ -0,0 +1,67 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
public static class CollectionExtensions
{
// https://stackoverflow.com/a/800469
public static string GetHashSHA1(this byte[] data)
{
using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider())
{
return string.Concat(sha1.ComputeHash(data).Select(x => x.ToString("X2")));
}
}
// https://stackoverflow.com/a/3188835
public static T MaxBy<T, U>(this IEnumerable<T> items, Func<T, U> selector)
{
if (!items.Any())
{
throw new InvalidOperationException("Empty input sequence");
}
var comparer = Comparer<U>.Default;
T maxItem = items.First();
U maxValue = selector(maxItem);
foreach (T item in items.Skip(1))
{
// Get the value of the item and compare it to the current max.
U value = selector(item);
if (comparer.Compare(value, maxValue) > 0)
{
maxValue = value;
maxItem = item;
}
}
return maxItem;
}
public static T MinBy<T, U>(this IEnumerable<T> items, Func<T, U> selector)
{
if (!items.Any())
{
throw new InvalidOperationException("Empty input sequence");
}
var comparer = Comparer<U>.Default;
T maxItem = items.First();
U maxValue = selector(maxItem);
foreach (T item in items.Skip(1))
{
// Get the value of the item and compare it to the current max.
U value = selector(item);
if (comparer.Compare(value, maxValue) < 0)
{
maxValue = value;
maxItem = item;
}
}
return maxItem;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: eed05df00a9a6b84292c81be1662a66e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -14,10 +14,10 @@ public class CultCache
{
public event Action<DatabaseEntry> OnDataInsertLocal;
public event Action<DatabaseEntry> OnDataUpdateLocal;
public event Action<DatabaseEntry> OnDataDeleteLocal;
public event Action<DatabaseEntry> OnDataRemoveLocal;
public event Action<DatabaseEntry> OnDataInsertRemote;
public event Action<DatabaseEntry> OnDataUpdateRemote;
public event Action<DatabaseEntry> OnDataDeleteRemote;
public event Action<DatabaseEntry> OnDataRemoveRemote;
private readonly object addLock = new object();
@ -26,6 +26,7 @@ public class CultCache
private readonly Dictionary<Guid, DatabaseEntry> _entries = new Dictionary<Guid, DatabaseEntry>();
private readonly Dictionary<Type, DatabaseEntry> _globals = new Dictionary<Type, DatabaseEntry>();
private readonly Dictionary<Type, HashSet<DatabaseEntry>> _types = new Dictionary<Type, HashSet<DatabaseEntry>>();
private readonly Dictionary<Type, (DirectoryInfo directory, List<Guid> entries)> _externalTypes = new Dictionary<Type, (DirectoryInfo directory, List<Guid> entries)>();
@ -48,6 +49,7 @@ public class CultCache
public CultCache(string filePath)
{
DatabaseLinkBase.Cache = this;
RegisterResolver.Register();
_filePath = filePath;
var fileInfo = new FileInfo(filePath);
@ -61,6 +63,7 @@ public class CultCache
var linkFields = type.GetFields().Where(f => f.FieldType.IsAssignableToGenericType(typeof(DatabaseLink<>))).ToArray();
if(linkFields.Length > 0)
_linkFields[type] = linkFields;
if (type.GetCustomAttribute<ExternalEntryAttribute>() != null)
{
var typeDirectory = dataDirectory.CreateSubdirectory(type.Name);
@ -79,6 +82,12 @@ public class CultCache
}
}
else _types[type] = new HashSet<DatabaseEntry>();
if (type.GetCustomAttribute<GlobalSettingsAttribute>() != null)
{
_globals[type] = null;
Add(Activator.CreateInstance(type) as DatabaseEntry);
}
}
}
@ -90,19 +99,9 @@ public class CultCache
{
var exists = _entries.ContainsKey(entry.ID);
// If an external entry is added, store it separately
var type = entry.GetType();
if (_linkFields.ContainsKey(type))
{
foreach (var linkField in _linkFields[type])
{
var link = (DatabaseLinkBase) linkField.GetValue(entry);
if (link != null)
{
link.Cache = this;
}
}
}
// If an external entry is added, store it separately
if (_externalTypes.ContainsKey(type))
{
if (_externalEntries.ContainsKey(entry.ID))
@ -119,6 +118,16 @@ public class CultCache
}
else
{
if (_globals.ContainsKey(type))
{
if(_globals[type]!=null)
{
Remove(_globals[type], remote);
exists = true;
}
_globals[type] = entry;
}
_entries[entry.ID] = entry;
_types[type].Add(entry);
foreach (var parentType in type.GetParentTypes())
@ -146,6 +155,9 @@ public class CultCache
}
}
public bool IsExternal(DatabaseEntry entry) => _externalTypes.ContainsKey(entry.GetType());
public bool IsGlobal(DatabaseEntry entry) => _globals.ContainsKey(entry.GetType());
public void AddAll(IEnumerable<DatabaseEntry> entries, bool remote = false)
{
foreach (var entry in entries)
@ -178,6 +190,17 @@ public class CultCache
return Get(guid) as T;
}
public DatabaseEntry GetGlobal(Type type)
{
if (_globals.ContainsKey(type)) return _globals[type];
return null;
}
public T GetGlobal<T>() where T : DatabaseEntry
{
return GetGlobal(typeof(T)) as T;
}
public IEnumerable<DatabaseEntry> GetAll(Type type)
{
if (_externalTypes.ContainsKey(type))
@ -197,14 +220,19 @@ public class CultCache
return !_types.ContainsKey(type) ? Enumerable.Empty<T>() : _types[type].Cast<T>();
}
public void Delete(DatabaseEntry entry, bool remote = false)
public void Remove(DatabaseEntry entry, bool remote = false)
{
_entries.Remove(entry.ID);
foreach (var parentType in entry.GetType().GetParentTypes())
{
if(_types.ContainsKey(parentType))
_types[parentType].Remove(entry);
}
if (remote)
OnDataDeleteRemote?.Invoke(entry);
OnDataRemoveRemote?.Invoke(entry);
else
OnDataDeleteLocal?.Invoke(entry);
OnDataRemoveLocal?.Invoke(entry);
}
public void Load()

View file

@ -55,6 +55,17 @@ public abstract class DatabaseEntry
{
[JsonProperty("id"), Key(0)]
public Guid ID = Guid.NewGuid();
public override int GetHashCode()
{
return ID.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj is DatabaseEntry entry) return entry.ID == ID;
return false;
}
}
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
@ -71,5 +82,10 @@ public class DatabaseLinkBase
public Guid LinkID;
[IgnoreMember]
public CultCache Cache;
public static CultCache Cache;
}
public interface ITintInspector
{
float3 TintColor { get; }
}

View file

@ -1,4 +0,0 @@
public static class MathExtensions
{
}

View file

@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: 5effe288f2074414930e040d4531709f
timeCreated: 1617057296

View file

@ -2,9 +2,11 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
public static class CultCacheExtensions
public static class ReflectionExtensions
{
private static Dictionary<Type,Type[]> InterfaceClasses = new Dictionary<Type, Type[]>();
public static Type[] GetAllInterfaceClasses(this Type type)
@ -85,9 +87,34 @@ public static class CultCacheExtensions
return IsAssignableToGenericType(baseType, genericType);
}
public static async void WrapAwait(this Task task)
public static string SplitCamelCase( this string str )
{
await task;
return Regex.Replace(
Regex.Replace(
str,
@"(\P{Ll})(\P{Ll}\p{Ll})",
"$1 $2"
),
@"(\p{Ll})(\P{Ll})",
"$1 $2"
);
}
public static string FormatTypeName(this string typeName)
{
return (typeName.EndsWith("Data")
? typeName.Substring(0, typeName.Length - 4)
: typeName).SplitCamelCase();
}
public static string GetFullName(this Type t)
{
if (!t.IsGenericType)
return t.Name.FormatTypeName();
var name = t.Name.FormatTypeName();
return
$"{name.Substring(0, name.LastIndexOf("`"))}{t.GetGenericArguments().Aggregate("<", (aggregate, type) => $"{aggregate}{(aggregate == "<" ? "" : ",")}{GetFullName(type)}")}>";
}
}

View file

@ -0,0 +1,147 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RethinkDb.Driver;
using RethinkDb.Driver.Ast;
using RethinkDb.Driver.Net;
public static class RethinkConnection
{
public static RethinkDB R = RethinkDB.R;
public static RethinkQueryStatus RethinkConnect(CultCache cache, string connectionString, string dbName, bool syncLocalChanges = true)
{
// Add Unity.Mathematics serialization support to RethinkDB Driver
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
new MathJsonConverter(),
Converter.DateTimeConverter,
Converter.BinaryConverter,
Converter.GroupingConverter,
Converter.PocoExprConverter
}
};
var syncTables = typeof(DatabaseEntry).GetAllChildClasses()
.Select(t => t.GetCustomAttribute<RethinkTableAttribute>()?.TableName ?? "Default").Distinct();
var connectionStringDomainLength = connectionString.IndexOf(':');
if (connectionStringDomainLength < 1)
throw new ArgumentException("Illegal Connection String: must include port!");
var portString = connectionString.Substring(connectionStringDomainLength + 1);
if (!int.TryParse(portString, out var port))
throw new ArgumentException($"Illegal connection string! \"{portString}\" is not a valid port number!");
var connection = R.Connection()
.Hostname(connectionString.Substring(0,connectionStringDomainLength))
.Port(port).Timeout(60).Connect();
var tables = R.Db(dbName).TableList().RunAtom<string[]>(connection);
foreach (var st in syncTables.Where(st => !tables.Contains(st)))
R.Db(dbName).TableCreate(st).RunNoReply(connection);
if (syncLocalChanges)
{
// When entries are changed locally, push the changes to RethinkDB
cache.OnDataUpdateLocal += async entry =>
{
var table = entry.GetType().GetCustomAttribute<RethinkTableAttribute>()?.TableName ?? "Other";
var result = await R
.Db(dbName)
.Table(table)
.Get(entry.ID)
.Replace(entry)
.RunAsync(connection);
};
cache.OnDataInsertLocal += async entry =>
{
var table = entry.GetType().GetCustomAttribute<RethinkTableAttribute>()?.TableName ?? "Other";
var result = await R
.Db(dbName)
.Table(table)
.Insert(entry)
.RunAsync(connection);
};
cache.OnDataRemoveLocal += async entry =>
{
var table = entry.GetType().GetCustomAttribute<RethinkTableAttribute>()?.TableName ?? "Other";
var result = await R
.Db(dbName)
.Table(table)
.Get(entry.ID)
.Delete()
.RunAsync(connection);
};
}
var status = new RethinkQueryStatus();
foreach (var table in syncTables)
{
// Get entries from RethinkDB
Task.Run(async () =>
{
status.TotalEntries += R
.Db(dbName)
.Table(table)
.Count().RunAtom<int>(connection);
var result = await R
.Db(dbName)
.Table(table)
.RunCursorAsync<DatabaseEntry>(connection);
while (await result.MoveNextAsync())
{
var entry = result.Current;
cache.Add(entry, true);
status.RetrievedEntries++;
}
}).WrapAwait();
// Subscribe to changes from RethinkDB
Task.Run(async () =>
{
var result = await R
.Db(dbName)
.Table(table)
.Changes()
.RunChangesAsync<DatabaseEntry>(connection);
while (await result.MoveNextAsync())
{
var change = result.Current;
cache.Add(change.NewValue, true);
}
}).WrapAwait();
}
return status;
}
}
public static class AsyncAwaitExtensions
{
public static async void WrapAwait(this Task task)
{
await task;
}
}
public class RethinkQueryStatus
{
public int RetrievedEntries;
public int TotalEntries;
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a8fce60db4f3e614c8d19c3da4cede0e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,7 +1,6 @@
using System.Collections;
using System.Collections.Generic;
using MessagePack;
using MessagePack.ReactivePropertyExtension;
using MessagePack.Resolvers;
public static class RegisterResolver
@ -16,8 +15,7 @@ public static class RegisterResolver
MathResolver.Instance,
TypeResolver.Instance,
NativeGuidResolver.Instance,
StandardResolver.Instance,
ReactivePropertyResolver.Instance
StandardResolver.Instance
);
var options = MessagePackSerializerOptions.Standard.WithResolver(resolver);
MessagePackSerializer.DefaultOptions = options;

View file

@ -0,0 +1,16 @@
using System;
using MessagePack;
using Newtonsoft.Json;
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class EnumDictionary<E, T> where E : Enum
{
[JsonProperty("values"), Key(0)] public T[] Values;
public EnumDictionary()
{
Values = new T[Enum.GetNames(typeof(E)).Length];
}
public T this[E key] => Values[Convert.ToInt32(key)];
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 96c57746cba54d3f9933d93b3242df04
timeCreated: 1617745268

View file

@ -22,15 +22,6 @@ public static class Extensions
{
return baseType.GetInterfaces().Any(interfaceType.Equals);
}
// https://stackoverflow.com/a/800469
public static string GetHashSHA1(this byte[] data)
{
using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider())
{
return string.Concat(sha1.ComputeHash(data).Select(x => x.ToString("X2")));
}
}
public static void Send<T>(this NetPeer peer, T message, DeliveryMethod method = DeliveryMethod.ReliableOrdered) where T : Message
{
@ -125,26 +116,6 @@ public static class Extensions
throw new ArgumentOutOfRangeException(nameof(rotation), rotation, null);
}
}
public static string SplitCamelCase( this string str )
{
return Regex.Replace(
Regex.Replace(
str,
@"(\P{Ll})(\P{Ll}\p{Ll})",
"$1 $2"
),
@"(\p{Ll})(\P{Ll})",
"$1 $2"
);
}
public static string FormatTypeName(this string typeName)
{
return (typeName.EndsWith("Data")
? typeName.Substring(0, typeName.Length - 4)
: typeName).SplitCamelCase();
}
public static string SignificantDigits(this float d, int digits=10)
{
@ -177,152 +148,11 @@ public static class Extensions
return pair.Equals(new KeyValuePair<T, TU>());
}
private static Dictionary<float4[], int2> _cachedIndices = new Dictionary<float4[], int2>();
public static float Evaluate(this float4[] curve, float time)
{
// Clamp time
time = math.clamp(time, curve[0].x, curve[curve.Length - 1].x);
FindSurroundingKeyframes(time, curve);
return HermiteInterpolate(time, curve[_cachedIndices[curve].x], curve[_cachedIndices[curve].y]);
}
static void FindSurroundingKeyframes(float time, float4[] curve)
{
// Check that time is within cached keyframe time
if (_cachedIndices.ContainsKey(curve) &&
_cachedIndices[curve].x != _cachedIndices[curve].y &&
time >= curve[_cachedIndices[curve].x].x &&
time <= curve[_cachedIndices[curve].y].x)
{
return;
}
// Fall back to using dichotomic search.
var length = curve.Length;
int half;
int middle;
int first = 0;
while (length > 0)
{
half = length >> 1;
middle = first + half;
if (time < curve[middle].x)
{
length = half;
}
else
{
first = middle + 1;
length = length - half - 1;
}
}
// If not within range, we pick the last element twice.
var indices = int2(first - 1, math.min(curve.Length - 1, first));
_cachedIndices[curve] = indices;
}
static float HermiteInterpolate(float time, in float4 leftKeyframe, in float4 rightKeyframe)
{
// Handle stepped curve.
if (math.isinf(leftKeyframe.w) || math.isinf(rightKeyframe.z))
{
return leftKeyframe.y;
}
float dx = rightKeyframe.x - leftKeyframe.x;
float m0;
float m1;
float t;
if (dx != 0.0f)
{
t = (time - leftKeyframe.x) / dx;
m0 = leftKeyframe.w * dx;
m1 = rightKeyframe.z * dx;
}
else
{
t = 0.0f;
m0 = 0;
m1 = 0;
}
return HermiteInterpolate(t, leftKeyframe.y, m0, m1, rightKeyframe.y);
}
static float HermiteInterpolate(float t, float p0, float m0, float m1, float p1)
{
// Unrolled the equations to avoid precision issue.
// (2 * t^3 -3 * t^2 +1) * p0 + (t^3 - 2 * t^2 + t) * m0 + (-2 * t^3 + 3 * t^2) * p1 + (t^3 - t^2) * m1
var a = 2.0f * p0 + m0 - 2.0f * p1 + m1;
var b = -3.0f * p0 - 2.0f * m0 + 3.0f * p1 - m1;
var c = m0;
var d = p0;
return t * (t * (a * t + b) + c) + d;
}
public static float Angle(this float2 from, float2 to)
{
var num = sqrt(lengthsq(from) * lengthsq(to));
return num < 1.00000000362749E-15 ? 0.0f : acos(clamp(dot(from, to) / num, -1f, 1f)) * 57.29578f;
}
// https://stackoverflow.com/a/3188835
public static T MaxBy<T, U>(this IEnumerable<T> items, Func<T, U> selector)
{
if (!items.Any())
{
throw new InvalidOperationException("Empty input sequence");
}
var comparer = Comparer<U>.Default;
T maxItem = items.First();
U maxValue = selector(maxItem);
foreach (T item in items.Skip(1))
{
// Get the value of the item and compare it to the current max.
U value = selector(item);
if (comparer.Compare(value, maxValue) > 0)
{
maxValue = value;
maxItem = item;
}
}
return maxItem;
}
public static T MinBy<T, U>(this IEnumerable<T> items, Func<T, U> selector)
{
if (!items.Any())
{
throw new InvalidOperationException("Empty input sequence");
}
var comparer = Comparer<U>.Default;
T maxItem = items.First();
U maxValue = selector(maxItem);
foreach (T item in items.Skip(1))
{
// Get the value of the item and compare it to the current max.
U value = selector(item);
if (comparer.Compare(value, maxValue) < 0)
{
maxValue = value;
maxItem = item;
}
}
return maxItem;
}
}
// https://github.com/Burtsev-Alexey/net-object-deep-copy

View file

@ -322,8 +322,8 @@ public abstract class EquippableItemData : CraftedItemData
// [InspectableField, JsonProperty("heatExponent"), Key(16), SimplePerformanceStat]
// public PerformanceStat HeatExponent = new PerformanceStat();
[InspectableAnimationCurve, JsonProperty("performanceCurve"), Key(17)]
public float4[] HeatPerformanceCurve;
[InspectableAnimationCurve, JsonProperty("heatCurve"), Key(17)]
public BezierCurve HeatPerformanceCurve;
[Inspectable, JsonProperty("resilience"), Key(18)]
public float ThermalResilience = 1;
@ -553,9 +553,4 @@ public class PersonalityAttribute : DatabaseEntry, INamedEntry
get => Name;
set => Name = value;
}
}
public interface ITintInspector
{
float3 TintColor { get; }
}