Database Support
Refactored almost everything, but most importantly we now integrate with RethinkDB for game data.
This commit is contained in:
parent
5ffeb55214
commit
0b46d5ee39
839 changed files with 77349 additions and 112660 deletions
73
Assets/Scripts/ServerShared/Attributes.cs
Normal file
73
Assets/Scripts/ServerShared/Attributes.cs
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
using System;
|
||||
|
||||
public class NameAttribute : Attribute
|
||||
{
|
||||
public string Name;
|
||||
|
||||
public NameAttribute(string name)
|
||||
{
|
||||
Name = name;
|
||||
}
|
||||
}
|
||||
|
||||
public class UpdateOrderAttribute : Attribute
|
||||
{
|
||||
public int Order;
|
||||
|
||||
public UpdateOrderAttribute(int order)
|
||||
{
|
||||
Order = order;
|
||||
}
|
||||
}
|
||||
|
||||
[AttributeUsage(AttributeTargets.Class)]
|
||||
public class InspectableAttribute : Attribute { }
|
||||
|
||||
public class InspectableFieldAttribute : Attribute { }
|
||||
|
||||
[AttributeUsage(AttributeTargets.Field)]
|
||||
public class InspectableTextAttribute : InspectableFieldAttribute { }
|
||||
|
||||
[AttributeUsage(AttributeTargets.Field)]
|
||||
public class InspectablePrefabAttribute : InspectableFieldAttribute { }
|
||||
|
||||
[AttributeUsage(AttributeTargets.Field)]
|
||||
public class TemperatureInspectableAttribute : InspectableFieldAttribute { }
|
||||
|
||||
[AttributeUsage(AttributeTargets.Field)]
|
||||
public class InspectableAnimationCurveAttribute : InspectableFieldAttribute { }
|
||||
|
||||
[AttributeUsage(AttributeTargets.Field)]
|
||||
public class InspectableDatabaseLinkAttribute : InspectableFieldAttribute
|
||||
{
|
||||
public readonly Type EntryType;
|
||||
|
||||
public InspectableDatabaseLinkAttribute(Type entryType)
|
||||
{
|
||||
EntryType = entryType;
|
||||
}
|
||||
}
|
||||
|
||||
[AttributeUsage(AttributeTargets.Field)]
|
||||
public class RangedFloatInspectableAttribute : InspectableFieldAttribute
|
||||
{
|
||||
public readonly float Min, Max;
|
||||
|
||||
public RangedFloatInspectableAttribute(float min, float max)
|
||||
{
|
||||
Min = min;
|
||||
Max = max;
|
||||
}
|
||||
}
|
||||
|
||||
[AttributeUsage(AttributeTargets.Field)]
|
||||
public class RangedIntInspectableAttribute : InspectableFieldAttribute
|
||||
{
|
||||
public readonly int Min, Max;
|
||||
|
||||
public RangedIntInspectableAttribute(int min, int max)
|
||||
{
|
||||
Min = min;
|
||||
Max = max;
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Attributes.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Attributes.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: f68edb6415593e542b4ba42ff5bec0c0
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
68
Assets/Scripts/ServerShared/DatabaseCache.cs
Normal file
68
Assets/Scripts/ServerShared/DatabaseCache.cs
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using MessagePack;
|
||||
|
||||
public class DatabaseCache
|
||||
{
|
||||
public event Action<DatabaseEntry> OnDataUpdateLocal;
|
||||
public event Action<DatabaseEntry> OnDataUpdateRemote;
|
||||
|
||||
public Action<string> Logger = Console.WriteLine;
|
||||
|
||||
private readonly Dictionary<Guid, DatabaseEntry> _entries = new Dictionary<Guid, DatabaseEntry>();
|
||||
|
||||
private readonly Dictionary<Type, Dictionary<Guid, DatabaseEntry>> _types = new Dictionary<Type, Dictionary<Guid, DatabaseEntry>>();
|
||||
|
||||
private DirectoryInfo _dir;
|
||||
|
||||
public IEnumerable<DatabaseEntry> AllEntries => _entries.Values;
|
||||
|
||||
public void Add(DatabaseEntry entry, bool remote = false)
|
||||
{
|
||||
if (entry != null)
|
||||
{
|
||||
_entries[entry.ID] = entry;
|
||||
var type = entry.GetType();
|
||||
var types = type.FindInterfaces((_, __) => true, null).Append(type);
|
||||
foreach (var t in types)
|
||||
{
|
||||
if(!_types.ContainsKey(t))
|
||||
_types[t] = new Dictionary<Guid, DatabaseEntry>();
|
||||
_types[t][entry.ID] = entry;
|
||||
}
|
||||
if(remote)
|
||||
OnDataUpdateRemote?.Invoke(entry);
|
||||
else
|
||||
OnDataUpdateLocal?.Invoke(entry);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddAll(IEnumerable<DatabaseEntry> entries, bool remote = false)
|
||||
{
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
Add(entry, remote);
|
||||
}
|
||||
}
|
||||
|
||||
public DatabaseEntry Get(Guid guid)
|
||||
{
|
||||
DatabaseEntry entry;
|
||||
_entries.TryGetValue(guid, out entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
public T Get<T>(Guid guid) where T : DatabaseEntry
|
||||
{
|
||||
DatabaseEntry entry;
|
||||
_types[typeof(T)].TryGetValue(guid, out entry);
|
||||
return (T) entry;
|
||||
}
|
||||
|
||||
public IEnumerable<T> GetAll<T>()
|
||||
{
|
||||
return _types[typeof(T)].Values.Cast<T>();
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/DatabaseCache.cs.meta
Normal file
11
Assets/Scripts/ServerShared/DatabaseCache.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: a43b39c6991618b43aed4a24ffcdc0ff
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
71
Assets/Scripts/ServerShared/DatabaseItems.cs
Normal file
71
Assets/Scripts/ServerShared/DatabaseItems.cs
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using JsonKnownTypes;
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
// TODO: USE THIS EVERYWHERE
|
||||
using Unity.Mathematics;
|
||||
using static Unity.Mathematics.math;
|
||||
#if UNITY_EDITOR
|
||||
using UnityEditor;
|
||||
#endif
|
||||
|
||||
public interface INamedEntry
|
||||
{
|
||||
string EntryName { get; set; }
|
||||
}
|
||||
|
||||
[InspectableField]
|
||||
[MessagePackObject]
|
||||
[Union(0, typeof(SimpleCommodityData))]
|
||||
[Union(1, typeof(CompoundCommodityData))]
|
||||
[Union(2, typeof(GearData))]
|
||||
[Union(3, typeof(HullData))]
|
||||
[Union(4, typeof(ShieldData))]
|
||||
[Union(5, typeof(ThrusterData))]
|
||||
[Union(6, typeof(SimpleCommodity))]
|
||||
[Union(7, typeof(CompoundCommodity))]
|
||||
[Union(8, typeof(Gear))]
|
||||
[Union(9, typeof(GlobalData))]
|
||||
[Union(10, typeof(ZoneData))]
|
||||
[Union(11, typeof(Player))]
|
||||
[Union(12, typeof(Corporation))]
|
||||
[Union(13, typeof(Ship))]
|
||||
[Union(14, typeof(Station))]
|
||||
[Union(15, typeof(OrbitData))]
|
||||
[Union(16, typeof(PlanetData))]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
[JsonConverter(typeof(JsonKnownTypesConverter<DatabaseEntry>))]
|
||||
//[Union(21, typeof(ContractData))]
|
||||
//[Union(22, typeof(Station))]
|
||||
public abstract class DatabaseEntry
|
||||
{
|
||||
[JsonProperty("id")] [Key(0)] public Guid ID = Guid.NewGuid();
|
||||
[IgnoreMember] public GameContext Context { get; set; }
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class Player : DatabaseEntry
|
||||
{
|
||||
[JsonProperty("email")] [Key(1)]
|
||||
public string Email;
|
||||
|
||||
[JsonProperty("password")] [Key(2)]
|
||||
public string Password;
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class Corporation : DatabaseEntry, INamedEntry
|
||||
{
|
||||
[JsonProperty("name")] [Key(1)]
|
||||
public string Name;
|
||||
|
||||
[IgnoreMember] public string EntryName
|
||||
{
|
||||
get => Name;
|
||||
set => Name = value;
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/DatabaseItems.cs.meta
Normal file
11
Assets/Scripts/ServerShared/DatabaseItems.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 3bb4780bed7bb544dbf6ea2223dd8f06
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -2,7 +2,8 @@
|
|||
"name": "Economy.Shared.Unity",
|
||||
"references": [
|
||||
"MessagePack",
|
||||
"MagicOnion.Abstractions"
|
||||
"MagicOnion.Abstractions",
|
||||
"Unity.Mathematics"
|
||||
],
|
||||
"optionalUnityReferences": [],
|
||||
"includePlatforms": [],
|
||||
|
|
|
|||
32
Assets/Scripts/ServerShared/Enums.cs
Normal file
32
Assets/Scripts/ServerShared/Enums.cs
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
public enum LauncherCaliber
|
||||
{
|
||||
Micro,
|
||||
Missile,
|
||||
Fighter
|
||||
}
|
||||
|
||||
public enum HardpointType
|
||||
{
|
||||
Hull,
|
||||
Thruster,
|
||||
WarpThruster,
|
||||
Reactor,
|
||||
Radiator,
|
||||
Shield,
|
||||
Cooler,
|
||||
Sensors,
|
||||
Tool,
|
||||
Energy,
|
||||
Ballistic,
|
||||
Launcher
|
||||
}
|
||||
|
||||
public enum DamageType
|
||||
{
|
||||
Kinetic,
|
||||
Corrosive,
|
||||
Electric,
|
||||
Thermal,
|
||||
Optical,
|
||||
Ionizing
|
||||
}
|
||||
3
Assets/Scripts/ServerShared/Enums.cs.meta
Normal file
3
Assets/Scripts/ServerShared/Enums.cs.meta
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 6e2409e0d3b04b6993851cd463a78e91
|
||||
timeCreated: 1584286938
|
||||
180
Assets/Scripts/ServerShared/Extensions.cs
Normal file
180
Assets/Scripts/ServerShared/Extensions.cs
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using MessagePack;
|
||||
using Unity.Mathematics;
|
||||
using static Unity.Mathematics.math;
|
||||
using Random = Unity.Mathematics.Random;
|
||||
|
||||
public static class Extensions
|
||||
{
|
||||
//public static IDatabaseEntry Get(this Guid entry) => Database.Get(entry);
|
||||
//public static T Get<T>(this Guid entry) where T : class, IDatabaseEntry => Database.Get(entry) as T;
|
||||
public static string ToJson(this DatabaseEntry entry) => MessagePackSerializer.SerializeToJson(entry);
|
||||
public static byte[] Serialize(this DatabaseEntry entry) => MessagePackSerializer.Serialize(entry);
|
||||
|
||||
public static bool IsImplementationOf(this Type baseType, Type interfaceType)
|
||||
{
|
||||
return baseType.GetInterfaces().Any(interfaceType.Equals);
|
||||
}
|
||||
|
||||
private static readonly Dictionary<CraftedItemInstance, float> Quality = new Dictionary<CraftedItemInstance, float>();
|
||||
public static float CompoundQuality(this CraftedItemInstance item)
|
||||
{
|
||||
if (Quality.ContainsKey(item)) return Quality[item];
|
||||
|
||||
var quality = item.Quality;
|
||||
|
||||
var craftedIngredients = item.Ingredients.Where(i => i is CraftedItemInstance).ToArray();
|
||||
if (craftedIngredients.Length > 0)
|
||||
{
|
||||
quality *= craftedIngredients.Cast<CraftedItemInstance>().Average(CompoundQuality);
|
||||
}
|
||||
|
||||
Quality[item] = quality;
|
||||
|
||||
return Quality[item];
|
||||
}
|
||||
|
||||
|
||||
public static float Performance(this EquippableItemData itemData, float temperature)
|
||||
{
|
||||
return saturate(itemData.HeatPerformanceCurve.Evaluate(saturate(
|
||||
(temperature - itemData.MinimumTemperature) /
|
||||
(itemData.MaximumTemperature - itemData.MinimumTemperature))));
|
||||
}
|
||||
|
||||
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"
|
||||
);
|
||||
}
|
||||
|
||||
private static Random? _random;
|
||||
private static Random Random => (Random) (_random ?? (_random = new Random(1337)));
|
||||
public static T RandomElement<T>(this IEnumerable<T> enumerable) => enumerable.ElementAt(Random.NextInt(0, enumerable.Count()));
|
||||
|
||||
private static Dictionary<Type,Type[]> InterfaceClasses = new Dictionary<Type, Type[]>();
|
||||
public static Type[] GetAllInterfaceClasses(this Type type)
|
||||
{
|
||||
if (InterfaceClasses.ContainsKey(type))
|
||||
return InterfaceClasses[type];
|
||||
return InterfaceClasses[type] = AppDomain.CurrentDomain.GetAssemblies()
|
||||
.SelectMany(ass => ass.GetTypes()).Where(t => t.IsClass && t.GetInterfaces().Contains(type)).ToArray();
|
||||
}
|
||||
|
||||
private static Dictionary<Type,Type[]> ChildClasses = new Dictionary<Type, Type[]>();
|
||||
public static Type[] GetAllChildClasses(this Type type)
|
||||
{
|
||||
if (ChildClasses.ContainsKey(type))
|
||||
return ChildClasses[type];
|
||||
return ChildClasses[type] = AppDomain.CurrentDomain.GetAssemblies()
|
||||
.SelectMany(ass => ass.GetTypes()).Where(type.IsAssignableFrom).ToArray();
|
||||
}
|
||||
|
||||
public static bool IsDefault<T>(this T value) where T : struct
|
||||
{
|
||||
bool isDefault = value.Equals(default(T));
|
||||
|
||||
return isDefault;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Extensions.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Extensions.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 076c6aac5ccefb844a1848f5294df565
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
182
Assets/Scripts/ServerShared/GameContext.cs
Normal file
182
Assets/Scripts/ServerShared/GameContext.cs
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using static Unity.Mathematics.math;
|
||||
|
||||
public class GameContext
|
||||
{
|
||||
private DatabaseCache _databaseCache;
|
||||
|
||||
public GlobalData GlobalData => _databaseCache.GetAll<GlobalData>().FirstOrDefault();
|
||||
|
||||
private readonly Dictionary<CraftedItemData, int> Tier = new Dictionary<CraftedItemData, int>();
|
||||
|
||||
public float PlanetRadius(float mass)
|
||||
{
|
||||
return pow(mass, 1 / GlobalData.RadiusPower);
|
||||
}
|
||||
|
||||
public int ItemTier(CraftedItemData itemData)
|
||||
{
|
||||
if (Tier.ContainsKey(itemData)) return Tier[itemData];
|
||||
|
||||
Tier[itemData] = itemData.Ingredients.Keys.Max(ci => _databaseCache.Get<ItemData>(ci) is CraftedItemData craftableIngredient ? ItemTier(craftableIngredient) : 0);
|
||||
|
||||
return Tier[itemData];
|
||||
}
|
||||
|
||||
public ItemData GetData(ItemInstance item)
|
||||
{
|
||||
return _databaseCache.Get<ItemData>(item.Data);
|
||||
}
|
||||
|
||||
public SimpleCommodityData GetData(SimpleCommodity item)
|
||||
{
|
||||
return _databaseCache.Get<SimpleCommodityData>(item.Data);
|
||||
}
|
||||
|
||||
public CraftedItemData GetData(CraftedItemInstance item)
|
||||
{
|
||||
return _databaseCache.Get<CraftedItemData>(item.Data);
|
||||
}
|
||||
|
||||
public EquippableItemData GetData(Gear gear)
|
||||
{
|
||||
return _databaseCache.Get<EquippableItemData>(gear.Data);
|
||||
}
|
||||
|
||||
public float GetMass(ItemInstance item)
|
||||
{
|
||||
var data = GetData(item);
|
||||
switch (item)
|
||||
{
|
||||
case CraftedItemInstance _:
|
||||
return data.Mass;
|
||||
case SimpleCommodity commodity:
|
||||
return data.Mass * commodity.Quantity;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
public float GetHeatCapacity(ItemInstance item)
|
||||
{
|
||||
var data = GetData(item);
|
||||
switch (item)
|
||||
{
|
||||
case CraftedItemInstance _:
|
||||
return data.Mass * data.SpecificHeat;
|
||||
case SimpleCommodity commodity:
|
||||
return data.Mass * data.SpecificHeat * commodity.Quantity;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Determine quality of either the item itself or the specific ingredient this stat depends on
|
||||
public float Quality(PerformanceStat stat, Gear item)
|
||||
{
|
||||
Guid? ingredientID = stat.Ingredient;
|
||||
float quality;
|
||||
if (ingredientID == null)
|
||||
quality = item.CompoundQuality();
|
||||
else
|
||||
{
|
||||
var ingredientInstance =
|
||||
item.Ingredients.FirstOrDefault(i => i.Data == ingredientID) as CraftedItemInstance;
|
||||
if (ingredientInstance == null)
|
||||
throw new InvalidOperationException(
|
||||
$"Item {item.ID} has invalid crafting ingredients!");
|
||||
quality = ingredientInstance.CompoundQuality();
|
||||
}
|
||||
|
||||
return quality;
|
||||
}
|
||||
|
||||
// Returns stat when not equipped
|
||||
public float Evaluate(PerformanceStat stat, Gear item)
|
||||
{
|
||||
var quality = pow(Quality(stat, item), stat.QualityExponent);
|
||||
|
||||
var result = lerp(stat.Min, stat.Max, quality);
|
||||
|
||||
if (float.IsNaN(result))
|
||||
return stat.Min;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Returns stat using ship temperature and modifiers
|
||||
public float Evaluate(PerformanceStat stat, Gear item, Ship ship)
|
||||
{
|
||||
var itemData = GetData(item);
|
||||
|
||||
var heat = !stat.HeatDependent ? 1 : pow(itemData.Performance(ship.Temperature), Evaluate(itemData.HeatExponent,item));
|
||||
var durability = !stat.DurabilityDependent ? 1 : pow(item.Durability / itemData.Durability, Evaluate(itemData.DurabilityExponent,item));
|
||||
var quality = pow(Quality(stat, item), stat.QualityExponent);
|
||||
|
||||
var scaleModifier = stat.GetScaleModifiers(ship).Values.Aggregate(1.0f, (current, mod) => current * mod);
|
||||
|
||||
var constantModifier = stat.GetConstantModifiers(ship).Values.Sum();
|
||||
|
||||
var result = lerp(stat.Min, stat.Max, heat * durability * quality) * scaleModifier + constantModifier;
|
||||
if (float.IsNaN(result))
|
||||
return stat.Min;
|
||||
return result;
|
||||
}
|
||||
|
||||
public SimpleCommodity CreateInstance(Guid data, int count)
|
||||
{
|
||||
var item = _databaseCache.Get<SimpleCommodityData>(data);
|
||||
if (item != null)
|
||||
return new SimpleCommodity
|
||||
{
|
||||
Data = data,
|
||||
Quantity = count,
|
||||
ID = Guid.NewGuid()
|
||||
};
|
||||
|
||||
throw new InvalidOperationException("Attempted to create Simple Commodity instance using missing or incorrect item id");
|
||||
}
|
||||
|
||||
public CraftedItemInstance CreateInstance(Guid data, float quality)
|
||||
{
|
||||
var item = _databaseCache.Get<CraftedItemData>(data);
|
||||
if (item == null)
|
||||
{
|
||||
throw new InvalidOperationException("Attempted to create crafted item instance using missing or incorrect item id");
|
||||
}
|
||||
|
||||
var ingredients = item.Ingredients.SelectMany(ci =>
|
||||
{
|
||||
var ingredient = _databaseCache.Get(ci.Key);
|
||||
return ingredient is SimpleCommodityData
|
||||
? (IEnumerable<ItemInstance>) new[] {CreateInstance(ci.Key, ci.Value)}
|
||||
: Enumerable.Range(0, ci.Value).Select(i => CreateInstance(ci.Key, quality));
|
||||
})
|
||||
.ToList();
|
||||
|
||||
if (item is EquippableItemData equippableItemData)
|
||||
{
|
||||
return new Gear
|
||||
{
|
||||
Context = this,
|
||||
Data = data,
|
||||
Durability = equippableItemData.Durability,
|
||||
ID = Guid.NewGuid(),
|
||||
Ingredients = ingredients,
|
||||
Quality = quality
|
||||
};
|
||||
}
|
||||
|
||||
return new CompoundCommodity
|
||||
{
|
||||
Context = this,
|
||||
Data = data,
|
||||
ID = Guid.NewGuid(),
|
||||
Ingredients = ingredients,
|
||||
Quality = quality
|
||||
};
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/GameContext.cs.meta
Normal file
11
Assets/Scripts/ServerShared/GameContext.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: daddadd3fcdca5a4fbc366d24caaa7ca
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
45
Assets/Scripts/ServerShared/GlobalData.cs
Normal file
45
Assets/Scripts/ServerShared/GlobalData.cs
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class GlobalData : DatabaseEntry
|
||||
{
|
||||
[InspectableField] [JsonProperty("targetPersistenceDuration")] [Key(1)]
|
||||
public float TargetPersistenceDuration;
|
||||
|
||||
[InspectableField] [JsonProperty("heatRadiationPower")] [Key(2)]
|
||||
public float HeatRadiationPower;
|
||||
|
||||
[InspectableField] [JsonProperty("heatRadiationMultiplier")] [Key(3)]
|
||||
public float HeatRadiationMultiplier;
|
||||
|
||||
[InspectableField] [JsonProperty("radiusPower")] [Key(4)]
|
||||
public float RadiusPower = 1.75f;
|
||||
|
||||
[InspectableField] [JsonProperty("massFloor")] [Key(5)]
|
||||
public float MassFloor = 1;
|
||||
|
||||
[InspectableField] [JsonProperty("sunMass")] [Key(6)]
|
||||
public float SunMass = 10000;
|
||||
|
||||
[InspectableField] [JsonProperty("gasGiantMass")] [Key(7)]
|
||||
public float GasGiantMass = 2000;
|
||||
|
||||
[InspectableField] [JsonProperty("dockingDistance")] [Key(8)]
|
||||
public float DockingDistance = 10;
|
||||
|
||||
[InspectableField] [JsonProperty("satelliteCreationMassFloor")] [Key(9)]
|
||||
public float SatelliteCreationMassFloor = 100;
|
||||
|
||||
[InspectableField] [JsonProperty("satelliteCreationProbability")] [Key(10)]
|
||||
public float SatelliteCreationProbability = .25f;
|
||||
|
||||
[InspectableField] [JsonProperty("binaryCreationProbability")] [Key(11)]
|
||||
public float BinaryCreationProbability = .25f;
|
||||
|
||||
[InspectableField] [JsonProperty("rosetteProbability")] [Key(12)]
|
||||
public float RosetteProbability = .25f;
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/GlobalData.cs.meta
Normal file
11
Assets/Scripts/ServerShared/GlobalData.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: b7bd4d9c038c3c24b86780de3f29f10e
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
3
Assets/Scripts/ServerShared/ItemBehaviors.meta
Normal file
3
Assets/Scripts/ServerShared/ItemBehaviors.meta
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 4647a795d3cb42e39d05a1764383b845
|
||||
timeCreated: 1584292631
|
||||
79
Assets/Scripts/ServerShared/ItemBehaviors/Afterburner.cs
Normal file
79
Assets/Scripts/ServerShared/ItemBehaviors/Afterburner.cs
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
|
||||
using System.Collections.Generic;
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
[InspectableField]
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class AfterburnerBehaviorData : IItemBehaviorData
|
||||
{
|
||||
[InspectableField] [JsonProperty("thrust")] [Key(0)]
|
||||
public PerformanceStat ThrustModifier;
|
||||
|
||||
[InspectableField] [JsonProperty("speed")] [Key(1)]
|
||||
public PerformanceStat SpeedModifier;
|
||||
|
||||
[InspectableField] [JsonProperty("torque")] [Key(2)]
|
||||
public PerformanceStat TorqueModifier;
|
||||
|
||||
public IItemBehavior CreateInstance(GameContext context, Ship ship, Gear item)
|
||||
{
|
||||
return new AfterburnerBehavior(context, this, ship, item);
|
||||
}
|
||||
}
|
||||
|
||||
public class AfterburnerBehavior : IActivatedItemBehavior
|
||||
{
|
||||
private List<Dictionary<IItemBehavior,float>> _modifiers = new List<Dictionary<IItemBehavior, float>>();
|
||||
private AfterburnerBehaviorData _data;
|
||||
|
||||
public Ship Ship { get; }
|
||||
public Gear Item { get; }
|
||||
public GameContext Context { get; }
|
||||
|
||||
public IItemBehaviorData Data => _data;
|
||||
|
||||
public AfterburnerBehavior(GameContext context, AfterburnerBehaviorData data, Ship ship, Gear item)
|
||||
{
|
||||
Context = context;
|
||||
_data = data;
|
||||
Ship = ship;
|
||||
Item = item;
|
||||
}
|
||||
|
||||
public void Update(float delta)
|
||||
{
|
||||
}
|
||||
|
||||
public void FixedUpdate(float delta)
|
||||
{
|
||||
}
|
||||
|
||||
public void Activate()
|
||||
{
|
||||
var thrustMod = Ship.GetEquipped<ThrusterData>().Thrust.GetScaleModifiers(Ship);
|
||||
_modifiers.Add(thrustMod);
|
||||
thrustMod.Add(this,Context.Evaluate(_data.ThrustModifier,Item, Ship));
|
||||
|
||||
var speedMod = (Ship.Hull.ItemData as HullData).TopSpeed.GetScaleModifiers(Ship);
|
||||
_modifiers.Add(speedMod);
|
||||
speedMod.Add(this,Context.Evaluate(_data.SpeedModifier,Item, Ship));
|
||||
|
||||
var torqueMod = (Ship.GetEquipped(HardpointType.Thruster).ItemData as ThrusterData).Torque.GetScaleModifiers(Ship);
|
||||
_modifiers.Add(torqueMod);
|
||||
torqueMod.Add(this,Context.Evaluate(_data.TorqueModifier,Item, Ship));
|
||||
|
||||
Ship.ForceThrust = true;
|
||||
}
|
||||
|
||||
public void Deactivate()
|
||||
{
|
||||
Ship.ForceThrust = false;
|
||||
foreach (var mod in _modifiers)
|
||||
{
|
||||
mod.Remove(this);
|
||||
}
|
||||
_modifiers.Clear();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 967ca96c9f90416887db9a6a0341f58c
|
||||
timeCreated: 1584292755
|
||||
40
Assets/Scripts/ServerShared/ItemBehaviors/Behaviors.cs
Normal file
40
Assets/Scripts/ServerShared/ItemBehaviors/Behaviors.cs
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using JsonKnownTypes;
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
using Unity.Mathematics;
|
||||
using static Unity.Mathematics.math;
|
||||
using static Unity.Mathematics.noise;
|
||||
|
||||
public interface IItemBehavior
|
||||
{
|
||||
void Update(float delta);
|
||||
void FixedUpdate(float delta);
|
||||
Ship Ship { get; }
|
||||
Gear Item { get; }
|
||||
GameContext Context { get; }
|
||||
IItemBehaviorData Data { get; }
|
||||
}
|
||||
|
||||
public interface IActivatedItemBehavior : IItemBehavior
|
||||
{
|
||||
void Activate();
|
||||
void Deactivate();
|
||||
}
|
||||
|
||||
[InspectableField]
|
||||
[Union(0, typeof(CannonBehaviorData))]
|
||||
[Union(1, typeof(LauncherBehaviorData))]
|
||||
[Union(2, typeof(ReactorBehaviorData))]
|
||||
// [Union(3, typeof(PlusUltraBehaviorData))]
|
||||
[Union(4, typeof(AfterburnerBehaviorData))]
|
||||
[Union(5, typeof(SensorBehaviorData))]
|
||||
[JsonConverter(typeof(JsonKnownTypesConverter<IItemBehaviorData>))]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public interface IItemBehaviorData
|
||||
{
|
||||
IItemBehavior CreateInstance(GameContext context, Ship ship, Gear item);
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/ItemBehaviors/Behaviors.cs.meta
Normal file
11
Assets/Scripts/ServerShared/ItemBehaviors/Behaviors.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: c15c37d98e3dc844aafd0dedc16ce0ae
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
132
Assets/Scripts/ServerShared/ItemBehaviors/Cannon.cs
Normal file
132
Assets/Scripts/ServerShared/ItemBehaviors/Cannon.cs
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
[InspectableField]
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class CannonBehaviorData : IItemBehaviorData
|
||||
{
|
||||
[InspectablePrefab] [JsonProperty("bullet")] [Key(0)]
|
||||
public string BulletPrefab;
|
||||
|
||||
[InspectableField] [JsonProperty("damageType")] [Key(1)]
|
||||
public DamageType DamageType;
|
||||
|
||||
[InspectableField] [JsonProperty("burstCount")] [Key(2)]
|
||||
public int BurstCount;
|
||||
|
||||
[InspectableField] [JsonProperty("burstTime")] [Key(3)]
|
||||
public PerformanceStat BurstTime;
|
||||
|
||||
[InspectableField] [JsonProperty("bulletRange")] [Key(4)]
|
||||
public PerformanceStat Range;
|
||||
|
||||
[InspectableField] [JsonProperty("spread")] [Key(5)]
|
||||
public PerformanceStat Spread;
|
||||
|
||||
[InspectableField] [JsonProperty("bulletInherit")] [Key(6)]
|
||||
public float Inherit;
|
||||
|
||||
[InspectableField] [JsonProperty("deflection")] [Key(7)]
|
||||
public float Deflection;
|
||||
|
||||
[InspectableField] [JsonProperty("visibility")] [Key(8)]
|
||||
public PerformanceStat Visibility;
|
||||
|
||||
[InspectableField] [JsonProperty("visibilityDecay")] [Key(9)]
|
||||
public PerformanceStat VisibilityDecay;
|
||||
|
||||
[InspectableField] [JsonProperty("bulletVelocity")] [Key(10)]
|
||||
public PerformanceStat Velocity;
|
||||
|
||||
[InspectableField] [JsonProperty("cooldown")] [Key(11)]
|
||||
public PerformanceStat Cooldown;
|
||||
|
||||
[InspectableField] [JsonProperty("damage")] [Key(12)]
|
||||
public PerformanceStat Damage;
|
||||
|
||||
[InspectableField] [JsonProperty("heat")] [Key(13)]
|
||||
public PerformanceStat Heat;
|
||||
|
||||
public IItemBehavior CreateInstance(GameContext context, Ship ship, Gear item)
|
||||
{
|
||||
return new CannonBehavior(context, this, ship, item);
|
||||
}
|
||||
}
|
||||
|
||||
public class CannonBehavior : IActivatedItemBehavior
|
||||
{
|
||||
private bool _firing;
|
||||
private float _cooldown; // normalized
|
||||
private CannonBehaviorData _cannon;
|
||||
public Ship Ship { get; }
|
||||
public Gear Item { get; }
|
||||
public GameContext Context { get; }
|
||||
private float _firingVisibility;
|
||||
|
||||
public CannonBehavior(GameContext context, CannonBehaviorData c, Ship ship, Gear item)
|
||||
{
|
||||
Context = context;
|
||||
_cannon = c;
|
||||
Ship = ship;
|
||||
Item = item;
|
||||
}
|
||||
|
||||
public void Activate()
|
||||
{
|
||||
// Debug.Log("Activating Cannon");
|
||||
// _firing = true;
|
||||
// Observable.EveryUpdate().TakeWhile(_ => _firing).Subscribe(_ =>
|
||||
// {
|
||||
// // Debug.Log($"Updating Observable {_cooldown}");
|
||||
// if (_cooldown < 0)
|
||||
// {
|
||||
// _cooldown = 1;
|
||||
// Fire(0);
|
||||
// if(_cannon.BurstCount>1)
|
||||
// Observable.Interval(TimeSpan.FromSeconds(_cannon.BurstTime.Evaluate(Hardpoint) / (_cannon.BurstCount-1))).Take(_cannon.BurstCount-1)
|
||||
// .Subscribe(l => Fire(l+1));
|
||||
// }
|
||||
// });
|
||||
}
|
||||
|
||||
private void Fire(long b)
|
||||
{
|
||||
// _firingVisibility += _cannon.Visibility.Evaluate(Hardpoint);
|
||||
// Hardpoint.Temperature += _cannon.Heat.Evaluate(Hardpoint) / Hardpoint.HeatCapacity;
|
||||
// var inst = GameObject.Instantiate(_cannon.BulletPrefab).transform;
|
||||
// Physics.IgnoreCollision(Hardpoint.Ship.Ship.GetComponent<Collider>(), inst.GetComponent<Collider>());
|
||||
// var bullet = inst.GetComponent<Bullet>();
|
||||
// bullet.Target = Hardpoint.Ship.Ship.Target;
|
||||
// bullet.Source = Hardpoint.Ship.Ship.Hitpoints;
|
||||
// bullet.Lifetime = _cannon.Range.Evaluate(Hardpoint) / _cannon.Velocity.Evaluate(Hardpoint);
|
||||
// bullet.Damage = _cannon.Damage.Evaluate(Hardpoint);
|
||||
// inst.position = Hardpoint.Proxy.position;
|
||||
// inst.rotation = Hardpoint.Proxy.rotation;
|
||||
// inst.GetComponent<Rigidbody>().velocity = _cannon.Velocity.Evaluate(Hardpoint) * Vector3.RotateTowards(-inst.forward, Hardpoint.Ship.Ship.Direction, _cannon.Deflection * Mathf.Deg2Rad, 1);
|
||||
// Hardpoint.Ship.Ship.AudioSource.PlayOneShot(_cannon.Sounds.RandomElement());
|
||||
// Debug.Log($"Firing bullet {b}");
|
||||
}
|
||||
|
||||
public void Deactivate()
|
||||
{
|
||||
_firing = false;
|
||||
}
|
||||
|
||||
public void Update(float delta)
|
||||
{
|
||||
_cooldown -= delta / Context.Evaluate(_cannon.Cooldown, Item, Ship);
|
||||
|
||||
if (_firingVisibility < 0.01f)
|
||||
{
|
||||
Ship.VisibilitySources.Remove(this);
|
||||
}
|
||||
}
|
||||
|
||||
public void FixedUpdate(float delta)
|
||||
{
|
||||
_firingVisibility *= Context.Evaluate(_cannon.VisibilityDecay, Item, Ship);
|
||||
}
|
||||
|
||||
public IItemBehaviorData Data => _cannon;
|
||||
}
|
||||
3
Assets/Scripts/ServerShared/ItemBehaviors/Cannon.cs.meta
Normal file
3
Assets/Scripts/ServerShared/ItemBehaviors/Cannon.cs.meta
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 77453d9e23d44c69bb853e3092f2b18d
|
||||
timeCreated: 1584292789
|
||||
201
Assets/Scripts/ServerShared/ItemBehaviors/Launcher.cs
Normal file
201
Assets/Scripts/ServerShared/ItemBehaviors/Launcher.cs
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
|
||||
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
using Unity.Mathematics;
|
||||
|
||||
[InspectableField]
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class LauncherBehaviorData : IItemBehaviorData
|
||||
{
|
||||
// [MessagePackFormatter(typeof(UnityGameObjectFormatter))]
|
||||
// [Inspectable] [Key("missile")] public GameObject MissilePrefab;
|
||||
// [MessagePackFormatter(typeof(ClipListFormatter))]
|
||||
// [Inspectable] [Key("sounds")] public List<AudioClip> Sounds;
|
||||
// [MessagePackFormatter(typeof(UnityAudioClipFormatter))]
|
||||
// [Inspectable] [Key("beepSound")] public AudioClip BeepSound;
|
||||
// [Inspectable] [Key("beepCount")] public int Beeps;
|
||||
[InspectableField] [JsonProperty("damageType")] [Key(0)]
|
||||
public DamageType DamageType;
|
||||
|
||||
[InspectableField] [JsonProperty("burstCount")] [Key(1)]
|
||||
public int BurstCount;
|
||||
|
||||
[InspectableField] [JsonProperty("burstTime")] [Key(2)]
|
||||
public PerformanceStat BurstTime;
|
||||
|
||||
[InspectableField] [JsonProperty("range")] [Key(3)]
|
||||
public PerformanceStat Range;
|
||||
|
||||
[InspectableAnimationCurve] [JsonProperty("guidance")] [Key(4)]
|
||||
public float4[] GuidanceCurve;
|
||||
|
||||
[InspectableAnimationCurve] [JsonProperty("thrustCurve")] [Key(5)]
|
||||
public float4[] ThrustCurve;
|
||||
|
||||
[InspectableAnimationCurve] [JsonProperty("liftCurve")] [Key(6)]
|
||||
public float4[] LiftCurve;
|
||||
|
||||
[InspectableField] [JsonProperty("thrust")] [Key(7)]
|
||||
public PerformanceStat Thrust;
|
||||
|
||||
[InspectableField] [JsonProperty("deflection")] [Key(8)]
|
||||
public float Deflection;
|
||||
|
||||
[InspectableField] [JsonProperty("lockOnBuffer")] [Key(9)]
|
||||
public float LockOnDegrees;
|
||||
|
||||
[InspectableField] [JsonProperty("frequency")] [Key(10)]
|
||||
public float DodgeFrequency;
|
||||
|
||||
[InspectableField] [JsonProperty("visibility")] [Key(11)]
|
||||
public PerformanceStat Visibility;
|
||||
|
||||
[InspectableField] [JsonProperty("launchSpeed")] [Key(12)]
|
||||
public PerformanceStat LaunchSpeed;
|
||||
|
||||
[InspectableField] [JsonProperty("missileSpeed")] [Key(13)]
|
||||
public PerformanceStat MissileSpeed;
|
||||
|
||||
[InspectableField] [JsonProperty("cooldown")] [Key(14)]
|
||||
public PerformanceStat Cooldown;
|
||||
|
||||
[InspectableField] [JsonProperty("lockOnTime")] [Key(15)]
|
||||
public PerformanceStat LockOnTime;
|
||||
|
||||
[InspectableField] [JsonProperty("damage")] [Key(16)]
|
||||
public PerformanceStat Damage;
|
||||
|
||||
[InspectableField] [JsonProperty("heat")] [Key(17)]
|
||||
public PerformanceStat Heat;
|
||||
|
||||
public IItemBehavior CreateInstance(GameContext context, Ship ship, Gear item)
|
||||
{
|
||||
return new LauncherBehavior(context, this, ship, item);
|
||||
}
|
||||
}
|
||||
|
||||
public class LauncherBehavior : IActivatedItemBehavior
|
||||
{
|
||||
private bool _locking;
|
||||
private float _lockingTimer;
|
||||
private float _cooldown; // normalized
|
||||
private bool _locked;
|
||||
|
||||
private LauncherBehaviorData _launcher;
|
||||
public Ship Ship { get; }
|
||||
public Gear Item { get; }
|
||||
public GameContext Context { get; }
|
||||
private float _firingVisibility;
|
||||
|
||||
public LauncherBehavior(GameContext context, LauncherBehaviorData m, Ship ship, Gear item)
|
||||
{
|
||||
Context = context;
|
||||
_launcher = m;
|
||||
Ship = ship;
|
||||
Item = item;
|
||||
// _audio = hp.Proxy.GetComponent<AudioSource>();
|
||||
// if(_audio==null)
|
||||
// _audio = hp.Proxy.gameObject.AddComponent<AudioSource>();
|
||||
// _audio.clip = _launcher.BeepSound;
|
||||
// _audio.loop = true;
|
||||
// _audio.volume = .5f;
|
||||
}
|
||||
|
||||
public void Activate()
|
||||
{
|
||||
_locking = true;
|
||||
_lockingTimer = 1;
|
||||
}
|
||||
|
||||
private void Fire(long b)
|
||||
{
|
||||
|
||||
// _firingVisibility += _launcher.Visibility.Evaluate(Hardpoint);
|
||||
// Hardpoint.Temperature += _launcher.Heat.Evaluate(Hardpoint) / Hardpoint.HeatCapacity;
|
||||
// var inst = GameObject.Instantiate(_launcher.MissilePrefab).transform;
|
||||
// var missile = inst.GetComponent<Bullet>();
|
||||
// missile.Target = Hardpoint.Ship.Ship.Target;
|
||||
// missile.Source = Hardpoint.Ship.Ship.Hitpoints;
|
||||
// missile.Lifetime = _launcher.Range.Evaluate(Hardpoint) / _launcher.MissileSpeed.Evaluate(Hardpoint);
|
||||
// missile.Damage = _launcher.Damage.Evaluate(Hardpoint);
|
||||
// inst.position = Hardpoint.Proxy.position;
|
||||
// inst.rotation = Hardpoint.Proxy.rotation;
|
||||
// inst.GetComponent<Rigidbody>().velocity = _launcher.LaunchSpeed.Evaluate(Hardpoint) * Hardpoint.Proxy.forward;
|
||||
// Physics.IgnoreCollision(Hardpoint.Ship.Ship.GetComponent<Collider>(), inst.GetComponent<Collider>());
|
||||
// var proj = inst.gameObject.AddComponent<GuidedProjectile>();
|
||||
// proj.GuidanceCurve = _launcher.GuidanceCurve;
|
||||
// proj.ThrustCurve = _launcher.ThrustCurve;
|
||||
// proj.LiftCurve = _launcher.LiftCurve;
|
||||
// proj.TopSpeed = _launcher.MissileSpeed.Evaluate(Hardpoint);
|
||||
// proj.Frequency = _launcher.DodgeFrequency;
|
||||
// proj.Target = Hardpoint.Ship.Ship.Target;
|
||||
// proj.Source = Hardpoint.Ship.Ship.Hitpoints;
|
||||
// proj.Thrust = _launcher.Thrust.Evaluate(Hardpoint);
|
||||
// _audio.PlayOneShot(_launcher.Sounds.RandomElement());
|
||||
// Debug.Log($"Firing bullet {b}");
|
||||
}
|
||||
|
||||
public void Deactivate()
|
||||
{
|
||||
// if (_lockingTimer < 0)
|
||||
// {
|
||||
// Fire(0);
|
||||
// if(_launcher.BurstCount>1)
|
||||
// Observable.Interval(TimeSpan.FromSeconds(_launcher.BurstTime.Evaluate(Hardpoint) / (_launcher.BurstCount-1))).Take(_launcher.BurstCount-1)
|
||||
// .Subscribe(l => Fire(l+1));
|
||||
// _lockingTimer = _cooldown = 1;
|
||||
// _locking = _locked = false;
|
||||
// _audio.Stop();
|
||||
// }
|
||||
// _locking = false;
|
||||
// _lockingTimer = 1;
|
||||
}
|
||||
|
||||
public void Update(float delta)
|
||||
{
|
||||
// if (Ship.Target == null)
|
||||
// return;
|
||||
//
|
||||
// if (_locking && _cooldown < 0)
|
||||
// {
|
||||
// //if the crosshair stays under a certain LockOnBuffer distance for a certain amount of time (LockOnTime)
|
||||
// if (acos(Vector2.Dot(Ship.Direction, (Ship.Target.transform.position-Ship.transform.position).normalized)) * Mathf.Rad2Deg < _launcher.LockOnDegrees)
|
||||
// {
|
||||
// var d = delta / _launcher.LockOnTime.Evaluate(Hardpoint);
|
||||
// _lockingTimer -= d;
|
||||
// if (!_locked && _lockingTimer < 0)
|
||||
// {
|
||||
// _locked = true;
|
||||
// _audio.Play();
|
||||
// } else if(Mathf.Repeat(_lockingTimer,1.0f/(_launcher.Beeps+1))-d<0)
|
||||
// GameManager.Instance.InterfaceAudio.PlayOneShot(_launcher.BeepSound);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// _lockingTimer = 1;
|
||||
// _audio.Stop();
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// _cooldown -= delta / _launcher.Cooldown.Evaluate(Hardpoint);
|
||||
// }
|
||||
//
|
||||
//
|
||||
// if (_firingVisibility > 0.01f)
|
||||
// {
|
||||
// Hardpoint.Ship.Visibility += _firingVisibility;
|
||||
// _firingVisibility = 0;
|
||||
// }
|
||||
|
||||
|
||||
}
|
||||
|
||||
public void FixedUpdate(float delta)
|
||||
{
|
||||
}
|
||||
|
||||
public IItemBehaviorData Data => _launcher;
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 5fd0ce9fd7384ba5a40c2ba41ece74eb
|
||||
timeCreated: 1584292825
|
||||
73
Assets/Scripts/ServerShared/ItemBehaviors/Reactor.cs
Normal file
73
Assets/Scripts/ServerShared/ItemBehaviors/Reactor.cs
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class ReactorBehaviorData : IItemBehaviorData
|
||||
{
|
||||
[InspectableField] [JsonProperty("charge")] [Key(0)]
|
||||
public PerformanceStat Charge;
|
||||
|
||||
[InspectableField] [JsonProperty("capacitance")] [Key(1)]
|
||||
public PerformanceStat Capacitance;
|
||||
|
||||
[InspectableField] [JsonProperty("efficiency")] [Key(2)]
|
||||
public PerformanceStat Efficiency;
|
||||
|
||||
[InspectableField] [JsonProperty("overload")] [Key(3)]
|
||||
public PerformanceStat OverloadEfficiency;
|
||||
|
||||
[InspectableField] [JsonProperty("underload")] [Key(4)]
|
||||
public PerformanceStat UnderloadRecovery;
|
||||
|
||||
public IItemBehavior CreateInstance(GameContext context, Ship ship, Gear item)
|
||||
{
|
||||
return new ReactorBehavior(context, this, ship, item);
|
||||
}
|
||||
}
|
||||
|
||||
public class ReactorBehavior : IItemBehavior
|
||||
{
|
||||
private ReactorBehaviorData _data;
|
||||
|
||||
public Ship Ship { get; }
|
||||
public Gear Item { get; }
|
||||
public GameContext Context { get; }
|
||||
|
||||
public IItemBehaviorData Data => _data;
|
||||
|
||||
public ReactorBehavior(GameContext context, ReactorBehaviorData data, Ship ship, Gear item)
|
||||
{
|
||||
Context = context;
|
||||
_data = data;
|
||||
Ship = ship;
|
||||
Item = item;
|
||||
}
|
||||
|
||||
public void FixedUpdate(float delta)
|
||||
{
|
||||
var cap = Context.Evaluate(_data.Capacitance, Item, Ship);
|
||||
var charge = Context.Evaluate(_data.Charge, Item, Ship) * delta;
|
||||
var efficiency = Context.Evaluate(_data.Efficiency, Item, Ship);
|
||||
|
||||
Ship.AddHeat(charge / efficiency);
|
||||
Ship.Charge += charge;
|
||||
|
||||
if (Ship.Charge > cap)
|
||||
{
|
||||
Ship.AddHeat(-(Ship.Charge - cap) / efficiency * (1 - 1 / Context.Evaluate(_data.UnderloadRecovery, Item, Ship)));
|
||||
Ship.Charge = cap;
|
||||
}
|
||||
|
||||
if (Ship.Charge < 0)
|
||||
{
|
||||
Ship.AddHeat( -Ship.Charge / Context.Evaluate(_data.OverloadEfficiency, Item, Ship));
|
||||
Ship.Charge = 0;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void Update(float delta)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: ca5f08285ca3403a8abe46001a16b6c4
|
||||
timeCreated: 1584292860
|
||||
70
Assets/Scripts/ServerShared/ItemBehaviors/Sensor.cs
Normal file
70
Assets/Scripts/ServerShared/ItemBehaviors/Sensor.cs
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
[InspectableField]
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class SensorBehaviorData : IItemBehaviorData
|
||||
{
|
||||
[InspectableField] [JsonProperty("radiance")] [Key(0)]
|
||||
public PerformanceStat Radiance;
|
||||
|
||||
[InspectableField] [JsonProperty("masking")] [Key(1)]
|
||||
public PerformanceStat RadianceMasking;
|
||||
|
||||
[InspectableField] [JsonProperty("sensitivity")] [Key(2)]
|
||||
public PerformanceStat Sensitivity;
|
||||
|
||||
[InspectableField] [JsonProperty("range")] [Key(3)]
|
||||
public PerformanceStat Range;
|
||||
|
||||
public IItemBehavior CreateInstance(GameContext context, Ship ship, Gear item)
|
||||
{
|
||||
return new SensorBehavior(context, this, ship, item);
|
||||
}
|
||||
}
|
||||
|
||||
public class SensorBehavior : IItemBehavior
|
||||
{
|
||||
private SensorBehaviorData _data;
|
||||
|
||||
public Ship Ship { get; }
|
||||
public Gear Item { get; }
|
||||
public GameContext Context { get; }
|
||||
|
||||
public IItemBehaviorData Data => _data;
|
||||
|
||||
public SensorBehavior(GameContext context, SensorBehaviorData data, Ship ship, Gear item)
|
||||
{
|
||||
_data = data;
|
||||
Ship = ship;
|
||||
Item = item;
|
||||
Context = context;
|
||||
}
|
||||
|
||||
public void Update(float delta)
|
||||
{
|
||||
// var ship = Hardpoint.Ship.Ship.transform;
|
||||
// var contacts =
|
||||
// Physics.OverlapSphere(ship.position, _data.Range.Evaluate(Hardpoint)).Where(c=>c.attachedRigidbody?.GetComponent<Targetable>()!=null).Select(c=>c.attachedRigidbody.GetComponent<Targetable>());
|
||||
// foreach (var contact in contacts)
|
||||
// {
|
||||
// var diff = (contact.transform.position - ship.position).Flatland();
|
||||
// var angle = acos(dot(ship.forward.Flatland().normalized,
|
||||
// diff.normalized)) / (float)PI;
|
||||
// var sens = _data.Sensitivity.Evaluate(Hardpoint) *
|
||||
// Hardpoint.Ship.HullData.VisibilityCurve.Evaluate(saturate(angle));
|
||||
// var vis = contact.Visibility / diff.sqrMagnitude;
|
||||
// if(vis > 1/sens)
|
||||
// Hardpoint.Ship.Contacts[contact] = Time.time;
|
||||
// }
|
||||
//
|
||||
// Hardpoint.Ship.VisibilitySources[this] = _data.Radiance.Evaluate(Hardpoint) / _data.RadianceMasking.Evaluate(Hardpoint);
|
||||
// TODO: Handle Active Detection / Visibility From Reflected Radiance
|
||||
}
|
||||
|
||||
public void FixedUpdate(float delta)
|
||||
{
|
||||
}
|
||||
}
|
||||
3
Assets/Scripts/ServerShared/ItemBehaviors/Sensor.cs.meta
Normal file
3
Assets/Scripts/ServerShared/ItemBehaviors/Sensor.cs.meta
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 8bd975480c8d4206bd1831fd9f51529f
|
||||
timeCreated: 1584292693
|
||||
259
Assets/Scripts/ServerShared/ItemData.cs
Normal file
259
Assets/Scripts/ServerShared/ItemData.cs
Normal file
|
|
@ -0,0 +1,259 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using JsonKnownTypes;
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
using Unity.Mathematics;
|
||||
|
||||
[MessagePackObject]
|
||||
[Union(0, typeof(SimpleCommodityData))]
|
||||
[Union(1, typeof(CompoundCommodityData))]
|
||||
[Union(2, typeof(GearData))]
|
||||
[Union(3, typeof(HullData))]
|
||||
[Union(4, typeof(ShieldData))]
|
||||
[Union(5, typeof(ThrusterData))]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
[JsonConverter(typeof(JsonKnownTypesConverter<ItemData>))]
|
||||
public abstract class ItemData : DatabaseEntry, INamedEntry
|
||||
{
|
||||
[InspectableField] [JsonProperty("name")] [Key(1)]
|
||||
public string Name;
|
||||
|
||||
[InspectableField] [JsonProperty("mass")] [Key(2)]
|
||||
public float Mass;
|
||||
|
||||
[InspectableField] [JsonProperty("size")] [Key(3)]
|
||||
public float Size;
|
||||
|
||||
[InspectableField] [JsonProperty("specificHeat")] [Key(4)]
|
||||
public float SpecificHeat;
|
||||
|
||||
[IgnoreMember] public string EntryName
|
||||
{
|
||||
get => Name;
|
||||
set => Name = value;
|
||||
}
|
||||
}
|
||||
|
||||
[Inspectable]
|
||||
[MessagePackObject]
|
||||
public class SimpleCommodityData : ItemData {}
|
||||
|
||||
[MessagePackObject]
|
||||
[Union(0, typeof(CompoundCommodityData))]
|
||||
[Union(1, typeof(GearData))]
|
||||
[Union(2, typeof(HullData))]
|
||||
[Union(3, typeof(ShieldData))]
|
||||
[Union(4, typeof(ThrusterData))]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
[JsonConverter(typeof(JsonKnownTypesConverter<CraftedItemData>))]
|
||||
public abstract class CraftedItemData : ItemData
|
||||
{
|
||||
[InspectableField] [JsonProperty("ingredients")] [Key(5)]
|
||||
public Dictionary<Guid, int> Ingredients = new Dictionary<Guid, int>();
|
||||
}
|
||||
|
||||
[Inspectable]
|
||||
[MessagePackObject]
|
||||
public class CompoundCommodityData : CraftedItemData {}
|
||||
|
||||
[Union(0, typeof(GearData))]
|
||||
[Union(1, typeof(HullData))]
|
||||
[Union(2, typeof(ShieldData))]
|
||||
[Union(3, typeof(ThrusterData))]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
[JsonConverter(typeof(JsonKnownTypesConverter<EquippableItemData>))]
|
||||
public abstract class EquippableItemData : CraftedItemData
|
||||
{
|
||||
|
||||
[InspectableField] [JsonProperty("draw")] [Key(6)]
|
||||
public PerformanceStat EnergyDraw;
|
||||
|
||||
[InspectableAnimationCurve] [JsonProperty("performanceCurve")] [Key(7)]
|
||||
public float4[] HeatPerformanceCurve;
|
||||
|
||||
[TemperatureInspectable] [JsonProperty("minTemp")] [Key(8)]
|
||||
public float MinimumTemperature;
|
||||
|
||||
[TemperatureInspectable] [JsonProperty("maxTemp")] [Key(9)]
|
||||
public float MaximumTemperature;
|
||||
|
||||
[InspectableField] [JsonProperty("durability")] [Key(10)]
|
||||
public float Durability;
|
||||
|
||||
[InspectableField] [JsonProperty("durabilityExponent")] [Key(11)]
|
||||
public PerformanceStat DurabilityExponent;
|
||||
|
||||
[InspectableField] [JsonProperty("heatExponent")] [Key(12)]
|
||||
public PerformanceStat HeatExponent;
|
||||
|
||||
[InspectableField] [JsonProperty("behaviors")] [Key(13)]
|
||||
public List<IItemBehaviorData> Behaviors = new List<IItemBehaviorData>();
|
||||
|
||||
[IgnoreMember]
|
||||
public abstract HardpointType HardpointType { get; }
|
||||
|
||||
[IgnoreMember] private const int STEPS = 64;
|
||||
|
||||
[IgnoreMember] private float? _optimum;
|
||||
[IgnoreMember]
|
||||
public float OptimalTemperature
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_optimum==null)
|
||||
{
|
||||
var samples = Enumerable.Range(0, STEPS).Select(i => (float) i / STEPS).ToArray();
|
||||
float max = 0;
|
||||
_optimum = 0;
|
||||
foreach (var f in samples)
|
||||
{
|
||||
var p = HeatPerformanceCurve?.Evaluate(f)??0;
|
||||
if (p > max)
|
||||
{
|
||||
max = p;
|
||||
_optimum = f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (float) (MinimumTemperature + _optimum * (MaximumTemperature - MinimumTemperature));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Inspectable]
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class GearData : EquippableItemData
|
||||
{
|
||||
[InspectableField] [JsonProperty("hardpointType")] [Key(14)] public HardpointType Hardpoint;
|
||||
|
||||
[IgnoreMember] public override HardpointType HardpointType => Hardpoint;
|
||||
}
|
||||
|
||||
[Inspectable]
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class HullData : EquippableItemData
|
||||
{
|
||||
[InspectableField] [JsonProperty("hullCapacity")] [Key(14)]
|
||||
public PerformanceStat Capacity;
|
||||
|
||||
[InspectableField] [JsonProperty("traction")] [Key(15)]
|
||||
public PerformanceStat Traction;
|
||||
|
||||
[InspectableField] [JsonProperty("topSpeed")] [Key(16)]
|
||||
public PerformanceStat TopSpeed;
|
||||
|
||||
[InspectableField] [JsonProperty("emissivity")] [Key(17)]
|
||||
public PerformanceStat Emissivity;
|
||||
|
||||
[InspectableField] [JsonProperty("crossSection")] [Key(18)]
|
||||
public PerformanceStat CrossSection;
|
||||
|
||||
[InspectableField] [JsonProperty("hardpoints")] [Key(19)]
|
||||
public List<HardpointData> Hardpoints = new List<HardpointData>();
|
||||
|
||||
[InspectableAnimationCurve] [JsonProperty("visibility")] [Key(20)]
|
||||
public float4[] VisibilityCurve;
|
||||
|
||||
[InspectablePrefab] [JsonProperty("prefab")] [Key(21)]
|
||||
public string Prefab;
|
||||
|
||||
[IgnoreMember] public override HardpointType HardpointType => HardpointType.Hull;
|
||||
}
|
||||
|
||||
[InspectableField]
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class HardpointData
|
||||
{
|
||||
[JsonProperty("type")] [Key(0)]
|
||||
public HardpointType Type;
|
||||
}
|
||||
|
||||
[Inspectable]
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class ShieldData : EquippableItemData
|
||||
{
|
||||
[InspectableField] [JsonProperty("efficiency")] [Key(14)]
|
||||
public PerformanceStat Efficiency;
|
||||
|
||||
[InspectableField] [JsonProperty("shielding")] [Key(15)]
|
||||
public PerformanceStat Shielding;
|
||||
|
||||
[IgnoreMember] public override HardpointType HardpointType => HardpointType.Shield;
|
||||
}
|
||||
|
||||
[Inspectable]
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class ThrusterData : EquippableItemData
|
||||
{
|
||||
[InspectableField] [JsonProperty("thrust")] [Key(14)]
|
||||
public PerformanceStat Thrust;
|
||||
|
||||
[InspectableField] [JsonProperty("torque")] [Key(15)]
|
||||
public PerformanceStat Torque;
|
||||
|
||||
[InspectableField] [JsonProperty("visibility")] [Key(16)]
|
||||
public PerformanceStat Visibility;
|
||||
|
||||
[InspectableField] [JsonProperty("thrusterHeat")] [Key(17)]
|
||||
public PerformanceStat Heat;
|
||||
|
||||
[IgnoreMember] public override HardpointType HardpointType => HardpointType.Thruster;
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public struct PerformanceStat
|
||||
{
|
||||
[JsonProperty("min")] [Key(0)]
|
||||
public float Min;
|
||||
|
||||
[JsonProperty("max")] [Key(1)]
|
||||
public float Max;
|
||||
|
||||
[JsonProperty("durabilityDependent")] [Key(2)]
|
||||
public bool DurabilityDependent;
|
||||
|
||||
[JsonProperty("heatDependent")] [Key(3)]
|
||||
public bool HeatDependent;
|
||||
|
||||
[JsonProperty("qualityExponent")] [Key(4)]
|
||||
public float QualityExponent;
|
||||
|
||||
[JsonProperty("ingredient")] [Key(5)]
|
||||
public Guid? Ingredient;
|
||||
|
||||
[IgnoreMember] private Dictionary<Ship,Dictionary<IItemBehavior,float>> _scaleModifiers;
|
||||
[IgnoreMember] private Dictionary<Ship,Dictionary<IItemBehavior,float>> _constantModifiers;
|
||||
|
||||
[IgnoreMember]
|
||||
private Dictionary<Ship, Dictionary<IItemBehavior, float>> ScaleModifiers =>
|
||||
_scaleModifiers ?? (_scaleModifiers = new Dictionary<Ship, Dictionary<IItemBehavior, float>>());
|
||||
|
||||
[IgnoreMember]
|
||||
private Dictionary<Ship, Dictionary<IItemBehavior, float>> ConstantModifiers =>
|
||||
_constantModifiers ?? (_constantModifiers = new Dictionary<Ship, Dictionary<IItemBehavior, float>>());
|
||||
|
||||
public Dictionary<IItemBehavior, float> GetScaleModifiers(Ship ship)
|
||||
{
|
||||
if(!ScaleModifiers.ContainsKey(ship))
|
||||
ScaleModifiers[ship] = new Dictionary<IItemBehavior, float>();
|
||||
|
||||
return ScaleModifiers[ship];
|
||||
}
|
||||
|
||||
public Dictionary<IItemBehavior, float> GetConstantModifiers(Ship ship)
|
||||
{
|
||||
if(!ConstantModifiers.ContainsKey(ship))
|
||||
ConstantModifiers[ship] = new Dictionary<IItemBehavior, float>();
|
||||
|
||||
return ConstantModifiers[ship];
|
||||
}
|
||||
}
|
||||
3
Assets/Scripts/ServerShared/ItemData.cs.meta
Normal file
3
Assets/Scripts/ServerShared/ItemData.cs.meta
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 25f318aff9c2426dbbfda22cb37e63b2
|
||||
timeCreated: 1584282670
|
||||
74
Assets/Scripts/ServerShared/ItemInstance.cs
Normal file
74
Assets/Scripts/ServerShared/ItemInstance.cs
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using JsonKnownTypes;
|
||||
//using JM.LinqFaster;
|
||||
using MessagePack;
|
||||
using MessagePack.Formatters;
|
||||
using Newtonsoft.Json;
|
||||
using Unity.Mathematics;
|
||||
// TODO: USE THIS EVERYWHERE
|
||||
using static Unity.Mathematics.math;
|
||||
|
||||
[Union(0, typeof(SimpleCommodity))]
|
||||
[Union(1, typeof(CompoundCommodity))]
|
||||
[Union(2, typeof(Gear))]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
[JsonConverter(typeof(JsonKnownTypesConverter<ItemInstance>))]
|
||||
public abstract class ItemInstance : DatabaseEntry
|
||||
{
|
||||
[JsonProperty("data")] [Key(1)]
|
||||
public Guid Data;
|
||||
|
||||
public float Mass => Context.GetMass(this);
|
||||
public float HeatCapacity => Context.GetHeatCapacity(this);
|
||||
}
|
||||
|
||||
[Union(0, typeof(CompoundCommodity))]
|
||||
[Union(1, typeof(Gear))]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
[JsonConverter(typeof(JsonKnownTypesConverter<CraftedItemInstance>))]
|
||||
public abstract class CraftedItemInstance : ItemInstance
|
||||
{
|
||||
[JsonProperty("quality")] [Key(2)]
|
||||
public float Quality;
|
||||
|
||||
[JsonProperty("ingredients")] [Key(3)]
|
||||
public List<ItemInstance> Ingredients = new List<ItemInstance>();
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class CompoundCommodity : CraftedItemInstance {}
|
||||
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class SimpleCommodity : ItemInstance
|
||||
{
|
||||
[JsonProperty("quantity")] [Key(2)]
|
||||
public int Quantity;
|
||||
|
||||
public SimpleCommodityData ItemData => Context.GetData(this);
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class Gear : CraftedItemInstance
|
||||
{
|
||||
[JsonProperty("durability")] [Key(4)]
|
||||
public float Durability;
|
||||
|
||||
public EquippableItemData ItemData => Context.GetData(this);
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class Hardpoint
|
||||
{
|
||||
[JsonProperty("item")] [Key(0)]
|
||||
public Gear Item;
|
||||
|
||||
[IgnoreMember] public HardpointData HardpointData;
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/ItemInstance.cs.meta
Normal file
11
Assets/Scripts/ServerShared/ItemInstance.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 99494d40ccacd2d46a84062749ed38aa
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
8
Assets/Scripts/ServerShared/NIH.meta
Normal file
8
Assets/Scripts/ServerShared/NIH.meta
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 20104a5f50e5af947994250904c73928
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
8
Assets/Scripts/ServerShared/NIH/JsonKnownTypes.meta
Normal file
8
Assets/Scripts/ServerShared/NIH/JsonKnownTypes.meta
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
fileFormatVersion: 2
|
||||
guid: f94c63c8b140fb34bb5d70a8d8a5dbd6
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
using System;
|
||||
|
||||
namespace JsonKnownTypes
|
||||
{
|
||||
public static class AttributesManager
|
||||
{
|
||||
public static JsonKnownTypeAttribute[] GetJsonKnownAttributes(Type type) =>
|
||||
(JsonKnownTypeAttribute[])Attribute.GetCustomAttributes(type, typeof(JsonKnownTypeAttribute));
|
||||
|
||||
public static JsonKnownThisTypeAttribute GetJsonKnownThisAttribute(Type type) =>
|
||||
(JsonKnownThisTypeAttribute)Attribute.GetCustomAttribute(type, typeof(JsonKnownThisTypeAttribute));
|
||||
|
||||
public static JsonDiscriminatorAttribute GetJsonDiscriminatorAttribute(Type type) =>
|
||||
(JsonDiscriminatorAttribute)Attribute.GetCustomAttribute(type, typeof(JsonDiscriminatorAttribute));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 6036d25d64e90064ca92c91f6d7827b2
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 01722fba3f2fd3942bca61d48508ad27
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
using System;
|
||||
|
||||
namespace JsonKnownTypes.Exceptions
|
||||
{
|
||||
public class JsonKnownTypesException : Exception
|
||||
{
|
||||
public JsonKnownTypesException(string message)
|
||||
: base(message)
|
||||
{ }
|
||||
|
||||
public JsonKnownTypesException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{ }
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 36f9ed87d773cf146bf68e828cefe89c
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
using System;
|
||||
|
||||
namespace JsonKnownTypes
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)]
|
||||
public class JsonDiscriminatorAttribute : Attribute
|
||||
{
|
||||
public string Name { get; set; }
|
||||
|
||||
internal bool? _autoJson;
|
||||
|
||||
public bool AutoJson
|
||||
{
|
||||
get => _autoJson != null && (bool) _autoJson;
|
||||
set => _autoJson = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: f7c6582f43e22994ebbaf0e139e63dc5
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
namespace JsonKnownTypes
|
||||
{
|
||||
public class JsonDiscriminatorSettings
|
||||
{
|
||||
public string Name { get; set; } = "$type";
|
||||
public bool AutoJsonKnown { get; set; } = true;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: b5f09ee78f257904caa3ab939d3edc65
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
using System;
|
||||
|
||||
namespace JsonKnownTypes
|
||||
{
|
||||
public class JsonKnownThisTypeAttribute : Attribute
|
||||
{
|
||||
public string Discriminator { get; }
|
||||
|
||||
public JsonKnownThisTypeAttribute()
|
||||
{ }
|
||||
|
||||
public JsonKnownThisTypeAttribute(string discriminator)
|
||||
{
|
||||
Discriminator = discriminator;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: c8dc4cbd1c54167409cf14ec8ec37d70
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
using System;
|
||||
|
||||
namespace JsonKnownTypes
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true)]
|
||||
public class JsonKnownTypeAttribute : Attribute
|
||||
{
|
||||
public Type Type { get; }
|
||||
public string Discriminator { get; }
|
||||
|
||||
public JsonKnownTypeAttribute(Type type)
|
||||
{
|
||||
Type = type;
|
||||
}
|
||||
|
||||
public JsonKnownTypeAttribute(Type type, string discriminator)
|
||||
{
|
||||
Type = type;
|
||||
Discriminator = discriminator;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: ecbe3646a4d9ca04eac598b60e5c77ca
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||
<Version>0.2.0</Version>
|
||||
<Authors>Dmitry Kaznacheev</Authors>
|
||||
<PackageProjectUrl>https://github.com/dmitry-bym/JsonKnownTypes</PackageProjectUrl>
|
||||
<PackageLicenseUrl>https://github.com/dmitry-bym/JsonKnownTypes/blob/master/LICENSE</PackageLicenseUrl>
|
||||
<Copyright>Dmitry Kaznacheev</Copyright>
|
||||
<RepositoryUrl>https://github.com/dmitry-bym/JsonKnownTypes</RepositoryUrl>
|
||||
<PackageTags>json known polymorphic types</PackageTags>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 937d902757d946b47a7bea20ade37beb
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
using System;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
|
||||
namespace JsonKnownTypes
|
||||
{
|
||||
public class JsonKnownTypesContractResolver<T> : DefaultContractResolver
|
||||
{
|
||||
protected override JsonConverter ResolveContractConverter(Type objectType)
|
||||
{
|
||||
if (typeof(T).IsAssignableFrom(objectType) && !objectType.IsAbstract)
|
||||
return null;
|
||||
return base.ResolveContractConverter(objectType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: bce1b7fa2da230447b3614d23394ee9f
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
using System;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace JsonKnownTypes
|
||||
{
|
||||
public class JsonKnownTypesConverter<T> : JsonConverter
|
||||
{
|
||||
private readonly JsonKnownTypesSettings _typesSettings
|
||||
= JsonKnownTypesSettingsManager.GetSettings<T>();
|
||||
|
||||
private JsonSerializerSettings SpecifiedSubclassConversion
|
||||
{
|
||||
get =>
|
||||
new JsonSerializerSettings
|
||||
{
|
||||
ContractResolver = new JsonKnownTypesContractResolver<T>()
|
||||
};
|
||||
}
|
||||
|
||||
public override bool CanConvert(Type objectType)
|
||||
=> _typesSettings.TypeToDiscriminator.ContainsKey(objectType);
|
||||
|
||||
public override bool CanWrite { get => true; }
|
||||
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
||||
{
|
||||
var jo = JObject.Load(reader);
|
||||
|
||||
var discriminator = jo[_typesSettings.Name].ToString();
|
||||
|
||||
if(_typesSettings.DiscriminatorToType.TryGetValue(discriminator, out var typeForObject))
|
||||
return JsonConvert.DeserializeObject(jo.ToString(), typeForObject, SpecifiedSubclassConversion);
|
||||
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
||||
{
|
||||
var objectType = value.GetType();
|
||||
if (_typesSettings.TypeToDiscriminator.TryGetValue(objectType, out var discriminator))
|
||||
{
|
||||
var json = JsonConvert.SerializeObject(value, SpecifiedSubclassConversion);
|
||||
var jo = JObject.Parse(json);
|
||||
jo.Add(_typesSettings.Name, new JValue(discriminator));
|
||||
jo.WriteTo(writer);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: b0a6c832fc846634789aa691cd2b81d9
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using JsonKnownTypes.Exceptions;
|
||||
|
||||
namespace JsonKnownTypes
|
||||
{
|
||||
internal static class JsonKnownTypesDictionaryManager
|
||||
{
|
||||
public static void AddJsonKnown<T>(this Dictionary<Type, string> dictionary)
|
||||
{
|
||||
var attrs = AttributesManager.GetJsonKnownAttributes(typeof(T));
|
||||
foreach (var attr in attrs)
|
||||
{
|
||||
var discriminator = attr.Discriminator ?? attr.Type.Name;
|
||||
dictionary.TryAdd(attr.Type, discriminator);
|
||||
}
|
||||
}
|
||||
|
||||
public static void AddJsonKnownThis(this Dictionary<Type, string> dictionary, Type[] inherited)
|
||||
{
|
||||
foreach (var type in inherited)
|
||||
{
|
||||
var attr = AttributesManager.GetJsonKnownThisAttribute(type);
|
||||
if (attr != null)
|
||||
{
|
||||
var discriminator = attr.Discriminator ?? type.Name;
|
||||
dictionary.TryAdd(type, discriminator);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void AddAutoGenerated(this Dictionary<Type, string> dictionary, Type[] inherited)
|
||||
{
|
||||
foreach (var type in inherited.Except(dictionary.Keys))
|
||||
{
|
||||
dictionary.TryAdd(type, type.Name);
|
||||
}
|
||||
}
|
||||
|
||||
public static void TryAdd(this Dictionary<Type, string> dictionary, Type key, string discriminator)
|
||||
{
|
||||
if (dictionary.ContainsKey(key))
|
||||
throw new JsonKnownTypesException($"Dictionary already contains the key {key.Name}");//todo
|
||||
|
||||
if (dictionary.ContainsValue(discriminator))
|
||||
throw new JsonKnownTypesException($"Dictionary already contains the value {discriminator}");//todo
|
||||
|
||||
dictionary.Add(key, discriminator);
|
||||
}
|
||||
|
||||
public static Dictionary<string, Type> Revert(this Dictionary<Type, string> dictionary)
|
||||
{
|
||||
try
|
||||
{
|
||||
return dictionary.ToDictionary(x => x.Value, x => x.Key);
|
||||
}
|
||||
catch (ArgumentException e)
|
||||
{
|
||||
throw new JsonKnownTypesException("Dictionary has a repeated value", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 77ce621509349204a87085f089b3daa3
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JsonKnownTypes
|
||||
{
|
||||
public class JsonKnownTypesSettings
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public Dictionary<string, Type> DiscriminatorToType { get; set; } = new Dictionary<string, Type>();
|
||||
public Dictionary<Type, string> TypeToDiscriminator { get; set; } = new Dictionary<Type, string>();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 99b988650c739094aa3a5ba7040ea379
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using JsonKnownTypes.Exceptions;
|
||||
using JsonKnownTypes.Utils;
|
||||
|
||||
namespace JsonKnownTypes
|
||||
{
|
||||
public static class JsonKnownTypesSettingsManager
|
||||
{
|
||||
public static JsonDiscriminatorSettings DefaultDiscriminatorSettings { get; set; } = new JsonDiscriminatorSettings();
|
||||
|
||||
public static JsonKnownTypesSettings GetSettings<T>()
|
||||
{
|
||||
var discriminatorAttribute = AttributesManager.GetJsonDiscriminatorAttribute(typeof(T));
|
||||
|
||||
var discriminatorSettings = discriminatorAttribute == null ? DefaultDiscriminatorSettings : Mapper.Map(discriminatorAttribute);
|
||||
|
||||
var typeSettings = new JsonKnownTypesSettings
|
||||
{
|
||||
Name = discriminatorSettings.Name
|
||||
};
|
||||
|
||||
var allTypes = GetAllInheritance<T>();
|
||||
|
||||
typeSettings.TypeToDiscriminator.AddJsonKnown<T>();
|
||||
typeSettings.TypeToDiscriminator.AddJsonKnownThis(allTypes);
|
||||
|
||||
if (discriminatorSettings.AutoJsonKnown)
|
||||
{
|
||||
typeSettings.TypeToDiscriminator.AddAutoGenerated(allTypes);
|
||||
}
|
||||
else if(!allTypes.All(typeSettings.TypeToDiscriminator.ContainsKey))
|
||||
{
|
||||
throw new JsonKnownTypesException("Dictionary contains not all types of hierarchy, enable AutoJsonKnow or add attributes for all classes"); //todo
|
||||
}
|
||||
|
||||
typeSettings.DiscriminatorToType = typeSettings.TypeToDiscriminator.Revert();
|
||||
|
||||
return typeSettings;
|
||||
}
|
||||
|
||||
private static Type[] GetAllInheritance<T>()
|
||||
{
|
||||
var type = typeof(T);
|
||||
return type.Assembly
|
||||
.GetTypes()
|
||||
.Where(x => type.IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)
|
||||
.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: a361505c5408b374788cbaeed6fa2f55
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 6d6706b0998d8af458321fd5f35906fb
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
namespace JsonKnownTypes.Utils
|
||||
{
|
||||
internal static class Mapper
|
||||
{
|
||||
public static JsonDiscriminatorSettings Map(JsonDiscriminatorAttribute entity)
|
||||
{
|
||||
var settings = new JsonDiscriminatorSettings();
|
||||
|
||||
settings.Name = entity.Name ?? settings.Name;
|
||||
settings.AutoJsonKnown = entity._autoJson ?? settings.AutoJsonKnown;
|
||||
|
||||
return settings;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: c30d51fc767627a41b65f5cdd2b22cc3
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
20
Assets/Scripts/ServerShared/OrbitInstance.cs
Normal file
20
Assets/Scripts/ServerShared/OrbitInstance.cs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using Unity.Mathematics;
|
||||
using static Unity.Mathematics.math;
|
||||
|
||||
public class OrbitInstance
|
||||
{
|
||||
private OrbitData _data;
|
||||
|
||||
public OrbitInstance(OrbitData data)
|
||||
{
|
||||
_data = data;
|
||||
}
|
||||
|
||||
public static float2 Evaluate(float phase)
|
||||
{
|
||||
phase *= (PI * 2);
|
||||
return new float2(sin(phase), cos(phase));
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/OrbitInstance.cs.meta
Normal file
11
Assets/Scripts/ServerShared/OrbitInstance.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: fc9a1d6d35b2ac14eb8c1092432ae217
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
195
Assets/Scripts/ServerShared/Ship.cs
Normal file
195
Assets/Scripts/ServerShared/Ship.cs
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using MessagePack;
|
||||
using Unity.Mathematics;
|
||||
using static Unity.Mathematics.math;
|
||||
|
||||
[MessagePackObject]
|
||||
public class Ship : DatabaseEntry
|
||||
{
|
||||
[Key("hull")]
|
||||
public Gear Hull;
|
||||
[Key("hardpoints")]
|
||||
public List<Hardpoint> Hardpoints = new List<Hardpoint>();
|
||||
[Key("cargo")]
|
||||
public List<ItemInstance> Cargo = new List<ItemInstance>();
|
||||
|
||||
// [Key("bindings")] public Dictionary<KeyCode,Guid> Bindings = new Dictionary<KeyCode,Guid>();
|
||||
//[IgnoreMember] public int HullHardpointCount;
|
||||
[IgnoreMember] public Dictionary<Guid, IActivatedItemBehavior[]> ItemBindings;
|
||||
[IgnoreMember] public IItemBehavior[] ItemBehaviors;
|
||||
|
||||
[IgnoreMember] public bool ForceThrust;
|
||||
// [IgnoreMember] public Dictionary<Targetable, float> Contacts = new Dictionary<Targetable, float>();
|
||||
[IgnoreMember] public float Temperature;
|
||||
[IgnoreMember] public float Charge;
|
||||
// [IgnoreMember] public Targetable Target;
|
||||
[IgnoreMember] public float2 Direction;
|
||||
[IgnoreMember] public Dictionary<object, float> VisibilitySources = new Dictionary<object, float>();
|
||||
|
||||
private HullData _hullData;
|
||||
private bool _hydrated = false;
|
||||
|
||||
[IgnoreMember] public float Mass { get; private set; }
|
||||
[IgnoreMember] public float SpecificHeat { get; private set; }
|
||||
|
||||
//[IgnoreMember] public float Visibility => VisibilitySources.Values.Sum();
|
||||
|
||||
public Gear GetEquipped(HardpointType type)
|
||||
{
|
||||
return Hardpoints.FirstOrDefault(hp => hp.HardpointData.Type == type)?.Item;
|
||||
}
|
||||
|
||||
public T GetEquipped<T>() where T : EquippableItemData
|
||||
{
|
||||
var data = Hardpoints.FirstOrDefault(hp => Context.GetData(hp.Item) is T);
|
||||
if (data != null)
|
||||
return Context.GetData(data.Item) as T;
|
||||
return null;
|
||||
}
|
||||
|
||||
public void AddHeat(float heat)
|
||||
{
|
||||
Temperature += heat / SpecificHeat;
|
||||
}
|
||||
|
||||
public void Hydrate()
|
||||
{
|
||||
GenerateBehaviors();
|
||||
|
||||
Mass = Hull.Mass +
|
||||
Hardpoints.Sum(hp => hp.Item?.Mass ?? 0) +
|
||||
Cargo.Sum(ii => ii.Mass);
|
||||
|
||||
SpecificHeat = Hull.HeatCapacity +
|
||||
Hardpoints.Sum(hp => hp.Item?.HeatCapacity ?? 0) +
|
||||
Cargo.Sum(ii => ii.HeatCapacity);
|
||||
|
||||
//HullHardpointCount = Hardpoints.Count(hp => hp.HardpointData.Type == HardpointType.Hull);
|
||||
_hydrated = true;
|
||||
}
|
||||
|
||||
private void GenerateBehaviors()
|
||||
{
|
||||
ItemBehaviors = Hardpoints.Where(hp=>hp.Item!=null)
|
||||
.Where(hp=>hp.Item.ItemData.Behaviors?.Any()??false)
|
||||
.SelectMany(hp => hp.Item.ItemData.Behaviors
|
||||
.Select(bd => bd.CreateInstance(Context, this, hp.Item)))
|
||||
.OrderBy(b => b.GetType().GetCustomAttribute<UpdateOrderAttribute>()?.Order ?? 0).ToArray();
|
||||
|
||||
ItemBindings = ItemBehaviors
|
||||
.Where(b => b is IActivatedItemBehavior)
|
||||
.GroupBy(b => b.Item.ID, (guid, behaviors) => new {guid, behaviors})
|
||||
.ToDictionary(g => g.guid, g => g.behaviors.Cast<IActivatedItemBehavior>().ToArray());
|
||||
}
|
||||
|
||||
// public void GenerateBindings()
|
||||
// {
|
||||
// Bindings = new Dictionary<KeyCode, Guid>();
|
||||
//
|
||||
// var bindables =
|
||||
// ItemBindings.Select(id => new {id=id.Key, eq = id.Value.First().Hardpoint.Item.ItemData}).ToList();
|
||||
//
|
||||
// var weapons = bindables.Where(i => i.eq.HardpointType.IsWeapon()).ToArray();
|
||||
//
|
||||
// var mouseButtons = Enumerable.Range((int) KeyCode.Mouse0, 3).Cast<KeyCode>();
|
||||
// foreach (var x in weapons.Zip(mouseButtons, (binding, key) => new {binding,key}))
|
||||
// {
|
||||
// Bindings.Add(x.key, x.binding.id);
|
||||
// bindables.Remove(x.binding);
|
||||
// }
|
||||
//
|
||||
// var thruster = bindables.FirstOrDefault(x => x.eq.HardpointType == HardpointType.Thruster);
|
||||
// if (thruster != null)
|
||||
// {
|
||||
// Bindings.Add(KeyCode.LeftShift, thruster.id);
|
||||
// bindables.Remove(thruster);
|
||||
// }
|
||||
//
|
||||
// var utility = bindables.FirstOrDefault(x => !x.eq.HardpointType.IsWeapon());
|
||||
// if (utility != null)
|
||||
// {
|
||||
// Bindings.Add(KeyCode.Space, utility.id);
|
||||
// bindables.Remove(utility);
|
||||
// }
|
||||
//
|
||||
// var numKeys = Enumerable.Range((int) KeyCode.Alpha1, 9).Cast<KeyCode>();
|
||||
// foreach (var x in bindables.Zip(numKeys, (binding, key) => new {binding,key}))
|
||||
// {
|
||||
// Bindings.Add(x.key, x.binding.id);
|
||||
// }
|
||||
//
|
||||
// }
|
||||
|
||||
// public void Activate(KeyCode binding)
|
||||
// {
|
||||
// if (Bindings.ContainsKey(binding))
|
||||
// foreach (var behavior in ItemBindings[Bindings[binding]])
|
||||
// {
|
||||
// behavior.Activate();
|
||||
// if(behavior.Hardpoint.ActionBarButton!=null)
|
||||
// behavior.Hardpoint.ActionBarButton.Background.color = Color.yellow;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public void Deactivate(KeyCode binding)
|
||||
// {
|
||||
// if(Bindings.ContainsKey(binding))
|
||||
// foreach (var behavior in ItemBindings[Bindings[binding]])
|
||||
// {
|
||||
// behavior.Deactivate();
|
||||
// if(behavior.Hardpoint.ActionBarButton!=null)
|
||||
// behavior.Hardpoint.ActionBarButton.Background.color = GlobalData.Instance.UnselectedElementColor;
|
||||
// }
|
||||
// }
|
||||
|
||||
public void FixedUpdate(float delta)
|
||||
{
|
||||
// foreach (var kvp in Contacts.ToArray())
|
||||
// if (kvp.Key == null || Time.time - kvp.Value > GlobalData.Instance.TargetPersistenceDuration)
|
||||
// {
|
||||
// Contacts.Remove(kvp.Key);
|
||||
// if (kvp.Key == Target)
|
||||
// Target = null;
|
||||
// }
|
||||
|
||||
if (_hydrated)
|
||||
{
|
||||
var hull = Hull.ItemData;
|
||||
|
||||
var rad = pow(Temperature, Context.GlobalData.HeatRadiationPower) * Context.GlobalData.HeatRadiationMultiplier;
|
||||
Temperature -= rad * delta;
|
||||
VisibilitySources[this] = rad;
|
||||
|
||||
foreach(var behavior in ItemBehaviors)
|
||||
behavior.FixedUpdate(delta);
|
||||
|
||||
foreach (var hardpoint in Hardpoints)
|
||||
{
|
||||
if (hardpoint.Item.ItemData.Performance(Temperature) < .01f)
|
||||
hardpoint.Item.Durability -= delta;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Update(float delta)
|
||||
{
|
||||
foreach(var behavior in ItemBehaviors)
|
||||
behavior.Update(delta);
|
||||
}
|
||||
|
||||
// public void UpdateInput(float delta)
|
||||
// {
|
||||
// foreach (var key in Bindings.Keys)
|
||||
// {
|
||||
// if(Input.GetKeyDown(key))
|
||||
// Activate(key);
|
||||
// if(Input.GetKeyUp(key))
|
||||
// Deactivate(key);
|
||||
// }
|
||||
//
|
||||
// }
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Ship.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Ship.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 59cf788469bddba49b3f1845fb077ac8
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
101
Assets/Scripts/ServerShared/ZoneData.cs
Normal file
101
Assets/Scripts/ServerShared/ZoneData.cs
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class ZoneData : DatabaseEntry, INamedEntry
|
||||
{
|
||||
[JsonProperty("name")] [Key(1)]
|
||||
public string Name;
|
||||
|
||||
[JsonProperty("radius")] [Key(2)]
|
||||
public float Radius = 500;
|
||||
|
||||
[JsonProperty("wormholes")] [Key(4)]
|
||||
public List<Guid> Wormholes = new List<Guid>();
|
||||
|
||||
[JsonProperty("stations")] [Key(3)]
|
||||
public List<Guid> Stations = new List<Guid>();
|
||||
|
||||
[JsonProperty("planets")] [Key(4)]
|
||||
public List<Guid> Planets = new List<Guid>();
|
||||
|
||||
[JsonProperty("orbits")] [Key(5)]
|
||||
public List<Guid> Orbits = new List<Guid>();
|
||||
|
||||
[IgnoreMember] public string EntryName
|
||||
{
|
||||
get => Name;
|
||||
set => Name = value;
|
||||
}
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class Station : DatabaseEntry, INamedEntry
|
||||
{
|
||||
[JsonProperty("name")] [Key(1)]
|
||||
public string Name;
|
||||
|
||||
// Can be Planet or Orbit
|
||||
[JsonProperty("parent")] [Key(2)]
|
||||
public Guid Parent;
|
||||
|
||||
[JsonProperty("owner")] [Key(3)]
|
||||
public Guid Owner;
|
||||
|
||||
[JsonProperty("inventory")] [Key(4)]
|
||||
public List<ItemInstance> Inventory = new List<ItemInstance>();
|
||||
|
||||
[JsonProperty("buying")] [Key(5)]
|
||||
public Dictionary<Guid, float> BuyPrices = new Dictionary<Guid, float>();
|
||||
|
||||
[JsonProperty("selling")] [Key(6)]
|
||||
public Dictionary<Guid, float> SellPrices = new Dictionary<Guid, float>();
|
||||
|
||||
[IgnoreMember] public string EntryName
|
||||
{
|
||||
get => Name;
|
||||
set => Name = value;
|
||||
}
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class PlanetData : DatabaseEntry, INamedEntry
|
||||
{
|
||||
[JsonProperty("name")] [Key(1)]
|
||||
public string Name;
|
||||
|
||||
[JsonProperty("orbit")] [Key(2)]
|
||||
public Guid Orbit;
|
||||
|
||||
[JsonProperty("mass")] [Key(3)]
|
||||
public float Mass;
|
||||
|
||||
[IgnoreMember] public string EntryName
|
||||
{
|
||||
get => Name;
|
||||
set => Name = value;
|
||||
}
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class OrbitData : DatabaseEntry
|
||||
{
|
||||
[JsonProperty("parent")] [Key(1)]
|
||||
public Guid Parent;
|
||||
|
||||
[JsonProperty("distance")] [Key(2)]
|
||||
public float Distance;
|
||||
|
||||
[JsonProperty("phase")] [Key(3)]
|
||||
public float Phase;
|
||||
|
||||
[JsonProperty("period")] [Key(4)]
|
||||
public float Period;
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/ZoneData.cs.meta
Normal file
11
Assets/Scripts/ServerShared/ZoneData.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: caacacff891c73d49aca6390abd3efe4
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
246
Assets/Scripts/ServerShared/ZoneGenerator.cs
Normal file
246
Assets/Scripts/ServerShared/ZoneGenerator.cs
Normal file
|
|
@ -0,0 +1,246 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using MessagePack;
|
||||
using Unity.Mathematics;
|
||||
// TODO: USE THIS EVERYWHERE
|
||||
using static Unity.Mathematics.math;
|
||||
using Random = Unity.Mathematics.Random;
|
||||
|
||||
public class ZoneGenerator
|
||||
{
|
||||
// public float BinaryFloor = 100;
|
||||
// public float BinaryProbability = .1f;
|
||||
// public float MassPowerMinimum = 1.35f;
|
||||
// public float MassPowerMaximum = 1.75f;
|
||||
// public float DistancePowerMinimum = 1.35f;
|
||||
// public float DistancePowerMaximum = 1.75f;
|
||||
// public float Radius = 500;
|
||||
// public float Mass = 100000;
|
||||
// public float MassFloor = 1;
|
||||
// public float SunMass = 10000;
|
||||
// public float GasGiantMass = 2000;
|
||||
// public float RadiusPower = 1.75f;
|
||||
|
||||
public static Planet[] GenerateEntities(GameContext context, ZoneData data, float mass)
|
||||
{
|
||||
var random = new Random();
|
||||
random.InitState(unchecked((uint)data.Name.GetHashCode()));
|
||||
|
||||
var root = new Planet
|
||||
{
|
||||
Random = random,
|
||||
Context = context,
|
||||
Mass = mass,
|
||||
ChildDistanceMaximum = data.Radius,
|
||||
ChildDistanceMinimum = context.PlanetRadius(mass)
|
||||
};
|
||||
|
||||
// There is some chance of generating a rosette or binary system
|
||||
var rosette = random.NextFloat() < context.GlobalData.RosetteProbability;
|
||||
|
||||
if (rosette)
|
||||
{
|
||||
// Create a rosette with a number of vertices between 2 and 9 inclusive
|
||||
root.ExpandRosette((int)(random.NextFloat(1, 3) * random.NextFloat(2, 3)));
|
||||
|
||||
// Create a small number of less massive "captured" planets orbiting past the rosette
|
||||
root.ExpandSolar(
|
||||
count: random.NextInt(1,5),
|
||||
massMulMin: .6f,
|
||||
massMulMax: .8f,
|
||||
distMulMin: 1.25f,
|
||||
distMulMax: 1.75f,
|
||||
jupiterJump: 1,
|
||||
massFraction: .1f);
|
||||
|
||||
var averageChildMass = root.Children.Sum(p => p.Mass) / root.Children.Count;
|
||||
foreach(var p in root.Children.Where(c=>c.Mass>context.GlobalData.GasGiantMass))
|
||||
{
|
||||
var m = p.Mass / averageChildMass;
|
||||
// Give each child in the rosette its own mini solar system
|
||||
p.ExpandSolar(
|
||||
count: (int) (m * 5),
|
||||
massMulMin: 0.75f,
|
||||
massMulMax: 2.5f,
|
||||
distMulMin: 1 + m * .05f,
|
||||
distMulMax: 1.05f + m * .15f,
|
||||
jupiterJump: random.NextFloat() * random.NextFloat() * 10 + 1,
|
||||
massFraction: .5f
|
||||
);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Create a regular old boring solar system
|
||||
root.ExpandSolar(
|
||||
count: random.NextInt(5, 15),
|
||||
massMulMin: 0.5f,
|
||||
massMulMax: 2.0f,
|
||||
distMulMin: 1.1f,
|
||||
distMulMax: 1.35f,
|
||||
jupiterJump: random.NextFloat() * random.NextFloat() * 10 + 1,
|
||||
massFraction: .25f
|
||||
);
|
||||
}
|
||||
|
||||
// Get all children that are above the satellite creation mass floor and not rosette members
|
||||
var satelliteCandidates = rosette
|
||||
? root.AllPlanets().Where(p => p.Parent != root && p.Mass > context.GlobalData.SatelliteCreationMassFloor)
|
||||
: root.AllPlanets().Where(p => p.Mass > context.GlobalData.SatelliteCreationMassFloor);
|
||||
|
||||
foreach (var planet in satelliteCandidates)
|
||||
{
|
||||
// There's a chance of generating satellites for each qualified planet
|
||||
if (random.NextFloat() < context.GlobalData.SatelliteCreationProbability)
|
||||
{
|
||||
// Sometimes the satellite is so massive that it forms a binary system (like Earth!)
|
||||
if(random.NextFloat() < context.GlobalData.BinaryCreationProbability)
|
||||
planet.ExpandRosette(2);
|
||||
// Otherwise, terrestrial planets get a couple satellites while gas giants get many
|
||||
else planet.ExpandSolar(
|
||||
count: planet.Mass < context.GlobalData.GasGiantMass ? random.NextInt(1,3) : random.NextInt(4,10),
|
||||
massMulMin: .75f,
|
||||
massMulMax: 1.5f,
|
||||
distMulMin: 1.05f,
|
||||
distMulMax: 1.25f,
|
||||
jupiterJump: 1,
|
||||
massFraction: .15f); // Planetary satellites are not nearly as massive as planets themselves
|
||||
}
|
||||
}
|
||||
|
||||
return root.AllPlanets().ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
public class Planet
|
||||
{
|
||||
public Random Random;
|
||||
public GameContext Context;
|
||||
public float Distance;
|
||||
public float Phase;
|
||||
public float Mass;
|
||||
public float Period;
|
||||
public float ChildDistanceMinimum;
|
||||
public float ChildDistanceMaximum;
|
||||
public bool Empty = false;
|
||||
public List<Planet> Children = new List<Planet>();
|
||||
public Planet Parent;
|
||||
|
||||
public IEnumerable<Planet> AllPlanets()
|
||||
{
|
||||
return new[]{this}.Concat(Children.SelectMany(c=>c.AllPlanets()));
|
||||
}
|
||||
|
||||
// Create children that fill a single orbit, equally spaced
|
||||
// https://en.wikipedia.org/wiki/Klemperer_rosette
|
||||
public void ExpandRosette(int vertices)
|
||||
{
|
||||
// Rosette children replace the parent, parent orbital node is left empty
|
||||
Empty = true;
|
||||
|
||||
// Masses in a rosette alternate, so every sequential pair has the same shared mass
|
||||
var sharedMass = Mass / vertices * 2;
|
||||
|
||||
// Proportion of the masses of sequential pairs is random, but only for even vertex counts
|
||||
var proportion = vertices % 2 == 0 ? Random.NextFloat(.5f,.95f) : .5f;
|
||||
|
||||
// Place children at a fixed distance in the center of the range
|
||||
var dist = (ChildDistanceMinimum + ChildDistanceMaximum) / 2;
|
||||
|
||||
// Position of first child
|
||||
var p0 = new float2(0, dist);
|
||||
|
||||
// Position of second child
|
||||
var p1 = OrbitInstance.Evaluate(1.0f / vertices) * dist;
|
||||
|
||||
// Maximum child distance is half the distance to the neighbor minus the neighbor's radius
|
||||
var p0ChildDist = distance(p0, p1) * proportion - Context.PlanetRadius(sharedMass * (1 - proportion));
|
||||
var p1ChildDist = distance(p0, p1) * (1 - proportion) - Context.PlanetRadius(sharedMass * proportion);
|
||||
|
||||
for (int i = 0; i < vertices; i++)
|
||||
{
|
||||
var child = new Planet
|
||||
{
|
||||
Random = Random,
|
||||
Context = Context,
|
||||
Parent = this,
|
||||
Mass = sharedMass * (i % 2 == 0 ? proportion : 1 - proportion), // Masses alternate
|
||||
Distance = dist,
|
||||
Phase = (float) i / vertices,
|
||||
ChildDistanceMaximum = (i % 2 == 0 ? p0ChildDist : p1ChildDist)
|
||||
};
|
||||
child.ChildDistanceMinimum = Context.PlanetRadius(child.Mass) * 2;
|
||||
child.Period = child.Distance * child.Distance / 100;
|
||||
Children.Add(child);
|
||||
}
|
||||
|
||||
ChildDistanceMinimum = dist + p0ChildDist;
|
||||
}
|
||||
|
||||
// Create children that mimic the distribution of planetary masses in the solar system
|
||||
public void ExpandSolar(int count, float massMulMin, float massMulMax, float distMulMin, float distMulMax, float jupiterJump, float massFraction)
|
||||
{
|
||||
// Expansion is impossible when child space is full
|
||||
if (count == 0 || ChildDistanceMaximum < ChildDistanceMinimum)
|
||||
return;
|
||||
|
||||
var masses = new float[count];
|
||||
var distances = new float[count];
|
||||
|
||||
// Accumulate total mass
|
||||
// Initialize first mass and distance, actual number doesn't matter since total mass will be divided proportionally
|
||||
float massTotal = distances[0] = masses[0] = 1;
|
||||
|
||||
// Masses and distances multiply from one planet to the next
|
||||
// Mass typically increases exponentially as you go further out
|
||||
// jupiterJump is an additional mass multiplier applied after half of the planets
|
||||
for (var i = 1; i < count; i++)
|
||||
{
|
||||
massTotal += masses[i] = masses[i - 1] * Random.NextFloat(massMulMin, massMulMax) * (count/2==i ? jupiterJump : 1);
|
||||
distances[i] = distances[i - 1] * Random.NextFloat(distMulMin, distMulMax);
|
||||
}
|
||||
|
||||
// Add some randomness to child masses
|
||||
for (var i = 0; i < masses.Length; i++)
|
||||
masses[i] *= Random.NextFloat(.1f, 1f);
|
||||
|
||||
// Normalize the masses of the children
|
||||
for (var i = 0; i < count; i++)
|
||||
masses[i] = masses[i] / massTotal * Mass * massFraction;
|
||||
|
||||
// Map child distances to range between minimum and maximum
|
||||
var oldDistances = (float[]) distances.Clone();
|
||||
for (var i = 0; i < count; i++)
|
||||
distances[i] = lerp(ChildDistanceMinimum, ChildDistanceMaximum,
|
||||
(oldDistances[i] - oldDistances[0]) / (oldDistances[count - 1] - oldDistances[0])) + Context.PlanetRadius(masses[i]);
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
// Only instantiate children above the mass floor
|
||||
if (masses[i] > Context.GlobalData.MassFloor)
|
||||
{
|
||||
var child = new Planet
|
||||
{
|
||||
Random = Random,
|
||||
Context = Context,
|
||||
Parent = this,
|
||||
Mass = masses[i],
|
||||
Distance = distances[i],
|
||||
Phase = Random.NextFloat()
|
||||
};
|
||||
child.Period = child.Distance * child.Distance / 100;
|
||||
child.ChildDistanceMinimum = Context.PlanetRadius(child.Mass) * 2;
|
||||
// Maximum child distance of child is the smallest distance to either of its neighbors
|
||||
child.ChildDistanceMaximum = min(i == 0 ? child.Distance - ChildDistanceMinimum : child.Distance - distances[i - 1],
|
||||
i < count - 1 ? distances[i + 1] - child.Distance : float.PositiveInfinity);
|
||||
if (float.IsNaN(child.Distance))
|
||||
throw new NotFiniteNumberException($"Planet created with NaN distance, something went very wrong!");
|
||||
if (child.ChildDistanceMaximum > child.ChildDistanceMinimum)
|
||||
Children.Add(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/ZoneGenerator.cs.meta
Normal file
11
Assets/Scripts/ServerShared/ZoneGenerator.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 34a41f4864c0c954ead2276bae0e8abb
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Loading…
Reference in a new issue