Restore the stable legacy Unity project
This commit is contained in:
parent
56a156ee87
commit
7006a6b0dd
2070 changed files with 180490 additions and 169303 deletions
|
|
@ -1,7 +1,7 @@
|
|||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// This code was auto-generated by com.unity.inputsystem:InputActionCodeGenerator
|
||||
// version 1.19.0
|
||||
// version 1.14.0
|
||||
// from Assets/Resources/Aetheria.inputactions
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
|
|
@ -85,7 +85,6 @@ public partial class @AetheriaInput: IInputActionCollection2, IDisposable
|
|||
public @AetheriaInput()
|
||||
{
|
||||
asset = InputActionAsset.FromJson(@"{
|
||||
""version"": 1,
|
||||
""name"": ""Aetheria"",
|
||||
""maps"": [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
fileFormatVersion: 2
|
||||
guid: b3c453d425710cb47bfcde9c9acf3b15
|
||||
guid: 2501605fca062c84d963e811df551698
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
46
Assets/Scripts/CultCache/Editor/AetheriaDatabaseView.cs
Normal file
46
Assets/Scripts/CultCache/Editor/AetheriaDatabaseView.cs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
public class AetheriaDatabaseView : DatabaseListView
|
||||
{
|
||||
// Singleton to avoid multiple instances of window.
|
||||
private static DatabaseListView _instance;
|
||||
private string tableName;
|
||||
public static DatabaseListView Instance => _instance ? _instance : GetWindow<AetheriaDatabaseView>();
|
||||
[MenuItem("Window/Aetheria/Database Tools")]
|
||||
static void Init() => Instance.Show();
|
||||
private void Awake()
|
||||
{
|
||||
_instance = this;
|
||||
}
|
||||
|
||||
protected override string DatabaseName => "Aetheria";
|
||||
|
||||
protected override string FilePath => new DirectoryInfo(Application.dataPath).Parent.CreateSubdirectory("GameData").FullName;
|
||||
|
||||
protected override DatabaseEntryGroup[] Groupers => new DatabaseEntryGroup[]
|
||||
{
|
||||
new DatabaseEntryGroup<SimpleCommodityData,SimpleCommodityCategory>(
|
||||
data => data.Category,
|
||||
category => Enum.GetName(typeof(SimpleCommodityCategory), category),
|
||||
(data, category) => data.Category = category ),
|
||||
new DatabaseEntryGroup<CompoundCommodityData, CompoundCommodityCategory>(
|
||||
data => data.Category,
|
||||
category => Enum.GetName(typeof(CompoundCommodityCategory), category),
|
||||
(data, category) => data.Category = category ),
|
||||
new DatabaseEntryGroup<GearData, HardpointType>(
|
||||
data => data.HardpointType,
|
||||
type => Enum.GetName(typeof(HardpointType), type),
|
||||
(data, type) => data.Hardpoint = type),
|
||||
new DatabaseEntryGroup<GearData, Guid>(
|
||||
data => data.Manufacturer,
|
||||
factionID => factionID == Guid.Empty ? "Default" : cultCache.Get<Faction>(factionID).ShortName,
|
||||
(data, faction) => data.Manufacturer = faction),
|
||||
new DatabaseEntryGroup<HullData, HullType>(
|
||||
data => data.HullType,
|
||||
type => Enum.GetName(typeof(HullType), type),
|
||||
(data, type) => data.HullType = type)
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 4016d25951e246a184441b2aae75eba0
|
||||
timeCreated: 1617151686
|
||||
31
Assets/Scripts/CultCache/Editor/BaseInspector.cs
Normal file
31
Assets/Scripts/CultCache/Editor/BaseInspector.cs
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
using System;
|
||||
|
||||
public abstract class BaseInspector<T>
|
||||
{
|
||||
protected const int width = 150;
|
||||
protected const int labelWidth = 20;
|
||||
protected const int toggleWidth = 18;
|
||||
protected const int arrowWidth = 22;
|
||||
|
||||
public abstract T Inspect(string label, T value, object parent, DatabaseInspector inspectorWindow);
|
||||
}
|
||||
|
||||
public abstract class BaseInspector<T, A> where A : Attribute
|
||||
{
|
||||
protected const int width = 150;
|
||||
protected const int labelWidth = 20;
|
||||
protected const int toggleWidth = 18;
|
||||
protected const int arrowWidth = 22;
|
||||
|
||||
public abstract T Inspect(string label, T value, object parent, DatabaseInspector inspectorWindow, A attribute);
|
||||
}
|
||||
|
||||
public abstract class BaseInspector<T, A, B> where A : Attribute where B : Attribute
|
||||
{
|
||||
protected const int width = 150;
|
||||
protected const int labelWidth = 20;
|
||||
protected const int toggleWidth = 18;
|
||||
protected const int arrowWidth = 22;
|
||||
|
||||
public abstract T Inspect(string label, T value, object parent, DatabaseInspector inspectorWindow, A attributeA, B attributeB);
|
||||
}
|
||||
3
Assets/Scripts/CultCache/Editor/BaseInspector.cs.meta
Normal file
3
Assets/Scripts/CultCache/Editor/BaseInspector.cs.meta
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: f3cde78766994141a3da6ab88d09118f
|
||||
timeCreated: 1617052142
|
||||
293
Assets/Scripts/CultCache/Editor/DatabaseInspector.cs
Normal file
293
Assets/Scripts/CultCache/Editor/DatabaseInspector.cs
Normal file
|
|
@ -0,0 +1,293 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
using Unity.Mathematics;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using static Unity.Mathematics.math;
|
||||
using static UnityEditor.EditorGUILayout;
|
||||
using int2 = Unity.Mathematics.int2;
|
||||
using Object = UnityEngine.Object;
|
||||
|
||||
public class DatabaseInspector : EditorWindow
|
||||
{
|
||||
public static CultCache CultCache;
|
||||
public DatabaseEntry entry;
|
||||
|
||||
// Singleton to avoid multiple instances of window.
|
||||
private static DatabaseInspector _instance;
|
||||
public static DatabaseInspector Instance => _instance ? _instance : GetWindow<DatabaseInspector>();
|
||||
private static bool _listItemStyle;
|
||||
public static GUIStyle ListItemStyle => (_listItemStyle = !_listItemStyle) ? DatabaseListView.ListStyleEven : DatabaseListView.ListStyleOdd;
|
||||
|
||||
public const int Width = 150;
|
||||
|
||||
private Vector2 _view;
|
||||
private GUIStyle _warning;
|
||||
private List<(Type targetType, HashSet<Type> attributes, Type inspectorType, object instance)> _inspectors =
|
||||
new List<(Type targetType, HashSet<Type> attributes, Type inspectorType, object instance)>();
|
||||
|
||||
private List<(Type targetType, HashSet<Type> attributes, Type inspectorType, Dictionary<Type, object> instances)> _genericInspectors =
|
||||
new List<(Type targetType, HashSet<Type> attributes, Type inspectorType, Dictionary<Type, object> instances)>();
|
||||
private HashSet<object> _foldouts = new HashSet<object>();
|
||||
|
||||
public Color LabelColor => EditorGUIUtility.isProSkin ? Color.white : Color.black;
|
||||
|
||||
void OnEnable()
|
||||
{
|
||||
_instance = this;
|
||||
CultCache.OnUpdate += (_,__) => EditorDispatcher.Dispatch(Repaint);
|
||||
wantsMouseMove = true;
|
||||
_warning = new GUIStyle(EditorStyles.boldLabel);
|
||||
_warning.normal.textColor = Color.red;
|
||||
|
||||
var inspectorTypes = typeof(BaseInspector<>).GetAllGenericChildClasses()
|
||||
.Concat(typeof(BaseInspector<,>).GetAllGenericChildClasses())
|
||||
.Concat(typeof(BaseInspector<,,>).GetAllGenericChildClasses());
|
||||
foreach (var type in inspectorTypes)
|
||||
{
|
||||
var genericArguments = type.BaseType.GetGenericArguments();
|
||||
if(genericArguments.Any())
|
||||
{
|
||||
if (genericArguments[0].ContainsGenericParameters)
|
||||
{
|
||||
_genericInspectors.Add((
|
||||
genericArguments[0].GetGenericTypeDefinition(),
|
||||
new HashSet<Type>(genericArguments.Skip(1)),
|
||||
type,
|
||||
new Dictionary<Type, object>()
|
||||
));
|
||||
}
|
||||
else
|
||||
{
|
||||
_inspectors.Add((
|
||||
genericArguments[0],
|
||||
new HashSet<Type>(genericArguments.Skip(1)),
|
||||
type,
|
||||
Activator.CreateInstance(type)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Inspect(object obj, object parent = null)
|
||||
{
|
||||
foreach (var field in obj.GetType().GetFields().OrderBy(f=>f.GetCustomAttribute<KeyAttribute>()?.IntKey ?? 0))
|
||||
{
|
||||
Inspect(obj, field, parent);
|
||||
}
|
||||
}
|
||||
|
||||
public void Inspect(object obj, FieldInfo field, object parent = null)
|
||||
{
|
||||
var inspectable = field.GetCustomAttribute<InspectableAttribute>();
|
||||
if (inspectable == null) return;
|
||||
|
||||
var attributes = field.GetCustomAttributes(false);
|
||||
|
||||
var type = field.FieldType;
|
||||
var value = field.GetValue(obj);
|
||||
|
||||
field.SetValue(obj, InspectMember(field.Name.SplitCamelCase(), value, parent ?? obj, type, false, attributes));
|
||||
}
|
||||
|
||||
public object InspectMember(string label, object value, object parent, Type type, bool suppressContainer = false, params object[] attributes)
|
||||
{
|
||||
var style = _listItemStyle;
|
||||
object GetAttribute(Type attributeType)
|
||||
{
|
||||
return attributes.FirstOrDefault(attributeType.IsInstanceOfType);
|
||||
}
|
||||
|
||||
if (value == null && type != typeof(string) && !(type.IsInterface || type.IsAbstract)) value = Activator.CreateInstance(type);
|
||||
|
||||
var potentialInspectors = _inspectors
|
||||
.Where(pi =>
|
||||
pi.targetType == type &&
|
||||
pi.attributes.All(attributeType => GetAttribute(attributeType) != null));
|
||||
if (potentialInspectors.Any())
|
||||
{
|
||||
var preferredInspector = potentialInspectors.MaxBy(i => i.attributes.Count);
|
||||
var parameters = new[] {label, value, parent, this}
|
||||
.Concat(preferredInspector.attributes.Select(GetAttribute))
|
||||
.ToArray();
|
||||
value = preferredInspector.inspectorType.GetMethod("Inspect").Invoke(preferredInspector.instance, parameters);
|
||||
_listItemStyle = style;
|
||||
return value;
|
||||
}
|
||||
|
||||
if (type.IsEnum)
|
||||
{
|
||||
var isflags = type.GetCustomAttributes<FlagsAttribute>().Any();
|
||||
var names = Enum.GetNames(type);
|
||||
value = InspectEnum(label, (int) value, isflags ? names.Skip(1).ToArray() : names, isflags);
|
||||
_listItemStyle = style;
|
||||
return value;
|
||||
}
|
||||
|
||||
if (type.GetCustomAttribute<InspectableAttribute>() != null)
|
||||
{
|
||||
if(!suppressContainer)
|
||||
GUILayout.BeginVertical(GUI.skin.box);
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
if(!suppressContainer)
|
||||
{
|
||||
if (Foldout(_foldouts.Contains(value), label, true, EditorStyles.boldLabel))
|
||||
_foldouts.Add(value);
|
||||
else _foldouts.Remove(value);
|
||||
}
|
||||
if (type.IsInterface || type.IsAbstract)
|
||||
{
|
||||
var subTypes = type.GetAllChildClasses().Where(t=>!(t.IsInterface || t.IsAbstract)).ToArray();
|
||||
var selected = value != null ? Array.IndexOf(subTypes, value.GetType()) + 1 : 0;
|
||||
var newSelection = Popup(selected,
|
||||
subTypes.Select(t => t.Name.SplitCamelCase()).Prepend("None").ToArray());
|
||||
if (newSelection != selected)
|
||||
value = newSelection == 0 ? null : Activator.CreateInstance(subTypes[newSelection - 1]);
|
||||
}
|
||||
else if (value == null) value = Activator.CreateInstance(type);
|
||||
}
|
||||
|
||||
if (value != null && (_foldouts.Contains(value) || suppressContainer)) Inspect(value, parent);
|
||||
if(!suppressContainer)
|
||||
GUILayout.EndVertical();
|
||||
_listItemStyle = style;
|
||||
return value;
|
||||
}
|
||||
|
||||
if (type.IsGenericType)
|
||||
{
|
||||
var genericTypeDefinition = type.GetGenericTypeDefinition();
|
||||
var potentialGenericInspectors = _genericInspectors
|
||||
.Where(pi =>
|
||||
pi.targetType == genericTypeDefinition &&
|
||||
pi.attributes.All(attributeType => GetAttribute(attributeType) != null));
|
||||
if (potentialGenericInspectors.Any())
|
||||
{
|
||||
var genericTypeArguments = type.GenericTypeArguments;
|
||||
var preferredInspector = potentialGenericInspectors.MaxBy(i => i.attributes.Count);
|
||||
var genericInspectorType = preferredInspector.inspectorType.MakeGenericType(genericTypeArguments);
|
||||
if (!preferredInspector.instances.ContainsKey(genericInspectorType))
|
||||
preferredInspector.instances[genericInspectorType] =
|
||||
Activator.CreateInstance(genericInspectorType);
|
||||
var parameters = new[] {label, value, parent, this};
|
||||
value = genericInspectorType.GetMethod("Inspect").Invoke(preferredInspector.instances[genericInspectorType], parameters);
|
||||
_listItemStyle = style;
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
Debug.Log($"Field \"{label}\" has unknown type {type.Name}. No inspector was generated.");
|
||||
|
||||
_listItemStyle = style;
|
||||
return value;
|
||||
}
|
||||
|
||||
public int InspectEnum(string label, int value, string[] enumOptions, bool flags)
|
||||
{
|
||||
if (flags)
|
||||
{
|
||||
Space();
|
||||
LabelField(label, EditorStyles.boldLabel);
|
||||
using (new VerticalScope(GUI.skin.box))
|
||||
{
|
||||
for (var i = 0; i < enumOptions.Length; i++)
|
||||
{
|
||||
using (var h = new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(enumOptions[i], GUILayout.Width(Width));
|
||||
var set = Toggle(1 << i == (1 << i & value));
|
||||
if (set)
|
||||
value |= 1 << i;
|
||||
else value &= ~(1 << i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
using (var h = new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(Width));
|
||||
return Popup(value, enumOptions);
|
||||
}
|
||||
}
|
||||
|
||||
public void OnGUI()
|
||||
{
|
||||
if (entry==null)
|
||||
{
|
||||
LabelField("No Entry Selected!");
|
||||
return;
|
||||
}
|
||||
|
||||
if(entry is INamedEntry namedEntry)
|
||||
GUILayout.Label(namedEntry.EntryName, EditorStyles.boldLabel);
|
||||
|
||||
_view = BeginScrollView(
|
||||
_view,
|
||||
false,
|
||||
false,
|
||||
GUIStyle.none,
|
||||
GUI.skin.verticalScrollbar,
|
||||
GUI.skin.scrollView,
|
||||
GUILayout.Width(EditorGUIUtility.currentViewWidth),
|
||||
GUILayout.ExpandHeight(true));
|
||||
|
||||
// Serialize inspected object so we can check whether it has actually changed
|
||||
RegisterResolver.Register();
|
||||
var previousBytes = MessagePackSerializer.Serialize<DatabaseEntry>(entry);
|
||||
var previousHash = previousBytes.GetHashSHA1();
|
||||
|
||||
EditorGUI.BeginChangeCheck();
|
||||
|
||||
var dataEntry = entry;
|
||||
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
// if(GUILayout.Button("Print JSON"))
|
||||
// Debug.Log(entry.ToJson());
|
||||
if (GUILayout.Button("Delete Entry"))
|
||||
{
|
||||
CultCache.Remove(entry);
|
||||
entry = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (GUILayout.Button("Clone Entry"))
|
||||
{
|
||||
var copy = MessagePackSerializer.Deserialize<DatabaseEntry>(previousBytes);
|
||||
copy.ID = Guid.NewGuid();
|
||||
CultCache.Add(copy);
|
||||
}
|
||||
}
|
||||
|
||||
using (var h = new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label("ID");
|
||||
LabelField(dataEntry.ID.ToString());
|
||||
}
|
||||
|
||||
_listItemStyle = false;
|
||||
Inspect(entry);
|
||||
|
||||
if (EditorGUI.EndChangeCheck())
|
||||
{
|
||||
if(previousHash != MessagePackSerializer.Serialize(entry).GetHashSHA1())
|
||||
CultCache.Add(entry);
|
||||
}
|
||||
|
||||
EndScrollView();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 0f3c143f0a844f38a109f2de02ce4423
|
||||
guid: 30b612dc279f724418b8a7a5426287c2
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
363
Assets/Scripts/CultCache/Editor/DatabaseView.cs
Normal file
363
Assets/Scripts/CultCache/Editor/DatabaseView.cs
Normal file
|
|
@ -0,0 +1,363 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using JsonKnownTypes;
|
||||
using RethinkDb.Driver;
|
||||
using RethinkDb.Driver.Net;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using static UnityEditor.EditorGUILayout;
|
||||
|
||||
public abstract class DatabaseListView : EditorWindow
|
||||
{
|
||||
public static GUIStyle ListStyleOdd;
|
||||
public static GUIStyle ListStyleEven;
|
||||
|
||||
public Guid SelectedItem;
|
||||
public GUIStyle SelectedStyle;
|
||||
|
||||
public static RethinkDB R = RethinkDB.R;
|
||||
|
||||
protected CultCache cultCache;
|
||||
private static DatabaseInspector _inspector;
|
||||
private Dictionary<string, (bool foldout, (Type entryType, bool foldout)[] types)> _tables;
|
||||
//private Type[] _entryTypes;
|
||||
private Type[] _globalTypes;
|
||||
private string _connectionString;
|
||||
private Vector2 _view;
|
||||
private RethinkQueryStatus _queryStatus;
|
||||
|
||||
private HashSet<int> _groupFoldouts = new HashSet<int>();
|
||||
|
||||
protected abstract string DatabaseName { get; }
|
||||
protected abstract string FilePath { get; }
|
||||
protected virtual DatabaseEntryGroup[] Groupers => new DatabaseEntryGroup[] { };
|
||||
|
||||
protected class DatabaseEntryGroup<T, K> : DatabaseEntryGroup where T : DatabaseEntry
|
||||
{
|
||||
public Func<T,K> GroupSelector { get; }
|
||||
public Func<K,string> GroupLabel { get; }
|
||||
public Action<T, K> Activator { get; }
|
||||
|
||||
public DatabaseEntryGroup(Func<T, K> groupSelector, Func<K, string> groupLabel, Action<T, K> activator)
|
||||
{
|
||||
GroupSelector = groupSelector;
|
||||
GroupLabel = groupLabel;
|
||||
Activator = activator;
|
||||
}
|
||||
|
||||
public override bool CanGroup(Type type)
|
||||
{
|
||||
return typeof(T) == type;
|
||||
}
|
||||
|
||||
public override object SelectGroup(DatabaseEntry o)
|
||||
{
|
||||
if (o is T t) return GroupSelector(t);
|
||||
return null;
|
||||
}
|
||||
|
||||
public override string GetGroupName(object o)
|
||||
{
|
||||
if (o is K k) return GroupLabel(k);
|
||||
return "ERROR";
|
||||
}
|
||||
|
||||
public override int HashGroup(object o)
|
||||
{
|
||||
return o.GetHashCode();
|
||||
if (o is K k) return k.GetHashCode();
|
||||
return 0;
|
||||
}
|
||||
|
||||
public override void Activate(DatabaseEntry o, object g)
|
||||
{
|
||||
if(o is T t && g is K k) Activator(t, k);
|
||||
throw new ArgumentException(
|
||||
$"Entry group activation failed! Expected: object type {typeof(T)}, group type {typeof(K)}; received: object type {o.GetType()}, group type {g.GetType()}");
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract class DatabaseEntryGroup
|
||||
{
|
||||
public abstract bool CanGroup(Type type);
|
||||
public abstract object SelectGroup(DatabaseEntry o);
|
||||
public abstract string GetGroupName(object o);
|
||||
public abstract int HashGroup(object o);
|
||||
public abstract void Activate(DatabaseEntry o, object g);
|
||||
}
|
||||
|
||||
public Color LabelColor => EditorGUIUtility.isProSkin ? Color.white : Color.black;
|
||||
|
||||
private bool _listItemStyle;
|
||||
private SingleFileMessagePackBackingStore _msgPackStore;
|
||||
private MultiFileJsonBackingStore _jsonStore;
|
||||
public GUIStyle ListItemStyle => (_listItemStyle = !_listItemStyle) ? ListStyleEven : ListStyleOdd;
|
||||
|
||||
void OnEnable()
|
||||
{
|
||||
ListStyleOdd = new GUIStyle
|
||||
{
|
||||
normal = {background = EditorGUIUtility.isProSkin ? XKCDColors.DarkGrey.ToTexture() : XKCDColors.LightGrey.ToTexture()},
|
||||
margin = new RectOffset(0, 0, 0, 0)
|
||||
};
|
||||
ListStyleEven = new GUIStyle
|
||||
{
|
||||
normal = {background = EditorGUIUtility.isProSkin ? Color.Lerp(XKCDColors.DarkGrey,Color.black,.5f).ToTexture() : Color.Lerp(XKCDColors.LightGrey,Color.white,.5f).ToTexture()},
|
||||
margin = new RectOffset(0, 0, 0, 0)
|
||||
};
|
||||
|
||||
//_jsonStore = new MultiFileJsonBackingStore(FilePath);
|
||||
_msgPackStore = new SingleFileMessagePackBackingStore(Path.Combine(FilePath, "AetherDB.msgpack"));
|
||||
cultCache = new CultCache();
|
||||
//cultCache.AddBackingStore(_jsonStore);
|
||||
cultCache.AddBackingStore(_msgPackStore);
|
||||
cultCache.AddBackingStore(new MultiFileMessagePackBackingStore(FilePath), typeof(NameFile));
|
||||
cultCache.PullAllBackingStores();
|
||||
|
||||
cultCache.OnUpdate += (_,__) => EditorDispatcher.Dispatch(Repaint);
|
||||
DatabaseInspector.CultCache = cultCache;
|
||||
_inspector = DatabaseInspector.Instance;
|
||||
_inspector.Show();
|
||||
|
||||
_globalTypes = typeof(DatabaseEntry).GetAllChildClasses()
|
||||
.Where(t => t.GetCustomAttribute<InspectableAttribute>() != null && t.GetCustomAttribute<GlobalSettingsAttribute>() != null).ToArray();
|
||||
_tables = typeof(DatabaseEntry).GetAllChildClasses()
|
||||
.Where(t => t.GetCustomAttribute<InspectableAttribute>() != null && t.GetCustomAttribute<GlobalSettingsAttribute>() == null)
|
||||
.GroupBy(t=>t.GetCustomAttribute<RethinkTableAttribute>()?.TableName ?? "Default")
|
||||
.ToDictionary(group=>group.Key, group=> (false, group.Select(t=>(t, false)).ToArray()));
|
||||
|
||||
if (EditorPrefs.HasKey("RethinkDB.URL"))
|
||||
_connectionString = EditorPrefs.GetString("RethinkDB.URL");
|
||||
else
|
||||
_connectionString = "Enter DB URL";
|
||||
|
||||
InitStyles();
|
||||
}
|
||||
|
||||
private void InitStyles()
|
||||
{
|
||||
SelectedStyle = new GUIStyle
|
||||
{
|
||||
normal = {background = EditorGUIUtility.isProSkin ? XKCDColors.DarkGreyBlue.ToTexture() : XKCDColors.Greyblue.ToTexture()},
|
||||
margin = new RectOffset(0, 0, 0, 0)
|
||||
};
|
||||
}
|
||||
|
||||
public void OnGUI()
|
||||
{
|
||||
Event currentEvent = Event.current;
|
||||
EventType currentEventType = currentEvent.type;
|
||||
|
||||
if (currentEventType == EventType.DragUpdated)
|
||||
// Indicate that we don't accept drags ourselves
|
||||
DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
|
||||
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
_connectionString = TextField(_connectionString);
|
||||
if (GUILayout.Button("Connect"))
|
||||
{
|
||||
EditorPrefs.SetString("RethinkDB.URL", _connectionString);
|
||||
JsonKnownTypesSettingsManager.RegisterTypeAssembly<ItemData>();
|
||||
_queryStatus = RethinkConnection.RethinkConnect(cultCache, _connectionString, DatabaseName);
|
||||
}
|
||||
}
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label("Export");
|
||||
//_fileName = TextField(_fileName);
|
||||
if (GUILayout.Button("JSON"))
|
||||
{
|
||||
_jsonStore.PushAll();
|
||||
Debug.Log("Exported DB to JSON!");
|
||||
}
|
||||
|
||||
if (GUILayout.Button("MsgPack"))
|
||||
{
|
||||
_msgPackStore.PushAll();
|
||||
Debug.Log("Exported DB to MessagePack!");
|
||||
}
|
||||
}
|
||||
|
||||
if (_queryStatus != null && _queryStatus.RetrievedEntries < _queryStatus.TotalEntries)
|
||||
{
|
||||
var progressRect = GetControlRect(false, 20);
|
||||
EditorGUI.ProgressBar(progressRect, (float)_queryStatus.RetrievedEntries/_queryStatus.TotalEntries, "Sync Progress");
|
||||
}
|
||||
GUILayout.Space(5);
|
||||
|
||||
_view = BeginScrollView(
|
||||
_view,
|
||||
false,
|
||||
false,
|
||||
GUIStyle.none,
|
||||
GUI.skin.verticalScrollbar,
|
||||
GUI.skin.scrollView,
|
||||
GUILayout.Width(EditorGUIUtility.currentViewWidth),
|
||||
GUILayout.ExpandHeight(true));
|
||||
|
||||
foreach (var globalType in _globalTypes)
|
||||
{
|
||||
var globalEntry = cultCache.GetGlobal(globalType);
|
||||
var style = ListItemStyle;
|
||||
var selected = SelectedItem == globalEntry.ID;
|
||||
using (new HorizontalScope(selected?SelectedStyle:style))
|
||||
{
|
||||
using (var h = new HorizontalScope())
|
||||
{
|
||||
if (h.rect.Contains(currentEvent.mousePosition))
|
||||
{
|
||||
if (currentEventType == EventType.MouseUp)
|
||||
Select(globalEntry);
|
||||
}
|
||||
|
||||
GUILayout.Label(globalType.Name.SplitCamelCase(), selected ? EditorStyles.whiteLabel : GUI.skin.label);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void DisplayGroup(Type entryType, IEnumerable<DatabaseEntry> entries, IEnumerable<DatabaseEntryGroup> nestedGroups, int indent = 2, Action<DatabaseEntry> activatePreviousGroups = null, string previousGroupNames = "")
|
||||
{
|
||||
var grouper = nestedGroups.FirstOrDefault();
|
||||
if (grouper != null)
|
||||
{
|
||||
var groups = entries.GroupBy(o => grouper.SelectGroup(o));
|
||||
foreach (var group in groups)
|
||||
{
|
||||
//var groupHash = grouper.HashGroup(group.Key);
|
||||
var groupName = grouper.GetGroupName(group.Key);
|
||||
var groupHash = groupName.GetHashCode();
|
||||
using (new HorizontalScope(ListItemStyle))
|
||||
{
|
||||
GUILayout.Space(indent*10);
|
||||
if (Foldout(_groupFoldouts.Contains(groupHash), FormatTypeName(groupName), true))
|
||||
_groupFoldouts.Add(groupHash);
|
||||
else _groupFoldouts.Remove(groupHash);
|
||||
}
|
||||
|
||||
if (_groupFoldouts.Contains(groupHash))
|
||||
{
|
||||
Action<DatabaseEntry> activate = entry =>
|
||||
{
|
||||
activatePreviousGroups?.Invoke(entry);
|
||||
grouper.Activate(entry, group.Key);
|
||||
};
|
||||
|
||||
DisplayGroup(entryType, group, nestedGroups.Skip(1), indent + 1, activate, $"{groupName} {previousGroupNames}");
|
||||
|
||||
using (var h = new HorizontalScope(ListItemStyle))
|
||||
{
|
||||
if (GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
|
||||
CreateItem(entryType, activate);
|
||||
GUILayout.Space((indent+1)*10);
|
||||
GUILayout.Label($"Create {groupName} {previousGroupNames}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
int index = 0;
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
index++;
|
||||
var style = ListItemStyle;
|
||||
var selected = SelectedItem == entry.ID;
|
||||
using (var h = new HorizontalScope(selected ? SelectedStyle : style))
|
||||
{
|
||||
if (h.rect.Contains(currentEvent.mousePosition))
|
||||
{
|
||||
if (currentEventType == EventType.MouseDrag)
|
||||
{
|
||||
DragAndDrop.PrepareStartDrag();
|
||||
DragAndDrop.SetGenericData("Item", entry.ID);
|
||||
DragAndDrop.StartDrag("Database Item");
|
||||
}
|
||||
else if (currentEventType == EventType.MouseUp)
|
||||
Select(entry);
|
||||
}
|
||||
|
||||
GUILayout.Space(indent*10);
|
||||
GUILayout.Label((entry as INamedEntry)?.EntryName ?? index.ToString(),
|
||||
selected ? EditorStyles.whiteLabel : GUI.skin.label);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var table in _tables.Keys.ToArray())
|
||||
{
|
||||
var (tableFoldout, _) = _tables[table];
|
||||
using (new HorizontalScope(ListItemStyle))
|
||||
{
|
||||
_tables[table] = (Foldout(tableFoldout = _tables[table].foldout, table, true), _tables[table].types);
|
||||
}
|
||||
|
||||
if (tableFoldout)
|
||||
{
|
||||
for (var i = 0; i < _tables[table].types.Length; i++)
|
||||
{
|
||||
var (entryType, typeFoldout) = _tables[table].types[i];
|
||||
using (new HorizontalScope(ListItemStyle))
|
||||
{
|
||||
GUILayout.Space(10);
|
||||
_tables[table].types[i] = (entryType, typeFoldout = Foldout(typeFoldout,
|
||||
((NameAttribute) entryType.GetCustomAttribute(typeof(NameAttribute)))?.Name ?? FormatTypeName(entryType.Name),
|
||||
true));
|
||||
}
|
||||
|
||||
if (typeFoldout)
|
||||
{
|
||||
var entries = cultCache.GetAll(entryType)
|
||||
.OrderBy(entry => entry is INamedEntry namedEntry ? namedEntry.EntryName : entry.ID.ToString());
|
||||
var groupers = Groupers.Where(g => g.CanGroup(entryType));
|
||||
DisplayGroup(entryType, entries, groupers);
|
||||
|
||||
using (var h = new HorizontalScope(ListItemStyle))
|
||||
{
|
||||
if (GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
|
||||
CreateItem(entryType);
|
||||
GUILayout.Space(20);
|
||||
GUILayout.Label($"Create {FormatTypeName(entryType.Name)}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
EndScrollView();
|
||||
}
|
||||
|
||||
public static string FormatTypeName(string typeName)
|
||||
{
|
||||
return (typeName.EndsWith("Data")
|
||||
? typeName.Substring(0, typeName.Length - 4)
|
||||
: typeName).SplitCamelCase();
|
||||
}
|
||||
|
||||
void Select(DatabaseEntry item)
|
||||
{
|
||||
SelectedItem = item.ID;
|
||||
Repaint();
|
||||
_inspector.entry = cultCache.Get(SelectedItem);
|
||||
_inspector.Repaint();
|
||||
}
|
||||
|
||||
private DatabaseEntry CreateItem(Type type, Action<DatabaseEntry> onCreate = null)
|
||||
{
|
||||
var newEntry = (DatabaseEntry) Activator.CreateInstance(type);
|
||||
if(newEntry is INamedEntry entry)
|
||||
entry.EntryName = $"New {FormatTypeName(type.Name)}";
|
||||
onCreate?.Invoke(newEntry);
|
||||
cultCache.Add(newEntry);
|
||||
Select(newEntry);
|
||||
return newEntry;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
fileFormatVersion: 2
|
||||
guid: f5150857a83849f195312d13b8f4d19b
|
||||
guid: b514fcab25f3b914b89824efbe244591
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
81
Assets/Scripts/CultCache/Editor/EditorDispatch.cs
Normal file
81
Assets/Scripts/CultCache/Editor/EditorDispatch.cs
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
public static class EditorDispatcher
|
||||
{
|
||||
private static readonly Queue<Action> dispatchQueue = new Queue<Action>();
|
||||
private static double timeSliceLimit = 10.0; // in miliseconds
|
||||
private static Stopwatch timer;
|
||||
|
||||
static EditorDispatcher()
|
||||
{
|
||||
EditorApplication.update += Update;
|
||||
timer = new Stopwatch();
|
||||
}
|
||||
|
||||
private static void Update ()
|
||||
{
|
||||
lock (dispatchQueue)
|
||||
{
|
||||
int dispatchCount = 0;
|
||||
|
||||
timer.Reset();
|
||||
timer.Start();
|
||||
|
||||
while (dispatchQueue.Count > 0 && (timer.Elapsed.TotalMilliseconds <= timeSliceLimit))
|
||||
{
|
||||
dispatchQueue.Dequeue().Invoke();
|
||||
|
||||
dispatchCount++;
|
||||
}
|
||||
|
||||
timer.Stop();
|
||||
|
||||
// if (dispatchCount > 0)
|
||||
// UnityEngine.Debug.Log(string.Format("[EditorDispatcher] Dispatched {0} calls in {1}ms", dispatchCount, timer.Elapsed.TotalMilliseconds));
|
||||
|
||||
// todo some logic for disconnecting update when the queue is empty
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Send an Action Delegate to be run on the main thread. See EditorDispatchActions for some common usecases.
|
||||
/// </summary>
|
||||
/// <param name="task">An action delegate to run on the main thread</param>
|
||||
/// <returns>An AsyncDispatch that can be used to track if the dispatch has completed.</returns>
|
||||
public static AsyncDispatch Dispatch(Action task)
|
||||
{
|
||||
lock (dispatchQueue)
|
||||
{
|
||||
AsyncDispatch dispatch = new AsyncDispatch();
|
||||
|
||||
// enqueue a new task that runs the supplied task and completes the dispatcher
|
||||
dispatchQueue.Enqueue(() => { task(); dispatch.FinishedDispatch(); });
|
||||
|
||||
return dispatch;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents the progress of the dispatched action. Can be yielded to in a coroutine.
|
||||
/// If not using coroutines, look at the IsDone property to find out when its okay to proceed.
|
||||
/// </summary>
|
||||
public class AsyncDispatch : CustomYieldInstruction
|
||||
{
|
||||
public bool IsDone { get; private set; }
|
||||
public override bool keepWaiting { get { return !IsDone; } }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Flags this dispatch as completed.
|
||||
/// </summary>
|
||||
internal void FinishedDispatch()
|
||||
{
|
||||
IsDone = true;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 9e78937590444255a8c972a3d4f69130
|
||||
guid: b7269ba738c469a4ea5b50811ef07f11
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
8
Assets/Scripts/CultCache/Editor/Inspectors.meta
Normal file
8
Assets/Scripts/CultCache/Editor/Inspectors.meta
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
fileFormatVersion: 2
|
||||
guid: b62c0242f5704a96829889e1d4c44900
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
234
Assets/Scripts/CultCache/Editor/Inspectors/AetheriaInspectors.cs
Normal file
234
Assets/Scripts/CultCache/Editor/Inspectors/AetheriaInspectors.cs
Normal file
|
|
@ -0,0 +1,234 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Unity.Mathematics;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using static UnityEditor.EditorGUILayout;
|
||||
using static Unity.Mathematics.math;
|
||||
|
||||
public class StatReferenceInspector : BaseInspector<StatReference>
|
||||
{
|
||||
public override StatReference Inspect(string label, StatReference value, object parent, DatabaseInspector inspectorWindow)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
|
||||
using (new VerticalScope())
|
||||
{
|
||||
var targetObjects = typeof(BehaviorData).GetAllChildClasses()
|
||||
.Concat(typeof(EquippableItemData).GetAllChildClasses()).ToArray();
|
||||
var objectNames = targetObjects.Select(b => b.Name).ToArray();
|
||||
var selectedIndex = Array.IndexOf(objectNames, value.Target);
|
||||
if (selectedIndex == -1)
|
||||
{
|
||||
selectedIndex = 0;
|
||||
GUI.changed = true;
|
||||
}
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label("Target", GUILayout.Width(width));
|
||||
var newSelection = Popup(selectedIndex, objectNames);
|
||||
if (newSelection != selectedIndex)
|
||||
GUI.changed = true;
|
||||
value.Target = objectNames[newSelection];
|
||||
}
|
||||
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label("Stat", GUILayout.Width(width));
|
||||
var stats = targetObjects[selectedIndex].GetFields()
|
||||
.Where(f => f.FieldType == typeof(PerformanceStat)).ToArray();
|
||||
if(stats.Length==0)
|
||||
GUILayout.Label("No Stats!");
|
||||
else
|
||||
{
|
||||
var statNames = stats.Select(s => s.Name).ToArray();
|
||||
var selectedStatIndex = Array.IndexOf(statNames, value.Stat);
|
||||
if (selectedStatIndex == -1)
|
||||
{
|
||||
selectedStatIndex = 0;
|
||||
GUI.changed = true;
|
||||
}
|
||||
var newSelection = Popup(selectedStatIndex, statNames);
|
||||
if (newSelection != selectedStatIndex)
|
||||
GUI.changed = true;
|
||||
value.Stat = statNames[newSelection];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
public class PerformanceStatInspector : BaseInspector<PerformanceStat>
|
||||
{
|
||||
public override PerformanceStat Inspect(string label, PerformanceStat value, object parent, DatabaseInspector inspectorWindow)
|
||||
{
|
||||
if(value == null)
|
||||
value = new PerformanceStat();
|
||||
using (new VerticalScope())
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
GUILayout.Label("Min", EditorStyles.miniLabel, GUILayout.Width(labelWidth));
|
||||
value.Min = DelayedFloatField(value.Min);
|
||||
GUILayout.Label("Max", EditorStyles.miniLabel, GUILayout.Width(labelWidth + 5));
|
||||
value.Max = DelayedFloatField(value.Max);
|
||||
}
|
||||
|
||||
// Only display heat, durability and quality effects if the stat actually varies
|
||||
if (Math.Abs(value.Min - value.Max) > .0001f)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label("", GUILayout.Width(width));
|
||||
GUILayout.Label("H", EditorStyles.miniLabel, GUILayout.Width(labelWidth));
|
||||
value.HeatExponentMultiplier = DelayedFloatField(value.HeatExponentMultiplier);
|
||||
|
||||
GUILayout.Label("D", EditorStyles.miniLabel, GUILayout.Width(labelWidth));
|
||||
value.DurabilityExponentMultiplier = DelayedFloatField(value.DurabilityExponentMultiplier);
|
||||
|
||||
GUILayout.Label("Q", EditorStyles.miniLabel, GUILayout.Width(labelWidth));
|
||||
value.QualityExponent = DelayedFloatField(value.QualityExponent);
|
||||
}
|
||||
}
|
||||
|
||||
Space();
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
public class ShapeInspector : BaseInspector<Shape>
|
||||
{
|
||||
private Material _schematicMat = new Material(Shader.Find("Legacy Shaders/Particles/Additive"));
|
||||
|
||||
public override Shape Inspect(string label, Shape value, object parent, DatabaseInspector inspectorWindow)
|
||||
{
|
||||
if(value == null)
|
||||
{
|
||||
value = new Shape(1, 1);
|
||||
value[int2(0)] = true;
|
||||
}
|
||||
using (new VerticalScope())
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
GUILayout.Label("Size", GUILayout.ExpandWidth(false));
|
||||
GUILayout.Label("X", GUILayout.Width(labelWidth));
|
||||
value.Width = DelayedIntField(value.Width);
|
||||
GUILayout.Label("Y", GUILayout.Width(labelWidth));
|
||||
value.Height = DelayedIntField(value.Height);
|
||||
}
|
||||
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label("", GUILayout.Width(width));
|
||||
using (new VerticalScope())
|
||||
{
|
||||
for (var y = value.Height - 1; y >= 0; y--)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
for (var x = 0; x < value.Width; x++)
|
||||
{
|
||||
var oldColor = GUI.backgroundColor;
|
||||
value[int2(x, y)] = Toggle(value[int2(x, y)], GUILayout.Width(toggleWidth));
|
||||
GUI.backgroundColor = oldColor;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
GUILayout.FlexibleSpace();
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
public class ShapeSchematicInspector : BaseInspector<Shape, InspectableSchematicShapeAttribute>
|
||||
{
|
||||
private Material _schematicMat = new Material(Shader.Find("Legacy Shaders/Particles/Additive"));
|
||||
|
||||
public override Shape Inspect(string label, Shape value, object parent, DatabaseInspector inspectorWindow, InspectableSchematicShapeAttribute attribute)
|
||||
{
|
||||
var item = parent as EquippableItemData;
|
||||
if(value == null)
|
||||
{
|
||||
value = new Shape(1, 1);
|
||||
value[int2(0)] = true;
|
||||
}
|
||||
using (new VerticalScope())
|
||||
{
|
||||
Texture2D schematic = null;
|
||||
if(item != null && !string.IsNullOrEmpty(item.Schematic))
|
||||
schematic = AssetDatabase.LoadAssetAtPath<Texture2D>(item.Schematic);
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
GUILayout.Label("Size", GUILayout.ExpandWidth(false));
|
||||
if(schematic == null)
|
||||
{
|
||||
GUILayout.Label("X", GUILayout.Width(labelWidth));
|
||||
value.Width = DelayedIntField(value.Width);
|
||||
GUILayout.Label("Y", GUILayout.Width(labelWidth));
|
||||
value.Height = DelayedIntField(value.Height);
|
||||
}
|
||||
else
|
||||
{
|
||||
GUILayout.Label("X", GUILayout.Width(labelWidth));
|
||||
value.Width = DelayedIntField(value.Width);
|
||||
value.Height = Mathf.RoundToInt(value.Width * ((float)schematic.height / schematic.width));
|
||||
GUILayout.Label("Y", GUILayout.Width(labelWidth));
|
||||
LabelField($"{value.Height}");
|
||||
}
|
||||
}
|
||||
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label("", GUILayout.Width(width));
|
||||
using (var a = new VerticalScope())
|
||||
{
|
||||
if(schematic != null)
|
||||
{
|
||||
EditorGUI.DrawPreviewTexture(a.rect, schematic, _schematicMat);
|
||||
}
|
||||
for (var y = value.Height - 1; y >= 0; y--)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
for (var x = 0; x < value.Width; x++)
|
||||
{
|
||||
var oldColor = GUI.backgroundColor;
|
||||
if(item is HullData hull)
|
||||
{
|
||||
var hardpoint = hull.Hardpoints
|
||||
.FirstOrDefault(hp =>
|
||||
hp.Shape.Coordinates
|
||||
.Select(v => v + hp.Position)
|
||||
.Any(v => v.x == x && v.y == y));
|
||||
if (hardpoint != null)
|
||||
GUI.backgroundColor = hardpoint.TintColor.ToColor();
|
||||
}
|
||||
value[int2(x, y)] = Toggle(value[int2(x, y)], GUILayout.Width(toggleWidth));
|
||||
GUI.backgroundColor = oldColor;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
GUILayout.FlexibleSpace();
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 57d0bc090768458b9428efd7a8a33741
|
||||
timeCreated: 1617069994
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
using System.Linq;
|
||||
using Unity.Mathematics;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using static UnityEditor.EditorGUILayout;
|
||||
using static Unity.Mathematics.math;
|
||||
|
||||
public class AnimationCurveFloat4Inspector : BaseInspector<float4[]>
|
||||
{
|
||||
public override float4[] Inspect(string label, float4[] value, object parent, DatabaseInspector inspectorWindow)
|
||||
{
|
||||
var val = value != null && value.Length > 0
|
||||
? value.ToCurve()
|
||||
: new AnimationCurve();
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
val = CurveField(val, Color.yellow, new Rect(0, 0, 1, 1));
|
||||
}
|
||||
|
||||
return val.keys.Select(k => float4(k.time, k.value, k.inTangent, k.outTangent)).ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
public class BezierCurveInspector : BaseInspector<BezierCurve>
|
||||
{
|
||||
public override BezierCurve Inspect(string label, BezierCurve value, object parent, DatabaseInspector inspectorWindow)
|
||||
{
|
||||
var val = value != null && value.Keys != null && value.Keys.Length > 0
|
||||
? value.ToCurve()
|
||||
: new AnimationCurve();
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
val = CurveField(val, Color.yellow, new Rect(0, 0, 1, 1));
|
||||
}
|
||||
|
||||
value.Keys = val.keys.Select(k => float4(k.time, k.value, k.inTangent, k.outTangent)).ToArray();
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
public class AnimationCurveInspect : BaseInspector<AnimationCurve>
|
||||
{
|
||||
public override AnimationCurve Inspect(string label, AnimationCurve value, object parent, DatabaseInspector inspectorWindow)
|
||||
{
|
||||
using (var h = new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
if (value == null)
|
||||
value = new AnimationCurve();
|
||||
value = CurveField(value, Color.yellow, new Rect(0, 0, 1, 1));
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: c89e0e7eb9f243cbbce28df59f6fb1c9
|
||||
timeCreated: 1617066399
|
||||
|
|
@ -0,0 +1,169 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using static UnityEditor.EditorGUILayout;
|
||||
|
||||
public class DatabaseLinkInspector : BaseInspector<Guid, InspectableDatabaseLinkAttribute>
|
||||
{
|
||||
public override Guid Inspect(string label, Guid value, object parent, DatabaseInspector inspectorWindow, InspectableDatabaseLinkAttribute link)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
var valueEntry = DatabaseInspector.CultCache.Get(value);
|
||||
using (var h = new HorizontalScope(GUI.skin.box))
|
||||
{
|
||||
GUILayout.Label((valueEntry as INamedEntry)?.EntryName ?? valueEntry?.ID.ToString() ?? $"Drag and drop: {DatabaseListView.FormatTypeName(link.EntryType.Name)}");
|
||||
|
||||
if (h.rect.Contains(Event.current.mousePosition) && (Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragPerform))
|
||||
{
|
||||
var guid = (Guid) DragAndDrop.GetGenericData("Item");
|
||||
var dragEntry = DatabaseInspector.CultCache.Get(guid);
|
||||
var dragValid = dragEntry != null && link.EntryType.IsInstanceOfType(dragEntry) && dragEntry != valueEntry;
|
||||
if(Event.current.type == EventType.DragUpdated)
|
||||
DragAndDrop.visualMode = dragValid ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected;
|
||||
else if(Event.current.type == EventType.DragPerform)
|
||||
{
|
||||
if (dragValid)
|
||||
{
|
||||
DragAndDrop.AcceptDrag();
|
||||
GUI.changed = true;
|
||||
return guid;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (GUILayout.Button("-", GUILayout.Width((EditorGUIUtility.singleLineHeight - 3)*2), GUILayout.Height(EditorGUIUtility.singleLineHeight-3)))
|
||||
{
|
||||
return Guid.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
public class DatabaseLinkObjectInspector<T> : BaseInspector<DatabaseLink<T>> where T : DatabaseEntry
|
||||
{
|
||||
public override DatabaseLink<T> Inspect(string label, DatabaseLink<T> value, object parent, DatabaseInspector inspectorWindow)
|
||||
{
|
||||
if (value == null)
|
||||
value = new DatabaseLink<T>();
|
||||
|
||||
if(!string.IsNullOrEmpty(label))
|
||||
{
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
}
|
||||
|
||||
var valueEntry = value.Value;
|
||||
using (var h = string.IsNullOrEmpty(label) ? new HorizontalScope() : new HorizontalScope(GUI.skin.box))
|
||||
{
|
||||
GUILayout.Label((valueEntry as INamedEntry)?.EntryName ?? valueEntry?.ID.ToString() ?? $"Drag and drop: {DatabaseListView.FormatTypeName(typeof(T).Name)}");
|
||||
|
||||
if (h.rect.Contains(Event.current.mousePosition) && (Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragPerform))
|
||||
{
|
||||
var guid = (Guid) DragAndDrop.GetGenericData("Item");
|
||||
var dragEntry = DatabaseInspector.CultCache.Get(guid);
|
||||
var dragValid = dragEntry is T && dragEntry != valueEntry;
|
||||
if(Event.current.type == EventType.DragUpdated)
|
||||
DragAndDrop.visualMode = dragValid ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected;
|
||||
else if(Event.current.type == EventType.DragPerform)
|
||||
{
|
||||
if (dragValid)
|
||||
{
|
||||
DragAndDrop.AcceptDrag();
|
||||
value.LinkID = guid;
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(value.LinkID != Guid.Empty)
|
||||
{
|
||||
if (GUILayout.Button("-",
|
||||
GUILayout.Width((EditorGUIUtility.singleLineHeight - 3) * 2),
|
||||
GUILayout.Height(EditorGUIUtility.singleLineHeight - 3)))
|
||||
{
|
||||
value.LinkID = Guid.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(!string.IsNullOrEmpty(label))
|
||||
{
|
||||
GUILayout.EndHorizontal();
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
public class DatabaseLinkListInspector : BaseInspector<List<Guid>, InspectableDatabaseLinkAttribute>
|
||||
{
|
||||
private bool _listItemStyle;
|
||||
public GUIStyle ListItemStyle =>
|
||||
(_listItemStyle = !_listItemStyle) ? DatabaseListView.ListStyleEven : DatabaseListView.ListStyleOdd;
|
||||
|
||||
public override List<Guid> Inspect(string label,
|
||||
List<Guid> value,
|
||||
object parent,
|
||||
DatabaseInspector inspectorWindow,
|
||||
InspectableDatabaseLinkAttribute link)
|
||||
{
|
||||
using (var v = new VerticalScope(GUI.skin.box))
|
||||
{
|
||||
GUILayout.Label(label, EditorStyles.boldLabel);
|
||||
if (value.Count == 0)
|
||||
{
|
||||
using (new HorizontalScope(ListItemStyle))
|
||||
{
|
||||
GUILayout.Label($"Drag from list to add {link.EntryType.Name}");
|
||||
}
|
||||
}
|
||||
foreach (var guid in value.ToArray())
|
||||
{
|
||||
using (new HorizontalScope(ListItemStyle))
|
||||
{
|
||||
var entry = DatabaseInspector.CultCache.Get(guid);
|
||||
if (entry == null)
|
||||
{
|
||||
value.Remove(guid);
|
||||
GUI.changed = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
GUILayout.Label((entry as INamedEntry)?.EntryName ?? entry.ID.ToString());
|
||||
|
||||
// var rect = GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
|
||||
// GUI.DrawTexture(rect, Icons.Instance.minus, ScaleMode.StretchToFill, true, 1, LabelColor, 0, 0);
|
||||
if (GUILayout.Button("-", GUILayout.Width((EditorGUIUtility.singleLineHeight - 3)*2), GUILayout.Height(EditorGUIUtility.singleLineHeight-3)))
|
||||
{
|
||||
value.Remove(guid);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (v.rect.Contains(Event.current.mousePosition))
|
||||
{
|
||||
var guid = DragAndDrop.GetGenericData("Item");
|
||||
var dragObj = DragAndDrop.GetGenericData("Item") is Guid ? DatabaseInspector.CultCache.Get((Guid) guid) : null;
|
||||
var dragValid = dragObj != null && link.EntryType.IsInstanceOfType(dragObj) && !value.Contains(dragObj.ID);
|
||||
if(Event.current.type == EventType.DragUpdated)
|
||||
DragAndDrop.visualMode = dragValid ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected;
|
||||
else if(Event.current.type == EventType.DragPerform)
|
||||
{
|
||||
if (dragValid)
|
||||
{
|
||||
DragAndDrop.AcceptDrag();
|
||||
value.Add((Guid) guid);
|
||||
GUI.changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 5e08712ea4854536b130f82ad61db7a8
|
||||
timeCreated: 1617069551
|
||||
|
|
@ -0,0 +1,211 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using static UnityEditor.EditorGUILayout;
|
||||
|
||||
public class FloatDictionaryInspector : BaseInspector<Dictionary<Guid, float>, InspectableDatabaseLinkAttribute>
|
||||
{
|
||||
public override Dictionary<Guid, float> Inspect(string label,
|
||||
Dictionary<Guid, float> value,
|
||||
object parent,
|
||||
DatabaseInspector inspectorWindow,
|
||||
InspectableDatabaseLinkAttribute attribute)
|
||||
{
|
||||
Space();
|
||||
LabelField(label, EditorStyles.boldLabel);
|
||||
|
||||
using (var v = new VerticalScope(GUI.skin.box))
|
||||
{
|
||||
if (value.Count == 0)
|
||||
{
|
||||
using (new HorizontalScope(DatabaseInspector.ListItemStyle))
|
||||
{
|
||||
GUILayout.Label("Drag from list to add item");
|
||||
}
|
||||
}
|
||||
foreach (var ingredient in value.ToArray())
|
||||
{
|
||||
using (new HorizontalScope(DatabaseInspector.ListItemStyle))
|
||||
{
|
||||
var entry = DatabaseInspector.CultCache.Get(ingredient.Key);
|
||||
if (entry == null)
|
||||
{
|
||||
value.Remove(ingredient.Key);
|
||||
GUI.changed = true;
|
||||
return value;
|
||||
}
|
||||
|
||||
if(entry is INamedEntry named)
|
||||
GUILayout.Label(named.EntryName);
|
||||
else GUILayout.Label(entry.ID.ToString());
|
||||
value[ingredient.Key] = DelayedFloatField(value[ingredient.Key], GUILayout.Width(50));
|
||||
|
||||
// var rect = GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
|
||||
// GUI.DrawTexture(rect, Icons.Instance.minus, ScaleMode.StretchToFill, true, 1, LabelColor, 0, 0);
|
||||
if (GUILayout.Button("-", GUILayout.Width((EditorGUIUtility.singleLineHeight - 3)*2), GUILayout.Height(EditorGUIUtility.singleLineHeight-3)))
|
||||
value.Remove(ingredient.Key);
|
||||
}
|
||||
}
|
||||
|
||||
if (v.rect.Contains(Event.current.mousePosition))
|
||||
{
|
||||
var dragData = DragAndDrop.GetGenericData("Item");
|
||||
var isId = dragData is Guid;
|
||||
var dragEntry = isId ? DatabaseInspector.CultCache.Get((Guid)dragData) : null;
|
||||
var correctType = attribute.EntryType.IsInstanceOfType(dragEntry);
|
||||
if(Event.current.type == EventType.DragUpdated)
|
||||
DragAndDrop.visualMode = correctType ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected;
|
||||
else if(Event.current.type == EventType.DragPerform)
|
||||
{
|
||||
if (isId && correctType)
|
||||
{
|
||||
DragAndDrop.AcceptDrag();
|
||||
value[(Guid)dragData] = 1;
|
||||
GUI.changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
public class RangedFloatDictionaryInspector : BaseInspector<Dictionary<Guid, float>, InspectableDatabaseLinkAttribute, RangedFloatAttribute>
|
||||
{
|
||||
public override Dictionary<Guid, float> Inspect(string label,
|
||||
Dictionary<Guid, float> value,
|
||||
object parent,
|
||||
DatabaseInspector inspectorWindow,
|
||||
InspectableDatabaseLinkAttribute link,
|
||||
RangedFloatAttribute range)
|
||||
{
|
||||
Space();
|
||||
LabelField(label, EditorStyles.boldLabel);
|
||||
|
||||
using (var v = new VerticalScope(GUI.skin.box))
|
||||
{
|
||||
if (value.Count == 0)
|
||||
{
|
||||
using (new HorizontalScope(DatabaseInspector.ListItemStyle))
|
||||
{
|
||||
GUILayout.Label("Drag from list to add item");
|
||||
}
|
||||
}
|
||||
foreach (var ingredient in value.ToArray())
|
||||
{
|
||||
using (new HorizontalScope(DatabaseInspector.ListItemStyle))
|
||||
{
|
||||
var entry = DatabaseInspector.CultCache.Get(ingredient.Key);
|
||||
if (entry == null)
|
||||
{
|
||||
value.Remove(ingredient.Key);
|
||||
GUI.changed = true;
|
||||
return value;
|
||||
}
|
||||
|
||||
if(entry is INamedEntry named)
|
||||
GUILayout.Label(named.EntryName);
|
||||
else GUILayout.Label(entry.ID.ToString());
|
||||
value[ingredient.Key] = Slider(value[ingredient.Key], range.Min, range.Max);
|
||||
|
||||
// var rect = GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
|
||||
// GUI.DrawTexture(rect, Icons.Instance.minus, ScaleMode.StretchToFill, true, 1, LabelColor, 0, 0);
|
||||
if (GUILayout.Button("-", GUILayout.Width((EditorGUIUtility.singleLineHeight - 3)*2), GUILayout.Height(EditorGUIUtility.singleLineHeight-3)))
|
||||
value.Remove(ingredient.Key);
|
||||
}
|
||||
}
|
||||
|
||||
if (v.rect.Contains(Event.current.mousePosition))
|
||||
{
|
||||
var dragData = DragAndDrop.GetGenericData("Item");
|
||||
var isId = dragData is Guid;
|
||||
var dragEntry = isId ? DatabaseInspector.CultCache.Get((Guid)dragData) : null;
|
||||
var correctType = link.EntryType.IsInstanceOfType(dragEntry);
|
||||
if(Event.current.type == EventType.DragUpdated)
|
||||
DragAndDrop.visualMode = correctType ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected;
|
||||
else if(Event.current.type == EventType.DragPerform)
|
||||
{
|
||||
if (isId && correctType)
|
||||
{
|
||||
DragAndDrop.AcceptDrag();
|
||||
value[(Guid)dragData] = range.Max;
|
||||
GUI.changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
public class IntDictionaryInspector : BaseInspector<Dictionary<Guid, int>, InspectableDatabaseLinkAttribute>
|
||||
{
|
||||
public override Dictionary<Guid, int> Inspect(string label,
|
||||
Dictionary<Guid, int> value,
|
||||
object parent,
|
||||
DatabaseInspector inspectorWindow,
|
||||
InspectableDatabaseLinkAttribute attribute)
|
||||
{
|
||||
Space();
|
||||
LabelField(label, EditorStyles.boldLabel);
|
||||
|
||||
using (var v = new VerticalScope(GUI.skin.box))
|
||||
{
|
||||
if (value.Count == 0)
|
||||
{
|
||||
using (var h = new HorizontalScope(DatabaseInspector.ListItemStyle))
|
||||
{
|
||||
GUILayout.Label("Drag from list to add item");
|
||||
}
|
||||
}
|
||||
foreach (var ingredient in value.ToArray())
|
||||
{
|
||||
using (var h = new HorizontalScope(DatabaseInspector.ListItemStyle))
|
||||
{
|
||||
var entry = DatabaseInspector.CultCache.Get(ingredient.Key);
|
||||
if (entry == null)
|
||||
{
|
||||
value.Remove(ingredient.Key);
|
||||
GUI.changed = true;
|
||||
return value;
|
||||
}
|
||||
if(entry is INamedEntry named)
|
||||
GUILayout.Label(named.EntryName);
|
||||
else GUILayout.Label(entry.ID.ToString());
|
||||
|
||||
value[ingredient.Key] = DelayedIntField(value[ingredient.Key], GUILayout.Width(50));
|
||||
|
||||
// var rect = GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
|
||||
// GUI.DrawTexture(rect, Icons.Instance.minus, ScaleMode.StretchToFill, true, 1, LabelColor, 0, 0);
|
||||
if (GUILayout.Button("-", GUILayout.Width((EditorGUIUtility.singleLineHeight - 3)*2), GUILayout.Height(EditorGUIUtility.singleLineHeight-3)) || value[ingredient.Key]==0)
|
||||
value.Remove(ingredient.Key);
|
||||
}
|
||||
}
|
||||
|
||||
if (v.rect.Contains(Event.current.mousePosition))
|
||||
{
|
||||
var dragData = DragAndDrop.GetGenericData("Item");
|
||||
var isId = dragData is Guid;
|
||||
var dragEntry = isId ? DatabaseInspector.CultCache.Get((Guid)dragData) : null;
|
||||
var correctType = attribute.EntryType.IsInstanceOfType(dragEntry);
|
||||
if(Event.current.type == EventType.DragUpdated)
|
||||
DragAndDrop.visualMode = correctType ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected;
|
||||
else if(Event.current.type == EventType.DragPerform)
|
||||
{
|
||||
if (isId && correctType)
|
||||
{
|
||||
DragAndDrop.AcceptDrag();
|
||||
value[(Guid)dragData] = 1;
|
||||
GUI.changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: a42620fd406045889578e2ad8d5fd8de
|
||||
timeCreated: 1617067689
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using static Unity.Mathematics.math;
|
||||
using static UnityEditor.EditorGUILayout;
|
||||
|
||||
public class EnumInspector<T> : BaseInspector<List<T>, InspectableEnumValuesAttribute>
|
||||
{
|
||||
public override List<T> Inspect(string label, List<T> list, object parent, DatabaseInspector inspectorWindow, InspectableEnumValuesAttribute attribute)
|
||||
{
|
||||
var names = Enum.GetNames(attribute.EnumType);
|
||||
list ??= new List<T>();
|
||||
|
||||
while(list.Count < names.Length) list.Add(Activator.CreateInstance<T>());
|
||||
while(list.Count > names.Length) list.RemoveAt(list.Count-1);
|
||||
|
||||
for (var i = 0; i < names.Length; i++)
|
||||
inspectorWindow.InspectMember(names[i], list[i], parent, typeof(T));
|
||||
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
public class EnumDictionaryInspector<E, T> : BaseInspector<EnumDictionary<E, T>> where E : Enum
|
||||
{
|
||||
private static HashSet<object> _foldouts = new HashSet<object>();
|
||||
|
||||
public override EnumDictionary<E, T> Inspect(string label, EnumDictionary<E, T> dict, object parent, DatabaseInspector inspectorWindow)
|
||||
{
|
||||
var names = Enum.GetNames(typeof(E));
|
||||
if (dict == null || dict.Values.Length != names.Length)
|
||||
{
|
||||
var newValue = new T[names.Length];
|
||||
if(dict != null && dict.Values.Length > 0)
|
||||
Array.Copy(dict.Values, newValue, min(dict.Values.Length, newValue.Length));
|
||||
dict.Values = newValue;
|
||||
}
|
||||
|
||||
using (new VerticalScope(GUI.skin.box))
|
||||
{
|
||||
if (Foldout(_foldouts.Contains(dict), label, true, EditorStyles.boldLabel))
|
||||
_foldouts.Add(dict);
|
||||
else _foldouts.Remove(dict);
|
||||
if(_foldouts.Contains(dict))
|
||||
{
|
||||
for (var i = 0; i < names.Length; i++)
|
||||
{
|
||||
using (new VerticalScope(DatabaseInspector.ListItemStyle))
|
||||
{
|
||||
dict.Values[i] = (T) inspectorWindow.InspectMember(names[i], dict.Values[i], parent, typeof(T));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dict;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: da1b15e5564747958639c8f959226c74
|
||||
timeCreated: 1617335525
|
||||
54
Assets/Scripts/CultCache/Editor/Inspectors/FloatInspector.cs
Normal file
54
Assets/Scripts/CultCache/Editor/Inspectors/FloatInspector.cs
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using static UnityEditor.EditorGUILayout;
|
||||
|
||||
public class FloatInspector : BaseInspector<float>
|
||||
{
|
||||
public override float Inspect(string label, float value, object parent, DatabaseInspector inspectorWindow)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
return DelayedFloatField(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class RangedFloatInspector : BaseInspector<float, InspectableRangedFloatAttribute>
|
||||
{
|
||||
public override float Inspect(string label,
|
||||
float value,
|
||||
object parent,
|
||||
DatabaseInspector inspectorWindow,
|
||||
InspectableRangedFloatAttribute attribute)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
return Slider(value, attribute.Min, attribute.Max);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class TemperatureFloatInspector : BaseInspector<float, InspectableTemperatureAttribute>
|
||||
{
|
||||
public override float Inspect(string label,
|
||||
float value,
|
||||
object parent,
|
||||
DatabaseInspector inspectorWindow,
|
||||
InspectableTemperatureAttribute attribute)
|
||||
{
|
||||
using (var h = new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
GUILayout.Label("°K", EditorStyles.miniLabel, GUILayout.Width(labelWidth));
|
||||
value = DelayedFloatField(value);
|
||||
GUILayout.Label("°C", EditorStyles.miniLabel, GUILayout.Width(labelWidth));
|
||||
value = DelayedFloatField(value - 273.15f) + 273.15f;
|
||||
GUILayout.Label("°F", EditorStyles.miniLabel, GUILayout.Width(labelWidth));
|
||||
value = (DelayedFloatField((value - 273.15f) * 1.8f + 32) - 32) / 1.8f + 273.15f;
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 47b8e5bc90714055881eb31baf2ab879
|
||||
timeCreated: 1617065074
|
||||
40
Assets/Scripts/CultCache/Editor/Inspectors/IntInspector.cs
Normal file
40
Assets/Scripts/CultCache/Editor/Inspectors/IntInspector.cs
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
using static Unity.Mathematics.math;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using static UnityEditor.EditorGUILayout;
|
||||
|
||||
public class IntInspector : BaseInspector<int>
|
||||
{
|
||||
public override int Inspect(string label, int value, object parent, DatabaseInspector inspectorWindow)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
return DelayedIntField(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class UintInspector : BaseInspector<uint>
|
||||
{
|
||||
public override uint Inspect(string label, uint value, object parent, DatabaseInspector inspectorWindow)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
return (uint) max(DelayedIntField((int)value), 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class RangedIntInspector : BaseInspector<int, InspectableRangedIntAttribute>
|
||||
{
|
||||
public override int Inspect(string label, int value, object parent, DatabaseInspector inspectorWindow, InspectableRangedIntAttribute attribute)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
return IntSlider(value, attribute.Min, attribute.Max);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: ac7d3b8651964ce1a732a002447d6f69
|
||||
timeCreated: 1617065365
|
||||
132
Assets/Scripts/CultCache/Editor/Inspectors/ListInspector.cs
Normal file
132
Assets/Scripts/CultCache/Editor/Inspectors/ListInspector.cs
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using static UnityEditor.EditorGUILayout;
|
||||
|
||||
public class ListInspector<T> : BaseInspector<List<T>>
|
||||
{
|
||||
private static HashSet<object> _foldouts = new HashSet<object>();
|
||||
|
||||
public override List<T> Inspect(string label, List<T> list, object parent, DatabaseInspector inspectorWindow)
|
||||
{
|
||||
var listType = typeof(T);
|
||||
var inspectable = listType.GetCustomAttribute<InspectableAttribute>();
|
||||
// if (listType.GetCustomAttribute<InspectableAttribute>() != null)
|
||||
// {
|
||||
//Space();
|
||||
using (new VerticalScope(GUI.skin.box))
|
||||
{
|
||||
if (list == null)
|
||||
{
|
||||
list = new List<T>();
|
||||
}
|
||||
else
|
||||
{
|
||||
var sorted = true;
|
||||
var order = int.MinValue;
|
||||
foreach(var element in list)
|
||||
{
|
||||
if (element == null)
|
||||
{
|
||||
list.Remove(element);
|
||||
return list;
|
||||
}
|
||||
var elementType = element.GetType();
|
||||
var elementOrder = elementType.GetCustomAttribute<OrderAttribute>()?.Order ?? 0;
|
||||
if (elementOrder < order)
|
||||
sorted = false;
|
||||
order = elementOrder;
|
||||
}
|
||||
|
||||
if (!sorted)
|
||||
{
|
||||
list.Sort((x, y) => (x.GetType().GetCustomAttribute<OrderAttribute>()?.Order ?? 0).CompareTo(y.GetType().GetCustomAttribute<OrderAttribute>()?.Order ?? 0));
|
||||
}
|
||||
}
|
||||
if (Foldout(_foldouts.Contains(list), label, true, EditorStyles.boldLabel))
|
||||
_foldouts.Add(list);
|
||||
else _foldouts.Remove(list);
|
||||
if (_foldouts.Contains(list))
|
||||
{
|
||||
foreach (var o in list)
|
||||
{
|
||||
if (o == null)
|
||||
{
|
||||
list.Remove(o);
|
||||
break;
|
||||
}
|
||||
bool _tinted = false;
|
||||
var originalColor = GUI.backgroundColor;
|
||||
if (o is ITintInspector tint)
|
||||
{
|
||||
_tinted = true;
|
||||
GUI.backgroundColor = tint.TintColor.ToColor();
|
||||
}
|
||||
|
||||
using (new VerticalScope(DatabaseInspector.ListItemStyle))
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
if (inspectable != null)
|
||||
{
|
||||
if (Foldout(_foldouts.Contains(o), o.ToString(), true, EditorStyles.boldLabel))
|
||||
_foldouts.Add(o);
|
||||
else
|
||||
_foldouts.Remove(o);
|
||||
}
|
||||
else inspectorWindow.InspectMember("", o, parent, listType, true);
|
||||
|
||||
if (GUILayout.Button("-", GUILayout.Width((EditorGUIUtility.singleLineHeight - 3)*2), GUILayout.Height(EditorGUIUtility.singleLineHeight-3)))
|
||||
{
|
||||
list.Remove(o);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(inspectable != null && _foldouts.Contains(o))
|
||||
inspectorWindow.InspectMember("", o, parent, o.GetType(), true);
|
||||
}
|
||||
|
||||
if(_tinted)
|
||||
GUI.backgroundColor = originalColor;
|
||||
}
|
||||
using (new HorizontalScope(DatabaseInspector.ListItemStyle))
|
||||
{
|
||||
GUILayout.Label($"Add new {listType.GetFullName()}", GUILayout.ExpandWidth(true));
|
||||
// var rect = GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
|
||||
// GUI.DrawTexture(rect, Icons.Instance.plus, ScaleMode.StretchToFill, true, 1, LabelColor, 0, 0);
|
||||
if (GUILayout.Button("+", GUILayout.Width((EditorGUIUtility.singleLineHeight - 3)*2), GUILayout.Height(EditorGUIUtility.singleLineHeight-3)))
|
||||
{
|
||||
if (listType.IsAbstract || listType.IsInterface)
|
||||
{
|
||||
var menu = new GenericMenu();
|
||||
foreach (var childType in listType.GetAllChildClasses().Where(t=>!t.IsAbstract && !t.IsInterface))
|
||||
{
|
||||
menu.AddItem(new GUIContent(childType.Name), false, () =>
|
||||
{
|
||||
var o = (T) Activator.CreateInstance(childType);
|
||||
_foldouts.Add(o);
|
||||
list.Add(o);
|
||||
});
|
||||
}
|
||||
menu.ShowAsContext();
|
||||
}
|
||||
else
|
||||
{
|
||||
var o = Activator.CreateInstance<T>();
|
||||
_foldouts.Add(o);
|
||||
list.Add(o);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// }
|
||||
// else Debug.Log($"Field \"{label}\" is a list of non-Inspectable type {listType.Name}. No inspector was generated.");
|
||||
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 551335721057411d942b3317ae028546
|
||||
timeCreated: 1617145746
|
||||
|
|
@ -0,0 +1,144 @@
|
|||
using Unity.Mathematics;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using static UnityEditor.EditorGUILayout;
|
||||
|
||||
public class Float2Inspector : BaseInspector<float2>
|
||||
{
|
||||
public override float2 Inspect(string label, float2 value, object parent, DatabaseInspector inspectorWindow)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
GUILayout.Label("X", GUILayout.Width(labelWidth));
|
||||
value.x = DelayedFloatField(value.x);
|
||||
GUILayout.Label("Y", GUILayout.Width(labelWidth));
|
||||
value.y = DelayedFloatField(value.y);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class Float3Inspector : BaseInspector<float3>
|
||||
{
|
||||
public override float3 Inspect(string label, float3 value, object parent, DatabaseInspector inspectorWindow)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
GUILayout.Label("X", GUILayout.Width(labelWidth));
|
||||
value.x = DelayedFloatField(value.x);
|
||||
GUILayout.Label("Y", GUILayout.Width(labelWidth));
|
||||
value.y = DelayedFloatField(value.y);
|
||||
GUILayout.Label("Z", GUILayout.Width(labelWidth));
|
||||
value.z = DelayedFloatField(value.z);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class Float3ColorInspector : BaseInspector<float3, InspectableColorAttribute>
|
||||
{
|
||||
public override float3 Inspect(string label, float3 value, object parent, DatabaseInspector inspectorWindow, InspectableColorAttribute attribute)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
return ColorField(value.ToColor()).ToFloat3();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class Float4Inspector : BaseInspector<float4>
|
||||
{
|
||||
public override float4 Inspect(string label, float4 value, object parent, DatabaseInspector inspectorWindow)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
GUILayout.Label("X", GUILayout.Width(labelWidth));
|
||||
value.x = DelayedFloatField(value.x);
|
||||
GUILayout.Label("Y", GUILayout.Width(labelWidth));
|
||||
value.y = DelayedFloatField(value.y);
|
||||
GUILayout.Label("Z", GUILayout.Width(labelWidth));
|
||||
value.z = DelayedFloatField(value.z);
|
||||
GUILayout.Label("W", GUILayout.Width(labelWidth));
|
||||
value.w = DelayedFloatField(value.w);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class Float4ColorInspector : BaseInspector<float4, InspectableColorAttribute>
|
||||
{
|
||||
public override float4 Inspect(string label, float4 value, object parent, DatabaseInspector inspectorWindow, InspectableColorAttribute attribute)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
return ColorField(value.ToColor()).ToFloat4();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class Int2Inspector : BaseInspector<int2>
|
||||
{
|
||||
public override int2 Inspect(string label, int2 value, object parent, DatabaseInspector inspectorWindow)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
GUILayout.Label("X", GUILayout.Width(labelWidth));
|
||||
value.x = DelayedIntField(value.x);
|
||||
GUILayout.Label("Y", GUILayout.Width(labelWidth));
|
||||
value.y = DelayedIntField(value.y);
|
||||
if (GUILayout.Button("\u2190", GUILayout.Width(arrowWidth)))
|
||||
value.x--;
|
||||
if (GUILayout.Button("\u2192", GUILayout.Width(arrowWidth)))
|
||||
value.x++;
|
||||
if (GUILayout.Button("\u2191", GUILayout.Width(arrowWidth)))
|
||||
value.y++;
|
||||
if (GUILayout.Button("\u2193", GUILayout.Width(arrowWidth)))
|
||||
value.y--;
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class Int3Inspector : BaseInspector<int3>
|
||||
{
|
||||
public override int3 Inspect(string label, int3 value, object parent, DatabaseInspector inspectorWindow)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
GUILayout.Label("X", GUILayout.Width(labelWidth));
|
||||
value.x = DelayedIntField(value.x);
|
||||
GUILayout.Label("Y", GUILayout.Width(labelWidth));
|
||||
value.y = DelayedIntField(value.y);
|
||||
GUILayout.Label("Z", GUILayout.Width(labelWidth));
|
||||
value.z = DelayedIntField(value.z);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class Int4Inspector : BaseInspector<int4>
|
||||
{
|
||||
public override int4 Inspect(string label, int4 value, object parent, DatabaseInspector inspectorWindow)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
GUILayout.Label("X", GUILayout.Width(labelWidth));
|
||||
value.x = DelayedIntField(value.x);
|
||||
GUILayout.Label("Y", GUILayout.Width(labelWidth));
|
||||
value.y = DelayedIntField(value.y);
|
||||
GUILayout.Label("Z", GUILayout.Width(labelWidth));
|
||||
value.z = DelayedIntField(value.z);
|
||||
GUILayout.Label("W", GUILayout.Width(labelWidth));
|
||||
value.w = DelayedIntField(value.w);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 473b4029da16430aa0c0ef89298070d8
|
||||
guid: ae5bba94d1f1a7144944aebf833497b3
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using static UnityEditor.EditorGUILayout;
|
||||
|
||||
public class BoolInspector : BaseInspector<bool>
|
||||
{
|
||||
public override bool Inspect(string label, bool value, object parent, DatabaseInspector inspectorWindow)
|
||||
{
|
||||
using (var h = new EditorGUILayout.HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
return Toggle(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class StringInspector : BaseInspector<string>
|
||||
{
|
||||
public override string Inspect(string label, string value, object parent, DatabaseInspector inspectorWindow)
|
||||
{
|
||||
using (var h = new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
return DelayedTextField(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class StringAreaInspector : BaseInspector<string, InspectableTextAttribute>
|
||||
{
|
||||
public override string Inspect(string label, string value, object parent, DatabaseInspector inspectorWindow, InspectableTextAttribute attribute)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
EditorStyles.textArea.wordWrap = true;
|
||||
return DelayedTextField(value, EditorStyles.textArea, GUILayout.Height(100));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 91dcbfa1679e4be1944d6856ca63bf13
|
||||
timeCreated: 1617065181
|
||||
23
Assets/Scripts/CultCache/Editor/Inspectors/TypeInspector.cs
Normal file
23
Assets/Scripts/CultCache/Editor/Inspectors/TypeInspector.cs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using static UnityEditor.EditorGUILayout;
|
||||
|
||||
public class TypeInspector : BaseInspector<Type, InspectableTypeAttribute>
|
||||
{
|
||||
public override Type Inspect(string label, Type value, object parent, DatabaseInspector inspectorWindow, InspectableTypeAttribute attribute)
|
||||
{
|
||||
var types = attribute.Type.GetAllChildClasses();
|
||||
var enumOptions = new[] {"None"}.Concat(types.Select(t => t.Name)).ToArray();
|
||||
var index = Array.IndexOf(types, value) + 1;
|
||||
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
index = Popup(index, enumOptions);
|
||||
}
|
||||
|
||||
return index == 0 ? null : types[index - 1];
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 4762384a61dc4d08a1ba4e7564a20081
|
||||
timeCreated: 1617066802
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using static UnityEditor.EditorGUILayout;
|
||||
|
||||
public class TextureInspector : BaseInspector<string, InspectableTextureAttribute>
|
||||
{
|
||||
public override string Inspect(string label,
|
||||
string value,
|
||||
object parent,
|
||||
DatabaseInspector inspectorWindow,
|
||||
InspectableTextureAttribute attribute)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
return AssetDatabase.GetAssetPath(ObjectField(AssetDatabase.LoadAssetAtPath<Texture2D>(value), typeof(Texture2D), false));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class GameObjectInspector : BaseInspector<string, InspectablePrefabAttribute>
|
||||
{
|
||||
public override string Inspect(string label, string value, object parent, DatabaseInspector inspectorWindow, InspectablePrefabAttribute attribute)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
return AssetDatabase.GetAssetPath(ObjectField(AssetDatabase.LoadAssetAtPath<GameObject>(value), typeof(GameObject), false));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class TextAssetInspector : BaseInspector<string, InspectableTextAssetAttribute>
|
||||
{
|
||||
public override string Inspect(string label,
|
||||
string value,
|
||||
object parent,
|
||||
DatabaseInspector inspectorWindow,
|
||||
InspectableTextAssetAttribute attribute)
|
||||
{
|
||||
using (new HorizontalScope())
|
||||
{
|
||||
GUILayout.Label(label, GUILayout.Width(width));
|
||||
return AssetDatabase.GetAssetPath(ObjectField(AssetDatabase.LoadAssetAtPath<TextAsset>(value), typeof(TextAsset), false));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 8519fa7d4f06468bb9be151f053d1fcb
|
||||
timeCreated: 1617067005
|
||||
|
|
@ -40,24 +40,14 @@ public static class UnityExtensions
|
|||
return new AnimationCurve(keys.Select(v => new Keyframe(v.x, v.y, v.z, v.w)).ToArray());
|
||||
}
|
||||
|
||||
public static AnimationCurve ToCurve(this CultMath.float4[] keys)
|
||||
{
|
||||
return new AnimationCurve(keys.Select(v => new Keyframe(v.x, v.y, v.z, v.w)).ToArray());
|
||||
}
|
||||
|
||||
public static AnimationCurve ToCurve(this BezierCurve curve)
|
||||
{
|
||||
return new AnimationCurve(curve.Keys.Select(v => new Keyframe(v.x, v.y, v.z, v.w)).ToArray());
|
||||
}
|
||||
|
||||
public static Color ToColor(this float3 v) => new Color(v.x,v.y,v.z);
|
||||
public static Color ToColor(this CultMath.float3 v) => new Color(v.x,v.y,v.z);
|
||||
public static float3 ToUnityFloat3(this CultMath.float3 v) => float3(v.x, v.y, v.z);
|
||||
public static float3 ToFloat3(this Color c) => float3(c.r,c.g,c.b);
|
||||
public static CultMath.float3 ToCultFloat3(this Color c) => new(c.r, c.g, c.b);
|
||||
|
||||
public static Color ToColor(this float4 v) => new Color(v.x,v.y,v.z, v.w);
|
||||
public static Color ToColor(this CultMath.float4 v) => new Color(v.x,v.y,v.z, v.w);
|
||||
public static float4 ToFloat4(this Color c) => float4(c.r, c.g, c.b, c.a);
|
||||
public static CultMath.float4 ToCultFloat4(this Color c) => new(c.r, c.g, c.b, c.a);
|
||||
}
|
||||
}
|
||||
167
Assets/Scripts/CultClient.cs
Normal file
167
Assets/Scripts/CultClient.cs
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using LiteNetLib;
|
||||
using MessagePack;
|
||||
using MessagePack.Resolvers;
|
||||
using UniRx;
|
||||
using UnityEngine;
|
||||
|
||||
public static class CultClient {
|
||||
public static Action<string> Logger = s =>
|
||||
MainThreadDispatcher.Post(_=>Debug.Log(s),null);
|
||||
|
||||
public static event Action<string> OnError;
|
||||
public static int Ping;
|
||||
|
||||
private static NetManager _client;
|
||||
private static NetPeer _peer;
|
||||
private static Dictionary<Type, NotAnActionCollection> _messageCallbacks = new Dictionary<Type, NotAnActionCollection>();
|
||||
private static Guid _token;
|
||||
private static MD5 _hasher = MD5.Create();
|
||||
private static string _lastHost;
|
||||
private static int _lastPort;
|
||||
|
||||
public static bool Verified => _token != Guid.Empty;
|
||||
public static bool Connected => _client != null;
|
||||
|
||||
public static void Send<T>(T m) where T : Message
|
||||
{
|
||||
if (Connected)
|
||||
{
|
||||
if (Verified || m is LoginMessage || m is RegisterMessage || m is VerifyMessage)
|
||||
{
|
||||
Logger($"Sending message {MessagePackSerializer.SerializeToJson(m as Message)}");
|
||||
_peer.Send(m);
|
||||
}
|
||||
else OnError?.Invoke("Cannot send, client is not verified!");
|
||||
}
|
||||
else OnError?.Invoke("Cannot send, client is not connected!");
|
||||
}
|
||||
|
||||
public static void ClearMessageListeners()
|
||||
{
|
||||
_messageCallbacks.Clear();
|
||||
}
|
||||
|
||||
public static void AddMessageListener<T>(Action<T> callback) where T : Message
|
||||
{
|
||||
if (!_messageCallbacks.ContainsKey(typeof(T)))
|
||||
_messageCallbacks[typeof(T)] = new ActionCollection<T>();
|
||||
((ActionCollection<T>)_messageCallbacks[typeof(T)]).Add(callback);
|
||||
}
|
||||
|
||||
public static void Login(string auth, string password)
|
||||
{
|
||||
if (auth.Length>0)
|
||||
{
|
||||
if (8 <= password.Length && password.Length < 32)
|
||||
Send(new LoginMessage
|
||||
{
|
||||
Auth = auth,
|
||||
Password = _hasher.ComputeHash(Encoding.UTF8.GetBytes(password))
|
||||
});
|
||||
else OnError?.Invoke("Password Invalid: needs to be at least 8 characters");
|
||||
}
|
||||
else OnError?.Invoke("Email/Username Empty");
|
||||
}
|
||||
|
||||
public static void Register(string email, string username, string password)
|
||||
{
|
||||
if (email.Length > 0)
|
||||
{
|
||||
if (username.Length > 0)
|
||||
{
|
||||
if (8 <= password.Length && password.Length < 32)
|
||||
Send(new RegisterMessage
|
||||
{
|
||||
Email = email,
|
||||
Name = username,
|
||||
Password = _hasher.ComputeHash(Encoding.UTF8.GetBytes(password))
|
||||
});
|
||||
else OnError?.Invoke("Password Invalid: needs to be at least 8 characters");
|
||||
}
|
||||
else OnError?.Invoke("Username Empty");
|
||||
}
|
||||
else OnError?.Invoke("Email Empty");
|
||||
}
|
||||
|
||||
public static void Connect(string host = "localhost", int port = 3075)
|
||||
{
|
||||
_lastHost = host;
|
||||
_lastPort = port;
|
||||
// Set extensions to default resolver.
|
||||
var resolver = CompositeResolver.Create(
|
||||
MathResolver.Instance,
|
||||
NativeGuidResolver.Instance,
|
||||
StandardResolver.Instance
|
||||
);
|
||||
var options = MessagePackSerializerOptions.Standard.WithResolver(resolver);
|
||||
MessagePackSerializer.DefaultOptions = options;
|
||||
|
||||
EventBasedNetListener listener = new EventBasedNetListener();
|
||||
_client = new NetManager(listener)
|
||||
{
|
||||
// UnsyncedEvents = true,
|
||||
NatPunchEnabled = true
|
||||
};
|
||||
_client.Start(3074);
|
||||
_peer = _client.Connect(host, port, "aetheria-cc65a44d");
|
||||
Observable.EveryUpdate().Subscribe(_ => _client.PollEvents());
|
||||
listener.NetworkErrorEvent += (point, code) => Logger($"{point.Address}: Error {code}");
|
||||
listener.NetworkReceiveEvent += (peer, reader, method) =>
|
||||
{
|
||||
var bytes = reader.GetRemainingBytes();
|
||||
Logger($"Received message: {MessagePackSerializer.ConvertToJson(new ReadOnlyMemory<byte>(bytes))}");
|
||||
var message = MessagePackSerializer.Deserialize<Message>(bytes);
|
||||
var type = message.GetType();
|
||||
|
||||
if (!Verified)
|
||||
{
|
||||
switch (message)
|
||||
{
|
||||
case LoginSuccessMessage loginSuccess:
|
||||
_token = loginSuccess.Session;
|
||||
break;
|
||||
case NetErrorMessage error:
|
||||
OnError?.Invoke(error.Error);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (_messageCallbacks.ContainsKey(type))
|
||||
typeof(ActionCollection<>).MakeGenericType(new[] {type}).GetMethod("Invoke")
|
||||
.Invoke(_messageCallbacks[type], new object[] {message});
|
||||
else
|
||||
Logger(
|
||||
$"Received {type.Name} message but no one is listening for it so I'll just leave it here " +
|
||||
$"¯\\_(ツ)_/¯\n{MessagePackSerializer.ConvertToJson(new ReadOnlyMemory<byte>(bytes))}");
|
||||
|
||||
};
|
||||
|
||||
listener.PeerConnectedEvent += peer =>
|
||||
{
|
||||
Logger($"Peer {peer.EndPoint.Address}:{peer.EndPoint.Port} connected.");
|
||||
_peer = peer;
|
||||
if(Verified)
|
||||
peer.Send(new VerifyMessage{Session = _token});
|
||||
};
|
||||
|
||||
listener.PeerDisconnectedEvent += (peer, info) =>
|
||||
{
|
||||
Logger($"Peer {peer.EndPoint.Address}:{peer.EndPoint.Port} disconnected: {info.Reason}.");
|
||||
_peer = null;
|
||||
Connect(_lastHost, _lastPort);
|
||||
};
|
||||
|
||||
listener.NetworkLatencyUpdateEvent +=
|
||||
(peer, latency) => Ping = latency; //Logger($"Ping received: {latency} ms");
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/CultClient.cs.meta
Normal file
11
Assets/Scripts/CultClient.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 7e7103131b037e44095bb2e8a7c0b28a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -3,6 +3,8 @@ using System.Collections;
|
|||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using MessagePack;
|
||||
using MessagePack.Formatters;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
|
|
@ -16,6 +18,8 @@ public class GameSettingsEditor : Editor
|
|||
private bool _showWeaponCaliberIcons;
|
||||
private bool _showWeaponRangeIcons;
|
||||
private bool _showProperties;
|
||||
private bool _showDatabase;
|
||||
|
||||
// private ScriptableItem _prefab;
|
||||
|
||||
public override void OnInspectorGUI()
|
||||
|
|
@ -94,4 +98,4 @@ public class GameSettingsEditor : Editor
|
|||
|
||||
serializedObject.ApplyModifiedProperties();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,196 +1,115 @@
|
|||
using System.Buffers.Text;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using MessagePack;
|
||||
using Unity.Mathematics;
|
||||
using UnityEditor;
|
||||
using UnityEditor.UIElements;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
using Random = CultMath.Random;
|
||||
using UnityEditor;
|
||||
using Random = Unity.Mathematics.Random;
|
||||
|
||||
public class NameTools : EditorWindow
|
||||
{
|
||||
public TextAsset[] NameFiles;
|
||||
public int NameGeneratorMinLength = 5;
|
||||
public int NameGeneratorMaxLength = 10;
|
||||
public int NameGeneratorOrder = 4;
|
||||
|
||||
private int _minWordLength = 4;
|
||||
private TextAsset _nameFile;
|
||||
private int minWordLength = 4;
|
||||
private TextAsset nameFile;
|
||||
private MarkovNameGenerator _nameGenerator;
|
||||
private bool _stripNumberTokens;
|
||||
private Button _generateNameButton;
|
||||
private Label _statusLabel;
|
||||
|
||||
|
||||
// Add menu named "My Window" to the Window menu
|
||||
[MenuItem("Window/Aetheria/Name Tools")]
|
||||
private static void Init()
|
||||
static void Init()
|
||||
{
|
||||
var window = GetWindow<NameTools>();
|
||||
window.titleContent = new GUIContent("Name Tools");
|
||||
// Get existing open window or if none, make a new one:
|
||||
NameTools window = (NameTools)EditorWindow.GetWindow(typeof(NameTools));
|
||||
window.Show();
|
||||
}
|
||||
|
||||
private void CreateGUI()
|
||||
|
||||
bool HasNonASCIIChars(string str)
|
||||
{
|
||||
var root = rootVisualElement;
|
||||
root.Clear();
|
||||
root.style.paddingLeft = 12;
|
||||
root.style.paddingRight = 12;
|
||||
root.style.paddingTop = 12;
|
||||
root.style.paddingBottom = 12;
|
||||
root.style.flexDirection = FlexDirection.Column;
|
||||
|
||||
var nameFileField = new ObjectField("Name File")
|
||||
{
|
||||
objectType = typeof(TextAsset),
|
||||
allowSceneObjects = false,
|
||||
value = _nameFile
|
||||
};
|
||||
nameFileField.RegisterValueChangedCallback(evt => _nameFile = evt.newValue as TextAsset);
|
||||
root.Add(nameFileField);
|
||||
|
||||
root.Add(CreateIntegerField("Minimum File Word Length", _minWordLength, value => _minWordLength = value));
|
||||
root.Add(CreateIntegerField("Generated Minimum Word Length", NameGeneratorMinLength, value => NameGeneratorMinLength = value));
|
||||
root.Add(CreateIntegerField("Generated Maximum Word Length", NameGeneratorMaxLength, value => NameGeneratorMaxLength = value));
|
||||
root.Add(CreateIntegerField("Generator Order", NameGeneratorOrder, value => NameGeneratorOrder = value));
|
||||
|
||||
var stripNumbersField = new Toggle("Strip Number Tokens")
|
||||
{
|
||||
value = _stripNumberTokens
|
||||
};
|
||||
stripNumbersField.RegisterValueChangedCallback(evt => _stripNumberTokens = evt.newValue);
|
||||
root.Add(stripNumbersField);
|
||||
|
||||
var cleanButton = new Button(CleanNameFile)
|
||||
{
|
||||
text = "Clean Name File"
|
||||
};
|
||||
root.Add(cleanButton);
|
||||
|
||||
var processButton = new Button(ProcessNameFile)
|
||||
{
|
||||
text = "Process Name File"
|
||||
};
|
||||
root.Add(processButton);
|
||||
|
||||
_generateNameButton = new Button(GenerateName)
|
||||
{
|
||||
text = "Generate Name"
|
||||
};
|
||||
root.Add(_generateNameButton);
|
||||
|
||||
_statusLabel = new Label();
|
||||
_statusLabel.style.unityFontStyleAndWeight = FontStyle.Italic;
|
||||
_statusLabel.style.marginTop = 8;
|
||||
root.Add(_statusLabel);
|
||||
|
||||
RefreshUiState();
|
||||
return (System.Text.Encoding.UTF8.GetByteCount(str) != str.Length);
|
||||
}
|
||||
|
||||
private IntegerField CreateIntegerField(string label, int value, System.Action<int> onChanged)
|
||||
void OnGUI()
|
||||
{
|
||||
var field = new IntegerField(label)
|
||||
{
|
||||
value = value
|
||||
};
|
||||
field.RegisterValueChangedCallback(evt => onChanged(evt.newValue));
|
||||
return field;
|
||||
}
|
||||
ScriptableObject target = this;
|
||||
SerializedObject so = new SerializedObject(target);
|
||||
SerializedProperty stringsProperty = so.FindProperty("NameFiles");
|
||||
|
||||
private void CleanNameFile()
|
||||
{
|
||||
if (_nameFile == null)
|
||||
{
|
||||
SetStatus("Pick a name file first.");
|
||||
return;
|
||||
}
|
||||
EditorGUILayout.PropertyField(stringsProperty, true); // True means show children
|
||||
so.ApplyModifiedProperties(); // Remember to apply modified properties
|
||||
|
||||
var lines = _nameFile.text.Split('\n');
|
||||
var outputPath = Path.Combine(Application.dataPath, _nameFile.name + ".csv");
|
||||
using var outputFile = new StreamWriter(outputPath);
|
||||
var names = new HashSet<string>();
|
||||
foreach (var line in lines)
|
||||
if (GUILayout.Button("Save Name Files"))
|
||||
{
|
||||
var tokens = line.Split(',', ' ');
|
||||
foreach (var token in tokens)
|
||||
RegisterResolver.Register();
|
||||
var nameFilesDirectory = ActionGameManager.GameDataDirectory.CreateSubdirectory("NameFile");
|
||||
foreach (var nameFile in NameFiles)
|
||||
{
|
||||
if (HasNonAsciiChars(token))
|
||||
continue;
|
||||
var entry = new NameFile
|
||||
{
|
||||
Name = nameFile.name,
|
||||
Names = nameFile.text.Split('\n')
|
||||
};
|
||||
File.WriteAllBytes(Path.Combine(nameFilesDirectory.FullName, $"{entry.ID.ToString()}.msgpack"), MessagePackSerializer.Serialize((DatabaseEntry) entry));
|
||||
}
|
||||
}
|
||||
|
||||
nameFile = (TextAsset) EditorGUILayout.ObjectField("Name File", nameFile, typeof(TextAsset), false);
|
||||
minWordLength = EditorGUILayout.IntField("Minimum File Word Length", minWordLength);
|
||||
NameGeneratorMinLength = EditorGUILayout.IntField("Generated Minimum Word Length", NameGeneratorMinLength);
|
||||
NameGeneratorMaxLength = EditorGUILayout.IntField("Generated Maximum Word Length", NameGeneratorMaxLength);
|
||||
NameGeneratorOrder = EditorGUILayout.IntField("Generator Order", NameGeneratorOrder);
|
||||
_stripNumberTokens = GUILayout.Toggle(_stripNumberTokens, "Strip Number Tokens");
|
||||
|
||||
var cleaned = new string(token
|
||||
.Where(ch => char.IsLetter(ch) || ch == '-' || ch == '`' || ch == '\'')
|
||||
.ToArray())
|
||||
.Trim()
|
||||
.Trim('`', '-');
|
||||
|
||||
if (_stripNumberTokens && cleaned.Any(char.IsDigit))
|
||||
continue;
|
||||
|
||||
if (cleaned.Length < _minWordLength || !names.Add(cleaned))
|
||||
continue;
|
||||
|
||||
outputFile.WriteLine(cleaned);
|
||||
if (GUILayout.Button("Clean Name File"))
|
||||
{
|
||||
var lines = nameFile.text.Split('\n');
|
||||
using StreamWriter outputFile = new StreamWriter(Path.Combine(Application.dataPath, nameFile.name + ".csv"));
|
||||
var names = new HashSet<string>();
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var tokens = line.Split(',', ' ');
|
||||
foreach (var t in tokens)
|
||||
{
|
||||
if (!HasNonASCIIChars(t))
|
||||
{
|
||||
var s = new string(t.Where(c => char.IsLetter(c) || c == '-' || c == '`' || c == '\'').ToArray()).Trim().Trim('`','-');
|
||||
if(s.Length >= minWordLength && !names.Contains(s))
|
||||
{
|
||||
names.Add(s);
|
||||
outputFile.WriteLine(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
AssetDatabase.Refresh();
|
||||
SetStatus($"Wrote {names.Count} cleaned names to {Path.GetFileName(outputPath)}.");
|
||||
}
|
||||
|
||||
private void ProcessNameFile()
|
||||
{
|
||||
if (_nameFile == null)
|
||||
if (GUILayout.Button("Process Name File") && nameFile != null)
|
||||
{
|
||||
SetStatus("Pick a name file first.");
|
||||
return;
|
||||
var names = new HashSet<string>();
|
||||
var lines = nameFile.text.Split('\n');
|
||||
foreach (var line in lines)
|
||||
{
|
||||
foreach(var word in line.ToUpperInvariant().Split(' ', ',', '.', '"'))
|
||||
if (word.Length >= minWordLength && !names.Contains(word))
|
||||
names.Add(word);
|
||||
}
|
||||
Debug.Log($"Found {lines.Length} lines, with {names.Count} unique names!");
|
||||
var random = new Random(1337);
|
||||
_nameGenerator = new MarkovNameGenerator(ref random, names, NameGeneratorOrder, NameGeneratorMinLength, NameGeneratorMaxLength);
|
||||
}
|
||||
|
||||
var names = new HashSet<string>();
|
||||
var lines = _nameFile.text.Split('\n');
|
||||
foreach (var line in lines)
|
||||
if (_nameGenerator != null)
|
||||
{
|
||||
foreach (var word in line.ToUpperInvariant().Split(' ', ',', '.', '"'))
|
||||
if (GUILayout.Button("Generate Name"))
|
||||
{
|
||||
if (_stripNumberTokens && word.Any(char.IsDigit))
|
||||
continue;
|
||||
|
||||
if (word.Length >= _minWordLength)
|
||||
names.Add(word);
|
||||
Debug.Log(_nameGenerator.NextName);
|
||||
}
|
||||
}
|
||||
|
||||
Debug.Log($"Found {lines.Length} lines, with {names.Count} unique names!");
|
||||
var random = new Random(1337);
|
||||
_nameGenerator = new MarkovNameGenerator(ref random, names, NameGeneratorOrder, NameGeneratorMinLength, NameGeneratorMaxLength);
|
||||
SetStatus($"Processed {names.Count} unique names.");
|
||||
RefreshUiState();
|
||||
}
|
||||
|
||||
private void GenerateName()
|
||||
{
|
||||
if (_nameGenerator == null)
|
||||
{
|
||||
SetStatus("Process a name file before generating names.");
|
||||
return;
|
||||
}
|
||||
|
||||
var generatedName = _nameGenerator.NextName;
|
||||
Debug.Log(generatedName);
|
||||
SetStatus($"Generated: {generatedName}");
|
||||
}
|
||||
|
||||
private void RefreshUiState()
|
||||
{
|
||||
_generateNameButton?.SetEnabled(_nameGenerator != null);
|
||||
}
|
||||
|
||||
private void SetStatus(string message)
|
||||
{
|
||||
if (_statusLabel != null)
|
||||
_statusLabel.text = message ?? "";
|
||||
}
|
||||
|
||||
private static bool HasNonAsciiChars(string value)
|
||||
{
|
||||
return System.Text.Encoding.UTF8.GetByteCount(value ?? "") != (value ?? "").Length;
|
||||
}
|
||||
}
|
||||
}
|
||||
118
Assets/Scripts/Editor/SerializerTestWindow.cs
Normal file
118
Assets/Scripts/Editor/SerializerTestWindow.cs
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using MessagePack;
|
||||
using MessagePack.Formatters;
|
||||
using MessagePack.Resolvers;
|
||||
using Newtonsoft.Json;
|
||||
using RethinkDb.Driver;
|
||||
using RethinkDb.Driver.Net;
|
||||
using Unity.Mathematics;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using Object = UnityEngine.Object;
|
||||
using static Unity.Mathematics.math;
|
||||
|
||||
public class SerializerTestWindow : EditorWindow
|
||||
{
|
||||
// Singleton to avoid multiple instances of window.
|
||||
private static SerializerTestWindow _instance;
|
||||
|
||||
private static readonly RethinkDB R = RethinkDB.R;
|
||||
|
||||
private Connection _connection;
|
||||
|
||||
private Object _object;
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
_connection = R.Connection().Hostname(EditorPrefs.GetString("RethinkDB.URL")).Port(RethinkDBConstants.DefaultPort).Timeout(60).Connect();
|
||||
}
|
||||
|
||||
public void OnGUI()
|
||||
{
|
||||
//var obj = new ShieldData() {ID = Guid.NewGuid(), Name = "Bar" , HeatPerformanceCurve = new []{float4(0,0,0,0), float4(1,1,1,1)}} as DatabaseEntry;
|
||||
//var obj = new GalaxyRequestMessage() as Message;
|
||||
var obj = new Gradient();
|
||||
var times = Enumerable.Range(0, 5).Select(i => (float) i / 4).ToArray();
|
||||
obj.alphaKeys = times.Select(f => new GradientAlphaKey(1, f)).ToArray();
|
||||
obj.colorKeys = times.Select(f => new GradientColorKey(UnityEngine.Random.ColorHSV(), f)).ToArray();
|
||||
// JsonSerializer serializer = new JsonSerializer();
|
||||
// serializer.Converters.Add(new MathJsonConverter());
|
||||
// serializer.Converters.Add(Converter.DateTimeConverter);
|
||||
// serializer.Converters.Add(Converter.BinaryConverter);
|
||||
// serializer.Converters.Add(Converter.GroupingConverter);
|
||||
// serializer.Converters.Add(Converter.PocoExprConverter);
|
||||
|
||||
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
|
||||
{
|
||||
Converters = new List<JsonConverter>
|
||||
{
|
||||
new MathJsonConverter(),
|
||||
Converter.DateTimeConverter,
|
||||
Converter.BinaryConverter,
|
||||
Converter.GroupingConverter,
|
||||
Converter.PocoExprConverter
|
||||
}
|
||||
};
|
||||
|
||||
Converter.Serializer.Converters.Add(new MathJsonConverter());
|
||||
|
||||
RegisterResolver.Register();
|
||||
|
||||
if (GUILayout.Button("Print MsgPack JSON"))
|
||||
Debug.Log(MessagePackSerializer.SerializeToJson(obj));
|
||||
|
||||
//var writer = new StringWriter();
|
||||
if (GUILayout.Button("Print Newtonsoft JSON"))
|
||||
{
|
||||
//serializer.Serialize(writer, obj);
|
||||
Debug.Log(JsonConvert.SerializeObject(obj));
|
||||
}
|
||||
|
||||
if (GUILayout.Button("Create Database"))
|
||||
R.DbCreate("Aetheria").Run(_connection);
|
||||
|
||||
if (GUILayout.Button("Create Table"))
|
||||
R.Db("Aetheria").TableCreate("Items").Run(_connection);
|
||||
|
||||
if (GUILayout.Button("Send to RethinkDB"))
|
||||
R.Db("Aetheria").Table("Items").Insert(obj).Run(_connection);
|
||||
}
|
||||
|
||||
#region EditorWindow Boilerplate
|
||||
|
||||
public SerializerTestWindow()
|
||||
{
|
||||
_instance = this;
|
||||
}
|
||||
|
||||
static SerializerTestWindow ShowWindow()
|
||||
{
|
||||
if (_instance == null)
|
||||
{
|
||||
SerializerTestWindow window = EditorWindow.GetWindow<SerializerTestWindow>();
|
||||
window.titleContent = new GUIContent("Serializer Test");
|
||||
_instance = window;
|
||||
window.Show();
|
||||
}
|
||||
else
|
||||
_instance.Focus();
|
||||
|
||||
return _instance;
|
||||
}
|
||||
|
||||
[MenuItem("Window/Serializer Test Tool")]
|
||||
static void Init()
|
||||
{
|
||||
ShowWindow();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
|
||||
|
||||
11
Assets/Scripts/Editor/SerializerTestWindow.cs.meta
Normal file
11
Assets/Scripts/Editor/SerializerTestWindow.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: c18f225a1e4e8bc42bce3782701c9a6b
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -1,7 +1,8 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using GameCult.Mesh;
|
||||
using JsonKnownTypes;
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
using TMPro;
|
||||
using UniRx.Triggers;
|
||||
using UnityEngine;
|
||||
|
|
@ -18,16 +19,12 @@ public class ActionBarSlot : MonoBehaviour
|
|||
public ObservablePointerEnterTrigger PointerEnterTrigger;
|
||||
public ObservablePointerExitTrigger PointerExitTrigger;
|
||||
private ActionBarBinding binding;
|
||||
public string ControlPath { get; set; }
|
||||
|
||||
public ActionBarBinding Binding
|
||||
{
|
||||
get => binding;
|
||||
set
|
||||
{
|
||||
if (ReferenceEquals(binding, value))
|
||||
return;
|
||||
|
||||
binding = value;
|
||||
if (binding == null)
|
||||
{
|
||||
|
|
@ -39,99 +36,90 @@ public class ActionBarSlot : MonoBehaviour
|
|||
}
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
Binding = null;
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
Binding?.Update();
|
||||
}
|
||||
|
||||
public SavedActionBarBinding Save()
|
||||
{
|
||||
return Binding switch
|
||||
{
|
||||
ActionBarConsumableBinding actionBarConsumableBinding => new SavedActionBarConsumableBinding
|
||||
{
|
||||
Target = new DatabaseLink<ConsumableItemData>{LinkID = actionBarConsumableBinding.Target.ID}
|
||||
},
|
||||
ActionBarGearBinding actionBarGearBinding => new SavedActionBarGearBinding
|
||||
{
|
||||
EquipmentIndex = actionBarGearBinding.Entity.Equipment.IndexOf(actionBarGearBinding.Item),
|
||||
BehaviorIndex = Array.IndexOf(actionBarGearBinding.Item.Behaviors, actionBarGearBinding.Behavior)
|
||||
},
|
||||
ActionBarWeaponGroupBinding actionBarWeaponGroupBinding => new SavedActionBarWeaponGroupBinding
|
||||
{
|
||||
Group = actionBarWeaponGroupBinding.Group
|
||||
},
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
|
||||
public void Restore(SavedActionBarBinding binding, Entity entity)
|
||||
{
|
||||
Binding = binding switch
|
||||
{
|
||||
SavedActionBarConsumableBinding savedActionBarConsumableBinding =>
|
||||
new ActionBarConsumableBinding(
|
||||
entity,
|
||||
this,
|
||||
savedActionBarConsumableBinding.Target.Value),
|
||||
SavedActionBarGearBinding savedActionBarGearBinding =>
|
||||
new ActionBarGearBinding(
|
||||
entity,
|
||||
this,
|
||||
entity.Equipment[savedActionBarGearBinding.EquipmentIndex],
|
||||
entity.Equipment[savedActionBarGearBinding.EquipmentIndex]
|
||||
.Behaviors[savedActionBarGearBinding.BehaviorIndex] as IActivatedBehavior),
|
||||
SavedActionBarWeaponGroupBinding savedActionBarWeaponGroupBinding =>
|
||||
new ActionBarWeaponGroupBinding(entity, this, savedActionBarWeaponGroupBinding.Group),
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public abstract class ActionBarBinding
|
||||
{
|
||||
private static AetheriaClientState s_runtimeState;
|
||||
public Entity Entity { get; }
|
||||
private readonly Func<AetheriaControl> _resolveControl;
|
||||
protected ActionBarSlot Slot { get; }
|
||||
protected GameSettings Settings { get; }
|
||||
public abstract void Activate();
|
||||
public abstract void Deactivate();
|
||||
public abstract void Update();
|
||||
|
||||
protected ActionBarBinding(
|
||||
Entity entity,
|
||||
ActionBarSlot slot,
|
||||
Func<AetheriaControl> resolveControl,
|
||||
GameSettings settings)
|
||||
public ActionBarBinding(Entity entity, ActionBarSlot slot)
|
||||
{
|
||||
Entity = entity;
|
||||
Slot = slot;
|
||||
_resolveControl = resolveControl ?? (() => null);
|
||||
Settings = settings;
|
||||
}
|
||||
|
||||
protected bool TrySubmit(Action<AetheriaControl> submit, string label)
|
||||
{
|
||||
if (submit == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
var control = _resolveControl();
|
||||
if (control == null)
|
||||
return false;
|
||||
|
||||
submit(control);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogWarning($"Failed to send Aetheria daemon action-bar {label} operation; operation not submitted: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
protected AetheriaRuntimeCatalogItem FindCatalogItem(ItemInstance item)
|
||||
{
|
||||
try
|
||||
{
|
||||
s_runtimeState ??= AetheriaUnityRuntimeClientProvider.RuntimeState("unity-action-bar");
|
||||
return s_runtimeState.Catalog.Latest()?.FindItem(item, x => x.ItemKey);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogWarning($"Failed to bind Aetheria runtime catalog for action-bar binding: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class ActionBarConsumableBinding : ActionBarBinding
|
||||
{
|
||||
public AetheriaRuntimeCatalogItem Target { get; }
|
||||
public ConsumableItemData Target;
|
||||
|
||||
public ActionBarConsumableBinding(
|
||||
Entity entity,
|
||||
ActionBarSlot slot,
|
||||
Func<AetheriaControl> resolveControl,
|
||||
GameSettings settings,
|
||||
AetheriaRuntimeCatalogItem target) : base(entity, slot, resolveControl, settings)
|
||||
public ActionBarConsumableBinding(Entity entity, ActionBarSlot slot, ConsumableItemData target) : base(entity, slot)
|
||||
{
|
||||
Target = target;
|
||||
Slot.QuantityRemaining.gameObject.SetActive(true);
|
||||
Slot.Label.gameObject.SetActive(false);
|
||||
Slot.Icon.gameObject.SetActive(false);
|
||||
var data = Target;
|
||||
if(!string.IsNullOrEmpty(data.Icon))
|
||||
{
|
||||
Slot.Label.gameObject.SetActive(false);
|
||||
Slot.Icon.gameObject.SetActive(true);
|
||||
Slot.Icon.texture = Resources.Load<Texture2D>(data.Icon.Substring("Assets/Resources/".Length).Split('.').First());
|
||||
}
|
||||
else Slot.Icon.gameObject.SetActive(false);
|
||||
}
|
||||
|
||||
public override void Activate()
|
||||
{
|
||||
TrySubmit(
|
||||
operations => operations.ActivateConsumable(TargetItemKey),
|
||||
"consumable");
|
||||
Entity.TryActivateConsumable(Target);
|
||||
}
|
||||
|
||||
public override void Deactivate()
|
||||
|
|
@ -140,20 +128,11 @@ public class ActionBarConsumableBinding : ActionBarBinding
|
|||
|
||||
public override void Update()
|
||||
{
|
||||
Slot.QuantityRemaining.text = $"{Entity.CountItemsInCargo(TargetItemKey)}";
|
||||
if (string.IsNullOrWhiteSpace(TargetItemKey))
|
||||
{
|
||||
Slot.Fill.fillAmount = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
var instance = Entity.FindActiveConsumable(TargetItemKey);
|
||||
Slot.QuantityRemaining.text = $"{Entity.CountItemsInCargo(Target.ID)}";
|
||||
var instance = Entity.FindActiveConsumable(Target);
|
||||
if (instance == null) Slot.Fill.fillAmount = 0;
|
||||
else Slot.Fill.fillAmount = instance.RemainingDuration / instance.Duration;
|
||||
else Slot.Fill.fillAmount = instance.RemainingDuration / instance.Data.Duration;
|
||||
}
|
||||
|
||||
public string TargetItemKey => Target?.ItemKey ?? "";
|
||||
|
||||
}
|
||||
|
||||
public class ActionBarGearBinding : ActionBarBinding
|
||||
|
|
@ -163,75 +142,31 @@ public class ActionBarGearBinding : ActionBarBinding
|
|||
|
||||
public bool Active;
|
||||
|
||||
public int EquipmentIndex => Entity?.Equipment?.IndexOf(Item) ?? -1;
|
||||
|
||||
public int BehaviorIndex => Item?.Behaviors == null ? -1 : Array.IndexOf(Item.Behaviors, Behavior);
|
||||
|
||||
public string TargetItemKey => Item?.EquippableItem?.ItemKey ?? "";
|
||||
|
||||
public ActionBarGearBinding(
|
||||
Entity entity,
|
||||
ActionBarSlot slot,
|
||||
Func<AetheriaControl> resolveControl,
|
||||
GameSettings settings,
|
||||
EquippedItem item,
|
||||
IActivatedBehavior behavior) : base(entity, slot, resolveControl, settings)
|
||||
public ActionBarGearBinding(Entity entity, ActionBarSlot slot, EquippedItem item, IActivatedBehavior behavior) : base(entity, slot)
|
||||
{
|
||||
Item = item;
|
||||
var data = item.EquippableItem.Data.Value as EquippableItemData;
|
||||
Behavior = behavior;
|
||||
Slot.QuantityRemaining.gameObject.SetActive(false);
|
||||
Slot.Icon.gameObject.SetActive(true);
|
||||
Slot.Label.gameObject.SetActive(false);
|
||||
Slot.Icon.texture = ResolveIconTexture();
|
||||
}
|
||||
|
||||
private Texture2D ResolveIconTexture()
|
||||
{
|
||||
var typedItem = FindCatalogItem(Item.EquippableItem);
|
||||
if (typedItem != null)
|
||||
{
|
||||
var actionBarIcon = LoadActionBarIcon(typedItem.ActionBarIcon);
|
||||
if (actionBarIcon != null)
|
||||
return actionBarIcon;
|
||||
|
||||
if (Enum.TryParse<WeaponType>(typedItem.WeaponType, out var weaponType))
|
||||
return Settings.GetIcon(weaponType).texture;
|
||||
|
||||
if (Enum.TryParse<HardpointType>(typedItem.HardpointType, out var hardpointType))
|
||||
return Settings.GetIcon(hardpointType).texture;
|
||||
}
|
||||
|
||||
return Settings.GetIcon(HardpointType.Tool).texture;
|
||||
}
|
||||
|
||||
private static Texture2D LoadActionBarIcon(string path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path))
|
||||
return null;
|
||||
|
||||
const string resourcesPrefix = "Assets/Resources/";
|
||||
var resourcePath = path.StartsWith(resourcesPrefix, StringComparison.Ordinal)
|
||||
? path.Substring(resourcesPrefix.Length)
|
||||
: path;
|
||||
|
||||
resourcePath = resourcePath.Split('.').First();
|
||||
return Resources.Load<Texture2D>(resourcePath);
|
||||
if (!string.IsNullOrEmpty(Item.Data.ActionBarIcon))
|
||||
Slot.Icon.texture = Resources.Load<Texture2D>(Item.Data.ActionBarIcon.Substring("Assets/Resources/".Length).Split('.').First());
|
||||
else if (data is WeaponItemData weaponItemData)
|
||||
Slot.Icon.texture = ActionGameManager.Instance.Settings.GetIcon(weaponItemData.WeaponType).texture;
|
||||
else Slot.Icon.texture = ActionGameManager.Instance.Settings.GetIcon(data.HardpointType).texture;
|
||||
}
|
||||
|
||||
public override void Activate()
|
||||
{
|
||||
Active = true;
|
||||
TrySubmit(
|
||||
operations => operations.SetBehaviorActive(EquipmentIndex, BehaviorIndex, true),
|
||||
"behavior activation");
|
||||
Behavior.Activate();
|
||||
}
|
||||
|
||||
public override void Deactivate()
|
||||
{
|
||||
Active = false;
|
||||
TrySubmit(
|
||||
operations => operations.SetBehaviorActive(EquipmentIndex, BehaviorIndex, false),
|
||||
"behavior activation");
|
||||
Behavior.Deactivate();
|
||||
}
|
||||
|
||||
public override void Update()
|
||||
|
|
@ -240,16 +175,12 @@ public class ActionBarGearBinding : ActionBarBinding
|
|||
}
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
public class ActionBarWeaponGroupBinding : ActionBarBinding
|
||||
{
|
||||
public int Group;
|
||||
[Key(0)] public int Group;
|
||||
|
||||
public ActionBarWeaponGroupBinding(
|
||||
Entity entity,
|
||||
ActionBarSlot slot,
|
||||
Func<AetheriaControl> resolveControl,
|
||||
GameSettings settings,
|
||||
int group) : base(entity, slot, resolveControl, settings)
|
||||
public ActionBarWeaponGroupBinding(Entity entity, ActionBarSlot slot, int group) : base(entity, slot)
|
||||
{
|
||||
Group = group;
|
||||
slot.Label.gameObject.SetActive(true);
|
||||
|
|
@ -259,20 +190,22 @@ public class ActionBarWeaponGroupBinding : ActionBarBinding
|
|||
|
||||
public override void Activate()
|
||||
{
|
||||
TrySubmit(
|
||||
operations => operations.SetWeaponGroupActive(Group, true),
|
||||
"weapon-group");
|
||||
foreach (var weapon in Entity.WeaponGroups[Group].weapons)
|
||||
{
|
||||
weapon.Activate();
|
||||
}
|
||||
}
|
||||
|
||||
public override void Deactivate()
|
||||
{
|
||||
TrySubmit(
|
||||
operations => operations.SetWeaponGroupActive(Group, false),
|
||||
"weapon-group");
|
||||
foreach (var weapon in Entity.WeaponGroups[Group].weapons)
|
||||
{
|
||||
weapon.Deactivate();
|
||||
}
|
||||
}
|
||||
|
||||
public override void Update()
|
||||
{
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,266 +0,0 @@
|
|||
using System.Collections.Generic;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
|
||||
public sealed class AetheriaDaemonIndirectRenderer : MonoBehaviour
|
||||
{
|
||||
[SerializeField]
|
||||
private AetheriaDaemonObserver observer;
|
||||
|
||||
[SerializeField]
|
||||
private AetheriaDaemonRenderAssetCatalog assetCatalog;
|
||||
|
||||
[SerializeField]
|
||||
private bool logMissingAssets;
|
||||
|
||||
[SerializeField]
|
||||
private Camera targetCamera;
|
||||
|
||||
private MaterialPropertyBlock _properties;
|
||||
private readonly Dictionary<int, AetheriaDaemonRenderGroupBatch> _batchesByGroupId =
|
||||
new Dictionary<int, AetheriaDaemonRenderGroupBatch>();
|
||||
private readonly HashSet<int> _seenGroupIds = new HashSet<int>();
|
||||
private readonly List<int> _staleGroupIds = new List<int>();
|
||||
private readonly List<AetheriaRuntimeDaemonRenderGroupDocument> _visibleRenderGroups =
|
||||
new List<AetheriaRuntimeDaemonRenderGroupDocument>();
|
||||
private readonly Vector3[] _frustumCorners = new Vector3[8];
|
||||
private static readonly int MatrixBufferPropertyId =
|
||||
Shader.PropertyToID(AetheriaDaemonRenderBuffer.MatrixBufferPropertyName);
|
||||
private static readonly int InstanceCountPropertyId =
|
||||
Shader.PropertyToID(AetheriaDaemonRenderBuffer.InstanceCountPropertyName);
|
||||
|
||||
public int LastDrawnCount { get; private set; }
|
||||
public bool HasDrawTarget =>
|
||||
observer != null &&
|
||||
assetCatalog != null;
|
||||
|
||||
private void Reset()
|
||||
{
|
||||
observer = GetComponent<AetheriaDaemonObserver>();
|
||||
}
|
||||
|
||||
private void LateUpdate()
|
||||
{
|
||||
DrawLatest();
|
||||
}
|
||||
|
||||
public bool DrawLatest()
|
||||
{
|
||||
LastDrawnCount = 0;
|
||||
if (!HasDrawTarget)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!observer.HasRenderNativeView)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_properties ??= new MaterialPropertyBlock();
|
||||
var drewAny = false;
|
||||
var index = observer.LastSoaIndex;
|
||||
var view = observer.LastRenderNativeView;
|
||||
_seenGroupIds.Clear();
|
||||
var renderGroups = QueryRenderGroups(index);
|
||||
foreach (var renderGroup in renderGroups)
|
||||
{
|
||||
_seenGroupIds.Add(renderGroup.GroupId);
|
||||
if (!TryResolveMesh(renderGroup, out var mesh) ||
|
||||
!TryResolveMaterial(renderGroup, out var material))
|
||||
{
|
||||
if (logMissingAssets)
|
||||
{
|
||||
Debug.LogWarning(
|
||||
$"Could not resolve daemon render group {renderGroup.GroupId} " +
|
||||
$"mesh='{renderGroup.MeshKey}' material='{renderGroup.MaterialKey}'.");
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!_batchesByGroupId.TryGetValue(renderGroup.GroupId, out var batch))
|
||||
{
|
||||
batch = new AetheriaDaemonRenderGroupBatch();
|
||||
_batchesByGroupId.Add(renderGroup.GroupId, batch);
|
||||
}
|
||||
|
||||
if (batch.LastUploadedGeneration != view.Generation)
|
||||
{
|
||||
batch.UploadLatest(view, renderGroup, mesh, renderGroup.DefaultScale);
|
||||
}
|
||||
|
||||
if (!batch.HasGpuBuffers)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
_properties.Clear();
|
||||
_properties.SetInt(InstanceCountPropertyId, batch.InstanceCount);
|
||||
_properties.SetBuffer(MatrixBufferPropertyId, batch.MatrixBuffer);
|
||||
|
||||
Graphics.DrawMeshInstancedIndirect(
|
||||
mesh,
|
||||
renderGroup.SubMeshIndex,
|
||||
material,
|
||||
GetDrawBounds(renderGroup),
|
||||
batch.IndirectArgsBuffer,
|
||||
0,
|
||||
_properties,
|
||||
GetShadowCastingMode(renderGroup),
|
||||
renderGroup.ReceiveShadows,
|
||||
renderGroup.Layer,
|
||||
targetCamera);
|
||||
|
||||
LastDrawnCount += batch.InstanceCount;
|
||||
drewAny = true;
|
||||
}
|
||||
|
||||
ReleaseStaleBatches();
|
||||
return drewAny;
|
||||
}
|
||||
|
||||
private IReadOnlyList<AetheriaRuntimeDaemonRenderGroupDocument> QueryRenderGroups(
|
||||
AetheriaRuntimeDaemonSoaViewIndex index)
|
||||
{
|
||||
if (!TryGetCameraQueryBounds(out var min, out var max))
|
||||
{
|
||||
return index.RenderGroups;
|
||||
}
|
||||
|
||||
AetheriaRuntimeDaemonRenderQueries.QueryRenderGroups(
|
||||
index,
|
||||
min.x,
|
||||
min.y,
|
||||
min.z,
|
||||
max.x,
|
||||
max.y,
|
||||
max.z,
|
||||
_visibleRenderGroups);
|
||||
return _visibleRenderGroups;
|
||||
}
|
||||
|
||||
private bool TryGetCameraQueryBounds(out Vector3 min, out Vector3 max)
|
||||
{
|
||||
var camera = targetCamera != null ? targetCamera : Camera.main;
|
||||
if (camera == null || !camera.enabled)
|
||||
{
|
||||
min = default;
|
||||
max = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
var near = Mathf.Max(0.0f, camera.nearClipPlane);
|
||||
var far = Mathf.Max(near, camera.farClipPlane);
|
||||
_frustumCorners[0] = camera.ViewportToWorldPoint(new Vector3(0, 0, near));
|
||||
_frustumCorners[1] = camera.ViewportToWorldPoint(new Vector3(1, 0, near));
|
||||
_frustumCorners[2] = camera.ViewportToWorldPoint(new Vector3(0, 1, near));
|
||||
_frustumCorners[3] = camera.ViewportToWorldPoint(new Vector3(1, 1, near));
|
||||
_frustumCorners[4] = camera.ViewportToWorldPoint(new Vector3(0, 0, far));
|
||||
_frustumCorners[5] = camera.ViewportToWorldPoint(new Vector3(1, 0, far));
|
||||
_frustumCorners[6] = camera.ViewportToWorldPoint(new Vector3(0, 1, far));
|
||||
_frustumCorners[7] = camera.ViewportToWorldPoint(new Vector3(1, 1, far));
|
||||
|
||||
min = _frustumCorners[0];
|
||||
max = _frustumCorners[0];
|
||||
for (var i = 1; i < _frustumCorners.Length; i++)
|
||||
{
|
||||
min = Vector3.Min(min, _frustumCorners[i]);
|
||||
max = Vector3.Max(max, _frustumCorners[i]);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private Bounds GetDrawBounds(AetheriaRuntimeDaemonRenderGroupDocument renderGroup)
|
||||
{
|
||||
return new Bounds(
|
||||
new Vector3(
|
||||
renderGroup.BoundsCenterX,
|
||||
renderGroup.BoundsCenterY,
|
||||
renderGroup.BoundsCenterZ),
|
||||
new Vector3(
|
||||
renderGroup.BoundsSizeX,
|
||||
renderGroup.BoundsSizeY,
|
||||
renderGroup.BoundsSizeZ));
|
||||
}
|
||||
|
||||
private static ShadowCastingMode GetShadowCastingMode(AetheriaRuntimeDaemonRenderGroupDocument renderGroup)
|
||||
{
|
||||
switch (renderGroup.ShadowMode)
|
||||
{
|
||||
case AetheriaRuntimeDaemonRenderShadowModes.Off:
|
||||
return ShadowCastingMode.Off;
|
||||
case AetheriaRuntimeDaemonRenderShadowModes.TwoSided:
|
||||
return ShadowCastingMode.TwoSided;
|
||||
case AetheriaRuntimeDaemonRenderShadowModes.ShadowsOnly:
|
||||
return ShadowCastingMode.ShadowsOnly;
|
||||
default:
|
||||
return ShadowCastingMode.On;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
foreach (var batch in _batchesByGroupId.Values)
|
||||
{
|
||||
batch.Dispose();
|
||||
}
|
||||
|
||||
_batchesByGroupId.Clear();
|
||||
_seenGroupIds.Clear();
|
||||
}
|
||||
|
||||
private void ReleaseStaleBatches()
|
||||
{
|
||||
if (_batchesByGroupId.Count == _seenGroupIds.Count)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_staleGroupIds.Clear();
|
||||
foreach (var groupId in _batchesByGroupId.Keys)
|
||||
{
|
||||
if (!_seenGroupIds.Contains(groupId))
|
||||
{
|
||||
_staleGroupIds.Add(groupId);
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0; i < _staleGroupIds.Count; i++)
|
||||
{
|
||||
var groupId = _staleGroupIds[i];
|
||||
_batchesByGroupId[groupId].Dispose();
|
||||
_batchesByGroupId.Remove(groupId);
|
||||
}
|
||||
|
||||
_staleGroupIds.Clear();
|
||||
}
|
||||
|
||||
private bool TryResolveMesh(AetheriaRuntimeDaemonRenderGroupDocument renderGroup, out Mesh mesh)
|
||||
{
|
||||
if (renderGroup?.MeshAsset != null &&
|
||||
!string.IsNullOrWhiteSpace(renderGroup.MeshAsset.AssetKey) &&
|
||||
assetCatalog.TryResolveMesh(renderGroup.MeshAsset, out mesh))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
mesh = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool TryResolveMaterial(AetheriaRuntimeDaemonRenderGroupDocument renderGroup, out Material material)
|
||||
{
|
||||
if (renderGroup?.MaterialAsset != null &&
|
||||
!string.IsNullOrWhiteSpace(renderGroup.MaterialAsset.AssetKey) &&
|
||||
assetCatalog.TryResolveMaterial(renderGroup.MaterialAsset, out material))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
material = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 66b38a2f45120a041941eae4412f7da1
|
||||
|
|
@ -1,168 +0,0 @@
|
|||
using System;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using UnityEngine;
|
||||
|
||||
public sealed class AetheriaDaemonObserver : MonoBehaviour
|
||||
{
|
||||
[SerializeField]
|
||||
private bool pollInUpdate = true;
|
||||
|
||||
[SerializeField]
|
||||
private float pollIntervalSeconds = 0.05f;
|
||||
|
||||
[SerializeField]
|
||||
private bool logChanges;
|
||||
|
||||
[SerializeField]
|
||||
private string clientId = "unity-observer";
|
||||
|
||||
private readonly AetheriaRuntimeDaemonObservationCursor _cursor = new AetheriaRuntimeDaemonObservationCursor();
|
||||
private float _nextPollTime;
|
||||
private AetheriaDaemonSoaMemoryMap _soaMemoryMap;
|
||||
private AetheriaDaemonRenderNativeView _renderNativeView;
|
||||
private AetheriaUnityDaemonRenderDocuments _renderDocuments;
|
||||
|
||||
public AetheriaRuntimeDaemonRenderView LastRenderView { get; private set; }
|
||||
public AetheriaRuntimeDaemonObservationResult LastObservation { get; private set; }
|
||||
public long LastFrameId => _cursor.LastFrameId;
|
||||
public long LastSoaGeneration => _cursor.LastSoaGeneration;
|
||||
public bool HasAuthoritativeState => LastRenderView != null && LastRenderView.IsAuthoritative;
|
||||
public bool HasSoaView => LastRenderView != null && LastRenderView.HasSoaView;
|
||||
public AetheriaRuntimeDaemonSoaViewIndex LastSoaIndex =>
|
||||
LastRenderView?.SoaIndex ?? AetheriaRuntimeDaemonSoaViewIndex.Empty;
|
||||
public AetheriaDaemonSoaMemoryMap LastSoaMemoryMap => _soaMemoryMap;
|
||||
public AetheriaDaemonRenderNativeView LastRenderNativeView => _renderNativeView;
|
||||
public bool HasRenderNativeView => _renderNativeView.IsCreated;
|
||||
|
||||
public event Action<AetheriaRuntimeDaemonRenderView, AetheriaRuntimeDaemonObservationResult> DaemonRenderViewChanged;
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (!pollInUpdate || Time.unscaledTime < _nextPollTime)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_nextPollTime = Time.unscaledTime + Mathf.Max(0.001f, pollIntervalSeconds);
|
||||
Poll();
|
||||
}
|
||||
|
||||
public bool Poll()
|
||||
{
|
||||
var observed = ReadDaemonRenderView();
|
||||
if (observed == null)
|
||||
{
|
||||
LastObservation = _cursor.Observe(null);
|
||||
return false;
|
||||
}
|
||||
|
||||
var result = _cursor.Observe(observed);
|
||||
LastRenderView = observed;
|
||||
LastObservation = result;
|
||||
|
||||
if (result.SoaViewChanged)
|
||||
{
|
||||
RemapSoaView(observed);
|
||||
}
|
||||
|
||||
if (result.Changed)
|
||||
{
|
||||
DaemonRenderViewChanged?.Invoke(observed, result);
|
||||
if (logChanges)
|
||||
{
|
||||
Debug.Log(
|
||||
$"Observed Aetheria daemon frame {result.FrameId} " +
|
||||
$"soa generation {result.SoaGeneration} authoritative={result.IsAuthoritative}");
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public void ResetObservation()
|
||||
{
|
||||
_cursor.Reset();
|
||||
DisposeRenderViewDocuments();
|
||||
DisposeSoaMemoryMap();
|
||||
LastRenderView = null;
|
||||
LastObservation = null;
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
DisposeRenderViewDocuments();
|
||||
DisposeSoaMemoryMap();
|
||||
}
|
||||
|
||||
private AetheriaRuntimeDaemonRenderView ReadDaemonRenderView()
|
||||
{
|
||||
try
|
||||
{
|
||||
EnsureRenderViewDocuments();
|
||||
return _renderDocuments?.Current;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureRenderViewDocuments()
|
||||
{
|
||||
if (_renderDocuments != null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var stateBoot = AetheriaRuntimeStateBoot.Inspect(AetheriaUnityRuntimePaths.GameDataDirectory);
|
||||
if (!stateBoot.SupportsLocalStateFileRead || !stateBoot.StateFileExists)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Aetheria daemon observer requires a readable managed Verse target: {stateBoot.FailureMessage}");
|
||||
}
|
||||
|
||||
_renderDocuments = AetheriaUnityRuntimeClientProvider.DaemonRenderDocuments(stateBoot, clientId);
|
||||
}
|
||||
|
||||
private void RemapSoaView(AetheriaRuntimeDaemonRenderView observed)
|
||||
{
|
||||
DisposeSoaMemoryMap();
|
||||
if (observed == null || !observed.HasSoaView)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (AetheriaDaemonSoaMemoryMap.TryOpen(observed.SoaIndex, out var map, out var error))
|
||||
{
|
||||
_soaMemoryMap = map;
|
||||
if (!AetheriaDaemonRenderNativeView.TryCreate(observed.SoaIndex, map, out _renderNativeView))
|
||||
{
|
||||
_renderNativeView = default;
|
||||
if (logChanges)
|
||||
{
|
||||
Debug.LogWarning("Mapped Aetheria daemon SoA memory, but no complete render native view was published.");
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (logChanges)
|
||||
{
|
||||
Debug.LogWarning($"Could not map Aetheria daemon SoA view read-only: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
private void DisposeSoaMemoryMap()
|
||||
{
|
||||
_renderNativeView = default;
|
||||
_soaMemoryMap?.Dispose();
|
||||
_soaMemoryMap = null;
|
||||
}
|
||||
|
||||
private void DisposeRenderViewDocuments()
|
||||
{
|
||||
_renderDocuments?.Dispose();
|
||||
_renderDocuments = null;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 4f5008a2876ee014fb9e442f1f6103e0
|
||||
|
|
@ -1,118 +0,0 @@
|
|||
using System;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using UnityEngine;
|
||||
|
||||
[CreateAssetMenu(
|
||||
fileName = "AetheriaDaemonRenderAssetCatalog",
|
||||
menuName = "Aetheria/Daemon Render Asset Catalog")]
|
||||
public sealed class AetheriaDaemonRenderAssetCatalog : ScriptableObject
|
||||
{
|
||||
[SerializeField]
|
||||
private MeshEntry[] meshes = Array.Empty<MeshEntry>();
|
||||
|
||||
[SerializeField]
|
||||
private MaterialEntry[] materials = Array.Empty<MaterialEntry>();
|
||||
|
||||
[SerializeField]
|
||||
private TextureEntry[] textures = Array.Empty<TextureEntry>();
|
||||
|
||||
public bool TryResolveMesh(string key, out Mesh mesh)
|
||||
{
|
||||
mesh = null;
|
||||
if (string.IsNullOrWhiteSpace(key))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
for (var i = 0; i < meshes.Length; i++)
|
||||
{
|
||||
if (string.Equals(meshes[i].Key, key, StringComparison.Ordinal))
|
||||
{
|
||||
mesh = meshes[i].Mesh;
|
||||
return mesh != null;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool TryResolveMesh(AetheriaRuntimeAssetRef asset, out Mesh mesh)
|
||||
{
|
||||
return TryResolveMesh(ResolveLocalKey(asset), out mesh);
|
||||
}
|
||||
|
||||
public bool TryResolveMaterial(string key, out Material material)
|
||||
{
|
||||
material = null;
|
||||
if (string.IsNullOrWhiteSpace(key))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
for (var i = 0; i < materials.Length; i++)
|
||||
{
|
||||
if (string.Equals(materials[i].Key, key, StringComparison.Ordinal))
|
||||
{
|
||||
material = materials[i].Material;
|
||||
return material != null;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool TryResolveMaterial(AetheriaRuntimeAssetRef asset, out Material material)
|
||||
{
|
||||
return TryResolveMaterial(ResolveLocalKey(asset), out material);
|
||||
}
|
||||
|
||||
public bool TryResolveTexture(AetheriaRuntimeAssetRef asset, out Texture2D texture)
|
||||
{
|
||||
texture = null;
|
||||
var key = ResolveLocalKey(asset);
|
||||
if (string.IsNullOrWhiteSpace(key))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
for (var i = 0; i < textures.Length; i++)
|
||||
{
|
||||
if (string.Equals(textures[i].Key, key, StringComparison.Ordinal))
|
||||
{
|
||||
texture = textures[i].Texture;
|
||||
return texture != null;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static string ResolveLocalKey(AetheriaRuntimeAssetRef asset)
|
||||
{
|
||||
if (asset == null)
|
||||
return "";
|
||||
|
||||
return string.IsNullOrWhiteSpace(asset.AssetKey) ? asset.Uri ?? "" : asset.AssetKey;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
private struct MeshEntry
|
||||
{
|
||||
public string Key;
|
||||
public Mesh Mesh;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
private struct MaterialEntry
|
||||
{
|
||||
public string Key;
|
||||
public Material Material;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
private struct TextureEntry
|
||||
{
|
||||
public string Key;
|
||||
public Texture2D Texture;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 8fa370b1ea2904d40ae295007ac76b48
|
||||
|
|
@ -1,292 +0,0 @@
|
|||
using GameCult.Aetheria.State.Verse;
|
||||
using Unity.Collections;
|
||||
using Unity.Jobs;
|
||||
using Unity.Mathematics;
|
||||
using UnityEngine;
|
||||
|
||||
public sealed class AetheriaDaemonRenderBuffer : MonoBehaviour
|
||||
{
|
||||
public const string MatrixBufferPropertyName = "_AetheriaObjectToWorld";
|
||||
public const string InstanceCountPropertyName = "_AetheriaInstanceCount";
|
||||
|
||||
private const int MatrixStrideBytes = 64;
|
||||
private const int DrawMeshInstancedIndirectArgsCount = 5;
|
||||
|
||||
[SerializeField]
|
||||
private AetheriaDaemonObserver observer;
|
||||
|
||||
[SerializeField]
|
||||
private Mesh indirectArgsMesh;
|
||||
|
||||
[SerializeField]
|
||||
private int innerLoopBatchCount = 64;
|
||||
|
||||
[SerializeField]
|
||||
private bool updateInLateUpdate;
|
||||
|
||||
private readonly uint[] _indirectArgs = new uint[DrawMeshInstancedIndirectArgsCount];
|
||||
private NativeArray<float4x4> _nativeMatrices;
|
||||
private GraphicsBuffer _matrixBuffer;
|
||||
private GraphicsBuffer _indirectArgsBuffer;
|
||||
private long _allocatedGeneration = long.MinValue;
|
||||
private int _allocatedCount;
|
||||
|
||||
public GraphicsBuffer MatrixBuffer => _matrixBuffer;
|
||||
public GraphicsBuffer IndirectArgsBuffer => _indirectArgsBuffer;
|
||||
public int InstanceCount { get; private set; }
|
||||
public long LastUploadedFrameId { get; private set; }
|
||||
public long LastUploadedGeneration { get; private set; }
|
||||
public bool HasRenderableView => observer != null && observer.HasRenderNativeView;
|
||||
public bool HasGpuBuffers =>
|
||||
_matrixBuffer != null &&
|
||||
_matrixBuffer.IsValid() &&
|
||||
InstanceCount > 0;
|
||||
|
||||
private static readonly int MatrixBufferPropertyId = Shader.PropertyToID(MatrixBufferPropertyName);
|
||||
private static readonly int InstanceCountPropertyId = Shader.PropertyToID(InstanceCountPropertyName);
|
||||
|
||||
private void Reset()
|
||||
{
|
||||
observer = GetComponent<AetheriaDaemonObserver>();
|
||||
}
|
||||
|
||||
private void LateUpdate()
|
||||
{
|
||||
if (updateInLateUpdate)
|
||||
{
|
||||
UploadLatest();
|
||||
}
|
||||
}
|
||||
|
||||
public bool UploadLatest()
|
||||
{
|
||||
return UploadLatest(indirectArgsMesh);
|
||||
}
|
||||
|
||||
public bool UploadLatest(Mesh argsMesh)
|
||||
{
|
||||
return UploadLatest(argsMesh, -1);
|
||||
}
|
||||
|
||||
public bool UploadLatest(Mesh argsMesh, int renderGroupId)
|
||||
{
|
||||
return UploadLatest(argsMesh, renderGroupId, 0);
|
||||
}
|
||||
|
||||
public bool UploadLatest(Mesh argsMesh, int renderGroupId, int subMeshIndex)
|
||||
{
|
||||
if (!HasRenderableView)
|
||||
{
|
||||
InstanceCount = 0;
|
||||
UpdateIndirectArgs(null, 0);
|
||||
return false;
|
||||
}
|
||||
|
||||
var view = observer.LastRenderNativeView;
|
||||
EnsureCapacity(view);
|
||||
if (!_nativeMatrices.IsCreated || _nativeMatrices.Length == 0)
|
||||
{
|
||||
InstanceCount = 0;
|
||||
UpdateIndirectArgs(argsMesh, 0);
|
||||
return false;
|
||||
}
|
||||
|
||||
var index = observer.LastSoaIndex;
|
||||
var defaultScale = ResolveDefaultScale(index, renderGroupId);
|
||||
var renderLod = ResolveRenderLod(index, renderGroupId);
|
||||
var count = renderGroupId >= 0 && view.HasRenderGroupId
|
||||
? BuildRenderGroupMatrices(view, renderGroupId, renderLod, defaultScale)
|
||||
: BuildAllMatrices(view, renderLod, defaultScale);
|
||||
|
||||
_matrixBuffer.SetData(_nativeMatrices, 0, 0, count);
|
||||
InstanceCount = count;
|
||||
LastUploadedFrameId = view.FrameId;
|
||||
LastUploadedGeneration = view.Generation;
|
||||
UpdateIndirectArgs(argsMesh, count, subMeshIndex);
|
||||
return true;
|
||||
}
|
||||
|
||||
private int BuildAllMatrices(AetheriaDaemonRenderNativeView view, int renderLod, float defaultScale)
|
||||
{
|
||||
if (view.HasRenderVisibility || renderLod >= 0)
|
||||
{
|
||||
return BuildCompactedMatrices(view, -1, renderLod, defaultScale);
|
||||
}
|
||||
|
||||
var count = math.min(view.Count, _nativeMatrices.Length);
|
||||
var handle = view.ScheduleBuildRenderMatrices(
|
||||
_nativeMatrices,
|
||||
defaultScale,
|
||||
innerLoopBatchCount);
|
||||
handle.Complete();
|
||||
return count;
|
||||
}
|
||||
|
||||
private int BuildRenderGroupMatrices(
|
||||
AetheriaDaemonRenderNativeView view,
|
||||
int renderGroupId,
|
||||
int renderLod,
|
||||
float defaultScale)
|
||||
{
|
||||
return BuildCompactedMatrices(view, renderGroupId, renderLod, defaultScale);
|
||||
}
|
||||
|
||||
private int BuildCompactedMatrices(
|
||||
AetheriaDaemonRenderNativeView view,
|
||||
int renderGroupId,
|
||||
int renderLod,
|
||||
float defaultScale)
|
||||
{
|
||||
using var writtenCount = new NativeArray<int>(1, Allocator.TempJob);
|
||||
var job = new AetheriaDaemonRenderGroupMatrixJob
|
||||
{
|
||||
Position = view.Position,
|
||||
RotationRadians = view.RotationRadians,
|
||||
PhysicsBodyRadius = view.PhysicsBodyRadius,
|
||||
RenderScale = view.RenderScale,
|
||||
RenderVisibility = view.RenderVisibility,
|
||||
RenderLod = view.RenderLod,
|
||||
RenderGroupId = view.RenderGroupId,
|
||||
Matrices = _nativeMatrices,
|
||||
WrittenCount = writtenCount,
|
||||
TargetRenderGroupId = renderGroupId >= 0 ? (uint)renderGroupId : 0,
|
||||
TargetRenderLod = renderLod,
|
||||
HasRotation = view.HasRotation,
|
||||
HasPhysicsRadius = view.HasPhysicsRadius,
|
||||
HasRenderScale = view.HasRenderScale,
|
||||
HasRenderVisibility = view.HasRenderVisibility,
|
||||
HasRenderLod = view.HasRenderLod,
|
||||
HasRenderGroupFilter = renderGroupId >= 0,
|
||||
HasRenderLodFilter = renderLod >= 0,
|
||||
UniformScale = defaultScale
|
||||
};
|
||||
|
||||
job.Schedule().Complete();
|
||||
return math.clamp(writtenCount[0], 0, _nativeMatrices.Length);
|
||||
}
|
||||
|
||||
private static float ResolveDefaultScale(AetheriaRuntimeDaemonSoaViewIndex index, int renderGroupId)
|
||||
{
|
||||
if (index != null &&
|
||||
renderGroupId >= 0 &&
|
||||
index.TryGetRenderGroup(renderGroupId, out var renderGroup))
|
||||
{
|
||||
return math.max(renderGroup.DefaultScale, 0.0001f);
|
||||
}
|
||||
|
||||
var renderGroups = index?.RenderGroups;
|
||||
if (renderGroups != null && renderGroups.Count == 1)
|
||||
{
|
||||
return math.max(renderGroups[0].DefaultScale, 0.0001f);
|
||||
}
|
||||
|
||||
return 1.0f;
|
||||
}
|
||||
|
||||
private static int ResolveRenderLod(AetheriaRuntimeDaemonSoaViewIndex index, int renderGroupId)
|
||||
{
|
||||
if (index != null &&
|
||||
renderGroupId >= 0 &&
|
||||
index.TryGetRenderGroup(renderGroupId, out var renderGroup))
|
||||
{
|
||||
return renderGroup.Lod;
|
||||
}
|
||||
|
||||
var renderGroups = index?.RenderGroups;
|
||||
if (renderGroups != null && renderGroups.Count == 1)
|
||||
{
|
||||
return renderGroups[0].Lod;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
public void ApplyTo(MaterialPropertyBlock properties)
|
||||
{
|
||||
if (properties == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
properties.SetInt(InstanceCountPropertyId, InstanceCount);
|
||||
if (HasGpuBuffers)
|
||||
{
|
||||
properties.SetBuffer(MatrixBufferPropertyId, _matrixBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
ReleaseBuffers();
|
||||
InstanceCount = 0;
|
||||
LastUploadedFrameId = 0;
|
||||
LastUploadedGeneration = 0;
|
||||
}
|
||||
|
||||
private void EnsureCapacity(AetheriaDaemonRenderNativeView view)
|
||||
{
|
||||
var count = math.max(0, view.Count);
|
||||
if (_nativeMatrices.IsCreated &&
|
||||
_allocatedGeneration == view.Generation &&
|
||||
_allocatedCount == count)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
ReleaseBuffers();
|
||||
_allocatedGeneration = view.Generation;
|
||||
_allocatedCount = count;
|
||||
if (count <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_nativeMatrices = new NativeArray<float4x4>(
|
||||
count,
|
||||
Allocator.Persistent,
|
||||
NativeArrayOptions.UninitializedMemory);
|
||||
_matrixBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, count, MatrixStrideBytes);
|
||||
_indirectArgsBuffer = new GraphicsBuffer(
|
||||
GraphicsBuffer.Target.IndirectArguments,
|
||||
DrawMeshInstancedIndirectArgsCount,
|
||||
sizeof(uint));
|
||||
}
|
||||
|
||||
private void UpdateIndirectArgs(Mesh mesh, int instanceCount)
|
||||
{
|
||||
UpdateIndirectArgs(mesh, instanceCount, 0);
|
||||
}
|
||||
|
||||
private void UpdateIndirectArgs(Mesh mesh, int instanceCount, int subMeshIndex)
|
||||
{
|
||||
if (_indirectArgsBuffer == null || !_indirectArgsBuffer.IsValid())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var safeSubMeshIndex = mesh != null
|
||||
? math.clamp(subMeshIndex, 0, math.max(0, mesh.subMeshCount - 1))
|
||||
: 0;
|
||||
_indirectArgs[0] = mesh != null ? mesh.GetIndexCount(safeSubMeshIndex) : 0;
|
||||
_indirectArgs[1] = (uint)math.max(0, instanceCount);
|
||||
_indirectArgs[2] = mesh != null ? mesh.GetIndexStart(safeSubMeshIndex) : 0;
|
||||
_indirectArgs[3] = mesh != null ? mesh.GetBaseVertex(safeSubMeshIndex) : 0;
|
||||
_indirectArgs[4] = 0;
|
||||
_indirectArgsBuffer.SetData(_indirectArgs);
|
||||
}
|
||||
|
||||
private void ReleaseBuffers()
|
||||
{
|
||||
if (_nativeMatrices.IsCreated)
|
||||
{
|
||||
_nativeMatrices.Dispose();
|
||||
}
|
||||
|
||||
_matrixBuffer?.Release();
|
||||
_matrixBuffer = null;
|
||||
_indirectArgsBuffer?.Release();
|
||||
_indirectArgsBuffer = null;
|
||||
_allocatedGeneration = long.MinValue;
|
||||
_allocatedCount = 0;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 9cba277ef259bee438796ab4c0f3df64
|
||||
|
|
@ -1,175 +0,0 @@
|
|||
using System;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using Unity.Collections;
|
||||
using Unity.Jobs;
|
||||
using Unity.Mathematics;
|
||||
using UnityEngine;
|
||||
|
||||
public sealed class AetheriaDaemonRenderGroupBatch : IDisposable
|
||||
{
|
||||
private const int MatrixStrideBytes = 64;
|
||||
private const int DrawMeshInstancedIndirectArgsCount = 5;
|
||||
|
||||
private readonly uint[] _indirectArgs = new uint[DrawMeshInstancedIndirectArgsCount];
|
||||
private NativeArray<float4x4> _nativeMatrices;
|
||||
private GraphicsBuffer _matrixBuffer;
|
||||
private GraphicsBuffer _indirectArgsBuffer;
|
||||
private int _capacity;
|
||||
|
||||
public int GroupId { get; private set; }
|
||||
public int InstanceCount { get; private set; }
|
||||
public long LastUploadedFrameId { get; private set; }
|
||||
public long LastUploadedGeneration { get; private set; }
|
||||
public GraphicsBuffer MatrixBuffer => _matrixBuffer;
|
||||
public GraphicsBuffer IndirectArgsBuffer => _indirectArgsBuffer;
|
||||
public bool HasGpuBuffers =>
|
||||
_matrixBuffer != null &&
|
||||
_matrixBuffer.IsValid() &&
|
||||
_indirectArgsBuffer != null &&
|
||||
_indirectArgsBuffer.IsValid() &&
|
||||
InstanceCount > 0;
|
||||
|
||||
public bool UploadLatest(
|
||||
AetheriaDaemonRenderNativeView view,
|
||||
AetheriaRuntimeDaemonRenderGroupDocument renderGroup,
|
||||
Mesh mesh,
|
||||
float uniformScale)
|
||||
{
|
||||
if (!view.IsCreated || mesh == null)
|
||||
{
|
||||
InstanceCount = 0;
|
||||
UpdateIndirectArgs(mesh, 0, renderGroup?.SubMeshIndex ?? 0);
|
||||
return false;
|
||||
}
|
||||
|
||||
var targetCapacity = renderGroup.InstanceCount >= 0
|
||||
? math.min(renderGroup.InstanceCount, view.Count)
|
||||
: view.Count;
|
||||
EnsureCapacity(targetCapacity);
|
||||
if (!_nativeMatrices.IsCreated || _nativeMatrices.Length == 0)
|
||||
{
|
||||
InstanceCount = 0;
|
||||
UpdateIndirectArgs(mesh, 0, renderGroup.SubMeshIndex);
|
||||
return false;
|
||||
}
|
||||
|
||||
var count = view.HasRenderGroupId
|
||||
? BuildRenderGroupMatrices(view, renderGroup.GroupId, renderGroup.Lod, uniformScale)
|
||||
: BuildAllMatrices(view, renderGroup.Lod, uniformScale);
|
||||
|
||||
_matrixBuffer.SetData(_nativeMatrices, 0, 0, count);
|
||||
GroupId = renderGroup.GroupId;
|
||||
InstanceCount = count;
|
||||
LastUploadedFrameId = view.FrameId;
|
||||
LastUploadedGeneration = view.Generation;
|
||||
UpdateIndirectArgs(mesh, count, renderGroup.SubMeshIndex);
|
||||
return count > 0;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_nativeMatrices.IsCreated)
|
||||
{
|
||||
_nativeMatrices.Dispose();
|
||||
}
|
||||
|
||||
_matrixBuffer?.Release();
|
||||
_matrixBuffer = null;
|
||||
_indirectArgsBuffer?.Release();
|
||||
_indirectArgsBuffer = null;
|
||||
_capacity = 0;
|
||||
InstanceCount = 0;
|
||||
}
|
||||
|
||||
private int BuildAllMatrices(AetheriaDaemonRenderNativeView view, int renderLod, float uniformScale)
|
||||
{
|
||||
return BuildCompactedMatrices(view, -1, renderLod, uniformScale);
|
||||
}
|
||||
|
||||
private int BuildRenderGroupMatrices(
|
||||
AetheriaDaemonRenderNativeView view,
|
||||
int renderGroupId,
|
||||
int renderLod,
|
||||
float uniformScale)
|
||||
{
|
||||
return BuildCompactedMatrices(view, renderGroupId, renderLod, uniformScale);
|
||||
}
|
||||
|
||||
private int BuildCompactedMatrices(
|
||||
AetheriaDaemonRenderNativeView view,
|
||||
int renderGroupId,
|
||||
int renderLod,
|
||||
float uniformScale)
|
||||
{
|
||||
using var writtenCount = new NativeArray<int>(1, Allocator.TempJob);
|
||||
var job = new AetheriaDaemonRenderGroupMatrixJob
|
||||
{
|
||||
Position = view.Position,
|
||||
RotationRadians = view.RotationRadians,
|
||||
PhysicsBodyRadius = view.PhysicsBodyRadius,
|
||||
RenderScale = view.RenderScale,
|
||||
RenderVisibility = view.RenderVisibility,
|
||||
RenderLod = view.RenderLod,
|
||||
RenderGroupId = view.RenderGroupId,
|
||||
Matrices = _nativeMatrices,
|
||||
WrittenCount = writtenCount,
|
||||
TargetRenderGroupId = renderGroupId >= 0 ? (uint)renderGroupId : 0,
|
||||
TargetRenderLod = renderLod,
|
||||
HasRotation = view.HasRotation,
|
||||
HasPhysicsRadius = view.HasPhysicsRadius,
|
||||
HasRenderScale = view.HasRenderScale,
|
||||
HasRenderVisibility = view.HasRenderVisibility,
|
||||
HasRenderLod = view.HasRenderLod,
|
||||
HasRenderGroupFilter = renderGroupId >= 0,
|
||||
HasRenderLodFilter = renderLod >= 0,
|
||||
UniformScale = uniformScale
|
||||
};
|
||||
|
||||
job.Schedule().Complete();
|
||||
return math.clamp(writtenCount[0], 0, _nativeMatrices.Length);
|
||||
}
|
||||
|
||||
private void EnsureCapacity(int capacity)
|
||||
{
|
||||
capacity = math.max(0, capacity);
|
||||
if (_nativeMatrices.IsCreated && _capacity == capacity)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Dispose();
|
||||
_capacity = capacity;
|
||||
if (capacity <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_nativeMatrices = new NativeArray<float4x4>(
|
||||
capacity,
|
||||
Allocator.Persistent,
|
||||
NativeArrayOptions.UninitializedMemory);
|
||||
_matrixBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, capacity, MatrixStrideBytes);
|
||||
_indirectArgsBuffer = new GraphicsBuffer(
|
||||
GraphicsBuffer.Target.IndirectArguments,
|
||||
DrawMeshInstancedIndirectArgsCount,
|
||||
sizeof(uint));
|
||||
}
|
||||
|
||||
private void UpdateIndirectArgs(Mesh mesh, int instanceCount, int subMeshIndex)
|
||||
{
|
||||
if (_indirectArgsBuffer == null || !_indirectArgsBuffer.IsValid())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var safeSubMeshIndex = mesh != null
|
||||
? math.clamp(subMeshIndex, 0, math.max(0, mesh.subMeshCount - 1))
|
||||
: 0;
|
||||
_indirectArgs[0] = mesh != null ? mesh.GetIndexCount(safeSubMeshIndex) : 0;
|
||||
_indirectArgs[1] = (uint)math.max(0, instanceCount);
|
||||
_indirectArgs[2] = mesh != null ? mesh.GetIndexStart(safeSubMeshIndex) : 0;
|
||||
_indirectArgs[3] = mesh != null ? mesh.GetBaseVertex(safeSubMeshIndex) : 0;
|
||||
_indirectArgs[4] = 0;
|
||||
_indirectArgsBuffer.SetData(_indirectArgs);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 0038a222765ff82468c22a516cfcdbc1
|
||||
|
|
@ -1,86 +0,0 @@
|
|||
using Unity.Burst;
|
||||
using Unity.Collections;
|
||||
using Unity.Jobs;
|
||||
using Unity.Mathematics;
|
||||
|
||||
[BurstCompile]
|
||||
public struct AetheriaDaemonRenderGroupMatrixJob : IJob
|
||||
{
|
||||
[ReadOnly]
|
||||
public NativeArray<float3> Position;
|
||||
|
||||
[ReadOnly]
|
||||
public NativeArray<float> RotationRadians;
|
||||
|
||||
[ReadOnly]
|
||||
public NativeArray<float> PhysicsBodyRadius;
|
||||
|
||||
[ReadOnly]
|
||||
public NativeArray<float> RenderScale;
|
||||
|
||||
[ReadOnly]
|
||||
public NativeArray<byte> RenderVisibility;
|
||||
|
||||
[ReadOnly]
|
||||
public NativeArray<int> RenderLod;
|
||||
|
||||
[ReadOnly]
|
||||
public NativeArray<uint> RenderGroupId;
|
||||
|
||||
[WriteOnly]
|
||||
public NativeArray<float4x4> Matrices;
|
||||
|
||||
public NativeArray<int> WrittenCount;
|
||||
public uint TargetRenderGroupId;
|
||||
public int TargetRenderLod;
|
||||
public bool HasRotation;
|
||||
public bool HasPhysicsRadius;
|
||||
public bool HasRenderScale;
|
||||
public bool HasRenderVisibility;
|
||||
public bool HasRenderLod;
|
||||
public bool HasRenderGroupFilter;
|
||||
public bool HasRenderLodFilter;
|
||||
public float UniformScale;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var written = 0;
|
||||
for (var index = 0; index < Position.Length; index++)
|
||||
{
|
||||
if (HasRenderGroupFilter && RenderGroupId[index] != TargetRenderGroupId)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (HasRenderVisibility && RenderVisibility[index] == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (HasRenderLodFilter && (!HasRenderLod || RenderLod[index] != TargetRenderLod))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (written >= Matrices.Length)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
var position = Position[index];
|
||||
var rotation = HasRotation
|
||||
? quaternion.RotateY(RotationRadians[index])
|
||||
: quaternion.identity;
|
||||
var scaleValue = HasRenderScale
|
||||
? math.max(RenderScale[index], 0.0001f)
|
||||
: HasPhysicsRadius
|
||||
? math.max(PhysicsBodyRadius[index] * 2.0f, 0.0001f)
|
||||
: math.max(UniformScale, 0.0001f);
|
||||
|
||||
Matrices[written] = float4x4.TRS(position, rotation, new float3(scaleValue));
|
||||
written++;
|
||||
}
|
||||
|
||||
WrittenCount[0] = written;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 146aa8d6d00cc1a44b44a5f83d69edea
|
||||
|
|
@ -1,43 +0,0 @@
|
|||
using Unity.Burst;
|
||||
using Unity.Collections;
|
||||
using Unity.Jobs;
|
||||
using Unity.Mathematics;
|
||||
|
||||
[BurstCompile]
|
||||
public struct AetheriaDaemonRenderMatrixJob : IJobParallelFor
|
||||
{
|
||||
[ReadOnly]
|
||||
public NativeArray<float3> Position;
|
||||
|
||||
[ReadOnly]
|
||||
public NativeArray<float> RotationRadians;
|
||||
|
||||
[ReadOnly]
|
||||
public NativeArray<float> PhysicsBodyRadius;
|
||||
|
||||
[ReadOnly]
|
||||
public NativeArray<float> RenderScale;
|
||||
|
||||
[WriteOnly]
|
||||
public NativeArray<float4x4> Matrices;
|
||||
|
||||
public bool HasRotation;
|
||||
public bool HasPhysicsRadius;
|
||||
public bool HasRenderScale;
|
||||
public float UniformScale;
|
||||
|
||||
public void Execute(int index)
|
||||
{
|
||||
var position = Position[index];
|
||||
var rotation = HasRotation
|
||||
? quaternion.RotateY(RotationRadians[index])
|
||||
: quaternion.identity;
|
||||
var scaleValue = HasRenderScale
|
||||
? math.max(RenderScale[index], 0.0001f)
|
||||
: HasPhysicsRadius
|
||||
? math.max(PhysicsBodyRadius[index] * 2.0f, 0.0001f)
|
||||
: math.max(UniformScale, 0.0001f);
|
||||
|
||||
Matrices[index] = float4x4.TRS(position, rotation, new float3(scaleValue));
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: f6b3b3dc2e2a29245a24b772e2cb87b4
|
||||
|
|
@ -1,248 +0,0 @@
|
|||
using GameCult.Aetheria.State.Verse;
|
||||
using Unity.Collections;
|
||||
using Unity.Jobs;
|
||||
using Unity.Mathematics;
|
||||
|
||||
public struct AetheriaDaemonRenderNativeView
|
||||
{
|
||||
public long FrameId;
|
||||
public long Generation;
|
||||
public int Count;
|
||||
public NativeArray<int> EntityIndex;
|
||||
public NativeArray<float3> Position;
|
||||
public NativeArray<float> RotationRadians;
|
||||
public NativeArray<float3> Velocity;
|
||||
public NativeArray<float> PhysicsBodyRadius;
|
||||
public NativeArray<float> PhysicsBodyMass;
|
||||
public NativeArray<float> PhysicsBodyInverseMass;
|
||||
public NativeArray<float> RenderScale;
|
||||
public NativeArray<byte> RenderVisibility;
|
||||
public NativeArray<int> RenderLod;
|
||||
public NativeArray<uint> RenderGroupId;
|
||||
|
||||
public bool IsCreated =>
|
||||
Count > 0 &&
|
||||
Position.IsCreated;
|
||||
|
||||
public bool HasRotation => RotationRadians.IsCreated;
|
||||
public bool HasEntityIndex => EntityIndex.IsCreated;
|
||||
public bool HasVelocity => Velocity.IsCreated;
|
||||
public bool HasPhysicsRadius => PhysicsBodyRadius.IsCreated;
|
||||
public bool HasPhysicsMass => PhysicsBodyMass.IsCreated;
|
||||
public bool HasPhysicsInverseMass => PhysicsBodyInverseMass.IsCreated;
|
||||
public bool HasRenderScale => RenderScale.IsCreated;
|
||||
public bool HasRenderVisibility => RenderVisibility.IsCreated;
|
||||
public bool HasRenderLod => RenderLod.IsCreated;
|
||||
public bool HasRenderGroupId => RenderGroupId.IsCreated;
|
||||
|
||||
public JobHandle ScheduleBuildRenderMatrices(
|
||||
NativeArray<float4x4> matrices,
|
||||
float uniformScale = 1.0f,
|
||||
int innerLoopBatchCount = 64,
|
||||
JobHandle dependsOn = default)
|
||||
{
|
||||
if (!IsCreated)
|
||||
{
|
||||
return dependsOn;
|
||||
}
|
||||
|
||||
var count = math.min(Count, matrices.IsCreated ? matrices.Length : 0);
|
||||
if (count <= 0)
|
||||
{
|
||||
return dependsOn;
|
||||
}
|
||||
|
||||
var job = new AetheriaDaemonRenderMatrixJob
|
||||
{
|
||||
Position = Position,
|
||||
RotationRadians = RotationRadians,
|
||||
PhysicsBodyRadius = PhysicsBodyRadius,
|
||||
RenderScale = RenderScale,
|
||||
Matrices = matrices,
|
||||
HasRotation = HasRotation,
|
||||
HasPhysicsRadius = HasPhysicsRadius,
|
||||
HasRenderScale = HasRenderScale,
|
||||
UniformScale = uniformScale
|
||||
};
|
||||
|
||||
return job.Schedule(count, math.max(1, innerLoopBatchCount), dependsOn);
|
||||
}
|
||||
|
||||
public static bool TryCreate(
|
||||
AetheriaRuntimeDaemonSoaViewIndex index,
|
||||
AetheriaDaemonSoaMemoryMap map,
|
||||
out AetheriaDaemonRenderNativeView view)
|
||||
{
|
||||
view = default;
|
||||
if (index == null || map == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!map.TryCreateFirstNativeArrayOfKind(
|
||||
index,
|
||||
AetheriaRuntimeDaemonSoaColumnKinds.Position,
|
||||
out view.Position))
|
||||
{
|
||||
view = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
view.Count = view.Position.Length;
|
||||
|
||||
TryAssignOptionalIntColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.EntityIndex, view.Count, out view.EntityIndex);
|
||||
TryAssignOptionalColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.RotationRadians, view.Count, out view.RotationRadians);
|
||||
TryAssignOptionalFloat3Column(index, map, AetheriaRuntimeDaemonSoaColumnKinds.Velocity, view.Count, out view.Velocity);
|
||||
TryAssignOptionalColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.PhysicsBodyRadius, view.Count, out view.PhysicsBodyRadius);
|
||||
TryAssignOptionalColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.PhysicsBodyMass, view.Count, out view.PhysicsBodyMass);
|
||||
TryAssignOptionalColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.PhysicsBodyInverseMass, view.Count, out view.PhysicsBodyInverseMass);
|
||||
TryAssignOptionalColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.RenderScale, view.Count, out view.RenderScale);
|
||||
TryAssignOptionalByteColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.RenderVisibility, view.Count, out view.RenderVisibility);
|
||||
TryAssignOptionalIntColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.RenderLod, view.Count, out view.RenderLod);
|
||||
TryAssignOptionalUIntColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.RenderGroupId, view.Count, out view.RenderGroupId);
|
||||
|
||||
view.FrameId = index.View.FrameId;
|
||||
view.Generation = index.View.Generation;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryAssignOptionalFloat3Column(
|
||||
AetheriaRuntimeDaemonSoaViewIndex index,
|
||||
AetheriaDaemonSoaMemoryMap map,
|
||||
string kind,
|
||||
int expectedCount,
|
||||
out NativeArray<float3> array)
|
||||
{
|
||||
array = default;
|
||||
if (!index.TryGetFirstColumnOfKind(kind, out _))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!map.TryCreateFirstNativeArrayOfKind(index, kind, out array))
|
||||
{
|
||||
array = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (array.Length == expectedCount)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
array = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryAssignOptionalColumn(
|
||||
AetheriaRuntimeDaemonSoaViewIndex index,
|
||||
AetheriaDaemonSoaMemoryMap map,
|
||||
string kind,
|
||||
int expectedCount,
|
||||
out NativeArray<float> array)
|
||||
{
|
||||
array = default;
|
||||
if (!index.TryGetFirstColumnOfKind(kind, out _))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!map.TryCreateFirstNativeArrayOfKind(index, kind, out array))
|
||||
{
|
||||
array = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (array.Length == expectedCount)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
array = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryAssignOptionalUIntColumn(
|
||||
AetheriaRuntimeDaemonSoaViewIndex index,
|
||||
AetheriaDaemonSoaMemoryMap map,
|
||||
string kind,
|
||||
int expectedCount,
|
||||
out NativeArray<uint> array)
|
||||
{
|
||||
array = default;
|
||||
if (!index.TryGetFirstColumnOfKind(kind, out _))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!map.TryCreateFirstNativeArrayOfKind(index, kind, out array))
|
||||
{
|
||||
array = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (array.Length == expectedCount)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
array = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryAssignOptionalIntColumn(
|
||||
AetheriaRuntimeDaemonSoaViewIndex index,
|
||||
AetheriaDaemonSoaMemoryMap map,
|
||||
string kind,
|
||||
int expectedCount,
|
||||
out NativeArray<int> array)
|
||||
{
|
||||
array = default;
|
||||
if (!index.TryGetFirstColumnOfKind(kind, out _))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!map.TryCreateFirstNativeArrayOfKind(index, kind, out array))
|
||||
{
|
||||
array = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (array.Length == expectedCount)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
array = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryAssignOptionalByteColumn(
|
||||
AetheriaRuntimeDaemonSoaViewIndex index,
|
||||
AetheriaDaemonSoaMemoryMap map,
|
||||
string kind,
|
||||
int expectedCount,
|
||||
out NativeArray<byte> array)
|
||||
{
|
||||
array = default;
|
||||
if (!index.TryGetFirstColumnOfKind(kind, out _))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!map.TryCreateFirstNativeArrayOfKind(index, kind, out array))
|
||||
{
|
||||
array = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (array.Length == expectedCount)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
array = default;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 48740dbd37e79954ca00a3f6bd7ccef1
|
||||
|
|
@ -1,220 +0,0 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO.MemoryMappedFiles;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using Unity.Collections;
|
||||
using Unity.Collections.LowLevel.Unsafe;
|
||||
|
||||
public unsafe sealed class AetheriaDaemonSoaMemoryMap : IDisposable
|
||||
{
|
||||
private readonly Dictionary<string, MappedBuffer> _buffersById =
|
||||
new Dictionary<string, MappedBuffer>(StringComparer.Ordinal);
|
||||
|
||||
#if ENABLE_UNITY_COLLECTIONS_CHECKS
|
||||
private readonly List<AtomicSafetyHandle> _safetyHandles = new List<AtomicSafetyHandle>();
|
||||
#endif
|
||||
|
||||
private bool _disposed;
|
||||
|
||||
private AetheriaDaemonSoaMemoryMap()
|
||||
{
|
||||
}
|
||||
|
||||
public static bool TryOpen(
|
||||
AetheriaRuntimeDaemonSoaViewIndex index,
|
||||
out AetheriaDaemonSoaMemoryMap map,
|
||||
out string error)
|
||||
{
|
||||
map = null;
|
||||
error = "";
|
||||
|
||||
if (index == null)
|
||||
{
|
||||
error = "No daemon SoA view index was provided.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!index.IsValid)
|
||||
{
|
||||
error = index.ValidationErrors.Count > 0
|
||||
? index.ValidationErrors[0]
|
||||
: "Daemon SoA view index is invalid.";
|
||||
return false;
|
||||
}
|
||||
|
||||
var opened = new AetheriaDaemonSoaMemoryMap();
|
||||
try
|
||||
{
|
||||
foreach (var buffer in index.View.Buffers)
|
||||
{
|
||||
if (!IsMappableReadOnlyBuffer(buffer))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
opened.OpenBuffer(buffer);
|
||||
}
|
||||
|
||||
map = opened;
|
||||
return true;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
opened.Dispose();
|
||||
error = exception.Message;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryCreateNativeArray<T>(
|
||||
AetheriaRuntimeDaemonSoaColumnBinding binding,
|
||||
out NativeArray<T> array)
|
||||
where T : struct
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
array = default;
|
||||
|
||||
if (binding == null ||
|
||||
!binding.DirectMemoryCompatible ||
|
||||
!_buffersById.TryGetValue(binding.Buffer.BufferId, out var buffer))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var byteOffset = checked((ulong)binding.AbsoluteByteOffset);
|
||||
var byteLength = checked((ulong)Math.Max(0, binding.ByteLength));
|
||||
if (byteOffset + byteLength > buffer.ByteLength)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var pointer = buffer.Pointer + byteOffset;
|
||||
array = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<T>(
|
||||
pointer,
|
||||
binding.Column.ElementCount,
|
||||
Allocator.None);
|
||||
|
||||
#if ENABLE_UNITY_COLLECTIONS_CHECKS
|
||||
var safetyHandle = AtomicSafetyHandle.Create();
|
||||
_safetyHandles.Add(safetyHandle);
|
||||
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref array, safetyHandle);
|
||||
#endif
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryCreateFirstNativeArrayOfKind<T>(
|
||||
AetheriaRuntimeDaemonSoaViewIndex index,
|
||||
string kind,
|
||||
out NativeArray<T> array)
|
||||
where T : struct
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
array = default;
|
||||
|
||||
if (index == null || !index.TryGetFirstColumnOfKind(kind, out var binding))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return TryCreateNativeArray(binding, out array);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
#if ENABLE_UNITY_COLLECTIONS_CHECKS
|
||||
for (var i = 0; i < _safetyHandles.Count; i++)
|
||||
{
|
||||
AtomicSafetyHandle.Release(_safetyHandles[i]);
|
||||
}
|
||||
|
||||
_safetyHandles.Clear();
|
||||
#endif
|
||||
|
||||
foreach (var buffer in _buffersById.Values)
|
||||
{
|
||||
buffer.Dispose();
|
||||
}
|
||||
|
||||
_buffersById.Clear();
|
||||
_disposed = true;
|
||||
}
|
||||
|
||||
private void OpenBuffer(AetheriaRuntimeDaemonSoaBufferDocument buffer)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(buffer.BufferId) ||
|
||||
_buffersById.ContainsKey(buffer.BufferId))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var byteLength = checked((ulong)(buffer.ByteOffset + buffer.ByteLength));
|
||||
var memoryMappedFile = MemoryMappedFile.OpenExisting(
|
||||
buffer.Location,
|
||||
MemoryMappedFileRights.Read);
|
||||
var accessor = memoryMappedFile.CreateViewAccessor(0, (long)byteLength, MemoryMappedFileAccess.Read);
|
||||
|
||||
byte* pointer = null;
|
||||
accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref pointer);
|
||||
|
||||
_buffersById.Add(
|
||||
buffer.BufferId,
|
||||
new MappedBuffer(memoryMappedFile, accessor, pointer, byteLength));
|
||||
}
|
||||
|
||||
private static bool IsMappableReadOnlyBuffer(AetheriaRuntimeDaemonSoaBufferDocument buffer)
|
||||
{
|
||||
return buffer != null &&
|
||||
!buffer.ObserverWritable &&
|
||||
!string.IsNullOrWhiteSpace(buffer.Location) &&
|
||||
string.Equals(buffer.Backend, AetheriaRuntimeDaemonSoaBackends.MemoryMappedFile, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private void ThrowIfDisposed()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
throw new ObjectDisposedException(nameof(AetheriaDaemonSoaMemoryMap));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class MappedBuffer : IDisposable
|
||||
{
|
||||
private readonly MemoryMappedFile _memoryMappedFile;
|
||||
private readonly MemoryMappedViewAccessor _accessor;
|
||||
private bool _disposed;
|
||||
|
||||
public MappedBuffer(
|
||||
MemoryMappedFile memoryMappedFile,
|
||||
MemoryMappedViewAccessor accessor,
|
||||
byte* pointer,
|
||||
ulong byteLength)
|
||||
{
|
||||
_memoryMappedFile = memoryMappedFile;
|
||||
_accessor = accessor;
|
||||
Pointer = pointer;
|
||||
ByteLength = byteLength;
|
||||
}
|
||||
|
||||
public byte* Pointer { get; }
|
||||
public ulong ByteLength { get; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_accessor.SafeMemoryMappedViewHandle.ReleasePointer();
|
||||
_accessor.Dispose();
|
||||
_memoryMappedFile.Dispose();
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: d8988c7d796df504dab64fd2c64eb868
|
||||
|
|
@ -1,95 +0,0 @@
|
|||
using System;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using GameCult.Eve.PluginFields;
|
||||
using GameCult.Eve.UnityScene.Fields;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
||||
public sealed class AetheriaRenderSplatLayerRenderer : MonoBehaviour
|
||||
{
|
||||
[SerializeField] private EveFieldsSplatLayerRenderer renderer;
|
||||
[SerializeField] private AetheriaRenderSplatLayerBinding[] bindings =
|
||||
{
|
||||
Binding(EveFieldsSplatLayerKeys.GravityHeight, "_AetheriaGravityHeight"),
|
||||
Binding(EveFieldsSplatLayerKeys.FogTint, "_NebulaTint"),
|
||||
Binding(EveFieldsSplatLayerKeys.FogSurfaceHeight, "_NebulaSurfaceHeight", 0.5f),
|
||||
Binding(EveFieldsSplatLayerKeys.FogPatchHeight, "_NebulaPatchHeight", 0.5f),
|
||||
Binding(EveFieldsSplatLayerKeys.FogPatch, "_NebulaPatch", 0.5f),
|
||||
Binding(EveFieldsSplatLayerKeys.Influence, "_AetheriaInfluence")
|
||||
};
|
||||
|
||||
public bool TryGetTexture(string layerKey, out RenderTexture texture)
|
||||
{
|
||||
ResolveRenderer();
|
||||
if (renderer != null) return renderer.TryGetTexture(layerKey, out texture);
|
||||
texture = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
public void Render(EveFieldsSplatsDocument document, int width, int height)
|
||||
{
|
||||
if (document == null) return;
|
||||
ResolveRenderer();
|
||||
if (renderer == null) return;
|
||||
var targets = new EveFieldsSplatLayerTarget[bindings?.Length ?? 0];
|
||||
for (var index = 0; index < targets.Length; index++) targets[index] = bindings[index]?.CreateTarget();
|
||||
renderer.Render(document, targets, width, height);
|
||||
for (var index = 0; index < targets.Length; index++)
|
||||
{
|
||||
var binding = bindings[index];
|
||||
var target = targets[index];
|
||||
if (binding == null || target?.TargetTexture == null) continue;
|
||||
binding.TargetTexture = target.TargetTexture;
|
||||
ApplyBinding(binding, target.TargetTexture);
|
||||
}
|
||||
}
|
||||
|
||||
private void ResolveRenderer()
|
||||
{
|
||||
if (renderer != null) return;
|
||||
renderer = GetComponent<EveFieldsSplatLayerRenderer>();
|
||||
if (renderer == null) renderer = gameObject.AddComponent<EveFieldsSplatLayerRenderer>();
|
||||
}
|
||||
|
||||
private static AetheriaRenderSplatLayerBinding Binding(string layerKey, string globalTextureName, float scale = 1f) =>
|
||||
new AetheriaRenderSplatLayerBinding { LayerKey = layerKey, GlobalTextureName = globalTextureName, WidthScale = scale, HeightScale = scale };
|
||||
|
||||
private static void ApplyBinding(AetheriaRenderSplatLayerBinding binding, RenderTexture texture)
|
||||
{
|
||||
if (binding.Display != null)
|
||||
{
|
||||
var material = binding.Display.material;
|
||||
if (material != null && !string.IsNullOrWhiteSpace(binding.MaterialTextureProperty)) material.SetTexture(binding.MaterialTextureProperty, texture);
|
||||
else binding.Display.material.mainTexture = texture;
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(binding.GlobalTextureName)) Shader.SetGlobalTexture(binding.GlobalTextureName, texture);
|
||||
}
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class AetheriaRenderSplatLayerBinding
|
||||
{
|
||||
public bool Enabled = true;
|
||||
public string LayerKey = "";
|
||||
public Image Display;
|
||||
public string MaterialTextureProperty = "_DetailTex";
|
||||
public string GlobalTextureName = "";
|
||||
public string GraphicsFormatOverride = "";
|
||||
public float WidthScale = 1f;
|
||||
public float HeightScale = 1f;
|
||||
public bool UseMipMaps;
|
||||
public FilterMode FilterMode = FilterMode.Bilinear;
|
||||
[NonSerialized] public RenderTexture TargetTexture;
|
||||
|
||||
public EveFieldsSplatLayerTarget CreateTarget() => new EveFieldsSplatLayerTarget
|
||||
{
|
||||
Enabled = Enabled,
|
||||
LayerKey = LayerKey,
|
||||
GraphicsFormatOverride = GraphicsFormatOverride,
|
||||
WidthScale = WidthScale,
|
||||
HeightScale = HeightScale,
|
||||
UseMipMaps = UseMipMaps,
|
||||
FilterMode = FilterMode,
|
||||
TargetTexture = TargetTexture
|
||||
};
|
||||
}
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
using GameCult.Eve.UnityScene.Fields;
|
||||
|
||||
// Existing scenes retain this MonoScript GUID while EveUnity owns projection.
|
||||
public sealed class AetheriaRenderSplatRasterizer : EveFieldsSplatRasterizer
|
||||
{
|
||||
}
|
||||
|
|
@ -1,13 +0,0 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
public sealed class AetheriaUnityActionBarBinding
|
||||
{
|
||||
public string ControlPath { get; set; } = "";
|
||||
public string Kind { get; set; } = "";
|
||||
public string ItemKey { get; set; } = "";
|
||||
public int EquipmentIndex { get; set; } = -1;
|
||||
public int BehaviorIndex { get; set; } = -1;
|
||||
public int WeaponGroup { get; set; } = -1;
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: af36b057bd1c2ba46adad018b02fd568
|
||||
|
|
@ -1,273 +0,0 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using UnityEngine;
|
||||
|
||||
public sealed class AetheriaUnityActionBarPresentation
|
||||
{
|
||||
private IReadOnlyList<ActionBarSlot> _slots = Array.Empty<ActionBarSlot>();
|
||||
private AetheriaRuntimeCatalogSnapshot _catalog;
|
||||
private GameSettings _settings;
|
||||
private Func<Entity> _resolveEntity = () => null;
|
||||
private Func<AetheriaControl> _resolveControl = () => null;
|
||||
private IReadOnlyList<AetheriaUnityActionBarBinding> _localBindings =
|
||||
Array.Empty<AetheriaUnityActionBarBinding>();
|
||||
|
||||
public void Bind(
|
||||
IReadOnlyList<ActionBarSlot> slots,
|
||||
AetheriaRuntimeCatalogSnapshot catalog,
|
||||
GameSettings settings,
|
||||
Func<Entity> resolveEntity,
|
||||
Func<AetheriaControl> resolveControl)
|
||||
{
|
||||
_slots = slots ?? Array.Empty<ActionBarSlot>();
|
||||
_catalog = catalog;
|
||||
_settings = settings;
|
||||
_resolveEntity = resolveEntity ?? (() => null);
|
||||
_resolveControl = resolveControl ?? (() => null);
|
||||
}
|
||||
|
||||
public int SlotCount => _slots?.Count ?? 0;
|
||||
|
||||
public string SlotLabel(int slotIndex)
|
||||
{
|
||||
var slot = ResolveSlot(slotIndex);
|
||||
if (slot == null)
|
||||
return "";
|
||||
|
||||
var controlPath = slot.ControlPath ?? "";
|
||||
if (string.IsNullOrWhiteSpace(controlPath))
|
||||
return "Action Bar";
|
||||
|
||||
var slashIndex = controlPath.LastIndexOf('/');
|
||||
return slashIndex >= 0 && slashIndex < controlPath.Length - 1
|
||||
? controlPath.Substring(slashIndex + 1)
|
||||
: controlPath;
|
||||
}
|
||||
|
||||
public string BindingLabel(int slotIndex)
|
||||
{
|
||||
var slot = ResolveSlot(slotIndex);
|
||||
return slot?.Binding switch
|
||||
{
|
||||
ActionBarWeaponGroupBinding weaponGroup => $"G{weaponGroup.Group + 1}",
|
||||
ActionBarConsumableBinding consumable => consumable.Target?.Name ?? "Consumable",
|
||||
ActionBarGearBinding gear => _catalog?.FindItem(gear.Item?.EquippableItem, x => x.ItemKey)?.Name ?? "Gear",
|
||||
_ => "Empty"
|
||||
};
|
||||
}
|
||||
|
||||
public bool TryResolveControlPath(int slotIndex, out string controlPath)
|
||||
{
|
||||
controlPath = ResolveSlot(slotIndex)?.ControlPath ?? "";
|
||||
return !string.IsNullOrWhiteSpace(controlPath);
|
||||
}
|
||||
|
||||
public void RequestBinding(ActionBarSlot slot, DragObject dragAction)
|
||||
{
|
||||
var entity = _resolveEntity();
|
||||
if (slot == null || dragAction == null || entity == null)
|
||||
return;
|
||||
|
||||
var binding = CreateBindingCommit(slot, entity, dragAction);
|
||||
if (binding == null ||
|
||||
string.IsNullOrWhiteSpace(binding.ControlPath) ||
|
||||
string.IsNullOrWhiteSpace(binding.Kind))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
SetLocalBinding(binding);
|
||||
ApplyLocalBindings();
|
||||
}
|
||||
|
||||
public bool RequestWeaponGroupBinding(int slotIndex, int groupIndex)
|
||||
{
|
||||
if (groupIndex < 0 || !TryResolveControlPath(slotIndex, out var controlPath))
|
||||
return false;
|
||||
|
||||
SetLocalBinding(new AetheriaUnityActionBarBinding
|
||||
{
|
||||
ControlPath = controlPath,
|
||||
Kind = "weapon_group",
|
||||
ItemKey = "",
|
||||
EquipmentIndex = -1,
|
||||
BehaviorIndex = -1,
|
||||
WeaponGroup = groupIndex
|
||||
});
|
||||
ApplyLocalBindings();
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool ClearBinding(int slotIndex)
|
||||
{
|
||||
if (!TryResolveControlPath(slotIndex, out var controlPath))
|
||||
return false;
|
||||
|
||||
_localBindings = (_localBindings ?? Array.Empty<AetheriaUnityActionBarBinding>())
|
||||
.Where(binding => !string.Equals(binding?.ControlPath ?? "", controlPath, StringComparison.Ordinal))
|
||||
.ToArray();
|
||||
ApplyLocalBindings();
|
||||
return true;
|
||||
}
|
||||
|
||||
public void ApplyLocalBindings()
|
||||
{
|
||||
ApplyBindings(_resolveEntity(), _localBindings);
|
||||
}
|
||||
|
||||
public void ApplyBindings(
|
||||
Entity entity,
|
||||
IReadOnlyList<AetheriaUnityActionBarBinding> bindings)
|
||||
{
|
||||
if (_slots == null || _slots.Count == 0)
|
||||
return;
|
||||
|
||||
foreach (var slot in _slots)
|
||||
slot.Binding = null;
|
||||
|
||||
if (entity == null || bindings == null || bindings.Count == 0)
|
||||
return;
|
||||
|
||||
var slotsByControlPath = _slots
|
||||
.Where(slot => !string.IsNullOrWhiteSpace(slot?.ControlPath))
|
||||
.GroupBy(slot => slot.ControlPath, StringComparer.Ordinal)
|
||||
.ToDictionary(group => group.Key, group => group.First(), StringComparer.Ordinal);
|
||||
|
||||
foreach (var binding in bindings)
|
||||
{
|
||||
if (binding == null ||
|
||||
string.IsNullOrWhiteSpace(binding.ControlPath) ||
|
||||
!slotsByControlPath.TryGetValue(binding.ControlPath, out var slot))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var slotBinding = CreateBinding(slot, entity, binding);
|
||||
if (slotBinding != null)
|
||||
slot.Binding = slotBinding;
|
||||
}
|
||||
}
|
||||
|
||||
public ActionBarBinding CreateBinding(ActionBarSlot slot, Entity entity, DragObject dragAction)
|
||||
{
|
||||
var binding = CreateBindingCommit(slot, entity, dragAction);
|
||||
return binding == null ? null : CreateBinding(slot, entity, binding);
|
||||
}
|
||||
|
||||
private AetheriaUnityActionBarBinding CreateBindingCommit(
|
||||
ActionBarSlot slot,
|
||||
Entity entity,
|
||||
DragObject dragAction)
|
||||
{
|
||||
if (slot == null || entity == null || dragAction == null)
|
||||
return null;
|
||||
|
||||
switch (dragAction)
|
||||
{
|
||||
case EquippedItemDragObject equippedItemDragAction:
|
||||
var equippedItem = equippedItemDragAction.EquippedItem;
|
||||
var trigger = equippedItem?.GetBehavior<IActivatedBehavior>();
|
||||
var equipmentIndex = equippedItem == null ? -1 : entity.Equipment.IndexOf(equippedItem);
|
||||
var behaviorIndex = equippedItem?.Behaviors == null ? -1 : Array.IndexOf(equippedItem.Behaviors, trigger);
|
||||
return trigger == null || equipmentIndex < 0 || behaviorIndex < 0
|
||||
? null
|
||||
: new AetheriaUnityActionBarBinding
|
||||
{
|
||||
ControlPath = slot.ControlPath ?? "",
|
||||
Kind = "gear",
|
||||
ItemKey = equippedItem.EquippableItem?.ItemKey ?? "",
|
||||
EquipmentIndex = equipmentIndex,
|
||||
BehaviorIndex = behaviorIndex
|
||||
};
|
||||
case ItemInstanceDragObject itemInstanceDragAction:
|
||||
var consumable = FindConsumable(itemInstanceDragAction.Item);
|
||||
return consumable == null
|
||||
? null
|
||||
: new AetheriaUnityActionBarBinding
|
||||
{
|
||||
ControlPath = slot.ControlPath ?? "",
|
||||
Kind = "consumable",
|
||||
ItemKey = consumable.ItemKey ?? ""
|
||||
};
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void SetLocalBinding(AetheriaUnityActionBarBinding binding)
|
||||
{
|
||||
if (binding == null || string.IsNullOrWhiteSpace(binding.ControlPath))
|
||||
return;
|
||||
|
||||
_localBindings = (_localBindings ?? Array.Empty<AetheriaUnityActionBarBinding>())
|
||||
.Where(existing => !string.Equals(existing?.ControlPath ?? "", binding.ControlPath, StringComparison.Ordinal))
|
||||
.Concat(new[] { binding })
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
private ActionBarBinding CreateBinding(
|
||||
ActionBarSlot slot,
|
||||
Entity entity,
|
||||
AetheriaUnityActionBarBinding binding)
|
||||
{
|
||||
if (slot == null || entity == null || binding == null)
|
||||
return null;
|
||||
|
||||
switch (binding.Kind)
|
||||
{
|
||||
case "consumable":
|
||||
var consumable = _catalog?.FindItem(binding.ItemKey ?? "");
|
||||
return consumable != null &&
|
||||
string.Equals(consumable.Category, AetheriaRuntimeItemCategories.Consumable, StringComparison.Ordinal)
|
||||
? new ActionBarConsumableBinding(entity, slot, _resolveControl, _settings, consumable)
|
||||
: null;
|
||||
case "gear":
|
||||
if (binding.EquipmentIndex < 0 || binding.EquipmentIndex >= entity.Equipment.Count)
|
||||
return null;
|
||||
|
||||
var equippedItem = entity.Equipment[binding.EquipmentIndex];
|
||||
var behaviors = equippedItem?.Behaviors;
|
||||
if (equippedItem == null ||
|
||||
!string.Equals(equippedItem.EquippableItem?.ItemKey ?? "", binding.ItemKey ?? "", StringComparison.Ordinal) ||
|
||||
behaviors == null ||
|
||||
binding.BehaviorIndex < 0 ||
|
||||
binding.BehaviorIndex >= behaviors.Length)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!(behaviors[binding.BehaviorIndex] is IActivatedBehavior activatedBehavior))
|
||||
return null;
|
||||
|
||||
return new ActionBarGearBinding(entity, slot, _resolveControl, _settings, equippedItem, activatedBehavior);
|
||||
case "weapon_group":
|
||||
return entity.WeaponGroups != null &&
|
||||
binding.WeaponGroup >= 0 &&
|
||||
binding.WeaponGroup < entity.WeaponGroups.Length
|
||||
? new ActionBarWeaponGroupBinding(entity, slot, _resolveControl, _settings, binding.WeaponGroup)
|
||||
: null;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private AetheriaRuntimeCatalogItem FindConsumable(ItemInstance item)
|
||||
{
|
||||
var typedItem = _catalog?.FindItem(item, x => x.ItemKey);
|
||||
return typedItem != null &&
|
||||
string.Equals(typedItem.Category, AetheriaRuntimeItemCategories.Consumable, StringComparison.Ordinal)
|
||||
? typedItem
|
||||
: null;
|
||||
}
|
||||
|
||||
private ActionBarSlot ResolveSlot(int slotIndex)
|
||||
{
|
||||
return _slots != null &&
|
||||
slotIndex >= 0 &&
|
||||
slotIndex < _slots.Count
|
||||
? _slots[slotIndex]
|
||||
: null;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 0f239f607245e8143805587f4c34fbee
|
||||
|
|
@ -1,40 +0,0 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
|
||||
public sealed class AetheriaUnityCockpitHudShell
|
||||
{
|
||||
public InventoryPanel ShipPanel { get; set; }
|
||||
public InventoryPanel TargetShipPanel { get; set; }
|
||||
public SchematicDisplay SchematicDisplay { get; set; }
|
||||
public SchematicDisplay TargetSchematicDisplay { get; set; }
|
||||
public PlaceUIElementWorldspace TargetIndicator { get; set; }
|
||||
|
||||
public void SetRenderSettings(AetheriaRuntimeDaemonRenderSettings renderSettings)
|
||||
{
|
||||
SchematicDisplay?.SetRenderSettings(renderSettings);
|
||||
TargetSchematicDisplay?.SetRenderSettings(renderSettings);
|
||||
}
|
||||
|
||||
public void UpdatePlayer(Entity currentEntity)
|
||||
{
|
||||
ShipPanel?.Display(currentEntity, true);
|
||||
SchematicDisplay?.ShowShip(currentEntity);
|
||||
}
|
||||
|
||||
public void UpdateTarget(Entity target, Entity currentEntity)
|
||||
{
|
||||
if (TargetIndicator != null)
|
||||
TargetIndicator.gameObject.SetActive(target != null);
|
||||
if (TargetShipPanel != null)
|
||||
TargetShipPanel.gameObject.SetActive(target != null);
|
||||
|
||||
if (target == null)
|
||||
return;
|
||||
|
||||
TargetShipPanel?.Display(target, true);
|
||||
TargetSchematicDisplay?.ShowShip(target, currentEntity);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 027535b4501541f4aa60df9ae50d9eed
|
||||
|
|
@ -1,87 +0,0 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
using float3 = Unity.Mathematics.float3;
|
||||
|
||||
public sealed class AetheriaUnityCurrentEntityBinder
|
||||
{
|
||||
public ZoneRenderer ZoneRenderer { get; set; }
|
||||
public Volume DeathPost { get; set; }
|
||||
public CanvasGroup GameplayUI { get; set; }
|
||||
public AetheriaUnityCurrentEntityPresentation CurrentEntityPresentation { get; set; }
|
||||
public AetheriaUnityTargetPresentation TargetPresentation { get; set; }
|
||||
public Func<Entity> GetCurrentEntity { get; set; }
|
||||
public Func<Entity, Entity> ResolveDockParent { get; set; }
|
||||
public Action<Entity> SetCurrentEntity { get; set; }
|
||||
public Func<float3> GetViewDirection { get; set; }
|
||||
public Action<float3> SetViewDirection { get; set; }
|
||||
public Func<AetheriaRuntimeZoneRenderDocument> ResolveZoneRender { get; set; }
|
||||
public Action<IReadOnlyList<AetheriaUnityActionBarBinding>> ApplyActionBarBindings { get; set; }
|
||||
public Action EnablePlayerInput { get; set; }
|
||||
public Action DisablePlayerInput { get; set; }
|
||||
public Action<MusicType> PlayMusic { get; set; }
|
||||
public Action<Entity> UpdateTargetPanel { get; set; }
|
||||
|
||||
public void RestoreBinding(Entity currentEntity)
|
||||
{
|
||||
var dockParent = ResolveDockParent?.Invoke(currentEntity);
|
||||
if (dockParent != null)
|
||||
{
|
||||
SetCurrentEntity?.Invoke(currentEntity);
|
||||
ApplyActionBarBindings?.Invoke(Array.Empty<AetheriaUnityActionBarBinding>());
|
||||
CurrentEntityPresentation?.BindDocked(
|
||||
dockParent,
|
||||
null,
|
||||
ResolveZoneRender?.Invoke());
|
||||
return;
|
||||
}
|
||||
|
||||
BindUndocked(
|
||||
currentEntity);
|
||||
}
|
||||
|
||||
public void ClearBinding()
|
||||
{
|
||||
TargetPresentation?.ClearIndicators();
|
||||
CurrentEntityPresentation?.ClearBinding();
|
||||
DisablePlayerInput?.Invoke();
|
||||
Cursor.lockState = CursorLockMode.None;
|
||||
if (GameplayUI != null)
|
||||
GameplayUI.gameObject.SetActive(false);
|
||||
}
|
||||
|
||||
private void BindUndocked(Entity entity)
|
||||
{
|
||||
if (ZoneRenderer == null ||
|
||||
!ZoneRenderer.TryGetEntityInstance(entity, out var entityInstance))
|
||||
{
|
||||
Debug.LogError($"Attempted to bind to entity {entity?.Name}, but ZoneRenderer has no daemon-indexed instance.");
|
||||
return;
|
||||
}
|
||||
|
||||
SetCurrentEntity?.Invoke(entity);
|
||||
if (DeathPost != null)
|
||||
DeathPost.weight = 0;
|
||||
|
||||
if (CultMath.math.length(entity.CultDirection) > .1f)
|
||||
SetViewDirection?.Invoke((float3)AetheriaMath.ToUnityXZ(entity.CultDirection));
|
||||
|
||||
CurrentEntityPresentation?.BindUndocked(
|
||||
entity,
|
||||
entityInstance,
|
||||
Array.Empty<AetheriaUnityActionBarBinding>(),
|
||||
EnablePlayerInput,
|
||||
PlayMusic,
|
||||
SetCurrentEntity,
|
||||
UpdateTargetPanel,
|
||||
() => TargetPresentation?.ReconcileVisibleTargetIndicators(GetCurrentEntity?.Invoke()),
|
||||
ApplyActionBarBindings);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: c599c7371ae28e249bcf132744d4e547
|
||||
|
|
@ -1,228 +0,0 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Cinemachine;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using UniRx;
|
||||
using UnityEngine;
|
||||
|
||||
public sealed class AetheriaUnityCurrentEntityPresentation
|
||||
{
|
||||
private readonly List<IDisposable> _shipSubscriptions = new List<IDisposable>();
|
||||
private readonly List<IDisposable> _targetSubscriptions = new List<IDisposable>();
|
||||
private float _hitMarkerTime;
|
||||
|
||||
public ZoneRenderer ZoneRenderer { get; set; }
|
||||
public CinemachineVirtualCamera DockCamera { get; set; }
|
||||
public CinemachineVirtualCamera FollowCamera { get; set; }
|
||||
public MenuPanel Menu { get; set; }
|
||||
public TradeMenu TradeMenu { get; set; }
|
||||
public CanvasGroup GameplayUI { get; set; }
|
||||
public InventoryPanel ShipPanel { get; set; }
|
||||
public InventoryPanel TargetShipPanel { get; set; }
|
||||
public SchematicDisplay SchematicDisplay { get; set; }
|
||||
public SchematicDisplay TargetSchematicDisplay { get; set; }
|
||||
public ImageTargetPresentation TargetImages { get; set; }
|
||||
public AetheriaRuntimeCatalogSnapshot RuntimeCatalog { get; set; }
|
||||
public PlaceUIElementWorldspace[] Crosshairs { get; set; } = Array.Empty<PlaceUIElementWorldspace>();
|
||||
public Prototype LockIndicator { get; set; }
|
||||
public GameObject HitMarker { get; set; }
|
||||
public float HitMarkerDuration { get; set; }
|
||||
|
||||
public (HardpointData[] hardpoints, Transform[] barrels, PlaceUIElementWorldspace crosshair)[] ArticulationGroups { get; private set; } =
|
||||
Array.Empty<(HardpointData[] hardpoints, Transform[] barrels, PlaceUIElementWorldspace crosshair)>();
|
||||
|
||||
public (LockWeapon targetLock, PlaceUIElementWorldspace indicator, Rotate spin)[] LockingIndicators { get; private set; } =
|
||||
Array.Empty<(LockWeapon targetLock, PlaceUIElementWorldspace indicator, Rotate spin)>();
|
||||
|
||||
public void BindUndocked(
|
||||
Entity entity,
|
||||
EntityInstance entityInstance,
|
||||
IReadOnlyList<AetheriaUnityActionBarBinding> actionBarBindings,
|
||||
Action enablePlayerInput,
|
||||
Action<MusicType> playMusic,
|
||||
Action<Entity> updateCurrentEntity,
|
||||
Action<Entity> updateTargetPanel,
|
||||
Action reconcileVisibleTargetIndicators,
|
||||
Action<IReadOnlyList<AetheriaUnityActionBarBinding>> applyActionBarBindings)
|
||||
{
|
||||
if (entity == null || entityInstance == null)
|
||||
return;
|
||||
|
||||
updateCurrentEntity?.Invoke(entity);
|
||||
ZoneRenderer.PerspectiveEntity = entity;
|
||||
|
||||
Menu.gameObject.SetActive(false);
|
||||
DockCamera.enabled = false;
|
||||
FollowCamera.enabled = true;
|
||||
|
||||
Cursor.lockState = CursorLockMode.Locked;
|
||||
enablePlayerInput?.Invoke();
|
||||
GameplayUI.gameObject.SetActive(true);
|
||||
ShipPanel.Display(entity, true);
|
||||
SchematicDisplay.ShowShip(entity);
|
||||
|
||||
FollowCamera.LookAt = entityInstance.LookAtPoint;
|
||||
FollowCamera.Follow = entityInstance.transform;
|
||||
ArticulationGroups = entity.Equipment
|
||||
.Where(HasArticulatedWeaponBehavior)
|
||||
.GroupBy(item => entityInstance
|
||||
.GetBarrel(entity.Hardpoints[item.Position.x, item.Position.y])
|
||||
.GetComponentInParent<ArticulationPoint>()?.Group ?? -1)
|
||||
.Select((group, index) =>
|
||||
{
|
||||
return (
|
||||
group.Select(item => entity.Hardpoints[item.Position.x, item.Position.y]).ToArray(),
|
||||
group.Select(item => entityInstance.GetBarrel(entity.Hardpoints[item.Position.x, item.Position.y])).ToArray(),
|
||||
Crosshairs[index]
|
||||
);
|
||||
}).ToArray();
|
||||
|
||||
foreach (var crosshair in Crosshairs)
|
||||
crosshair.gameObject.SetActive(false);
|
||||
foreach (var group in ArticulationGroups)
|
||||
group.crosshair.gameObject.SetActive(true);
|
||||
|
||||
_shipSubscriptions.Add(entity.TargetedByCount.Subscribe(count =>
|
||||
{
|
||||
playMusic?.Invoke(count > 0 ? MusicType.Combat : MusicType.Overworld);
|
||||
}));
|
||||
|
||||
_shipSubscriptions.Add(entity.Target.Subscribe(target =>
|
||||
{
|
||||
ClearTargetSubscriptions();
|
||||
updateTargetPanel?.Invoke(target);
|
||||
ConfigureTargetShieldPresentation(target);
|
||||
if (target != null)
|
||||
{
|
||||
_targetSubscriptions.Add(target.IncomingHit.Where(e => e == entity).Subscribe(_ =>
|
||||
{
|
||||
HitMarker.SetActive(true);
|
||||
_hitMarkerTime = HitMarkerDuration;
|
||||
}));
|
||||
}
|
||||
}));
|
||||
|
||||
reconcileVisibleTargetIndicators?.Invoke();
|
||||
|
||||
LockingIndicators = entity.GetBehaviors<LockWeapon>()
|
||||
.Select(x =>
|
||||
{
|
||||
var indicator = LockIndicator.Instantiate<PlaceUIElementWorldspace>();
|
||||
return (x, indicator, indicator.GetComponent<Rotate>());
|
||||
}).ToArray();
|
||||
|
||||
applyActionBarBindings?.Invoke(actionBarBindings ?? Array.Empty<AetheriaUnityActionBarBinding>());
|
||||
}
|
||||
|
||||
public bool HasArticulatedWeaponBehavior(EquippedItem item)
|
||||
{
|
||||
return AetheriaUnityWeaponPresentationPolicy.HasArticulatedWeaponBehavior(RuntimeCatalog, item);
|
||||
}
|
||||
|
||||
public void BindDocked(
|
||||
Entity entity,
|
||||
AetheriaRuntimeCurrentDockingDocument docking,
|
||||
AetheriaRuntimeZoneRenderDocument zoneRender)
|
||||
{
|
||||
if (entity == null)
|
||||
return;
|
||||
|
||||
TradeMenu.Inventory = entity.CargoBays.First();
|
||||
ZoneRenderer.PerspectiveEntity = entity;
|
||||
DockCamera.enabled = true;
|
||||
FollowCamera.enabled = false;
|
||||
var orbital = entity as OrbitalEntity;
|
||||
if (orbital == null || !ZoneRenderer.TryGetEntityInstance(orbital, out var orbitalInstance))
|
||||
{
|
||||
Debug.LogError($"Attempted to dock at entity {entity.Name}, but ZoneRenderer has no daemon-indexed instance.");
|
||||
return;
|
||||
}
|
||||
|
||||
DockCamera.Follow = orbitalInstance.transform;
|
||||
var parentOrbitPlanetBodyKey = ResolveDockParentBodyKey(orbital, docking, zoneRender);
|
||||
if (ZoneRenderer.TryGetBodyView(parentOrbitPlanetBodyKey, out var parentBodyView))
|
||||
DockCamera.LookAt = parentBodyView.Body.transform;
|
||||
else DockCamera.LookAt = ZoneRenderer.ZoneRoot;
|
||||
Menu.ShowTab(MenuTab.Inventory);
|
||||
}
|
||||
|
||||
private static string ResolveDockParentBodyKey(
|
||||
OrbitalEntity orbital,
|
||||
AetheriaRuntimeCurrentDockingDocument docking,
|
||||
AetheriaRuntimeZoneRenderDocument zoneRender)
|
||||
{
|
||||
if (orbital == null)
|
||||
return "";
|
||||
|
||||
var bodyPoses = zoneRender?.BodyPoses ?? Array.Empty<AetheriaRuntimeZoneRenderBodyPose>();
|
||||
var parentOrbitKey = bodyPoses
|
||||
.FirstOrDefault(body => body != null &&
|
||||
string.Equals(body.OrbitKey ?? "", orbital.OrbitKey, StringComparison.Ordinal))
|
||||
?.ParentOrbitKey ?? docking?.DockParentParentOrbitKey ?? "";
|
||||
return bodyPoses
|
||||
.FirstOrDefault(body => body != null &&
|
||||
string.Equals(body.OrbitKey ?? "", parentOrbitKey, StringComparison.Ordinal))
|
||||
?.BodyKey ?? docking?.DockParentParentBodyKey ?? "";
|
||||
}
|
||||
|
||||
public void ClearBinding()
|
||||
{
|
||||
foreach (var (_, indicator, _) in LockingIndicators)
|
||||
indicator.GetComponent<Prototype>().ReturnToPool();
|
||||
LockingIndicators = Array.Empty<(LockWeapon targetLock, PlaceUIElementWorldspace indicator, Rotate spin)>();
|
||||
ArticulationGroups = Array.Empty<(HardpointData[] hardpoints, Transform[] barrels, PlaceUIElementWorldspace crosshair)>();
|
||||
|
||||
foreach (var subscription in _shipSubscriptions)
|
||||
subscription.Dispose();
|
||||
_shipSubscriptions.Clear();
|
||||
ClearTargetSubscriptions();
|
||||
}
|
||||
|
||||
public void Tick(float deltaTime)
|
||||
{
|
||||
_hitMarkerTime -= deltaTime;
|
||||
if (HitMarker.activeSelf && _hitMarkerTime < 0)
|
||||
HitMarker.SetActive(false);
|
||||
}
|
||||
|
||||
private void ClearTargetSubscriptions()
|
||||
{
|
||||
foreach (var subscription in _targetSubscriptions)
|
||||
subscription.Dispose();
|
||||
_targetSubscriptions.Clear();
|
||||
}
|
||||
|
||||
private void ConfigureTargetShieldPresentation(Entity target)
|
||||
{
|
||||
if (target == null || TargetImages == null)
|
||||
return;
|
||||
|
||||
if (target.Shield != null)
|
||||
{
|
||||
TargetImages.TargetShieldsBackground.color = new Color(TargetImages.ShieldColor.r, TargetImages.ShieldColor.g, TargetImages.ShieldColor.b, .4f);
|
||||
TargetImages.TargetShieldsIcon.color = TargetImages.ShieldColor;
|
||||
TargetImages.TargetShieldsIcon.sprite = TargetImages.ShieldIcon;
|
||||
}
|
||||
else
|
||||
{
|
||||
TargetImages.TargetShieldsBackground.color = new Color(TargetImages.NoShieldColor.r, TargetImages.NoShieldColor.g, TargetImages.NoShieldColor.b, .4f);
|
||||
TargetImages.TargetShieldsIcon.color = TargetImages.NoShieldColor;
|
||||
TargetImages.TargetShieldsIcon.sprite = TargetImages.NoShieldIcon;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ImageTargetPresentation
|
||||
{
|
||||
public UnityEngine.UI.Image TargetShieldsBackground { get; set; }
|
||||
public UnityEngine.UI.Image TargetShieldsIcon { get; set; }
|
||||
public Color ShieldColor { get; set; }
|
||||
public Color NoShieldColor { get; set; }
|
||||
public Sprite ShieldIcon { get; set; }
|
||||
public Sprite NoShieldIcon { get; set; }
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: f5a7b36e50785fc45ab94ae5a03dd1d6
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
using System;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using GameCult.Mesh;
|
||||
|
||||
public sealed class AetheriaUnityDaemonRenderDocuments : IDisposable
|
||||
{
|
||||
private readonly CultMeshReactiveDocument<AetheriaRuntimeDaemonFrameDocument> _frame;
|
||||
private readonly CultMeshReactiveDocument<AetheriaRuntimeDaemonSoaViewDocument> _soaView;
|
||||
private readonly CultMeshReactiveDocument<AetheriaRuntimeZoneRenderDocument> _zoneRender;
|
||||
|
||||
private AetheriaUnityDaemonRenderDocuments(AetheriaClientState state)
|
||||
{
|
||||
if (state == null)
|
||||
throw new ArgumentNullException(nameof(state));
|
||||
|
||||
_frame = state.DaemonFrame.Reactive();
|
||||
_soaView = state.DaemonSoaView.Reactive();
|
||||
_zoneRender = state.ZoneRender.Reactive();
|
||||
}
|
||||
|
||||
public AetheriaRuntimeDaemonRenderView Current =>
|
||||
TryRead(out var observed) ? observed : null;
|
||||
|
||||
public static AetheriaUnityDaemonRenderDocuments Open(AetheriaClientState state)
|
||||
{
|
||||
return new AetheriaUnityDaemonRenderDocuments(state);
|
||||
}
|
||||
|
||||
public bool TryRead(out AetheriaRuntimeDaemonRenderView observed)
|
||||
{
|
||||
return AetheriaRuntimeDaemonRenderView.TryCreateCurrent(
|
||||
_frame,
|
||||
_soaView,
|
||||
_zoneRender,
|
||||
out observed);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_frame?.Dispose();
|
||||
_soaView?.Dispose();
|
||||
_zoneRender?.Dispose();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: a5bd499492bebfb439338bc5283f6a23
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using int2 = Unity.Mathematics.int2;
|
||||
|
||||
public abstract class DragObject
|
||||
{
|
||||
}
|
||||
|
||||
public abstract class ItemDragObject : DragObject
|
||||
{
|
||||
protected ItemDragObject(int2 originCellOffset, ItemInstance item)
|
||||
{
|
||||
OriginCellOffset = originCellOffset;
|
||||
Item = item;
|
||||
}
|
||||
|
||||
public ItemInstance Item { get; }
|
||||
public int2 OriginCellOffset { get; }
|
||||
}
|
||||
|
||||
public class ItemInstanceDragObject : ItemDragObject
|
||||
{
|
||||
public ItemInstanceDragObject(ItemInstance item, EquippedCargoBay originInventory, int2 originCellOffset)
|
||||
: base(originCellOffset, item)
|
||||
{
|
||||
OriginInventory = originInventory;
|
||||
}
|
||||
|
||||
public EquippedCargoBay OriginInventory { get; }
|
||||
}
|
||||
|
||||
public class EquippedItemDragObject : ItemDragObject
|
||||
{
|
||||
public EquippedItemDragObject(EquippedItem item, Entity originEntity, int2 originCellOffset)
|
||||
: base(originCellOffset, item.EquippableItem)
|
||||
{
|
||||
EquippedItem = item;
|
||||
OriginEntity = originEntity;
|
||||
}
|
||||
|
||||
public EquippedItem EquippedItem { get; }
|
||||
public Entity OriginEntity { get; }
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 5f70b0c04a804c349915b07ef0fd9b13
|
||||
|
|
@ -1,37 +0,0 @@
|
|||
using System;
|
||||
|
||||
public sealed class AetheriaUnityDragSession
|
||||
{
|
||||
private DragObject _dragObject;
|
||||
private Action<DragObject> _endDragCallback;
|
||||
|
||||
public void Begin(DragObject dragObject)
|
||||
{
|
||||
_dragObject = dragObject;
|
||||
}
|
||||
|
||||
public bool TryGetDraggedItem(out ItemDragObject itemDragObject)
|
||||
{
|
||||
itemDragObject = _dragObject as ItemDragObject;
|
||||
return itemDragObject != null;
|
||||
}
|
||||
|
||||
public void RegisterTarget(Action<DragObject> onEndDrag)
|
||||
{
|
||||
_endDragCallback = onEndDrag;
|
||||
}
|
||||
|
||||
public void UnregisterTarget()
|
||||
{
|
||||
_endDragCallback = null;
|
||||
}
|
||||
|
||||
public bool End()
|
||||
{
|
||||
var hadTarget = _endDragCallback != null;
|
||||
_endDragCallback?.Invoke(_dragObject);
|
||||
_dragObject = null;
|
||||
_endDragCallback = null;
|
||||
return hadTarget;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 6454eeaf62eadb44abbe5d54bf497312
|
||||
|
|
@ -1,161 +0,0 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using Unity.Mathematics;
|
||||
|
||||
public sealed class AetheriaUnityEntityBlueprintMaterializer
|
||||
{
|
||||
private readonly AetheriaUnityLoadoutItemFactory _loadoutItemFactory;
|
||||
|
||||
public AetheriaUnityEntityBlueprintMaterializer(
|
||||
AetheriaUnityLoadoutItemFactory loadoutItemFactory)
|
||||
{
|
||||
_loadoutItemFactory = loadoutItemFactory ?? throw new ArgumentNullException(nameof(loadoutItemFactory));
|
||||
}
|
||||
|
||||
public EntityConstructionBlueprint MaterializeTemplate(AetheriaRuntimeLoadoutTemplateSnapshot template)
|
||||
{
|
||||
if (template == null)
|
||||
return null;
|
||||
|
||||
var blueprint = MaterializeLoadoutEntity(template.RootEntity);
|
||||
if (blueprint != null && string.IsNullOrWhiteSpace(blueprint.Name))
|
||||
blueprint.Name = template.Name;
|
||||
return blueprint;
|
||||
}
|
||||
|
||||
public EntityConstructionBlueprint MaterializeLoadoutEntity(AetheriaRuntimeEntityLoadoutSnapshot entity)
|
||||
{
|
||||
if (entity == null)
|
||||
return null;
|
||||
|
||||
var hull = CreateEquippableItem(entity.Hull);
|
||||
if (hull == null)
|
||||
return null;
|
||||
|
||||
var blueprint = CreateBlueprint(entity.Kind);
|
||||
if (blueprint is ShipConstructionBlueprint shipBlueprint)
|
||||
{
|
||||
shipBlueprint.Direction = new float2(0, 1);
|
||||
}
|
||||
|
||||
blueprint.Name = entity.Name;
|
||||
blueprint.FactionKey = entity.FactionKey ?? "";
|
||||
blueprint.Hull = hull;
|
||||
blueprint.Equipment = CreateEquippableSlots(entity.Equipment);
|
||||
blueprint.CargoBays = CreateEquippableSlots(entity.CargoBays);
|
||||
blueprint.DockingBays = CreateEquippableSlots(entity.DockingBays);
|
||||
blueprint.CargoContents = CreateCargoBayContents(entity.CargoContents);
|
||||
blueprint.DockingBayContents = CreateCargoBayContents(entity.DockingBayContents);
|
||||
blueprint.DockingBayAssignments = entity.DockingBayAssignments.ToArray();
|
||||
blueprint.WeaponGroups = entity.WeaponGroups.Select(group => group.ToArray()).ToArray();
|
||||
blueprint.Children = entity.Children
|
||||
.Select(MaterializeLoadoutEntity)
|
||||
.Where(child => child != null)
|
||||
.ToArray();
|
||||
return blueprint;
|
||||
}
|
||||
|
||||
public EntityConstructionBlueprint MaterializeObservedEntity(
|
||||
AetheriaRuntimeEntitySnapshot entity,
|
||||
bool isCurrentEntity)
|
||||
{
|
||||
if (entity == null)
|
||||
return null;
|
||||
|
||||
var hull = CreateEquippableItem(new AetheriaRuntimeLoadoutItemSnapshot(
|
||||
entity.HullItemKey,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
true,
|
||||
false));
|
||||
if (hull == null)
|
||||
return null;
|
||||
|
||||
var blueprint = CreateBlueprint(entity.Kind);
|
||||
if (blueprint is ShipConstructionBlueprint shipBlueprint)
|
||||
{
|
||||
shipBlueprint.Position = new float3((float)entity.PositionX, (float)entity.PositionY, (float)entity.PositionZ);
|
||||
shipBlueprint.Direction = new float2((float)entity.DirectionX, (float)entity.DirectionY);
|
||||
shipBlueprint.IsPlayerShip = isCurrentEntity;
|
||||
}
|
||||
else if (blueprint is OrbitalEntityConstructionBlueprint orbitalBlueprint)
|
||||
{
|
||||
orbitalBlueprint.OrbitKey = entity.OrbitKey ?? "";
|
||||
orbitalBlueprint.SecurityLevel = (SecurityLevel)entity.SecurityLevel;
|
||||
orbitalBlueprint.SecurityRadius = (float)entity.SecurityRadius;
|
||||
}
|
||||
|
||||
blueprint.Name = entity.Name ?? "";
|
||||
blueprint.FactionKey = entity.FactionKey ?? "";
|
||||
blueprint.Hull = hull;
|
||||
blueprint.Equipment = CreateEquippableSlots(entity.Equipment);
|
||||
blueprint.CargoBays = CreateEquippableSlots(entity.CargoBays);
|
||||
blueprint.DockingBays = CreateEquippableSlots(entity.DockingBays);
|
||||
blueprint.CargoContents = CreateCargoBayContents(entity.CargoContents);
|
||||
blueprint.DockingBayContents = CreateCargoBayContents(entity.DockingBayContents);
|
||||
blueprint.DockingBayAssignments = entity.DockingBayAssignments.ToArray();
|
||||
blueprint.WeaponGroups = entity.WeaponGroups.Select(group => group.ToArray()).ToArray();
|
||||
blueprint.Children = Array.Empty<EntityConstructionBlueprint>();
|
||||
return blueprint;
|
||||
}
|
||||
|
||||
private static EntityConstructionBlueprint CreateBlueprint(string kind)
|
||||
{
|
||||
return string.Equals(kind, "orbital", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(kind, "station", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(kind, "turret", StringComparison.OrdinalIgnoreCase)
|
||||
? new OrbitalEntityConstructionBlueprint()
|
||||
: new ShipConstructionBlueprint();
|
||||
}
|
||||
|
||||
private (int2 position, EquippableItem item)[] CreateEquippableSlots(
|
||||
IReadOnlyList<AetheriaRuntimeLoadoutItemSlotSnapshot> slots)
|
||||
{
|
||||
return (slots ?? Array.Empty<AetheriaRuntimeLoadoutItemSlotSnapshot>())
|
||||
.Select(slot => (position: new int2(slot.X, slot.Y), item: CreateEquippableItem(slot.Item)))
|
||||
.Where(slot => slot.item != null)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
private (int2 position, EquippableItem item)[] CreateEquippableSlots(
|
||||
IReadOnlyList<AetheriaRuntimeEntityItemSlotSnapshot> slots)
|
||||
{
|
||||
return (slots ?? Array.Empty<AetheriaRuntimeEntityItemSlotSnapshot>())
|
||||
.Select(slot => (position: new int2(slot.X, slot.Y), item: CreateEquippableItem(new AetheriaRuntimeLoadoutItemSnapshot(
|
||||
slot.ItemKey,
|
||||
slot.Quality,
|
||||
slot.Durability,
|
||||
slot.Quantity,
|
||||
slot.Enabled,
|
||||
slot.OverrideShutdown,
|
||||
slot.Temperature))))
|
||||
.Where(slot => slot.item != null)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
private (int2 position, ItemInstance item)[][] CreateCargoBayContents(
|
||||
IReadOnlyList<AetheriaRuntimeCargoBayLoadoutSnapshot> bays)
|
||||
{
|
||||
return (bays ?? Array.Empty<AetheriaRuntimeCargoBayLoadoutSnapshot>())
|
||||
.Select(bay => (bay.Items ?? Array.Empty<AetheriaRuntimeLoadoutItemSlotSnapshot>())
|
||||
.Select(slot => (position: new int2(slot.X, slot.Y), item: _loadoutItemFactory.CreateLoadoutItem(slot.Item)))
|
||||
.Where(slot => slot.item != null)
|
||||
.ToArray())
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
private EquippableItem CreateEquippableItem(AetheriaRuntimeLoadoutItemSnapshot item)
|
||||
{
|
||||
var instance = _loadoutItemFactory.CreateLoadoutItem(item) as EquippableItem;
|
||||
if (instance != null && item.Durability > 0)
|
||||
instance.Durability = (float)item.Durability;
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 88f0588c14c7a1d4c87095a96585c957
|
||||
|
|
@ -1,102 +0,0 @@
|
|||
using System;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using GameCult.Eve.PluginFields;
|
||||
using GameCult.Mesh;
|
||||
|
||||
public sealed class AetheriaUnityGameViewportDocuments : IDisposable
|
||||
{
|
||||
private readonly CultMeshReactiveDocument<AetheriaRuntimeZoneContactsDocument> _contacts;
|
||||
private readonly CultMeshReactiveDocument<AetheriaRuntimeObjectsViewportDocument> _objectsViewport;
|
||||
private readonly CultMeshReactiveDocument<EveFieldsSplatsDocument> _renderSplatsViewport;
|
||||
|
||||
private AetheriaUnityGameViewportDocuments(
|
||||
AetheriaClientState state,
|
||||
AetheriaRuntimeViewportBounds viewport,
|
||||
bool bindContacts,
|
||||
bool bindObjects,
|
||||
bool bindRenderSplats)
|
||||
{
|
||||
if (state == null)
|
||||
throw new ArgumentNullException(nameof(state));
|
||||
if (viewport == null)
|
||||
throw new ArgumentNullException(nameof(viewport));
|
||||
|
||||
Viewport = viewport;
|
||||
_contacts = bindContacts ? state.ZoneContacts.Reactive() : null;
|
||||
_objectsViewport = bindObjects ? state.ObjectsViewport(viewport).Reactive() : null;
|
||||
_renderSplatsViewport = bindRenderSplats ? state.RenderSplatsViewport(viewport).Reactive() : null;
|
||||
}
|
||||
|
||||
public AetheriaRuntimeViewportBounds Viewport { get; }
|
||||
|
||||
public AetheriaRuntimeZoneContactsDocument CurrentContacts => _contacts?.Current;
|
||||
public AetheriaRuntimeObjectsViewportDocument CurrentObjectsViewport => _objectsViewport?.Current;
|
||||
public EveFieldsSplatsDocument CurrentRenderSplatsViewport => _renderSplatsViewport?.Current;
|
||||
|
||||
public static AetheriaUnityGameViewportDocuments OpenMap(
|
||||
AetheriaClientState state,
|
||||
AetheriaRuntimeViewportBounds viewport)
|
||||
{
|
||||
return new AetheriaUnityGameViewportDocuments(
|
||||
state,
|
||||
viewport,
|
||||
bindContacts: false,
|
||||
bindObjects: true,
|
||||
bindRenderSplats: true);
|
||||
}
|
||||
|
||||
public static AetheriaUnityGameViewportDocuments OpenZonePresentation(
|
||||
AetheriaClientState state,
|
||||
AetheriaRuntimeViewportBounds viewport)
|
||||
{
|
||||
return new AetheriaUnityGameViewportDocuments(
|
||||
state,
|
||||
viewport,
|
||||
bindContacts: true,
|
||||
bindObjects: true,
|
||||
bindRenderSplats: false);
|
||||
}
|
||||
|
||||
public static AetheriaUnityGameViewportDocuments OpenRenderSplats(
|
||||
AetheriaClientState state,
|
||||
AetheriaRuntimeViewportBounds viewport)
|
||||
{
|
||||
return new AetheriaUnityGameViewportDocuments(
|
||||
state,
|
||||
viewport,
|
||||
bindContacts: false,
|
||||
bindObjects: false,
|
||||
bindRenderSplats: true);
|
||||
}
|
||||
|
||||
public bool Matches(AetheriaRuntimeViewportBounds viewport)
|
||||
{
|
||||
return SameViewport(Viewport, viewport);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_contacts?.Dispose();
|
||||
_objectsViewport?.Dispose();
|
||||
_renderSplatsViewport?.Dispose();
|
||||
}
|
||||
|
||||
public static bool SameViewport(
|
||||
AetheriaRuntimeViewportBounds left,
|
||||
AetheriaRuntimeViewportBounds right)
|
||||
{
|
||||
if (left == null || right == null)
|
||||
return false;
|
||||
|
||||
return Approximately(left.MinX, right.MinX) &&
|
||||
Approximately(left.MinY, right.MinY) &&
|
||||
Approximately(left.MaxX, right.MaxX) &&
|
||||
Approximately(left.MaxY, right.MaxY);
|
||||
}
|
||||
|
||||
private static bool Approximately(double left, double right)
|
||||
{
|
||||
var scale = Math.Max(1.0, Math.Max(Math.Abs(left), Math.Abs(right)));
|
||||
return Math.Abs(left - right) <= scale * 1e-6;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: e763d94f902249349a0f897ef12bd185
|
||||
|
|
@ -1,141 +0,0 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using GameCult.Mesh;
|
||||
|
||||
public sealed class AetheriaUnityGameplayBootShell
|
||||
{
|
||||
public GameSettings Settings { get; set; }
|
||||
public ZoneRenderer ZoneRenderer { get; set; }
|
||||
public AetheriaUnityCockpitHudShell CockpitHudShell { get; set; }
|
||||
public Action<string> Log { get; set; }
|
||||
|
||||
public AetheriaUnityGameplayBootResult Boot()
|
||||
{
|
||||
var stateBoot = AetheriaRuntimeStateBoot.Inspect(AetheriaUnityRuntimePaths.GameDataDirectory);
|
||||
Log?.Invoke($"Aetheria runtime target: {stateBoot.TargetLabel} via {stateBoot.TargetKind} ({stateBoot.TargetSource})");
|
||||
Log?.Invoke($"Aetheria runtime id: {stateBoot.RuntimeId}");
|
||||
Log?.Invoke($"Aetheria runtime state file: {stateBoot.StateFilePath}");
|
||||
stateBoot = SyncRemoteReplicaBeforeBoot(stateBoot);
|
||||
|
||||
if (!stateBoot.SupportsLocalStateFileRead)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Aetheria runtime target cannot read the daemon mirror state required for gameplay boot: {stateBoot.FailureMessage}");
|
||||
}
|
||||
|
||||
if (!stateBoot.StateFileExists)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Aetheria runtime state file is missing at {stateBoot.StateFilePath}; gameplay requires an authoritative daemon mirror.");
|
||||
}
|
||||
|
||||
var runtimeState = AetheriaUnityRuntimeClientProvider.RuntimeState(stateBoot, stateBoot.RuntimeId);
|
||||
var runtimeCatalog = runtimeState.Catalog.Latest();
|
||||
if (runtimeCatalog == null)
|
||||
throw new InvalidOperationException("Aetheria typed runtime catalog is required before gameplay boot.");
|
||||
var sectorMap = runtimeState.SectorMap.Latest();
|
||||
if (sectorMap == null)
|
||||
throw new InvalidOperationException("Aetheria typed sector map is required before gameplay boot.");
|
||||
|
||||
Log?.Invoke($"Aetheria runtime catalog: {runtimeCatalog.Items.Count} items, {runtimeCatalog.Corporations.Count} corporations, {runtimeCatalog.NameFiles.Count} name files");
|
||||
Log?.Invoke($"Aetheria observed sector-map frame: {sectorMap.FrameId}");
|
||||
|
||||
var backgroundSettings = sectorMap.IsTutorial
|
||||
? Settings.TutorialBackgroundSettings
|
||||
: Settings.SectorBackgroundSettings;
|
||||
backgroundSettings.NoisePosition = sectorMap.GenerationSeed == 0 ? 1 : sectorMap.GenerationSeed;
|
||||
var observedGalaxy = global::Galaxy.ProjectObservedSectorMap(
|
||||
sectorMap,
|
||||
backgroundSettings,
|
||||
runtimeCatalog,
|
||||
Log);
|
||||
|
||||
var itemManager = new ItemManager(
|
||||
runtimeCatalog,
|
||||
Settings.GameplaySettings,
|
||||
message => Log?.Invoke(message));
|
||||
var loadoutItemFactory = new AetheriaUnityLoadoutItemFactory(itemManager, runtimeCatalog);
|
||||
ZoneRenderer.SetDroppedPickupItemFactory(loadoutItemFactory.CreateLoadoutItem);
|
||||
ZoneRenderer.BodySettingsCollections = Settings.BodySettingsCollections;
|
||||
ZoneRenderer.RenderSettings = ResolveDaemonRenderSettings(runtimeState);
|
||||
CockpitHudShell.SetRenderSettings(ZoneRenderer.RenderSettings);
|
||||
|
||||
if (!AetheriaUnityRuntimeClientProvider.PlayerSettings.GraphicsSettings.ShowAsteroidsInMinimap)
|
||||
ZoneRenderer.ShowAsteroidUI = false;
|
||||
|
||||
return new AetheriaUnityGameplayBootResult(
|
||||
runtimeCatalog,
|
||||
observedGalaxy,
|
||||
itemManager,
|
||||
loadoutItemFactory);
|
||||
}
|
||||
|
||||
private AetheriaRuntimeDaemonRenderSettings ResolveDaemonRenderSettings(AetheriaClientState runtimeState)
|
||||
{
|
||||
var frame = runtimeState?.DaemonFrame?.Latest();
|
||||
if (frame == null)
|
||||
throw new InvalidOperationException("Aetheria daemon frame is required before gameplay boot; render/game-feel settings are daemon authority.");
|
||||
|
||||
Log?.Invoke($"Aetheria render/game-feel settings: daemon frame {frame.FrameId}");
|
||||
return frame.RenderSettings;
|
||||
}
|
||||
|
||||
private AetheriaRuntimeStateBootReport SyncRemoteReplicaBeforeBoot(AetheriaRuntimeStateBootReport stateBoot)
|
||||
{
|
||||
if (!ShouldSyncRemoteReplicaBeforeBoot(stateBoot))
|
||||
return stateBoot;
|
||||
|
||||
Log?.Invoke($"Aetheria remote Verse replica missing; syncing {stateBoot.TargetLabel} from {stateBoot.CultMeshAddress}");
|
||||
try
|
||||
{
|
||||
var target = AetheriaState.At(AetheriaUnityRuntimePaths.GameDataDirectory)
|
||||
.ClientTarget
|
||||
.SyncReplica();
|
||||
AetheriaUnityRuntimePaths.ClearRuntimeStateFilePathCache();
|
||||
|
||||
var refreshed = AetheriaRuntimeStateBoot.Inspect(AetheriaUnityRuntimePaths.GameDataDirectory);
|
||||
Log?.Invoke($"Aetheria remote Verse replica synced: {refreshed.StateFilePath}");
|
||||
if (!string.IsNullOrWhiteSpace(target.LastReplicaSyncAtUtc))
|
||||
Log?.Invoke($"Aetheria remote Verse replica sync time: {target.LastReplicaSyncAtUtc}");
|
||||
return refreshed;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AetheriaUnityRuntimePaths.ClearRuntimeStateFilePathCache();
|
||||
throw new InvalidOperationException(
|
||||
$"Aetheria remote Verse replica sync failed before gameplay boot: {ex.Message}",
|
||||
ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool ShouldSyncRemoteReplicaBeforeBoot(AetheriaRuntimeStateBootReport stateBoot)
|
||||
{
|
||||
return string.Equals(stateBoot.TargetSource, "client-target", StringComparison.Ordinal)
|
||||
&& string.Equals(stateBoot.TargetKind, AetheriaRuntimeClientTargetKinds.CultMeshVerse, StringComparison.Ordinal)
|
||||
&& (!stateBoot.SupportsLocalStateFileRead || !stateBoot.StateFileExists);
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct AetheriaUnityGameplayBootResult
|
||||
{
|
||||
public AetheriaUnityGameplayBootResult(
|
||||
AetheriaRuntimeCatalogSnapshot runtimeCatalog,
|
||||
Galaxy observedGalaxy,
|
||||
ItemManager itemManager,
|
||||
AetheriaUnityLoadoutItemFactory loadoutItemFactory)
|
||||
{
|
||||
RuntimeCatalog = runtimeCatalog;
|
||||
ObservedGalaxy = observedGalaxy;
|
||||
ItemManager = itemManager;
|
||||
LoadoutItemFactory = loadoutItemFactory;
|
||||
}
|
||||
|
||||
public AetheriaRuntimeCatalogSnapshot RuntimeCatalog { get; }
|
||||
public Galaxy ObservedGalaxy { get; }
|
||||
public ItemManager ItemManager { get; }
|
||||
public AetheriaUnityLoadoutItemFactory LoadoutItemFactory { get; }
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 70318b35e2014bdfad48683869bfc04d
|
||||
|
|
@ -1,218 +0,0 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using TMPro;
|
||||
using UniRx;
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
using UnityEngine.InputSystem;
|
||||
|
||||
public sealed class AetheriaUnityGameplayInputShell : IDisposable
|
||||
{
|
||||
private readonly List<ActionBarSlot> _actionBarSlots = new List<ActionBarSlot>();
|
||||
private readonly List<InputAction> _actionBarActions = new List<InputAction>();
|
||||
private bool _uiHidden;
|
||||
private int _zoomLevelIndex;
|
||||
|
||||
public AetheriaInput Input { get; private set; }
|
||||
public RuntimePlayerSettings RuntimePlayerSettings { get; set; }
|
||||
public InputDisplayLayout InputDisplayLayout { get; set; }
|
||||
public ConfirmationDialog Dialog { get; set; }
|
||||
public MainMenu MainMenu { get; set; }
|
||||
public MenuPanel Menu { get; set; }
|
||||
public MapRenderer MenuMap { get; set; }
|
||||
public CanvasGroup GameplayUI { get; set; }
|
||||
public Transform ActionBar { get; set; }
|
||||
public ActionBarSlot ActionBarSlot { get; set; }
|
||||
public ZoneRenderer ZoneRenderer { get; set; }
|
||||
public AetheriaUnityMenuShell MenuShell { get; set; }
|
||||
public AetheriaUnityDragSession DragSession { get; set; }
|
||||
public AetheriaUnityActionBarPresentation ActionBarPresentation { get; set; }
|
||||
public AetheriaUnityPilotOperationController PilotOperationController { get; set; }
|
||||
public Func<Entity> ResolveCurrentEntity { get; set; }
|
||||
public Action<AetheriaInput> SetInput { get; set; }
|
||||
|
||||
public IReadOnlyList<ActionBarSlot> ActionBarSlots => _actionBarSlots;
|
||||
|
||||
public void Bootstrap()
|
||||
{
|
||||
Input = new AetheriaInput();
|
||||
SetInput?.Invoke(Input);
|
||||
|
||||
if (RuntimePlayerSettings?.InputSettings != null)
|
||||
{
|
||||
foreach (var binding in RuntimePlayerSettings.InputSettings.InputActionMap)
|
||||
Input.asset[binding.Key.action].ApplyBindingOverride(binding.Key.binding, binding.Value);
|
||||
}
|
||||
|
||||
if (InputDisplayLayout != null)
|
||||
InputDisplayLayout.Input = Input.asset;
|
||||
|
||||
Dialog?.SetInputGate(
|
||||
() => Input.Global.Enable(),
|
||||
() => Input.Global.Disable());
|
||||
Input.Global.Enable();
|
||||
|
||||
_zoomLevelIndex = ZoneRenderer.RenderSettings.ResolveDefaultMinimapZoomIndex();
|
||||
ZoneRenderer.MinimapDistance = (float)ZoneRenderer.RenderSettings.ResolveMinimapDistance(_zoomLevelIndex);
|
||||
|
||||
RegisterGlobalInput();
|
||||
RegisterPlayerInput();
|
||||
RegisterActionBarInput();
|
||||
}
|
||||
|
||||
public void EnablePlayerInput()
|
||||
{
|
||||
Cursor.lockState = CursorLockMode.Locked;
|
||||
Input.Player.Enable();
|
||||
foreach (var action in _actionBarActions)
|
||||
action.Enable();
|
||||
}
|
||||
|
||||
public void DisablePlayerInput()
|
||||
{
|
||||
Cursor.lockState = CursorLockMode.None;
|
||||
Input.Player.Disable();
|
||||
foreach (var action in _actionBarActions)
|
||||
action.Disable();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var action in _actionBarActions)
|
||||
action.Dispose();
|
||||
_actionBarActions.Clear();
|
||||
_actionBarSlots.Clear();
|
||||
Input?.Dispose();
|
||||
Input = null;
|
||||
}
|
||||
|
||||
private void RegisterGlobalInput()
|
||||
{
|
||||
Input.Global.ZoneMap.performed += context =>
|
||||
{
|
||||
MenuShell.ToggleMenuTab(MenuTab.Map);
|
||||
var currentEntity = ResolveCurrentEntity?.Invoke();
|
||||
if (currentEntity == null)
|
||||
return;
|
||||
|
||||
MenuMap.Position = AetheriaMath.ToUnity(currentEntity.CultPositionXZ);
|
||||
};
|
||||
|
||||
Input.Global.Inventory.performed += context => MenuShell.ToggleMenuTab(MenuTab.Inventory);
|
||||
Input.Global.GalaxyMap.performed += context => MenuShell.ToggleMenuTab(MenuTab.Galaxy);
|
||||
|
||||
Input.Global.Interact.performed += context =>
|
||||
{
|
||||
if (IsTextInputFocused() || MainMenu.gameObject.activeSelf)
|
||||
return;
|
||||
|
||||
if (ResolveCurrentEntity?.Invoke() == null)
|
||||
{
|
||||
Dialog.Clear();
|
||||
Dialog.Title.text = "Can't undock. You dont have a ship!";
|
||||
Dialog.Show();
|
||||
Dialog.MoveToCursor();
|
||||
return;
|
||||
}
|
||||
|
||||
PilotOperationController.RequestInteract();
|
||||
};
|
||||
|
||||
Input.Global.MainMenu.performed += context =>
|
||||
{
|
||||
if (Menu.gameObject.activeSelf)
|
||||
MenuShell.ToggleMenuTab(Menu.CurrentTab);
|
||||
else
|
||||
MenuShell.ToggleFullscreenMenu(MainMenu.gameObject);
|
||||
};
|
||||
|
||||
Input.Global.InputScreen.performed += context => MenuShell.ToggleFullscreenMenu(MenuShell.HelpScreen);
|
||||
}
|
||||
|
||||
private void RegisterPlayerInput()
|
||||
{
|
||||
Input.Player.MinimapZoom.performed += context =>
|
||||
{
|
||||
_zoomLevelIndex = ZoneRenderer.RenderSettings.ResolveNextMinimapZoomIndex(_zoomLevelIndex);
|
||||
ZoneRenderer.MinimapDistance = (float)ZoneRenderer.RenderSettings.ResolveMinimapDistance(_zoomLevelIndex);
|
||||
};
|
||||
|
||||
Input.Player.HideUI.performed += context =>
|
||||
{
|
||||
_uiHidden = !_uiHidden;
|
||||
GameplayUI.alpha = _uiHidden ? 0 : 1;
|
||||
ActionBar.gameObject.SetActive(!_uiHidden);
|
||||
};
|
||||
|
||||
Input.Player.OverrideShutdown.performed += context =>
|
||||
{
|
||||
var currentEntity = ResolveCurrentEntity?.Invoke();
|
||||
if (currentEntity != null)
|
||||
PilotOperationController.RequestOverrideShutdown(!currentEntity.OverrideShutdown);
|
||||
};
|
||||
|
||||
Input.Player.Ping.performed += context => PilotOperationController.RequestSensorPing();
|
||||
Input.Player.ToggleHeatsinks.performed += context =>
|
||||
{
|
||||
var currentEntity = ResolveCurrentEntity?.Invoke();
|
||||
if (currentEntity != null)
|
||||
PilotOperationController.RequestHeatsinksEnabled(!currentEntity.HeatsinksEnabled);
|
||||
};
|
||||
Input.Player.ToggleShield.performed += context => PilotOperationController.RequestShieldToggle();
|
||||
Input.Player.TargetReticle.performed += context => PilotOperationController.RequestTargetReticle();
|
||||
Input.Player.TargetNearest.performed += context => PilotOperationController.RequestTargetNearest();
|
||||
Input.Player.TargetNext.performed += context => PilotOperationController.RequestTargetNext();
|
||||
Input.Player.TargetPrevious.performed += context => PilotOperationController.RequestTargetPrevious();
|
||||
}
|
||||
|
||||
private void RegisterActionBarInput()
|
||||
{
|
||||
foreach (var controlPath in (RuntimePlayerSettings?.InputSettings?.ActionBarInputs ?? Enumerable.Empty<string>()).OrderBy(input => input))
|
||||
CreateActionBarSlot(controlPath);
|
||||
}
|
||||
|
||||
private void CreateActionBarSlot(string controlPath)
|
||||
{
|
||||
var action = new InputAction(binding: controlPath);
|
||||
_actionBarActions.Add(action);
|
||||
|
||||
var slot = UnityEngine.Object.Instantiate(ActionBarSlot, ActionBar);
|
||||
slot.ControlPath = controlPath;
|
||||
slot.Binding = null;
|
||||
_actionBarSlots.Add(slot);
|
||||
|
||||
action.started += context => slot.Binding?.Activate();
|
||||
action.canceled += context => slot.Binding?.Deactivate();
|
||||
|
||||
var shortName = controlPath.Substring(controlPath.LastIndexOf('/') + 1);
|
||||
var sprite = Resources.Load<Sprite>($"Sprites/Input/{shortName}");
|
||||
if (sprite != null)
|
||||
{
|
||||
slot.InputIcon.sprite = sprite;
|
||||
slot.InputLabel.gameObject.SetActive(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
slot.InputLabel.text = shortName;
|
||||
slot.InputIcon.gameObject.SetActive(false);
|
||||
}
|
||||
|
||||
slot.PointerEnterTrigger.OnPointerEnterAsObservable().Subscribe(_ =>
|
||||
{
|
||||
DragSession.RegisterTarget(dragAction => ActionBarPresentation.RequestBinding(slot, dragAction));
|
||||
});
|
||||
slot.PointerExitTrigger.OnPointerExitAsObservable().Subscribe(_ => DragSession.UnregisterTarget());
|
||||
}
|
||||
|
||||
private static bool IsTextInputFocused()
|
||||
{
|
||||
return EventSystem.current != null &&
|
||||
EventSystem.current.currentSelectedGameObject != null &&
|
||||
EventSystem.current.currentSelectedGameObject.GetComponent<TMP_InputField>() != null;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 055f68d70b7c7634991717c468672f15
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
|
||||
public sealed class AetheriaUnityGameplayLoopShell
|
||||
{
|
||||
public bool Paused { get; set; }
|
||||
public Func<Entity> ResolveCurrentEntity { get; set; }
|
||||
public Func<bool> IsCurrentEntityUndocked { get; set; }
|
||||
public Action ApplyLatestZoneRender { get; set; }
|
||||
public AetheriaUnityCurrentEntityPresentation CurrentEntityPresentation { get; set; }
|
||||
public AetheriaUnityPilotFrameController PilotFrameController { get; set; }
|
||||
public AetheriaUnityTargetPresentation TargetPresentation { get; set; }
|
||||
|
||||
public void Tick(float deltaTime, float time)
|
||||
{
|
||||
if (Paused)
|
||||
return;
|
||||
|
||||
ApplyLatestZoneRender?.Invoke();
|
||||
CurrentEntityPresentation?.Tick(deltaTime);
|
||||
if (IsCurrentEntityUndocked?.Invoke() == true)
|
||||
PilotFrameController?.Tick(ResolveCurrentEntity?.Invoke(), deltaTime, time);
|
||||
}
|
||||
|
||||
public void LateTick()
|
||||
{
|
||||
TargetPresentation?.UpdateTargetIndicators(
|
||||
ResolveCurrentEntity?.Invoke(),
|
||||
IsCurrentEntityUndocked?.Invoke() == true,
|
||||
CurrentEntityPresentation);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: f4705e6dd36d4d89add3f3751008bf82
|
||||
|
|
@ -1,165 +0,0 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
using Cinemachine;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using GameCult.Mesh;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
||||
public sealed class AetheriaUnityGameplaySceneWiring
|
||||
{
|
||||
public ZoneRenderer ZoneRenderer { get; set; }
|
||||
public CinemachineVirtualCamera DockCamera { get; set; }
|
||||
public CinemachineVirtualCamera FollowCamera { get; set; }
|
||||
public MenuPanel Menu { get; set; }
|
||||
public TradeMenu TradeMenu { get; set; }
|
||||
public CanvasGroup GameplayUI { get; set; }
|
||||
public InventoryMenu Inventory { get; set; }
|
||||
public InventoryPanel ShipPanel { get; set; }
|
||||
public InventoryPanel TargetShipPanel { get; set; }
|
||||
public SchematicDisplay SchematicDisplay { get; set; }
|
||||
public SchematicDisplay TargetSchematicDisplay { get; set; }
|
||||
public PlaceUIElementWorldspace[] Crosshairs { get; set; } = Array.Empty<PlaceUIElementWorldspace>();
|
||||
public Prototype LockIndicator { get; set; }
|
||||
public GameObject HitMarker { get; set; }
|
||||
public float HitMarkerDuration { get; set; }
|
||||
public Image TargetShieldsBackground { get; set; }
|
||||
public Image TargetShieldsIcon { get; set; }
|
||||
public Color ShieldColor { get; set; }
|
||||
public Color NoShieldColor { get; set; }
|
||||
public Sprite ShieldIcon { get; set; }
|
||||
public Sprite NoShieldIcon { get; set; }
|
||||
public Prototype HostileTargetIndicator { get; set; }
|
||||
public Prototype FriendlyTargetIndicator { get; set; }
|
||||
|
||||
private AetheriaClientState _targetPresentationState;
|
||||
|
||||
private AetheriaClientState TargetPresentationState
|
||||
{
|
||||
get
|
||||
{
|
||||
_targetPresentationState ??= AetheriaUnityRuntimeClientProvider.RuntimeState("unity-target-presentation");
|
||||
return _targetPresentationState;
|
||||
}
|
||||
}
|
||||
public PlaceUIElementWorldspace ViewDot { get; set; }
|
||||
public PlaceUIElementWorldspace TargetIndicator { get; set; }
|
||||
public Image TargetHitpointsFill { get; set; }
|
||||
public Image TargetVisibilityFill { get; set; }
|
||||
public Image VisibilityToTargetFill { get; set; }
|
||||
public Image TargetShieldsFill { get; set; }
|
||||
public MainMenu MainMenu { get; set; }
|
||||
|
||||
public void ConfigureCurrentEntityPresentation(
|
||||
AetheriaUnityCurrentEntityPresentation presentation,
|
||||
AetheriaRuntimeCatalogSnapshot runtimeCatalog)
|
||||
{
|
||||
if (presentation == null)
|
||||
return;
|
||||
|
||||
presentation.ZoneRenderer = ZoneRenderer;
|
||||
presentation.RuntimeCatalog = runtimeCatalog;
|
||||
presentation.DockCamera = DockCamera;
|
||||
presentation.FollowCamera = FollowCamera;
|
||||
presentation.Menu = Menu;
|
||||
presentation.TradeMenu = TradeMenu;
|
||||
presentation.GameplayUI = GameplayUI;
|
||||
presentation.ShipPanel = ShipPanel;
|
||||
presentation.TargetShipPanel = TargetShipPanel;
|
||||
presentation.SchematicDisplay = SchematicDisplay;
|
||||
presentation.TargetSchematicDisplay = TargetSchematicDisplay;
|
||||
presentation.Crosshairs = Crosshairs;
|
||||
presentation.LockIndicator = LockIndicator;
|
||||
presentation.HitMarker = HitMarker;
|
||||
presentation.HitMarkerDuration = HitMarkerDuration;
|
||||
presentation.TargetImages = new ImageTargetPresentation
|
||||
{
|
||||
TargetShieldsBackground = TargetShieldsBackground,
|
||||
TargetShieldsIcon = TargetShieldsIcon,
|
||||
ShieldColor = ShieldColor,
|
||||
NoShieldColor = NoShieldColor,
|
||||
ShieldIcon = ShieldIcon,
|
||||
NoShieldIcon = NoShieldIcon
|
||||
};
|
||||
}
|
||||
|
||||
public void ConfigureTargetPresentation(
|
||||
AetheriaUnityTargetPresentation presentation,
|
||||
AetheriaRuntimeCatalogSnapshot runtimeCatalog,
|
||||
AetheriaUnityPresentationEntityIndex presentationEntityIndex)
|
||||
{
|
||||
if (presentation == null)
|
||||
return;
|
||||
|
||||
presentation.ZoneRenderer = ZoneRenderer;
|
||||
presentation.RuntimeCatalog = runtimeCatalog;
|
||||
presentation.HostileTargetIndicator = HostileTargetIndicator;
|
||||
presentation.FriendlyTargetIndicator = FriendlyTargetIndicator;
|
||||
presentation.ViewDot = ViewDot;
|
||||
presentation.TargetIndicator = TargetIndicator;
|
||||
presentation.TargetHitpointsFill = TargetHitpointsFill;
|
||||
presentation.TargetVisibilityFill = TargetVisibilityFill;
|
||||
presentation.VisibilityToTargetFill = VisibilityToTargetFill;
|
||||
presentation.TargetShieldsFill = TargetShieldsFill;
|
||||
presentation.ResolveEntity = daemonEntityIndex =>
|
||||
presentationEntityIndex != null &&
|
||||
presentationEntityIndex.TryGetPresentationEntityByDaemonIndex(daemonEntityIndex, out var entity)
|
||||
? entity
|
||||
: null;
|
||||
presentation.ResolveZoneContacts = ReadZoneContacts;
|
||||
}
|
||||
|
||||
private AetheriaRuntimeZoneContactsDocument ReadZoneContacts()
|
||||
{
|
||||
try
|
||||
{
|
||||
return TargetPresentationState.ZoneContacts.Latest();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogWarning($"Failed to read Aetheria zone contacts for target presentation: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void ConfigureInventoryDragSession(AetheriaUnityDragSession dragSession)
|
||||
{
|
||||
Inventory?.SetDragSession(dragSession);
|
||||
ShipPanel?.SetDragSession(dragSession);
|
||||
TargetShipPanel?.SetDragSession(dragSession);
|
||||
}
|
||||
|
||||
public void ConfigureActionBarPresentation(
|
||||
AetheriaUnityActionBarPresentation actionBarPresentation,
|
||||
AetheriaUnityGameplayInputShell gameplayInputShell,
|
||||
AetheriaRuntimeCatalogSnapshot runtimeCatalog,
|
||||
GameSettings settings,
|
||||
Func<Entity> resolveCurrentEntity,
|
||||
Func<AetheriaControl> resolveActionBarControl)
|
||||
{
|
||||
actionBarPresentation?.Bind(
|
||||
gameplayInputShell?.ActionBarSlots ?? Array.Empty<ActionBarSlot>(),
|
||||
runtimeCatalog,
|
||||
settings,
|
||||
resolveCurrentEntity,
|
||||
resolveActionBarControl);
|
||||
Inventory?.SetActionBarPresentation(actionBarPresentation);
|
||||
}
|
||||
|
||||
public void ConfigureRuntimeInputScreenShell(AetheriaUnityMenuShell menuShell)
|
||||
{
|
||||
MainMenu?.SetRuntimeInputScreenShell(menuShell.CanOpenRuntimeInputScreen, menuShell.ShowRuntimeInputScreen);
|
||||
}
|
||||
|
||||
public void ConfigurePresentationEntityIndex(AetheriaUnityPresentationEntityIndex presentationEntityIndex)
|
||||
{
|
||||
Inventory?.SetPresentationEntityIndex(presentationEntityIndex);
|
||||
ShipPanel?.SetPresentationEntityIndex(presentationEntityIndex);
|
||||
TargetShipPanel?.SetPresentationEntityIndex(presentationEntityIndex);
|
||||
foreach (var localMenu in UnityEngine.Object.FindObjectsByType<LocalMenu>(FindObjectsSortMode.None))
|
||||
localMenu.SetPresentationEntityIndex(presentationEntityIndex);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,63 +0,0 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
|
||||
public sealed class AetheriaUnityLoadoutItemFactory
|
||||
{
|
||||
private readonly ItemManager _itemManager;
|
||||
private readonly AetheriaRuntimeCatalogSnapshot _catalog;
|
||||
|
||||
public AetheriaUnityLoadoutItemFactory(
|
||||
ItemManager itemManager,
|
||||
AetheriaRuntimeCatalogSnapshot catalog)
|
||||
{
|
||||
_itemManager = itemManager ?? throw new ArgumentNullException(nameof(itemManager));
|
||||
_catalog = catalog ?? throw new ArgumentNullException(nameof(catalog));
|
||||
}
|
||||
|
||||
public ItemInstance CreateLoadoutItem(AetheriaRuntimeLoadoutItemCommit item)
|
||||
{
|
||||
if (item == null)
|
||||
return null;
|
||||
|
||||
return CreateLoadoutItem(
|
||||
item.ItemKey,
|
||||
item.Quality,
|
||||
item.Durability,
|
||||
Math.Max(1, item.Quantity));
|
||||
}
|
||||
|
||||
public ItemInstance CreateLoadoutItem(AetheriaRuntimeLoadoutItemSnapshot item)
|
||||
{
|
||||
if (item == null)
|
||||
return null;
|
||||
|
||||
return CreateLoadoutItem(
|
||||
item.ItemKey,
|
||||
item.Quality,
|
||||
item.Durability,
|
||||
Math.Max(1, item.Quantity));
|
||||
}
|
||||
|
||||
private ItemInstance CreateLoadoutItem(
|
||||
string itemKey,
|
||||
double quality,
|
||||
double durability,
|
||||
int quantity)
|
||||
{
|
||||
var typedItem = _catalog.FindItem(itemKey ?? "");
|
||||
if (typedItem == null)
|
||||
return null;
|
||||
|
||||
if (typedItem.Stackable)
|
||||
return _itemManager.CreateSimpleCommodityInstance(typedItem, Math.Max(1, quantity));
|
||||
|
||||
var instance = _itemManager.CreateCraftedInstance(typedItem, (float)quality);
|
||||
if (instance is EquippableItem equippable && durability > 0)
|
||||
equippable.Durability = (float)durability;
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: f14a61accda77214798bd71817fa2dcb
|
||||
|
|
@ -1,129 +0,0 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
|
||||
public sealed class AetheriaUnityMenuShell
|
||||
{
|
||||
public MainMenu MainMenu { get; set; }
|
||||
public GameObject HelpScreen { get; set; }
|
||||
public InputDisplayLayout InputDisplayLayout { get; set; }
|
||||
public GameObject UiRoot { get; set; }
|
||||
public MenuPanel Menu { get; set; }
|
||||
public CanvasGroup GameplayUI { get; set; }
|
||||
public Func<Entity> ResolveCurrentEntity { get; set; }
|
||||
public Func<bool> IsCurrentEntityUndocked { get; set; }
|
||||
public Func<Entity, Entity> ResolveObservedTarget { get; set; }
|
||||
public Action<bool> SetPaused { get; set; }
|
||||
public Action EnablePlayerInput { get; set; }
|
||||
public Action DisablePlayerInput { get; set; }
|
||||
public Action UpdatePlayerPanel { get; set; }
|
||||
public Action<Entity> UpdateTargetPanel { get; set; }
|
||||
|
||||
private bool _menuShownBeforeFullscreen;
|
||||
|
||||
public bool CanOpenRuntimeInputScreen()
|
||||
{
|
||||
return ResolveCurrentEntity?.Invoke() != null &&
|
||||
HelpScreen != null &&
|
||||
InputDisplayLayout != null;
|
||||
}
|
||||
|
||||
public void ShowRuntimeInputScreen()
|
||||
{
|
||||
ShowFullscreenMenu(HelpScreen);
|
||||
}
|
||||
|
||||
public void ToggleFullscreenMenu(GameObject menu)
|
||||
{
|
||||
if (IsTextInputFocused() || menu == null || ResolveCurrentEntity?.Invoke() == null)
|
||||
return;
|
||||
|
||||
if (menu.activeSelf)
|
||||
HideFullscreenMenu(menu);
|
||||
else
|
||||
ShowFullscreenMenu(menu);
|
||||
}
|
||||
|
||||
public void ToggleMenuTab(MenuTab tab)
|
||||
{
|
||||
if (IsTextInputFocused() || MainMenu == null || Menu == null)
|
||||
return;
|
||||
if (MainMenu.gameObject.activeSelf)
|
||||
return;
|
||||
|
||||
if (Menu.gameObject.activeSelf && Menu.CurrentTab == tab)
|
||||
{
|
||||
Menu.gameObject.SetActive(false);
|
||||
if (IsCurrentEntityUndocked?.Invoke() == true)
|
||||
{
|
||||
EnablePlayerInput?.Invoke();
|
||||
RefreshCurrentPanels();
|
||||
if (GameplayUI != null)
|
||||
GameplayUI.gameObject.SetActive(true);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
DisablePlayerInput?.Invoke();
|
||||
Menu.ShowTab(tab);
|
||||
if (GameplayUI != null)
|
||||
GameplayUI.gameObject.SetActive(false);
|
||||
}
|
||||
|
||||
private void ShowFullscreenMenu(GameObject menu)
|
||||
{
|
||||
if (IsTextInputFocused() || menu == null || ResolveCurrentEntity?.Invoke() == null)
|
||||
return;
|
||||
|
||||
if (MainMenu != null && MainMenu.gameObject != menu)
|
||||
MainMenu.gameObject.SetActive(false);
|
||||
if (HelpScreen != null && HelpScreen != menu)
|
||||
HelpScreen.SetActive(false);
|
||||
|
||||
SetPaused?.Invoke(true);
|
||||
menu.SetActive(true);
|
||||
if (UiRoot != null)
|
||||
UiRoot.SetActive(false);
|
||||
|
||||
_menuShownBeforeFullscreen = Menu != null && Menu.gameObject.activeSelf;
|
||||
if (!_menuShownBeforeFullscreen)
|
||||
DisablePlayerInput?.Invoke();
|
||||
}
|
||||
|
||||
private void HideFullscreenMenu(GameObject menu)
|
||||
{
|
||||
if (menu == null || ResolveCurrentEntity?.Invoke() == null)
|
||||
return;
|
||||
|
||||
SetPaused?.Invoke(false);
|
||||
menu.SetActive(false);
|
||||
if (UiRoot != null)
|
||||
UiRoot.SetActive(true);
|
||||
|
||||
if (!_menuShownBeforeFullscreen)
|
||||
{
|
||||
EnablePlayerInput?.Invoke();
|
||||
RefreshCurrentPanels();
|
||||
}
|
||||
}
|
||||
|
||||
private void RefreshCurrentPanels()
|
||||
{
|
||||
var currentEntity = ResolveCurrentEntity?.Invoke();
|
||||
UpdatePlayerPanel?.Invoke();
|
||||
UpdateTargetPanel?.Invoke(ResolveObservedTarget?.Invoke(currentEntity));
|
||||
}
|
||||
|
||||
private static bool IsTextInputFocused()
|
||||
{
|
||||
return EventSystem.current != null &&
|
||||
EventSystem.current.currentSelectedGameObject != null &&
|
||||
EventSystem.current.currentSelectedGameObject.GetComponent<TMP_InputField>() != null;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue