Database Support

Refactored almost everything, but most importantly we now integrate with RethinkDB for game data.
This commit is contained in:
hyperion51 2020-03-22 19:05:26 +00:00
commit 0b46d5ee39
839 changed files with 77349 additions and 112660 deletions

View file

@ -3,308 +3,17 @@ using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using UniRx;
using Unity.Mathematics;
using UnityEditor;
using UnityEngine;
using UnityEngine.Serialization;
// TODO: USE THIS EVERYWHERE
using static Unity.Mathematics.math;
using Object = UnityEngine.Object;
public class DatabaseListView : EditorWindow
{
// Singleton to avoid multiple instances of window.
private static DatabaseListView _instance;
public Guid SelectedItem;
public GUIStyle SelectedStyle;
private bool[] _gearFoldouts;
private bool _itemsFoldout;
private bool _compoundFoldout;
private bool _simpleFoldout;
private bool _commoditiesFoldout;
//private bool _consumablesFoldout;
private Type[] _itemTypes;
private bool _listItemStyle;
private GUIStyle _listStyleOdd;
private GUIStyle _listStyleEven;
private static DatabaseInspector _inspector;
private Type[] _entryTypes;
private bool[] _entryFoldouts;
private const float LineHeight = 20;
// Set instance on reloading the window, else it gets lost after script reload (due to PlayMode changes, ...).
public DatabaseListView()
{
_instance = this;
}
public static DatabaseListView ShowWindow()
{
if (_instance == null)
{
// "Get existing open window or if none, make a new one:" says documentation.
// But if called after script reloads a second instance will be opened! => Custom singleton required.
DatabaseListView window = EditorWindow.GetWindow<DatabaseListView>();
window.titleContent = new GUIContent("DB List");
_instance = window;
_instance.InitStyles();
window.Show();
}
else
_instance.Focus();
return _instance;
}
public GUIStyle ListItemStyle =>
(_listItemStyle = !_listItemStyle) ? _listStyleEven : _listStyleOdd;
[MenuItem("Window/Aetheria Database Tools")]
static void Init()
{
ShowWindow();
}
void OnEnable()
{
_inspector = DatabaseInspector.ShowWindow();
_itemTypes = typeof(IItem).GetAllInterfaceClasses();
_entryTypes = typeof(IDatabaseEntry).GetAllInterfaceClasses().Where(t => !t.GetInterfaces().Contains(typeof(IItem))&& !t.GetInterfaces().Contains(typeof(IItemInstance))).ToArray();
_gearFoldouts = new bool[_itemTypes.Length];
_entryFoldouts = new bool[_entryTypes.Length];
InitStyles();
Database.OnDataUpdate += Repaint;
}
private void InitStyles()
{
_listStyleOdd = new GUIStyle
{
normal = {background = XKCDColors.LightGrey.ToTexture()},
margin = new RectOffset(0, 0, 0, 0)
};
_listStyleEven = new GUIStyle
{
normal = {background = Color.Lerp(XKCDColors.LightGrey,Color.white,.5f).ToTexture()},
margin = new RectOffset(0, 0, 0, 0)
};
SelectedStyle = new GUIStyle
{
normal = {background = 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;
Action<IDatabaseEntry> select = item =>
{
SelectedItem = item.GetId();
Repaint();
_inspector.entry = Database.Get(SelectedItem);
_inspector.Repaint();
};
using (var h = new EditorGUILayout.HorizontalScope(ListItemStyle))
{
_itemsFoldout = EditorGUILayout.Foldout(_itemsFoldout, "Items", true);
}
if (_itemsFoldout)
{
var items = Database.AllEntries.Where(item => item is IItem).Cast<IItem>().ToArray();
for (var i = 0; i < _itemTypes.Length; i++)
{
using (var h = new EditorGUILayout.HorizontalScope(ListItemStyle))
{
GUILayout.Space(10);
_gearFoldouts[i] = EditorGUILayout.Foldout(_gearFoldouts[i],
((NameAttribute) _itemTypes[i].GetCustomAttribute(typeof(NameAttribute)))?.Name ?? _itemTypes[i].Name,
true);
}
if (_gearFoldouts[i])
{
foreach (var item in items.Where(e=>e.GetType()==_itemTypes[i]))
{
var style = ListItemStyle;
var selected = SelectedItem == item.GetId();
using (var h = new EditorGUILayout.HorizontalScope(selected?SelectedStyle:style))
{
if (h.rect.Contains(currentEvent.mousePosition))
{
if (currentEventType == EventType.MouseDrag)
{
DragAndDrop.PrepareStartDrag();
DragAndDrop.SetGenericData("Item", item.GetId());
DragAndDrop.StartDrag("Database Item");
}
else if (currentEventType == EventType.MouseUp)
select(item);
}
GUILayout.Space(20);
GUILayout.Label(item.Entry.Name, selected ? EditorStyles.whiteLabel : GUI.skin.label);
}
}
using (var h = new EditorGUILayout.HorizontalScope(ListItemStyle))
{
if(GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
CreateItem(_itemTypes[i]);
GUILayout.Space(20);
GUILayout.Label("New " + _itemTypes[i].Name);
var rect = EditorGUILayout.GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
GUI.DrawTexture(rect, Icons.Instance.plus, ScaleMode.StretchToFill, true, 1, Color.black, 0, 0);
}
}
}
}
var entries = Database.AllEntries.Where(item => !(item is IItem)).ToArray();
for (var i = 0; i < _entryTypes.Length; i++)
{
using (var h = new EditorGUILayout.HorizontalScope(ListItemStyle))
{
_entryFoldouts[i] = EditorGUILayout.Foldout(_entryFoldouts[i],
((NameAttribute) _entryTypes[i].GetCustomAttribute(typeof(NameAttribute)))?.Name ?? _entryTypes[i].Name,
true);
}
if (_entryFoldouts[i])
{
foreach (var entry in entries.Where(e=>e.GetType()==_entryTypes[i]))
{
var style = ListItemStyle;
var selected = SelectedItem == entry.GetId();
using (var h = new EditorGUILayout.HorizontalScope(selected?SelectedStyle:style))
{
if (h.rect.Contains(currentEvent.mousePosition))
{
if (currentEventType == EventType.MouseDrag)
{
DragAndDrop.PrepareStartDrag();
DragAndDrop.SetGenericData("Item", entry.GetId());
DragAndDrop.StartDrag("Database Item");
}
else if (currentEventType == EventType.MouseUp)
select(entry);
}
GUILayout.Space(10);
GUILayout.Label(entry.Entry.Name, selected ? EditorStyles.whiteLabel : GUI.skin.label);
}
}
using (var h = new EditorGUILayout.HorizontalScope(ListItemStyle))
{
if(GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
CreateItem(_entryTypes[i]);
GUILayout.Space(10);
GUILayout.Label("New " + _entryTypes[i].Name);
var rect = EditorGUILayout.GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
GUI.DrawTexture(rect, Icons.Instance.plus, ScaleMode.StretchToFill, true, 1, Color.black, 0, 0);
}
}
}
// EditorGUILayout.BeginHorizontal(ListItemStyle);
// _commoditiesFoldout = EditorGUILayout.Foldout(_commoditiesFoldout, "Commodities", true);
// EditorGUILayout.EndHorizontal();
// if (_commoditiesFoldout)
// {
// using (var h = new EditorGUILayout.HorizontalScope(ListItemStyle))
// {
// GUILayout.Space(10);
// _simpleFoldout = EditorGUILayout.Foldout(_simpleFoldout, "Simple", true);
// }
// if (_simpleFoldout)
// {
// foreach (var item in Database.Items.Values.Where(e=>e.GetType()==typeof(ItemData)).Cast<ItemData>())
// {
// var style = ListItemStyle;
// var selected = SelectedItem == item.ID;
// using (var h = new EditorGUILayout.HorizontalScope(selected?_selectedStyle:style))
// {
// if(GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
// select(item);
// GUILayout.Space(20);
// GUILayout.Label(item.Name, selected ? EditorStyles.whiteLabel : GUI.skin.label);
// }
// }
//
// using (var h = new EditorGUILayout.HorizontalScope(ListItemStyle))
// {
// if(GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
// CreateItem(typeof(ItemData));
// GUILayout.Space(20);
// var rect = EditorGUILayout.GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
// GUI.DrawTexture(rect, GlobalData.Instance.plus, ScaleMode.StretchToFill, true, 1, Color.black, 0, 0);
// GUILayout.Label("New Simple Commodity");
// }
// }
//
// using (var h = new EditorGUILayout.HorizontalScope(ListItemStyle))
// {
// GUILayout.Space(10);
// _compoundFoldout = EditorGUILayout.Foldout(_compoundFoldout, "Compound", true);
// }
// if (_compoundFoldout)
// {
// foreach (var item in Database.Items.Values.Where(e=>e.GetType()==typeof(CraftedItem)).Cast<CraftedItem>())
// {
// var style = ListItemStyle;
// var selected = SelectedItem == item.GetId();
// using (var h = new EditorGUILayout.HorizontalScope(selected?_selectedStyle:style))
// {
// if (GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
// select(item);
// GUILayout.Space(20);
// GUILayout.Label(item.Item.Name, selected ? EditorStyles.whiteLabel : GUI.skin.label);
// }
// }
//
// using (var h = new EditorGUILayout.HorizontalScope(ListItemStyle))
// {
// if(GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
// CreateItem(typeof(CraftedItem));
// GUILayout.Space(20);
// var rect = EditorGUILayout.GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
// GUI.DrawTexture(rect, GlobalData.Instance.plus, ScaleMode.StretchToFill, true, 1, Color.black, 0, 0);
// GUILayout.Label("New Compound Commodity");
// }
// }
// }
// EditorGUILayout.BeginHorizontal(ListItemStyle);
// _consumablesFoldout = EditorGUILayout.Foldout(_consumablesFoldout, "Consumables", true);
// EditorGUILayout.EndHorizontal();
// if (_consumablesFoldout)
// {
//
// }
// HACK: This ensures none of the controls in this window can be focused (usually from clicking foldouts)
GUI.SetNextControlName("");
GUI.FocusControl("");
}
private void CreateItem(Type type)
{
var newEntry = (IDatabaseEntry) Activator.CreateInstance(type);
SelectedItem = newEntry.GetId();
newEntry.Entry.Name = $"New {type.Name}";
Database.Save(newEntry);
}
}
using static Unity.Mathematics.math;
public class DatabaseInspector : EditorWindow
{
public IDatabaseEntry entry;
public static DatabaseCache DatabaseCache;
public DatabaseEntry entry;
// Singleton to avoid multiple instances of window.
private static DatabaseInspector _instance;
@ -313,7 +22,7 @@ public class DatabaseInspector : EditorWindow
private GUIStyle _labelStyle;
private Vector2 _view;
private const float IconSize = 1.0f / 16;
private static HardpointData _hardpoint;
// private static HardpointData _hardpoint;
private static float2 _dragOffset;
private bool _ctrlDown;
private string[] _hardpointTypes;
@ -346,23 +55,23 @@ public class DatabaseInspector : EditorWindow
void OnEnable()
{
_list = DatabaseListView.ShowWindow();
Database.OnDataUpdate += Repaint;
DatabaseCache.OnDataUpdateLocal += _ => Repaint();
DatabaseCache.OnDataUpdateRemote += _ => EditorDispatcher.Dispatch(Repaint);
wantsMouseMove = true;
_hardpoint = null;
_hardpointTypes = Enum.GetNames(typeof(HardpointType));
}
public void Inspect(object obj, bool inspectablesOnly = false, ICraftable craftable = null)
public void Inspect(object obj, bool inspectablesOnly = false)
{
foreach (var field in obj.GetType().GetFields())
{
Inspect(obj, field, inspectablesOnly, craftable);
Inspect(obj, field, inspectablesOnly);
}
}
public void Inspect(object obj, FieldInfo field, bool inspectablesOnly = false, ICraftable craftable = null)
public void Inspect(object obj, FieldInfo field, bool inspectablesOnly = false)
{
var inspectable = field.GetCustomAttribute<InspectableAttribute>();
var inspectable = field.GetCustomAttribute<InspectableFieldAttribute>();
if (inspectable == null && inspectablesOnly) return;
var type = field.FieldType;
@ -381,6 +90,10 @@ public class DatabaseInspector : EditorWindow
else
field.SetValue(obj, Inspect(field.Name.SplitCamelCase(), (float) value));
}
else if (type == typeof(float4[]) && inspectable is InspectableAnimationCurveAttribute)
{
field.SetValue(obj, InspectAnimationCurve(field.Name.SplitCamelCase(), (float4[]) value));
}
else if (type == typeof(int))
{
if (inspectable is RangedIntInspectableAttribute)
@ -394,10 +107,16 @@ public class DatabaseInspector : EditorWindow
else if (type.IsEnum) field.SetValue(obj, Inspect(field.Name.SplitCamelCase(), (int) field.GetValue(obj), Enum.GetNames(field.FieldType)));
//else if (field.FieldType == typeof(Color)) Inspect(field.Name, () => (Color) field.GetValue(obj), c => field.SetValue(obj, c));
else if (type == typeof(bool)) field.SetValue(obj, Inspect(field.Name.SplitCamelCase(), (bool) value));
else if (type == typeof(string)) field.SetValue(obj, Inspect(field.Name.SplitCamelCase(), (string) value, inspectable is InspectableTextAttribute));
else if (type == typeof(string))
{
if(inspectable is InspectablePrefabAttribute)
field.SetValue(obj, InspectGameObject(field.Name.SplitCamelCase(), (string) value));
else
field.SetValue(obj, Inspect(field.Name.SplitCamelCase(), (string) value, inspectable is InspectableTextAttribute));
}
else if (type == typeof(GameObject)) field.SetValue(obj, Inspect(field.Name.SplitCamelCase(), (GameObject) value));
else if (type == typeof(AnimationCurve)) field.SetValue(obj, Inspect(field.Name.SplitCamelCase(), (AnimationCurve) value));
else if (type == typeof(PerformanceStat)) field.SetValue(obj, Inspect(field.Name.SplitCamelCase(), (PerformanceStat) value, craftable));
else if (type == typeof(PerformanceStat)) field.SetValue(obj, Inspect(field.Name.SplitCamelCase(), (PerformanceStat) value, obj as CraftedItemData));
else if (type == typeof(PerformanceStat[]))
{
EditorGUILayout.LabelField(field.Name.SplitCamelCase(), EditorStyles.boldLabel);
@ -409,7 +128,7 @@ public class DatabaseInspector : EditorWindow
stats = new PerformanceStat[damageTypes.Length];
for (var i = 0; i < stats.Length; i++)
{
stats[i] = Inspect(damageTypes[i].SplitCamelCase(), stats[i], craftable);
stats[i] = Inspect(damageTypes[i].SplitCamelCase(), stats[i], obj as CraftedItemData);
}
field.SetValue(obj, stats);
}
@ -431,7 +150,7 @@ public class DatabaseInspector : EditorWindow
Inspect(field.Name.SplitCamelCase(), ref list, link.EntryType);
}
else if (type == typeof(Guid) && link != null) field.SetValue(obj, Inspect(field.Name.SplitCamelCase(), (Guid) value, link.EntryType));
else if (type.GetCustomAttribute<InspectableAttribute>() != null)
else if (type.GetCustomAttribute<InspectableFieldAttribute>() != null)
{
EditorGUILayout.Space();
using (new EditorGUILayout.HorizontalScope())
@ -447,12 +166,12 @@ public class DatabaseInspector : EditorWindow
field.SetValue(obj, value = newSelection==0?null:Activator.CreateInstance(subTypes[newSelection-1]));
} else if(value == null) field.SetValue(obj, value = Activator.CreateInstance(type));
}
if(value != null) Inspect(field.GetValue(obj), inspectablesOnly, craftable);
if(value != null) Inspect(field.GetValue(obj), inspectablesOnly);
}
else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
{
var listType = field.FieldType.GenericTypeArguments[0];
if (listType.GetCustomAttribute<InspectableAttribute>() != null)
if (listType.GetCustomAttribute<InspectableFieldAttribute>() != null)
{
EditorGUILayout.Space();
using (new EditorGUILayout.VerticalScope(GUI.skin.box))
@ -484,7 +203,7 @@ public class DatabaseInspector : EditorWindow
EditorGUILayout.Space();
Inspect(o, inspectablesOnly, craftable);
Inspect(o, inspectablesOnly);
}
}
using (new EditorGUILayout.HorizontalScope(_list.ListItemStyle))
@ -502,7 +221,7 @@ public class DatabaseInspector : EditorWindow
menu.AddItem(new GUIContent(behaviorType.Name), false, () =>
{
list.Add(Activator.CreateInstance(behaviorType));
Database.Save(entry);
DatabaseCache.Add(entry);
});
}
menu.ShowAsContext();
@ -670,6 +389,15 @@ public class DatabaseInspector : EditorWindow
}
}
public string InspectGameObject(string label, string value)
{
using (var h = new EditorGUILayout.HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
return AssetDatabase.GetAssetPath(EditorGUILayout.ObjectField(AssetDatabase.LoadAssetAtPath<GameObject>(value), typeof(GameObject), false));
}
}
public GameObject Inspect(string label, GameObject value)
{
using (var h = new EditorGUILayout.HorizontalScope())
@ -679,6 +407,20 @@ public class DatabaseInspector : EditorWindow
}
}
public float4[] InspectAnimationCurve(string label, float4[] value)
{
var val = value != null && value.Length > 0
? new AnimationCurve(value.Select(v => new Keyframe(v.x, v.y, v.z, v.w)).ToArray())
: new AnimationCurve();
using (var h = new EditorGUILayout.HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
val = EditorGUILayout.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 AnimationCurve Inspect(string label, AnimationCurve value)
{
using (var h = new EditorGUILayout.HorizontalScope())
@ -695,15 +437,15 @@ public class DatabaseInspector : EditorWindow
public Guid Inspect(string label, Guid value, Type entryType)
{
EditorGUILayout.LabelField(label, EditorStyles.boldLabel);
var valueEntry = Database.Get(value);
var valueEntry = DatabaseCache.Get(value);
using (var h = new EditorGUILayout.HorizontalScope(GUI.skin.box))
{
GUILayout.Label(valueEntry?.Entry.Name ?? $"Assign a {entryType.Name} by dragging from the list panel.");
GUILayout.Label((valueEntry as INamedEntry)?.EntryName ?? valueEntry?.ID.ToString() ?? $"Assign a {entryType.Name} by dragging from the list panel.");
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 = Database.Get(guid);
var dragEntry = DatabaseCache.Get(guid);
if(Event.current.type == EventType.DragUpdated)
DragAndDrop.visualMode = dragEntry != null && dragEntry.GetType()==entryType ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected;
else if(Event.current.type == EventType.DragPerform)
@ -739,7 +481,7 @@ public class DatabaseInspector : EditorWindow
{
using (var h = new EditorGUILayout.HorizontalScope(_list.ListItemStyle))
{
GUILayout.Label(Database.Get(ingredient.Key).Entry.Name);
GUILayout.Label(DatabaseCache.Get<ItemData>(ingredient.Key).Name);
value[ingredient.Key] = EditorGUILayout.DelayedIntField(value[ingredient.Key], GUILayout.Width(50));
var rect = EditorGUILayout.GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
@ -785,7 +527,7 @@ public class DatabaseInspector : EditorWindow
{
using (var h = new EditorGUILayout.HorizontalScope(_list.ListItemStyle))
{
GUILayout.Label(Database.Get(ingredient.Key).Entry.Name);
GUILayout.Label(DatabaseCache.Get(ingredient.Key).ID.ToString());
value[ingredient.Key] = EditorGUILayout.DelayedFloatField(value[ingredient.Key], GUILayout.Width(50));
var rect = EditorGUILayout.GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
@ -831,7 +573,7 @@ public class DatabaseInspector : EditorWindow
{
using (var h = new EditorGUILayout.HorizontalScope(_list.ListItemStyle))
{
GUILayout.Label(Database.Get(ingredient).Entry.Name);
GUILayout.Label((DatabaseCache.Get(ingredient) as INamedEntry)?.EntryName ?? DatabaseCache.Get(ingredient).ID.ToString());
var rect = EditorGUILayout.GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
GUI.DrawTexture(rect, Icons.Instance.minus, ScaleMode.StretchToFill, true, 1, Color.black, 0, 0);
@ -843,7 +585,7 @@ public class DatabaseInspector : EditorWindow
if (v.rect.Contains(Event.current.mousePosition))
{
var guid = DragAndDrop.GetGenericData("Item");
var dragObj = DragAndDrop.GetGenericData("Item") is Guid ? ((Guid) guid).Get() : null;
var dragObj = DragAndDrop.GetGenericData("Item") is Guid ? DatabaseCache.Get((Guid) guid) : null;
if(Event.current.type == EventType.DragUpdated)
DragAndDrop.visualMode = entryType.IsInstanceOfType(dragObj) ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected;
else if(Event.current.type == EventType.DragPerform)
@ -859,7 +601,7 @@ public class DatabaseInspector : EditorWindow
}
}
public PerformanceStat Inspect(string label, PerformanceStat value, ICraftable craftable)
public PerformanceStat Inspect(string label, PerformanceStat value, CraftedItemData crafted)
{
using (new EditorGUILayout.VerticalScope())
{
@ -887,14 +629,14 @@ public class DatabaseInspector : EditorWindow
{
GUILayout.Label("", GUILayout.Width(width));
GUILayout.Label("Ingredient", GUILayout.ExpandWidth(false));
var ingredients = craftable.CraftingIngredients.Keys.Select(Database.Get).Where(i => i is CraftedItem).Cast<CraftedItem>().ToList();
var ingredient = Database.Get(value.Ingredient) as CraftedItem;
var names = ingredients.Select(i => i.Entry.Name).Append("None").ToArray();
var selected = value.Ingredient == Guid.Empty || !craftable.CraftingIngredients.ContainsKey(value.Ingredient)
var ingredients = crafted.Ingredients.Keys.Select(DatabaseCache.Get).Where(i => i is CraftedItemData).Cast<CraftedItemData>().ToList();
var ingredient = value.Ingredient != null ? DatabaseCache.Get(value.Ingredient.Value) as CraftedItemData : null;
var names = ingredients.Select(i => i.Name).Append("None").ToArray();
var selected = value.Ingredient == null || !crafted.Ingredients.ContainsKey(value.Ingredient.Value)
? names.Length - 1
: ingredients.IndexOf(ingredient);
var selection = EditorGUILayout.Popup(selected, names);
value.Ingredient = selection == names.Length - 1 ? Guid.Empty : ingredients[selection].GetId();
value.Ingredient = selection == names.Length - 1 ? (Guid?) null : ingredients[selection].ID;
}
EditorGUILayout.Space();
@ -932,22 +674,22 @@ public class DatabaseInspector : EditorWindow
EditorGUI.BeginChangeCheck();
var dataEntry = entry.Entry;
var dataEntry = entry;
using (new EditorGUILayout.HorizontalScope())
{
if(GUILayout.Button("Print JSON"))
Debug.Log(entry.ToJson());
if (GUILayout.Button("Duplicate"))
{
Database.Duplicate(entry);
}
if (GUILayout.Button("Delete Entry"))
{
Database.Delete(entry);
entry = null;
return;
}
// if (GUILayout.Button("Duplicate"))
// {
// DatabaseCache.Duplicate(entry);
// }
// if (GUILayout.Button("Delete Entry"))
// {
// DatabaseCache.Delete(entry);
// entry = null;
// return;
// }
}
using (var h = new EditorGUILayout.HorizontalScope())
@ -956,10 +698,10 @@ public class DatabaseInspector : EditorWindow
EditorGUILayout.LabelField(dataEntry.ID.ToString());
}
Inspect(entry, true, entry as ICraftable);
Inspect(entry, true);
#region Hull
var hull = entry as Hull;
var hull = entry as HullData;
if (hull != null)
{
EditorGUILayout.Space();
@ -969,121 +711,121 @@ public class DatabaseInspector : EditorWindow
}
#endregion
#region Loadout
var loadout = entry as LoadoutDefinition;
if (loadout != null)
{
EditorGUILayout.Space();
EditorGUILayout.LabelField("Loadout Hull", EditorStyles.boldLabel);
var loadoutHull = Database.Get(loadout.Hull) as Hull;
if (loadoutHull != null)
{
// Reserve slots in the loadout for all equippable (non-hull) hardpoints
var hardpoints = loadoutHull.Hardpoints.Where(h => h.Type != HardpointType.Hull).ToArray();
if (loadout.Items.Count < hardpoints.Length)
loadout.Items.AddRange(Enumerable.Repeat(Guid.Empty, hardpoints.Length - loadout.Items.Count));
EditorGUILayout.Space();
using (var h = new EditorGUILayout.HorizontalScope())
{
GUILayout.Label($"Equipped Items: {loadout.Items.Sum(i=>((IItem) Database.Get(i))?.Data.Size ?? 0)}/{loadoutHull.Capacity.Min}", EditorStyles.boldLabel);
GUILayout.Label($"Mass: {loadout.Items.Sum(i=>((IItem) Database.Get(i))?.Data.Mass ?? 0)}", EditorStyles.boldLabel, GUILayout.ExpandWidth(false));
}
int itemIndex = 0;
using (var v = new EditorGUILayout.VerticalScope(GUI.skin.box))
{
for (; itemIndex < hardpoints.Length; itemIndex++)
{
var hp = hardpoints[itemIndex];
var loadoutItem = Database.Get(loadout.Items[itemIndex]) as IEquippable;
if (loadoutItem != null && loadoutItem.HardpointType != hp.Type)
{
loadout.Items[itemIndex] = Guid.Empty;
Debug.Log($"Invalid Item \"{loadoutItem.Entry.Name}\" in {Enum.GetName(typeof(HardpointType),hp.Type)} hardpoint for loadout \"{loadout.Entry.Name}\"");
Database.Save(entry);
}
using (var h = new EditorGUILayout.HorizontalScope(_list.ListItemStyle))
{
if (h.rect.Contains(current.mousePosition) &&
(currentEventType == EventType.DragUpdated || currentEventType == EventType.DragPerform))
{
var guid = (Guid) DragAndDrop.GetGenericData("Item");
var draggedEquippable = Database.Get(guid) as IEquippable;
var good = draggedEquippable != null && draggedEquippable.HardpointType == hp.Type;
if (currentEventType == EventType.DragUpdated)
DragAndDrop.visualMode = good ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected;
else if (currentEventType == EventType.DragPerform && good)
{
DragAndDrop.AcceptDrag();
loadout.Items[itemIndex] = guid;
Database.Save(entry);
}
}
GUILayout.Label(Enum.GetName(typeof(HardpointType), hp.Type));
if (loadoutItem == null || loadoutItem.HardpointType != hp.Type)
GUILayout.Label("Empty Hardpoint", GUILayout.ExpandWidth(false));
else
{
GUILayout.Label(loadoutItem.Entry.Name, GUILayout.ExpandWidth(false));
var rect = EditorGUILayout.GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
GUI.DrawTexture(rect, Icons.Instance.minus, ScaleMode.StretchToFill, true, 1, Color.black, 0, 0);
if (GUI.Button(rect, GUIContent.none, GUIStyle.none))
loadout.Items[itemIndex] = Guid.Empty;
}
}
}
}
EditorGUILayout.Space();
EditorGUILayout.LabelField("Cargo", EditorStyles.boldLabel);
using (var v = new EditorGUILayout.VerticalScope(GUI.skin.box))
{
if (v.rect.Contains(current.mousePosition) &&
(currentEventType == EventType.DragUpdated || currentEventType == EventType.DragPerform))
{
var guid = (Guid) DragAndDrop.GetGenericData("Item");
var dragItem = Database.Get(guid) as IItem;
if (currentEventType == EventType.DragUpdated)
DragAndDrop.visualMode = dragItem != null ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected;
else if (currentEventType == EventType.DragPerform && dragItem != null)
{
DragAndDrop.AcceptDrag();
loadout.Items.Add(guid);
Database.Save(entry);
}
}
if(itemIndex == loadout.Items.Count)
GUILayout.Label("Nothing Here!");
for (; itemIndex < loadout.Items.Count; itemIndex++)
{
var loadoutItem = Database.Get(loadout.Items[itemIndex]) as IItem;
using (var h = new EditorGUILayout.HorizontalScope(_list.ListItemStyle))
{
GUILayout.Label(loadoutItem?.Entry.Name ?? "Invalid Item");
var rect = EditorGUILayout.GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
GUI.DrawTexture(rect, Icons.Instance.minus, ScaleMode.StretchToFill, true, 1, Color.black, 0, 0);
if (GUI.Button(rect, GUIContent.none, GUIStyle.none))
loadout.Items.RemoveAt(itemIndex--);
}
}
}
}
}
#endregion
// #region Loadout
// var loadout = entry as LoadoutData;
// if (loadout != null)
// {
// EditorGUILayout.Space();
// EditorGUILayout.LabelField("Loadout Hull", EditorStyles.boldLabel);
//
// var loadoutHull = Database.Get(loadout.Hull) as HullData;
//
// if (loadoutHull != null)
// {
// // Reserve slots in the loadout for all equippable (non-hull) hardpoints
// var hardpoints = loadoutHull.Hardpoints.Where(h => h.Type != HardpointType.Hull).ToArray();
// if (loadout.Items.Count < hardpoints.Length)
// loadout.Items.AddRange(Enumerable.Repeat(Guid.Empty, hardpoints.Length - loadout.Items.Count));
//
// // EditorGUILayout.Space();
// // using (var h = new EditorGUILayout.HorizontalScope())
// // {
// // GUILayout.Label($"Equipped Items: {loadout.Items.Sum(i=>((ItemData) Database.Get(i))?.Data.Size ?? 0)}/{loadoutHull.Capacity.Min}", EditorStyles.boldLabel);
// // GUILayout.Label($"Mass: {loadout.Items.Sum(i=>((ItemData) Database.Get(i))?.Data.Mass ?? 0)}", EditorStyles.boldLabel, GUILayout.ExpandWidth(false));
// // }
//
// int itemIndex = 0;
// using (var v = new EditorGUILayout.VerticalScope(GUI.skin.box))
// {
// for (; itemIndex < hardpoints.Length; itemIndex++)
// {
// var hp = hardpoints[itemIndex];
//
// var loadoutItem = Database.Get(loadout.Items[itemIndex]) as EquippableItemData;
//
// if (loadoutItem != null && loadoutItem.HardpointType != hp.Type)
// {
// loadout.Items[itemIndex] = Guid.Empty;
// Debug.Log($"Invalid Item \"{loadoutItem.Name}\" in {Enum.GetName(typeof(HardpointType),hp.Type)} hardpoint for loadout \"{loadout.Name}\"");
// Database.Save(entry);
// }
//
// using (var h = new EditorGUILayout.HorizontalScope(_list.ListItemStyle))
// {
// if (h.rect.Contains(current.mousePosition) &&
// (currentEventType == EventType.DragUpdated || currentEventType == EventType.DragPerform))
// {
// var guid = (Guid) DragAndDrop.GetGenericData("Item");
// var draggedEquippable = Database.Get(guid) as EquippableItemData;
// var good = draggedEquippable != null && draggedEquippable.HardpointType == hp.Type;
// if (currentEventType == EventType.DragUpdated)
// DragAndDrop.visualMode = good ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected;
// else if (currentEventType == EventType.DragPerform && good)
// {
// DragAndDrop.AcceptDrag();
// loadout.Items[itemIndex] = guid;
//
// Database.Save(entry);
// }
// }
//
// GUILayout.Label(Enum.GetName(typeof(HardpointType), hp.Type));
// if (loadoutItem == null || loadoutItem.HardpointType != hp.Type)
// GUILayout.Label("Empty Hardpoint", GUILayout.ExpandWidth(false));
// else
// {
// GUILayout.Label(loadoutItem.Name, GUILayout.ExpandWidth(false));
// var rect = EditorGUILayout.GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
// GUI.DrawTexture(rect, Icons.Instance.minus, ScaleMode.StretchToFill, true, 1, Color.black, 0, 0);
// if (GUI.Button(rect, GUIContent.none, GUIStyle.none))
// loadout.Items[itemIndex] = Guid.Empty;
// }
// }
// }
// }
//
// EditorGUILayout.Space();
// EditorGUILayout.LabelField("Cargo", EditorStyles.boldLabel);
//
// using (var v = new EditorGUILayout.VerticalScope(GUI.skin.box))
// {
// if (v.rect.Contains(current.mousePosition) &&
// (currentEventType == EventType.DragUpdated || currentEventType == EventType.DragPerform))
// {
// var guid = (Guid) DragAndDrop.GetGenericData("Item");
// var dragItem = Database.Get(guid) as ItemData;
// if (currentEventType == EventType.DragUpdated)
// DragAndDrop.visualMode = dragItem != null ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected;
// else if (currentEventType == EventType.DragPerform && dragItem != null)
// {
// DragAndDrop.AcceptDrag();
//
// loadout.Items.Add(guid);
// Database.Save(entry);
// }
// }
// if(itemIndex == loadout.Items.Count)
// GUILayout.Label("Nothing Here!");
// for (; itemIndex < loadout.Items.Count; itemIndex++)
// {
// var loadoutItem = Database.Get(loadout.Items[itemIndex]) as ItemData;
// using (var h = new EditorGUILayout.HorizontalScope(_list.ListItemStyle))
// {
// GUILayout.Label(loadoutItem?.Name ?? "Invalid Item");
// var rect = EditorGUILayout.GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
// GUI.DrawTexture(rect, Icons.Instance.minus, ScaleMode.StretchToFill, true, 1, Color.black, 0, 0);
// if (GUI.Button(rect, GUIContent.none, GUIStyle.none))
// loadout.Items.RemoveAt(itemIndex--);
// }
// }
// }
// }
// }
// #endregion
if (EditorGUI.EndChangeCheck())
{
Database.Save(entry);
DatabaseCache.Add(entry);
}
EditorGUILayout.EndScrollView();

View file

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

View file

@ -0,0 +1,378 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using RethinkDb.Driver;
using RethinkDb.Driver.Net;
using UniRx;
using Unity.Mathematics;
using UnityEditor;
using UnityEngine;
using UnityEngine.Serialization;
// TODO: USE THIS EVERYWHERE
using static Unity.Mathematics.math;
using Object = UnityEngine.Object;
public class DatabaseListView : EditorWindow
{
// Singleton to avoid multiple instances of window.
private static DatabaseListView _instance;
public Guid SelectedItem;
public GUIStyle SelectedStyle;
public static RethinkDB R = RethinkDB.R;
private Connection _connection;
private DatabaseCache _databaseCache;
private bool[] _gearFoldouts;
private bool _itemsFoldout;
private bool _compoundFoldout;
private bool _simpleFoldout;
private bool _commoditiesFoldout;
//private bool _consumablesFoldout;
private Type[] _itemTypes;
private bool _listItemStyle;
private GUIStyle _listStyleOdd;
private GUIStyle _listStyleEven;
private static DatabaseInspector _inspector;
private Type[] _entryTypes;
private bool[] _entryFoldouts;
private string _connectionString;
private const float LineHeight = 20;
// Set instance on reloading the window, else it gets lost after script reload (due to PlayMode changes, ...).
public DatabaseListView()
{
_instance = this;
}
public static DatabaseListView ShowWindow()
{
if (_instance == null)
{
// "Get existing open window or if none, make a new one:" says documentation.
// But if called after script reloads a second instance will be opened! => Custom singleton required.
DatabaseListView window = EditorWindow.GetWindow<DatabaseListView>();
window.titleContent = new GUIContent("DB List");
_instance = window;
_instance.InitStyles();
window.Show();
}
else
_instance.Focus();
return _instance;
}
public GUIStyle ListItemStyle =>
(_listItemStyle = !_listItemStyle) ? _listStyleEven : _listStyleOdd;
[MenuItem("Window/Aetheria Database Tools")]
static void Init()
{
ShowWindow();
}
void OnEnable()
{
// Create database cache
_databaseCache = new DatabaseCache();
_databaseCache.OnDataUpdateLocal += _ => Repaint();
_databaseCache.OnDataUpdateRemote += _ => EditorDispatcher.Dispatch(Repaint);
DatabaseInspector.DatabaseCache = _databaseCache;
_inspector = DatabaseInspector.ShowWindow();
_itemTypes = typeof(ItemData).GetAllChildClasses()
.Where(t => t.GetCustomAttribute<InspectableAttribute>() != null).ToArray();
_entryTypes = typeof(DatabaseEntry).GetAllChildClasses()
.Where(t => t.GetCustomAttribute<InspectableAttribute>() != null && !typeof(ItemData).IsAssignableFrom(t)).ToArray();
_gearFoldouts = new bool[_itemTypes.Length];
_entryFoldouts = new bool[_entryTypes.Length];
if (EditorPrefs.HasKey("RethinkDB.URL"))
_connectionString = EditorPrefs.GetString("RethinkDB.URL");
else
_connectionString = "Enter DB URL";
InitStyles();
}
private void InitStyles()
{
var isDark = EditorGUIUtility.isProSkin;
_listStyleOdd = new GUIStyle
{
normal = {background = isDark ? XKCDColors.DarkGrey.ToTexture() : XKCDColors.LightGrey.ToTexture()},
margin = new RectOffset(0, 0, 0, 0)
};
_listStyleEven = new GUIStyle
{
normal = {background = isDark ? Color.Lerp(XKCDColors.DarkGrey,Color.black,.5f).ToTexture() : Color.Lerp(XKCDColors.LightGrey,Color.white,.5f).ToTexture()},
margin = new RectOffset(0, 0, 0, 0)
};
SelectedStyle = new GUIStyle
{
normal = {background = isDark ? 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 (var h = new EditorGUILayout.HorizontalScope())
{
_connectionString = EditorGUILayout.TextField(_connectionString);
if (GUILayout.Button("Connect"))
{
EditorPrefs.SetString("RethinkDB.URL", _connectionString);
_connection = R.Connection().Hostname(_connectionString).Port(RethinkDBConstants.DefaultPort).Timeout(60).Connect();
Debug.Log("Connected to RethinkDB");
// When entries are changed locally, push the changes to RethinkDB
_databaseCache.OnDataUpdateLocal +=
entry =>
{
Debug.Log($"Uploading entry to RethinkDB: {entry.ID}");
R.Db("Aetheria").Table("Items").Replace(entry).RunAsync(_connection);
};
// Get all item data from RethinkDB
Task.Run(async () =>
{
var result = await R.Db("Aetheria").Table("Items").RunCursorAsync<DatabaseEntry>(_connection);
while (await result.MoveNextAsync())
{
var entry = result.Current;
Debug.Log($"Received entry from RethinkDB: {entry.ID}");
_databaseCache.Add(entry, true);
}
}).WrapErrors();
// Subscribe to changes from RethinkDB
Task.Run(async () =>
{
var result = await R.Db("Aetheria").Table("Items").Changes()
.RunChangesAsync<DatabaseEntry>(_connection);
while (await result.MoveNextAsync())
{
var change = result.Current;
var entry = change.NewValue;
Debug.Log($"Received change to entry from RethinkDB: {entry.ID}");
_databaseCache.Add(entry, true);
}
}).WrapErrors();
}
}
GUILayout.Space(5);
Action<DatabaseEntry> select = item =>
{
SelectedItem = item.ID;
Repaint();
_inspector.entry = _databaseCache.Get(SelectedItem);
_inspector.Repaint();
};
using (var h = new EditorGUILayout.HorizontalScope(ListItemStyle))
{
_itemsFoldout = EditorGUILayout.Foldout(_itemsFoldout, "Items", true);
}
if (_itemsFoldout)
{
var items = _databaseCache.AllEntries.Where(item => item is ItemData).Cast<ItemData>().ToArray();
for (var i = 0; i < _itemTypes.Length; i++)
{
using (var h = new EditorGUILayout.HorizontalScope(ListItemStyle))
{
GUILayout.Space(10);
_gearFoldouts[i] = EditorGUILayout.Foldout(_gearFoldouts[i],
((NameAttribute) _itemTypes[i].GetCustomAttribute(typeof(NameAttribute)))?.Name ?? _itemTypes[i].Name,
true);
}
if (_gearFoldouts[i])
{
foreach (var item in items.Where(e=>e.GetType()==_itemTypes[i]))
{
var style = ListItemStyle;
var selected = SelectedItem == item.ID;
using (var h = new EditorGUILayout.HorizontalScope(selected?SelectedStyle:style))
{
if (h.rect.Contains(currentEvent.mousePosition))
{
if (currentEventType == EventType.MouseDrag)
{
DragAndDrop.PrepareStartDrag();
DragAndDrop.SetGenericData("Item", item.ID);
DragAndDrop.StartDrag("Database Item");
}
else if (currentEventType == EventType.MouseUp)
select(item);
}
GUILayout.Space(20);
GUILayout.Label(item.Name, selected ? EditorStyles.whiteLabel : GUI.skin.label);
}
}
using (var h = new EditorGUILayout.HorizontalScope(ListItemStyle))
{
if(GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
CreateItem(_itemTypes[i]);
GUILayout.Space(20);
GUILayout.Label("New " + _itemTypes[i].Name);
var rect = EditorGUILayout.GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
GUI.DrawTexture(rect, Icons.Instance.plus, ScaleMode.StretchToFill, true, 1, Color.black, 0, 0);
}
}
}
}
var entries = _databaseCache.AllEntries.Where(item => !(item is ItemData)).ToArray();
for (var i = 0; i < _entryTypes.Length; i++)
{
using (var h = new EditorGUILayout.HorizontalScope(ListItemStyle))
{
_entryFoldouts[i] = EditorGUILayout.Foldout(_entryFoldouts[i],
((NameAttribute) _entryTypes[i].GetCustomAttribute(typeof(NameAttribute)))?.Name ?? _entryTypes[i].Name,
true);
}
if (_entryFoldouts[i])
{
int index = 0;
foreach (var entry in entries.Where(e=>e.GetType()==_entryTypes[i]))
{
index++;
var style = ListItemStyle;
var selected = SelectedItem == entry.ID;
using (var h = new EditorGUILayout.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(10);
GUILayout.Label((entry as INamedEntry)?.EntryName ?? index.ToString(), selected ? EditorStyles.whiteLabel : GUI.skin.label);
}
}
using (var h = new EditorGUILayout.HorizontalScope(ListItemStyle))
{
if(GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
CreateItem(_entryTypes[i]);
GUILayout.Space(10);
GUILayout.Label("New " + _entryTypes[i].Name);
var rect = EditorGUILayout.GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
GUI.DrawTexture(rect, Icons.Instance.plus, ScaleMode.StretchToFill, true, 1, Color.black, 0, 0);
}
}
}
// EditorGUILayout.BeginHorizontal(ListItemStyle);
// _commoditiesFoldout = EditorGUILayout.Foldout(_commoditiesFoldout, "Commodities", true);
// EditorGUILayout.EndHorizontal();
// if (_commoditiesFoldout)
// {
// using (var h = new EditorGUILayout.HorizontalScope(ListItemStyle))
// {
// GUILayout.Space(10);
// _simpleFoldout = EditorGUILayout.Foldout(_simpleFoldout, "Simple", true);
// }
// if (_simpleFoldout)
// {
// foreach (var item in Database.Items.Values.Where(e=>e.GetType()==typeof(ItemData)).Cast<ItemData>())
// {
// var style = ListItemStyle;
// var selected = SelectedItem == item.ID;
// using (var h = new EditorGUILayout.HorizontalScope(selected?_selectedStyle:style))
// {
// if(GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
// select(item);
// GUILayout.Space(20);
// GUILayout.Label(item.Name, selected ? EditorStyles.whiteLabel : GUI.skin.label);
// }
// }
//
// using (var h = new EditorGUILayout.HorizontalScope(ListItemStyle))
// {
// if(GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
// CreateItem(typeof(ItemData));
// GUILayout.Space(20);
// var rect = EditorGUILayout.GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
// GUI.DrawTexture(rect, GlobalData.Instance.plus, ScaleMode.StretchToFill, true, 1, Color.black, 0, 0);
// GUILayout.Label("New Simple Commodity");
// }
// }
//
// using (var h = new EditorGUILayout.HorizontalScope(ListItemStyle))
// {
// GUILayout.Space(10);
// _compoundFoldout = EditorGUILayout.Foldout(_compoundFoldout, "Compound", true);
// }
// if (_compoundFoldout)
// {
// foreach (var item in Database.Items.Values.Where(e=>e.GetType()==typeof(CraftedItem)).Cast<CraftedItem>())
// {
// var style = ListItemStyle;
// var selected = SelectedItem == item.GetId();
// using (var h = new EditorGUILayout.HorizontalScope(selected?_selectedStyle:style))
// {
// if (GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
// select(item);
// GUILayout.Space(20);
// GUILayout.Label(item.Item.Name, selected ? EditorStyles.whiteLabel : GUI.skin.label);
// }
// }
//
// using (var h = new EditorGUILayout.HorizontalScope(ListItemStyle))
// {
// if(GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
// CreateItem(typeof(CraftedItem));
// GUILayout.Space(20);
// var rect = EditorGUILayout.GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
// GUI.DrawTexture(rect, GlobalData.Instance.plus, ScaleMode.StretchToFill, true, 1, Color.black, 0, 0);
// GUILayout.Label("New Compound Commodity");
// }
// }
// }
// EditorGUILayout.BeginHorizontal(ListItemStyle);
// _consumablesFoldout = EditorGUILayout.Foldout(_consumablesFoldout, "Consumables", true);
// EditorGUILayout.EndHorizontal();
// if (_consumablesFoldout)
// {
//
// }
// HACK: This ensures none of the controls in this window can be focused (usually from clicking foldouts)
//GUI.SetNextControlName("");
//GUI.FocusControl("");
}
private void CreateItem(Type type)
{
var newEntry = (DatabaseEntry) Activator.CreateInstance(type);
SelectedItem = newEntry.ID;
if(newEntry is INamedEntry entry)
entry.EntryName = $"New {type.Name}";
_databaseCache.Add(newEntry);
}
}

View 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;
}
}

View file

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

View file

@ -0,0 +1,79 @@
using System;
using MessagePack;
using MessagePack.Formatters;
using Newtonsoft.Json;
using RethinkDb.Driver;
using RethinkDb.Driver.Net;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
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("asgard.gamecult.games").Port(RethinkDBConstants.DefaultPort).Timeout(60).Connect();
}
public void OnGUI()
{
var obj = new ShieldData() {ID = Guid.NewGuid(), Name = "Foo"} as DatabaseEntry;
// This button serializes the texture reference and print the JSON representation
if (GUILayout.Button("Print MsgPack JSON"))
Debug.Log(MessagePackSerializer.SerializeToJson(obj));
if (GUILayout.Button("Print Newtonsoft JSON"))
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
}

View file

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