Equipment Data Simplification

Removed blueprint system for crafting (and excised anything depending on that)
Implemented smootherstep and used it for wormhole animation
Quality dependent durability and heat exponents are now global instead of item specific
Database list view now groups equipment by manufacturer
Thrusters can now consume energy
Weapons can have reloads even when they don't have ammo
This commit is contained in:
Reinier Vens 2021-03-22 05:22:31 +00:00
commit 47189c8a7e
49 changed files with 6943 additions and 1548 deletions

View file

@ -204,78 +204,6 @@ public class DatabaseInspector : EditorWindow
Inspect(field.Name.SplitCamelCase(), ref dict, link.EntryType, ranged.Min, ranged.Max);
else Inspect(field.Name.SplitCamelCase(), ref dict, link.EntryType);
}
else if (type == typeof(List<BlueprintStatEffect>))
{
var list = (List<BlueprintStatEffect>) field.GetValue(obj);
if(list==null) field.SetValue(obj, list = new List<BlueprintStatEffect>());
var blueprint = obj as BlueprintData;
var blueprintItem = DatabaseCache.Get(blueprint.Item);
if (blueprintItem is EquippableItemData equippableBlueprintItem)
{
Space();
LabelField(field.Name.SplitCamelCase(), EditorStyles.boldLabel);
using (var v = new VerticalScope(GUI.skin.box))
{
var ingredients = blueprint.Ingredients.Keys
.Select(i => DatabaseCache.Get(i))
.Where(i => i is CraftedItemData)
.Cast<CraftedItemData>().ToArray();
var ingredientNames = ingredients.Select(i => i.Name).ToArray();
foreach (var effect in list)
{
using (var v2 = new VerticalScope(_list.ListItemStyle))
{
using (var h = new HorizontalScope())
{
GUILayout.Label("Ingredient", GUILayout.Width(width));
if(ingredients.Length==0)
GUILayout.Label("No Ingredients!");
else
{
var selectedIngredientIndex =
Array.FindIndex(ingredients, item => item.ID == effect.Ingredient);
if (selectedIngredientIndex == -1)
{
selectedIngredientIndex = 0;
GUI.changed = true;
}
var newSelection = Popup(selectedIngredientIndex, ingredientNames);
if (newSelection != selectedIngredientIndex)
GUI.changed = true;
effect.Ingredient = ingredients[newSelection].ID;
}
var rect = GetControlRect(false,
GUILayout.Width(EditorGUIUtility.singleLineHeight));
GUI.DrawTexture(rect, Icons.Instance.minus, ScaleMode.StretchToFill, true, 1,
LabelColor, 0, 0);
if (GUI.Button(rect, GUIContent.none, GUIStyle.none))
{
list.Remove(effect);
break;
}
}
Inspect(ref effect.StatReference, equippableBlueprintItem);
}
}
using (var h = new HorizontalScope(_list.ListItemStyle))
{
GUILayout.Label("Add new Stat Effect", 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 (GUI.Button(rect, GUIContent.none, GUIStyle.none))
{
list.Add(new BlueprintStatEffect());
}
}
}
}
}
else if (type == typeof(List<Guid>) && link != null)
{
var list = (List<Guid>) field.GetValue(obj);
@ -735,6 +663,14 @@ public class DatabaseInspector : EditorWindow
}
}
}
var rect = GetControlRect(false,
GUILayout.Width(EditorGUIUtility.singleLineHeight));
GUI.DrawTexture(rect, Icons.Instance.minus, ScaleMode.StretchToFill, true, 1,
LabelColor, 0, 0);
if (GUI.Button(rect, GUIContent.none, GUIStyle.none))
{
return Guid.Empty;
}
}
return value;
@ -974,103 +910,6 @@ public class DatabaseInspector : EditorWindow
}
}
}
public void Inspect(string label, ref StatReference effect)
{
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, effect.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;
effect.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, effect.Stat);
if (selectedStatIndex == -1)
{
selectedStatIndex = 0;
GUI.changed = true;
}
var newSelection = Popup(selectedStatIndex, statNames);
if (newSelection != selectedStatIndex)
GUI.changed = true;
effect.Stat = statNames[newSelection];
}
}
}
}
}
public void Inspect(ref StatReference effect, EquippableItemData item)
{
using (new VerticalScope())
{
var behaviorNames = new []{item.Name}.Concat(item.Behaviors.Select(b => b.GetType().Name)).ToArray();
var selectedBehaviorIndex = Array.IndexOf(behaviorNames, effect.Target);
if (selectedBehaviorIndex == -1)
{
selectedBehaviorIndex = 0;
GUI.changed = true;
}
using (new HorizontalScope())
{
GUILayout.Label("Behavior", GUILayout.Width(width));
var newSelection = Popup(selectedBehaviorIndex, behaviorNames);
if (newSelection != selectedBehaviorIndex)
GUI.changed = true;
effect.Target = behaviorNames[newSelection];
}
using (new HorizontalScope())
{
GUILayout.Label("Stat", GUILayout.Width(width));
var stats = (selectedBehaviorIndex == 0 ? item.GetType() : item.Behaviors[selectedBehaviorIndex-1].GetType()).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, effect.Stat);
if (selectedStatIndex == -1)
{
selectedStatIndex = 0;
GUI.changed = true;
}
var newSelection = Popup(selectedStatIndex, statNames);
if (newSelection != selectedStatIndex)
GUI.changed = true;
effect.Stat = statNames[newSelection];
}
}
}
}
public Shape Inspect(string label, Shape value, HullData hull = null)
{
@ -1144,6 +983,58 @@ public class DatabaseInspector : EditorWindow
return value;
}
public void Inspect(string label, ref StatReference effect)
{
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, effect.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;
effect.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, effect.Stat);
if (selectedStatIndex == -1)
{
selectedStatIndex = 0;
GUI.changed = true;
}
var newSelection = Popup(selectedStatIndex, statNames);
if (newSelection != selectedStatIndex)
GUI.changed = true;
effect.Stat = statNames[newSelection];
}
}
}
}
}
public PerformanceStat Inspect(string label, PerformanceStat value, bool isSimple = false)
{
if(value == null)
@ -1167,13 +1058,13 @@ public class DatabaseInspector : EditorWindow
GUILayout.Label("", GUILayout.Width(width));
if (!isSimple)
{
GUILayout.Label("H", _labelStyle);
value.HeatDependent = Toggle(value.HeatDependent);
GUILayout.Label("HEx", _labelStyle, GUILayout.Width(labelWidth + 5));
GUILayout.Label("H", _labelStyle, GUILayout.Width(labelWidth));
value.HeatExponentMultiplier = DelayedFloatField(value.HeatExponentMultiplier);
GUILayout.Label("D", _labelStyle);
value.DurabilityDependent = Toggle(value.DurabilityDependent);
GUILayout.Label("QEx", _labelStyle, GUILayout.Width(labelWidth + 5));
GUILayout.Label("D", _labelStyle, GUILayout.Width(labelWidth));
value.DurabilityExponentMultiplier = DelayedFloatField(value.DurabilityExponentMultiplier);
GUILayout.Label("Q", _labelStyle, GUILayout.Width(labelWidth));
value.QualityExponent = DelayedFloatField(value.QualityExponent);
}
else
@ -1222,6 +1113,9 @@ public class DatabaseInspector : EditorWindow
return;
}
if(entry is INamedEntry namedEntry)
GUILayout.Label(namedEntry.EntryName, EditorStyles.boldLabel);
_view = BeginScrollView(
_view,
false,
@ -1282,86 +1176,6 @@ public class DatabaseInspector : EditorWindow
}
#endregion
#region Loadout
var loadout = entry as LoadoutData;
if (loadout != null)
{
Space();
LabelField("Loadout Hull", EditorStyles.boldLabel);
if (DatabaseCache.Get(loadout.Hull) is HullData loadoutHull)
{
// Reserve slots in the loadout for all equippable (non-hull) hardpoints
var hardpoints = loadoutHull.Hardpoints.Where(h => h.Type != HardpointType.Hull).ToArray();
if (loadout.Gear.Count < hardpoints.Length)
loadout.Gear.AddRange(Enumerable.Repeat(Guid.Empty, hardpoints.Length - loadout.Gear.Count));
Space();
using (var h = new HorizontalScope())
{
// GUILayout.Label($"Equipped Items: {loadout.Gear.Sum(i=>((ItemData) DatabaseCache.Get(i))?.Size ?? 0)}/{loadoutHull.Capacity.Min}", EditorStyles.boldLabel);
GUILayout.Label($"Mass: {loadout.Gear.Sum(i=>((ItemData) DatabaseCache.Get(i))?.Mass ?? 0)}", EditorStyles.boldLabel, GUILayout.ExpandWidth(false));
}
int itemIndex = 0;
using (var v = new VerticalScope(GUI.skin.box))
{
for (; itemIndex < hardpoints.Length; itemIndex++)
{
var hp = hardpoints[itemIndex];
var loadoutItem = DatabaseCache.Get(loadout.Gear[itemIndex]) as EquippableItemData;
if (loadoutItem != null && loadoutItem.HardpointType != hp.Type)
{
loadout.Gear[itemIndex] = Guid.Empty;
Debug.Log($"Invalid Item \"{loadoutItem.Name}\" in {Enum.GetName(typeof(HardpointType),hp.Type)} hardpoint for loadout \"{loadout.Name}\"");
GUI.changed = true;
}
using (var h = new HorizontalScope(_list.ListItemStyle))
{
if (h.rect.Contains(current.mousePosition) &&
(currentEventType == EventType.DragUpdated || currentEventType == EventType.DragPerform))
{
var guid = (Guid) DragAndDrop.GetGenericData("Item");
var draggedEquippable = DatabaseCache.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.Gear[itemIndex] = guid;
GUI.changed = true;
}
}
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 = 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.Gear[itemIndex] = Guid.Empty;
}
}
}
}
for (; itemIndex < loadout.Gear.Count; itemIndex++)
{
loadout.Gear.RemoveAt(itemIndex--);
GUI.changed = true;
}
}
}
#endregion
if (EditorGUI.EndChangeCheck())
{
if(!previousBytes.ByteEquals(MessagePackSerializer.Serialize(entry)))

View file

@ -48,9 +48,9 @@ public class DatabaseListView : EditorWindow
private const float LineHeight = 20;
private Vector2 _view;
private RethinkQueryStatus _queryStatus;
private Dictionary<Guid, HashSet<Guid>> _itemBlueprints = new Dictionary<Guid, HashSet<Guid>>();
private HashSet<Guid> _itemBlueprintFoldouts = new HashSet<Guid>();
private HashSet<string> _itemGroupFoldouts = new HashSet<string>();
private HashSet<Guid> _itemManufacturerFoldouts = new HashSet<Guid>();
private HashSet<(Guid, HardpointType)> _itemManufacturerTypeFoldouts = new HashSet<(Guid, HardpointType)>();
private string _filePath => Path.Combine(ActionGameManager.GameDataDirectory.FullName, _fileName);
private string _fileName = "AetherDB.msgpack";
@ -65,30 +65,17 @@ public class DatabaseListView : EditorWindow
// Create database cache
_databaseCache = new DatabaseCache(_filePath);
var onInsert = new Action<DatabaseEntry>(entry =>
{
if (entry is ItemData itemData)
{
if(!_itemBlueprints.ContainsKey(itemData.ID))
_itemBlueprints[itemData.ID] = new HashSet<Guid>();
}
if (entry is BlueprintData blueprintData)
{
if(!_itemBlueprints.ContainsKey(blueprintData.Item))
_itemBlueprints[blueprintData.Item] = new HashSet<Guid>();
_itemBlueprints[blueprintData.Item].Add(blueprintData.ID);
}
});
_databaseCache.OnDataInsertLocal += onInsert;
_databaseCache.OnDataInsertRemote += onInsert;
// var onInsert = new Action<DatabaseEntry>(entry =>
// {
// });
// _databaseCache.OnDataInsertLocal += onInsert;
// _databaseCache.OnDataInsertRemote += onInsert;
var onDelete = new Action<DatabaseEntry>(entry =>
{
if (entry is BlueprintData blueprintData)
_itemBlueprints[blueprintData.Item].Remove(blueprintData.ID);
});
_databaseCache.OnDataDeleteLocal += onDelete;
_databaseCache.OnDataDeleteRemote += onDelete;
// var onDelete = new Action<DatabaseEntry>(entry =>
// {
// });
// _databaseCache.OnDataDeleteLocal += onDelete;
// _databaseCache.OnDataDeleteRemote += onDelete;
_databaseCache.OnDataUpdateLocal += _ => Repaint();
_databaseCache.OnDataInsertLocal += _ => Repaint();
@ -176,23 +163,6 @@ public class DatabaseListView : EditorWindow
}
}
using (new HorizontalScope())
{
if (GUILayout.Button("Delete Orphaned Blueprints"))
{
int count = 0;
foreach (var blueprintData in _databaseCache.GetAll<BlueprintData>().ToArray())
{
if (_databaseCache.Get(blueprintData.Item) == null)
{
_databaseCache.Delete(blueprintData);
count++;
}
}
Debug.Log($"Deleted {count} orphaned blueprints!");
}
}
if (_queryStatus != null && _queryStatus.RetrievedItems < _queryStatus.GalaxyEntries + _queryStatus.ItemsEntries)
{
var progressRect = GetControlRect(false, 20);
@ -231,175 +201,169 @@ public class DatabaseListView : EditorWindow
}
if (_itemTypeFoldouts[i])
{
var typedItems = items.Where(e => e.GetType() == _itemTypes[i]).OrderBy(item => item.Name);
IEnumerable<IGrouping<string, ItemData>> itemGroups = new List<IGrouping<string, ItemData>>();
if(_itemTypes[i] == typeof(SimpleCommodityData))
itemGroups = typedItems.GroupBy(item => Enum.GetName(typeof(SimpleCommodityCategory), (item as SimpleCommodityData).Category));
else if(_itemTypes[i] == typeof(CompoundCommodityData))
itemGroups = typedItems.GroupBy(item => Enum.GetName(typeof(CompoundCommodityCategory), (item as CompoundCommodityData).Category));
else if(_itemTypes[i] == typeof(GearData) || _itemTypes[i] == typeof(WeaponItemData))
itemGroups = typedItems.GroupBy(item => Enum.GetName(typeof(HardpointType), (item as GearData).Hardpoint) ?? "Invalid Hardpoint");
else if (_itemTypes[i] == typeof(HullData))
itemGroups = typedItems.GroupBy(item => Enum.GetName(typeof(HullType), (item as HullData).HullType));
else itemGroups = typedItems.GroupBy(item => "All");
foreach (var itemGroup in itemGroups)
if (_itemTypes[i] == typeof(SimpleCommodityData) ||
_itemTypes[i] == typeof(CompoundCommodityData) ||
_itemTypes[i] == typeof(HullData))
{
using (var h = new HorizontalScope(ListItemStyle))
{
GUILayout.Space(20);
if (Foldout(_itemGroupFoldouts.Contains(itemGroup.Key), FormatTypeName(itemGroup.Key), true))
_itemGroupFoldouts.Add(itemGroup.Key);
else _itemGroupFoldouts.Remove(itemGroup.Key);
}
var typedItems = items
.Where(e => e.GetType() == _itemTypes[i])
.OrderBy(item => item.Name);
IEnumerable<IGrouping<string, ItemData>> itemGroups = new List<IGrouping<string, ItemData>>();
if(_itemTypes[i] == typeof(SimpleCommodityData))
itemGroups = typedItems.GroupBy(item => Enum.GetName(typeof(SimpleCommodityCategory), (item as SimpleCommodityData).Category));
else if(_itemTypes[i] == typeof(CompoundCommodityData))
itemGroups = typedItems.GroupBy(item => Enum.GetName(typeof(CompoundCommodityCategory), (item as CompoundCommodityData).Category));
else if (_itemTypes[i] == typeof(HullData))
itemGroups = typedItems.GroupBy(item => Enum.GetName(typeof(HullType), (item as HullData).HullType));
else itemGroups = typedItems.GroupBy(item => "All");
if (_itemGroupFoldouts.Contains(itemGroup.Key))
foreach (var itemGroup in itemGroups)
{
foreach (var item in itemGroup)
using (var h = new HorizontalScope(ListItemStyle))
{
var style = ListItemStyle;
var selected = SelectedItem == item.ID;
using (new HorizontalScope(selected?SelectedStyle:style))
{
using (var h = new HorizontalScope())
{
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);
if (Foldout(_itemGroupFoldouts.Contains(itemGroup.Key), FormatTypeName(itemGroup.Key), true))
_itemGroupFoldouts.Add(itemGroup.Key);
else _itemGroupFoldouts.Remove(itemGroup.Key);
}
GUILayout.Space(30);
GUILayout.Label(item.Name, selected ? EditorStyles.whiteLabel : GUI.skin.label);
}
using (var h = new HorizontalScope(GUILayout.Width(15)))
{
if (GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
{
if(_itemBlueprintFoldouts.Contains(item.ID))
_itemBlueprintFoldouts.Remove(item.ID);
else
_itemBlueprintFoldouts.Add(item.ID);
}
GUILayout.Label(_itemBlueprints[item.ID].Count.ToString());
var rect = GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
if (Event.current.type == EventType.Repaint)
{
var controlId = GUIUtility.GetControlID(1337, FocusType.Keyboard, position);
EditorStyles.foldout.Draw(rect, GUIContent.none, controlId, _itemBlueprintFoldouts.Contains(item.ID));
}
}
}
if (_itemBlueprintFoldouts.Contains(item.ID))
if (_itemGroupFoldouts.Contains(itemGroup.Key))
{
foreach (var item in itemGroup)
{
foreach (var blueprintData in _itemBlueprints[item.ID]
.Select(id => _databaseCache.Get<BlueprintData>(id))
.OrderBy(bp => bp.Quality))
var style = ListItemStyle;
var selected = SelectedItem == item.ID;
using (new HorizontalScope(selected?SelectedStyle:style))
{
var blueprintStyle = ListItemStyle;
var blueprintSelected = SelectedItem == blueprintData.ID;
using (var h = new HorizontalScope(blueprintSelected ? SelectedStyle : blueprintStyle))
using (var h = new HorizontalScope())
{
if (h.rect.Contains(currentEvent.mousePosition))
{
if (currentEventType == EventType.MouseDrag)
{
DragAndDrop.PrepareStartDrag();
DragAndDrop.SetGenericData("Item", blueprintData.ID);
DragAndDrop.SetGenericData("Item", item.ID);
DragAndDrop.StartDrag("Database Item");
}
else if (currentEventType == EventType.MouseUp)
Select(blueprintData);
Select(item);
}
GUILayout.Space(40);
GUILayout.Label(blueprintData.Name,
blueprintSelected ? EditorStyles.whiteLabel : GUI.skin.label);
GUILayout.Space(30);
GUILayout.Label(item.Name, selected ? EditorStyles.whiteLabel : GUI.skin.label);
}
}
using (var h = new HorizontalScope(ListItemStyle))
{
if (GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
{
var blueprint = new BlueprintData
{
Item = item.ID,
Name = item.Name
};
_databaseCache.Add(blueprint);
Select(blueprint);
}
GUILayout.Space(40);
GUILayout.Label("New Blueprint");
var rect = GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
GUI.DrawTexture(rect, Icons.Instance.plus, ScaleMode.StretchToFill, true, 1, LabelColor,
0, 0);
}
}
}
}
}
else
{
if (!typeof(EquippableItemData).IsAssignableFrom(_itemTypes[i]))
throw new InvalidCastException($"Type {_itemTypes[i].Name} is invalid! Expected equippable item.");
var typedItems = items
.Where(e => e.GetType() == _itemTypes[i])
.Cast<EquippableItemData>()
.OrderBy(item => item.Name);
var manufacturerGroups = typedItems.GroupBy(item => item.Manufacturer);
foreach (var manufacturerGroup in manufacturerGroups)
{
var manufacturer = _databaseCache.Get<Faction>(manufacturerGroup.Key);
var manufacturerName = manufacturer?.Name ?? "None";
using (var h = new HorizontalScope(ListItemStyle))
{
if (GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
GUILayout.Space(20);
if (Foldout(_itemManufacturerFoldouts.Contains(manufacturerGroup.Key), manufacturerName, true))
_itemManufacturerFoldouts.Add(manufacturerGroup.Key);
else _itemManufacturerFoldouts.Remove(manufacturerGroup.Key);
}
if (_itemManufacturerFoldouts.Contains(manufacturerGroup.Key))
{
if (_itemTypes[i] == typeof(GearData) || _itemTypes[i] == typeof(WeaponItemData))
{
CreateItem(_itemTypes[i], newItem =>
var itemGroups = manufacturerGroup.GroupBy(item => item.HardpointType);
foreach (var itemGroup in itemGroups)
{
if(newItem is SimpleCommodityData simpleCommodityData)
using (var h = new HorizontalScope(ListItemStyle))
{
simpleCommodityData.Category =
(SimpleCommodityCategory) Enum.Parse(typeof(SimpleCommodityCategory),
itemGroup.Key);
simpleCommodityData.Name = $"New {itemGroup.Key}";
GUILayout.Space(30);
if (Foldout(_itemManufacturerTypeFoldouts.Contains((manufacturerGroup.Key, itemGroup.Key)), Enum.GetName(typeof(HardpointType), itemGroup.Key), true))
_itemManufacturerTypeFoldouts.Add((manufacturerGroup.Key, itemGroup.Key));
else _itemManufacturerTypeFoldouts.Remove((manufacturerGroup.Key, itemGroup.Key));
}
else if(newItem is CompoundCommodityData compoundCommodityData)
if (_itemManufacturerTypeFoldouts.Contains((manufacturerGroup.Key, itemGroup.Key)))
{
compoundCommodityData.Category =
(CompoundCommodityCategory) Enum.Parse(
typeof(CompoundCommodityCategory), itemGroup.Key);
compoundCommodityData.Name = $"New {itemGroup.Key}";
foreach (var item in itemGroup)
{
var style = ListItemStyle;
var selected = SelectedItem == item.ID;
using (new HorizontalScope(selected?SelectedStyle:style))
{
using (var h = new HorizontalScope())
{
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(40);
GUILayout.Label(item.Name, selected ? EditorStyles.whiteLabel : GUI.skin.label);
}
}
}
}
else if(newItem is GearData gearData)
{
gearData.Hardpoint =
(HardpointType) Enum.Parse(typeof(HardpointType), itemGroup.Key);
gearData.Name = $"New {itemGroup.Key}";
}
else if(newItem is HullData hullData)
{
hullData.HullType = (HullType) Enum.Parse(typeof(HullType), itemGroup.Key);
hullData.Name = $"New {itemGroup.Key}";
}
});
}
}
else
{
foreach (var item in manufacturerGroup)
{
var style = ListItemStyle;
var selected = SelectedItem == item.ID;
using (new HorizontalScope(selected?SelectedStyle:style))
{
using (var h = new HorizontalScope())
{
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(30);
GUILayout.Label(item.Name, selected ? EditorStyles.whiteLabel : GUI.skin.label);
}
}
}
}
GUILayout.Space(30);
GUILayout.Label("New " + itemGroup.Key);
var rect = GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
GUI.DrawTexture(rect, Icons.Instance.plus, ScaleMode.StretchToFill, true, 1, LabelColor, 0, 0);
}
}
}
if (!itemGroups.Any())
using (var h = new HorizontalScope(ListItemStyle))
{
using (var h = new 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 = GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
GUI.DrawTexture(rect, Icons.Instance.plus, ScaleMode.StretchToFill, true, 1, LabelColor, 0, 0);
}
if(GUI.Button(h.rect, GUIContent.none, GUIStyle.none))
CreateItem(_itemTypes[i]);
GUILayout.Space(20);
GUILayout.Label("New " + FormatTypeName(_itemTypes[i].Name));
var rect = GetControlRect(false, GUILayout.Width(EditorGUIUtility.singleLineHeight));
GUI.DrawTexture(rect, Icons.Instance.plus, ScaleMode.StretchToFill, true, 1, LabelColor, 0, 0);
}
}
}

View file

@ -493,7 +493,7 @@ public class EntityInstance : MonoBehaviour
AkSoundEngine.SetObjectPosition(r.Value, r.Value.transform);
AkSoundEngine.SetRTPCValue("performance_durability", r.Key.Item.DurabilityPerformance, r.Value);
AkSoundEngine.SetRTPCValue("performance_thermal", r.Key.Item.ThermalPerformance, r.Value);
AkSoundEngine.SetRTPCValue("performance_quality", r.Key.Item.ItemManager.CompoundQuality(r.Key.Item.EquippableItem), r.Value);
AkSoundEngine.SetRTPCValue("performance_quality", r.Key.Item.EquippableItem.Quality, r.Value);
}
if (_reactor.reactor != null)
@ -503,7 +503,7 @@ public class EntityInstance : MonoBehaviour
AkSoundEngine.SetRTPCValue("reactor_load", _reactor.reactor.CurrentLoadRatio, _reactor.sfxSource);
AkSoundEngine.SetRTPCValue("performance_durability", _reactor.reactor.Item.DurabilityPerformance, _reactor.sfxSource);
AkSoundEngine.SetRTPCValue("performance_thermal", _reactor.reactor.Item.ThermalPerformance, _reactor.sfxSource);
AkSoundEngine.SetRTPCValue("performance_quality", _reactor.reactor.Item.ItemManager.CompoundQuality(_reactor.reactor.Item.EquippableItem), _reactor.sfxSource);
AkSoundEngine.SetRTPCValue("performance_quality", _reactor.reactor.Item.EquippableItem.Quality, _reactor.sfxSource);
}
foreach (var x in RadiatorMeshes)

View file

@ -96,8 +96,7 @@ public class ShipInstance : EntityInstance
AkSoundEngine.SetRTPCValue("thruster_throttle", throttle, thrusterInstance.SfxSource);
AkSoundEngine.SetRTPCValue("performance_durability", thrusterInstance.Thruster.Item.DurabilityPerformance, thrusterInstance.SfxSource);
AkSoundEngine.SetRTPCValue("performance_thermal", thrusterInstance.Thruster.Item.ThermalPerformance, thrusterInstance.SfxSource);
AkSoundEngine.SetRTPCValue("performance_quality",
thrusterInstance.Thruster.Item.ItemManager.CompoundQuality(thrusterInstance.Thruster.Item.EquippableItem), thrusterInstance.SfxSource);
AkSoundEngine.SetRTPCValue("performance_quality", thrusterInstance.Thruster.Item.EquippableItem.Quality, thrusterInstance.SfxSource);
}
}

View file

@ -38,7 +38,7 @@ public class GuidedProjectileManager : InstantWeaponEffectManager
var p = ProjectilePrototype.Instantiate<GuidedProjectile>();
p.Source = source.transform;
p.SourceEntity = source.Entity;
p.Target = target?.transform;
p.Target = target.transform;
p.Frequency = guidance.DodgeFrequency;
var hp = source.Entity.Hardpoints[item.Position.x, item.Position.y];
var barrel = source.GetBarrel(hp);
@ -56,6 +56,6 @@ public class GuidedProjectileManager : InstantWeaponEffectManager
p.TopSpeed = item.Evaluate(guidance.MissileVelocity);
p.TargetPosition = () => source.Entity.Position + length( (float3)source.LookAtPoint.position - source.Entity.Position) * source.Entity.LookDirection;
}
else Debug.LogError($"Weapon {item.EquippableItem.Name} linked to {name} effect, but is not a Launcher!");
else Debug.LogError($"Weapon {item.Data.Name} linked to {name} effect, but is not a Launcher!");
}
}

View file

@ -189,4 +189,10 @@ public static class AetheriaMath
x = saturate(x);
return x * x * (3 - 2 * x);
}
public static float Smootherstep(float x)
{
x = saturate(x);
return x * x * x * (x * (x * 6 - 15) + 10);
}
}

View file

@ -77,7 +77,6 @@ public interface IPopulationAssignment
}
[MessagePackObject,
Union(0, typeof(FactoryPersistence)),
JsonObject(MemberSerialization.OptIn),
JsonConverter(typeof(JsonKnownTypesConverter<PersistentBehaviorData>))]
public abstract class PersistentBehaviorData
@ -97,7 +96,6 @@ public abstract class PersistentBehaviorData
Union(9, typeof(WearData)),
Union(10, typeof(VelocityConversionData)),
Union(11, typeof(VelocityLimitData)),
Union(12, typeof(FactoryData)),
// Union(13, typeof(PatrolControllerData)),
// Union(14, typeof(TowingControllerData)),
Union(15, typeof(CooldownData)),

View file

@ -1,287 +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 MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using Random = Unity.Mathematics.Random;
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class FactoryData : BehaviorData
{
[InspectableField, JsonProperty("toolingTime"), Key(1)]
public PerformanceStat ToolingTime = new PerformanceStat();
[InspectableField, JsonProperty("automation"), Key(2)]
public int AutomationPoints;
[InspectableField, JsonProperty("automationQuality"), Key(3)]
public float AutomationQuality = .5f;
[InspectableDatabaseLink(typeof(PersonalityAttribute)), JsonProperty("productionProfile"), Key(4)]
public Dictionary<Guid, float> ProductionProfile = new Dictionary<Guid, float>();
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)
{
return new Factory(context, this, entity, item);
}
}
public class Factory : IBehavior//, IPersistentBehavior, IPopulationAssignment
{
public float ProductionQuality;
public double RetoolingTime;
public string ItemName;
public Guid ItemUnderConstruction;
public bool Active;
public int AssignedPopulation { get; set; }
public Entity Entity { get; }
public EquippedItem Item { get; }
public ItemManager Context { get; }
public BehaviorData Data => _data;
public float ToolingTime { get; private set; }
public Guid Blueprint
{
get => _blueprint;
set
{
if (value != _blueprint)
{
_blueprint = value;
Active = false;
if(value != Guid.Empty)
{
ItemName = Context.ItemData.Get<ItemData>(Context.ItemData.Get<BlueprintData>(value).Item).Name;
RetoolingTime = ToolingTime;
_retooling = true;
}
}
}
}
private FactoryData _data;
private Guid _blueprint;
private bool _retooling = false;
private float _currentProductionQuality;
public Factory(ItemManager context, FactoryData data, Entity entity, EquippedItem item)
{
Context = context;
_data = data;
Entity = entity;
Item = item;
}
public bool Execute(float delta)
{
// ToolingTime = Context.Evaluate(_data.ToolingTime, Item, Entity);
// var blueprint = Context.ItemData.Get<BlueprintData>(_blueprint);
// if (blueprint == null)
// return false;
//
// if (ItemUnderConstruction != Guid.Empty)
// {
// Entity.IncompleteCargo[ItemUnderConstruction] =
// Entity.IncompleteCargo[ItemUnderConstruction] - delta * (AssignedPopulation + _data.AutomationPoints) /
// pow(lerp(blueprint.QualityFloor, 1, saturate(_currentProductionQuality)),
// blueprint.ProductionExponent);
//
// if(Entity.IncompleteCargo[ItemUnderConstruction] < 0)
// {
// var item = Context.ItemData.Get<ItemInstance>(ItemUnderConstruction);
// if (item is SimpleCommodity simpleCommodity)
// Entity.AddCargo(simpleCommodity);
// else if (item is CraftedItemInstance craftedItemInstance)
// Entity.AddCargo(craftedItemInstance);
// Entity.IncompleteCargo.Remove(ItemUnderConstruction);
// ItemUnderConstruction = Guid.Empty;
// foreach (var attribute in _data.ProductionProfile)
// Entity.Personality[attribute.Key] = lerp(Entity.Personality[attribute.Key], attribute.Value,
// Context.GameplaySettings.ProductionPersonalityLerp * ((float) AssignedPopulation / Entity.Population));
// }
//
// return true;
// }
//
// if (RetoolingTime > 0)
// {
// RetoolingTime -= delta;
// return false;
// }
//
// if (_retooling)
// {
// _retooling = false;
// }
//
// if (Active)
// {
// var profileDistance = 0f;
// if (_data.ProductionProfile.Any())
// profileDistance = _data.ProductionProfile.Sum(x => abs(x.Value - Entity.Personality[x.Key])) /
// _data.ProductionProfile.Count;
// var personalityQuality =
// (_data.AutomationPoints * _data.AutomationQuality + AssignedPopulation * (1 - profileDistance)) /
// (_data.AutomationPoints + AssignedPopulation);
// ItemUnderConstruction = Entity.Build(blueprint,
// blueprint.Quality *
// pow(personalityQuality, blueprint.PersonalityExponent) *
// pow(ProductionQuality, blueprint.QualityExponent) *
// // Applying exponents to two random numbers and averaging them produces a range of interesting probability distributions for quality
// (pow(Context.Random.NextFloat(), blueprint.RandomQualityExponent) +
// pow(Context.Random.NextFloat(), blueprint.RandomQualityExponent)) / 2, ItemName);
// }
//
return false;
}
//
// // TODO Update Factory Persistence
// public PersistentBehaviorData Store()
// {
// return new FactoryPersistence
// {
// Blueprint = _blueprint,
// RetoolingTime = RetoolingTime,
// AssignedPopulation = AssignedPopulation,
// ProductionQuality = ProductionQuality
// };
// }
//
// public void Restore(PersistentBehaviorData data)
// {
// var factoryPersistence = data as FactoryPersistence;
// _blueprint = factoryPersistence.Blueprint;
// RetoolingTime = factoryPersistence.RetoolingTime;
// AssignedPopulation = factoryPersistence.AssignedPopulation;
// ProductionQuality = factoryPersistence.ProductionQuality;
// }
//
// public Guid Build(BlueprintData blueprint, float quality, string name, bool direct = false)
// {
// if (direct)
// {
// if(blueprint.FactoryItem!=Guid.Empty)
// throw new ArgumentException("Attempted to directly build a blueprint which requires a factory!");
// var blueprintItem = Context.Cache.Get<GearData>(blueprint.Item);
// if(blueprintItem == null)
// throw new ArgumentException("Attempted to directly build a blueprint for a missing or incompatible item!");
// }
//
// //var newItemID = Guid.Empty;
//
// // GetBlueprintIngredients will assign the output lists with the items matching the blueprint, and return false if they are not found
// if (!GetBlueprintIngredients(blueprint, out var simpleIngredients, out var compoundIngredients))
// return Guid.Empty;
//
// // These will be bundled with the data for the compound commodity instance
// var ingredients = new List<ItemInstance>();
// ingredients.AddRange(compoundIngredients.Select(RemoveCargo));
// ingredients.AddRange(simpleIngredients.Select(sc => RemoveCargo(sc, blueprint.Ingredients[sc.Data])));
//
// var blueprintItemData = Context.Cache.Get(blueprint.Item);
//
// // Creating new crafted item instances is a bit more complicated
// if (blueprintItemData is CraftedItemData)
// {
// CraftedItemInstance newItem;
//
// if (blueprintItemData is EquippableItemData equippableItemData)
// {
// var newGear = new EquippableItem
// {
// Context = Context,
// Data = blueprintItemData.ID,
// Ingredients = ingredients.Select(ii=>ii.ID).ToList(),
// Quality = quality,
// Blueprint = blueprint.ID,
// Name = name,
// SourceEntity = ID
// };
// newGear.Durability = Context.Evaluate(equippableItemData.Durability, newGear);
// newItem = newGear;
// }
// else
// {
// newItem = new CompoundCommodity
// {
// Context = Context,
// Data = blueprintItemData.ID,
// Ingredients = ingredients.Select(ii=>ii.ID).ToList(),
// Quality = quality,
// Blueprint = blueprint.ID,
// Name = name,
// SourceEntity = ID
// };
// }
// Context.Cache.Add(newItem);
// if (direct)
// IncompleteGear[newItem.ID] = blueprint.ProductionTime;
// else
// IncompleteCargo[newItem.ID] = blueprint.ProductionTime;
// return newItem.ID;
// }
//
// var newSimpleCommodity = new SimpleCommodity
// {
// Context = Context,
// Data = blueprintItemData.ID,
// Quantity = 1
// };
// Context.Cache.Add(newSimpleCommodity);
// IncompleteCargo[newSimpleCommodity.ID] = blueprint.ProductionTime;
// return newSimpleCommodity.ID;
// }
//
// public bool GetBlueprintIngredients(BlueprintData blueprint, out List<SimpleCommodity> simpleIngredients,
// out List<CompoundCommodity> compoundIngredients)
// {
// simpleIngredients = new List<SimpleCommodity>();
// compoundIngredients = new List<CompoundCommodity>();
// var hasAllIngredients = true;
// var cargoInstances = Cargo.Select(c => Context.Cache.Get<ItemInstance>(c));
// foreach (var kvp in blueprint.Ingredients)
// {
// var itemData = Context.Cache.Get(kvp.Key);
// if (itemData is SimpleCommodityData)
// {
// var matchingItem = cargoInstances.FirstOrDefault(ii =>
// {
// if (!(ii is SimpleCommodity simpleCommodity)) return false;
// return simpleCommodity.Data == itemData.ID && simpleCommodity.Quantity >= kvp.Value;
// }) as SimpleCommodity;
// hasAllIngredients = hasAllIngredients && matchingItem != null;
// if(matchingItem != null)
// simpleIngredients.Add(matchingItem);
// }
// else
// {
// var matchingItems =
// cargoInstances.Where(ii => (ii as CompoundCommodity)?.Data == itemData.ID).Cast<CompoundCommodity>().ToArray();
// hasAllIngredients = hasAllIngredients && matchingItems.Length >= kvp.Value;
// if(matchingItems.Length >= kvp.Value)
// compoundIngredients.AddRange(matchingItems.Take(kvp.Value));
// }
// }
//
// return hasAllIngredients;
// }
}
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class FactoryPersistence : PersistentBehaviorData
{
[JsonProperty("blueprint"), Key(0)] public Guid Blueprint;
[JsonProperty("retoolingTime"), Key(2)] public double RetoolingTime;
[JsonProperty("assignedPopulation"), Key(5)] public int AssignedPopulation;
[JsonProperty("productionQuality"), Key(6)] public float ProductionQuality;
}

View file

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

View file

@ -103,10 +103,13 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior
private bool UseAmmo()
{
if (_data.AmmoType != Guid.Empty)
if (_data.MagazineSize <= 1) return true;
if (_ammo > 0) _ammo--;
else
{
if (_data.MagazineSize > 1 && _ammo > 0) _ammo--;
else
var hasAmmo = true;
if (_data.AmmoType != Guid.Empty)
{
var cargo = Entity.FindItemInCargo(_data.AmmoType);
if (cargo != null)
@ -114,18 +117,18 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior
var item = cargo.ItemsOfType[_data.AmmoType][0];
if (item is SimpleCommodity simpleCommodity)
cargo.Remove(simpleCommodity, 1);
if(_data.MagazineSize > 1)
{
OnReloadBegin?.Invoke();
_cooldown = 1;
_coolingDown = true;
_firing = false;
}
}
_burstRemaining = 0;
return false;
else hasAmmo = false;
}
if(hasAmmo)
{
OnReloadBegin?.Invoke();
_cooldown = 1;
_coolingDown = true;
_firing = false;
}
_burstRemaining = 0;
return false;
}
return true;

View file

@ -101,4 +101,14 @@ public enum StatModifierType
{
Constant,
Multiplier
}
[InspectableField, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class StatReference
{
[InspectableType(typeof(BehaviorData)), JsonProperty("behavior"), Key(1)]
public string Target;
[InspectableField, JsonProperty("stat"), Key(2)]
public string Stat;
}

View file

@ -19,7 +19,10 @@ public class ThrusterData : BehaviorData
[InspectableField, JsonProperty("heat"), Key(3), RuntimeInspectable]
public PerformanceStat Heat = new PerformanceStat();
[InspectablePrefab, JsonProperty("Particles"), Key(4)]
[InspectableField, JsonProperty("energy"), Key(4), RuntimeInspectable]
public PerformanceStat EnergyUsage = new PerformanceStat();
[InspectablePrefab, JsonProperty("Particles"), Key(5)]
public string ParticlesPrefab;
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)
@ -66,13 +69,18 @@ public class Thruster : IAnalogBehavior
public bool Execute(float delta)
{
Thrust = Item.Evaluate(_data.Thrust);
Entity.Velocity -= Entity.Direction.Rotate(Item.EquippableItem.Rotation) * _input * Thrust / Entity.Mass * delta;
Entity.Direction = mul(Entity.Direction, Unity.Mathematics.float2x2.Rotate(_input * Torque * Thrust * Context.GameplaySettings.TorqueMultiplier / Entity.Mass * delta));
Item.AddHeat(_input * Item.Evaluate(_data.Heat) * delta);
var vis = _input * Item.Evaluate(_data.Visibility);
if(!Entity.VisibilitySources.ContainsKey(this) || vis > Entity.VisibilitySources[this])
Entity.VisibilitySources[this] = vis;
return _input > .01f;
if(_input > .01f && Item.Entity.TryConsumeEnergy(_input * Item.Evaluate(_data.EnergyUsage)))
{
Thrust = Item.Evaluate(_data.Thrust);
Entity.Velocity -= Entity.Direction.Rotate(Item.EquippableItem.Rotation) * _input * Thrust / Entity.Mass * delta;
Entity.Direction = mul(Entity.Direction,
Unity.Mathematics.float2x2.Rotate(_input * Torque * Thrust * Context.GameplaySettings.TorqueMultiplier / Entity.Mass * delta));
Item.AddHeat(_input * Item.Evaluate(_data.Heat) * delta);
var vis = _input * Item.Evaluate(_data.Visibility);
if (!Entity.VisibilitySources.ContainsKey(this) || vis > Entity.VisibilitySources[this])
Entity.VisibilitySources[this] = vis;
return true;
}
return false;
}
}

View file

@ -1,86 +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;
using System.Collections.Generic;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[RethinkTable("Items"), MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class BlueprintData : DatabaseEntry, INamedEntry
{
[InspectableField, JsonProperty("name"), Key(1)]
public string Name;
[InspectableDatabaseLink(typeof(ItemData)), JsonProperty("ingredients"), Key(2)]
public Dictionary<Guid, int> Ingredients = new Dictionary<Guid, int>();
[JsonProperty("item"), Key(3)]
public Guid Item;
[InspectableField, JsonProperty("productionTime"), Key(4)]
public float ProductionTime;
[InspectableField, JsonProperty("quality"), Key(5)]
public float Quality;
[InspectableField, JsonProperty("qualityExponent"), Key(6)]
public float QualityExponent = 1;
[InspectableField, JsonProperty("productionExponent"), Key(7)]
public float ProductionExponent = 1;
[InspectableField, JsonProperty("randomExponent"), Key(8)]
public float RandomQualityExponent = 1;
[InspectableField, JsonProperty("personalityExponent"), Key(9)]
public float PersonalityExponent = 1;
[InspectableField, JsonProperty("qualityFloor"), Key(10)]
public float QualityFloor = .25f;
[InspectableField, JsonProperty("statEffects"), Key(11)]
public List<BlueprintStatEffect> StatEffects = new List<BlueprintStatEffect>();
[InspectableField, JsonProperty("researchTime"), Key(12)]
public float ResearchTime;
[InspectableDatabaseLink(typeof(BlueprintData)), JsonProperty("researchDependencies"), Key(13)]
public List<Guid> Dependencies = new List<Guid>();
[InspectableDatabaseLink(typeof(CraftedItemData)), JsonProperty("factoryItem"), Key(14)]
public Guid FactoryItem;
[InspectableDatabaseLink(typeof(SimpleCommodityData)), JsonProperty("resourceRequirements"), Key(15)]
public Dictionary<Guid, int> ResourceRequirements = new Dictionary<Guid, int>();
[IgnoreMember] public string EntryName
{
get => Name;
set => Name = value;
}
}
[InspectableField, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class BlueprintStatEffect
{
[InspectableField, JsonProperty("ingredient"), Key(1)]
public Guid Ingredient;
[InspectableField, JsonProperty("stat"), Key(2)]
public StatReference StatReference = new StatReference();
}
[InspectableField, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class StatReference
{
[InspectableType(typeof(BehaviorData)), JsonProperty("behavior"), Key(1)]
public string Target;
[InspectableField, JsonProperty("stat"), Key(2)]
public string Stat;
}

View file

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

View file

@ -25,7 +25,6 @@ public interface INamedEntry
Union(4, typeof(SimpleCommodity)),
Union(5, typeof(CompoundCommodity)),
Union(6, typeof(EquippableItem)),
Union(7, typeof(BlueprintData)),
Union(8, typeof(GalaxyMapLayerData)),
Union(9, typeof(NameFile)),
//Union(10, typeof(ZoneData)),
@ -37,7 +36,7 @@ public interface INamedEntry
Union(16, typeof(BodyData)),
Union(17, typeof(PersonalityAttribute)),
Union(18, typeof(AgentTask)),
Union(19, typeof(LoadoutData)),
// Union(19, typeof(LoadoutData)),
Union(20, typeof(Ship)),
Union(21, typeof(Mining)),
Union(22, typeof(StationTowing)),

View file

@ -169,7 +169,7 @@ public abstract class Entity
Zone = zone;
Hull = hull;
HullData = itemManager.GetData(hull) as HullData;
Name = hull.Name;
Name = HullData.Name;
MapEntity();
TriggerGroups = new (List<Weapon> triggers, List<EquippedItem> items)[itemManager.GameplaySettings.TriggerGroupCount];
for(int i=0; i<itemManager.GameplaySettings.TriggerGroupCount; i++)
@ -955,8 +955,14 @@ public class EquippedItem
EquippableItem = item;
Position = position;
Conductivity = Data.Conductivity;
ThermalExponent = ItemManager.Evaluate(Data.HeatExponent, EquippableItem);
DurabilityExponent = ItemManager.Evaluate(Data.DurabilityExponent, EquippableItem);
ThermalExponent = lerp(
ItemManager.GameplaySettings.ThermalQualityMin,
ItemManager.GameplaySettings.ThermalQualityMax,
pow(item.Quality, ItemManager.GameplaySettings.ThermalQualityExponent));
DurabilityExponent = lerp(
ItemManager.GameplaySettings.DurabilityQualityMin,
ItemManager.GameplaySettings.DurabilityQualityMax,
pow(item.Quality, ItemManager.GameplaySettings.DurabilityQualityExponent));
var hullData = itemManager.GetData(entity.Hull);
InsetShape = hullData.Shape.Inset(Data.Shape, position, item.Rotation);
@ -989,13 +995,9 @@ public class EquippedItem
public float Evaluate(PerformanceStat stat)
{
var heat = 1f;
if(stat.HeatDependent)
heat = pow(ThermalPerformance, ThermalExponent * stat.HeatExponentMultiplier);
var durability = 1f;
if(stat.DurabilityDependent)
durability = pow(DurabilityPerformance, DurabilityExponent);
var quality = pow(ItemManager.Quality(stat, EquippableItem), stat.QualityExponent);
var heat = pow(ThermalPerformance, ThermalExponent * stat.HeatExponentMultiplier);
var durability = pow(DurabilityPerformance, DurabilityExponent * stat.DurabilityExponentMultiplier);
var quality = pow(EquippableItem.Quality, stat.QualityExponent);
var scaleModifier = 1.0f;
foreach (var value in stat.GetScaleModifiers(Entity).Values) scaleModifier = scaleModifier * value;
@ -1025,7 +1027,7 @@ public class EquippedItem
DurabilityPerformance = EquippableItem.Durability / Data.Durability;
var performanceThreshold = Entity.Settings.ShutdownPerformance;
Wear = (1 - pow(Data.Performance(temp),
(1 - pow(ItemManager.CompoundQuality(EquippableItem), ItemManager.GameplaySettings.QualityWearExponent)) *
(1 - pow(EquippableItem.Quality, ItemManager.GameplaySettings.QualityWearExponent)) *
ItemManager.GameplaySettings.ThermalWearExponent)
) * Data.Durability / Data.ThermalResilience;
ThermalOnline.Value = ThermalPerformance > performanceThreshold || Entity.OverrideShutdown && EquippableItem.OverrideShutdown;

View file

@ -316,11 +316,11 @@ public abstract class EquippableItemData : CraftedItemData
[InspectableTemperature, JsonProperty("maxTemp"), Key(14)]
public float MaximumTemperature;
[InspectableField, JsonProperty("durabilityExponent"), Key(15), SimplePerformanceStat]
public PerformanceStat DurabilityExponent = new PerformanceStat();
[InspectableField, JsonProperty("heatExponent"), Key(16), SimplePerformanceStat]
public PerformanceStat HeatExponent = new PerformanceStat();
// [InspectableField, JsonProperty("durabilityExponent"), Key(15), SimplePerformanceStat]
// public PerformanceStat DurabilityExponent = new PerformanceStat();
//
// [InspectableField, JsonProperty("heatExponent"), Key(16), SimplePerformanceStat]
// public PerformanceStat HeatExponent = new PerformanceStat();
[InspectableAnimationCurve, JsonProperty("performanceCurve"), Key(17)]
public float4[] HeatPerformanceCurve;
@ -495,17 +495,14 @@ public class PerformanceStat
[JsonProperty("max"), Key(1)] public float Max;
[JsonProperty("durabilityDependent"), Key(2)]
public bool DurabilityDependent;
[JsonProperty("heatExponentMultiplier"), Key(2)]
public float HeatExponentMultiplier;
[JsonProperty("qualityExponent"), Key(3)]
[JsonProperty("durabilityExponentMultiplier"), Key(3)]
public float DurabilityExponentMultiplier;
[JsonProperty("qualityExponent"), Key(4)]
public float QualityExponent;
[JsonProperty("heatDependent"), Key(4)]
public bool HeatDependent;
[JsonProperty("heatExponentMultiplier"), Key(5)]
public float HeatExponentMultiplier = 1;
//[JsonProperty("id"), Key(5)] public Guid ID = Guid.NewGuid();

View file

@ -34,13 +34,13 @@ public abstract class CraftedItemInstance : ItemInstance
{
[JsonProperty("quality"), Key(2)] public float Quality;
[JsonProperty("ingredients"), Key(3)] public List<ItemInstance> Ingredients = new List<ItemInstance>();
//[JsonProperty("ingredients"), Key(3)] public List<ItemInstance> Ingredients = new List<ItemInstance>();
[JsonProperty("blueprint"), Key(4)] public Guid Blueprint;
//[JsonProperty("blueprint"), Key(4)] public Guid Blueprint;
[JsonProperty("name"), Key(5)] public string Name;
//[JsonProperty("name"), Key(3)] public string Name;
[JsonProperty("sourceEntity"), Key(6)] public Guid SourceEntity;
//[JsonProperty("sourceEntity"), Key(4)] public Guid SourceEntity;
}
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]

View file

@ -24,9 +24,6 @@ public class ItemManager
private Action<string> _logger;
private Dictionary<BlueprintStatEffect, PerformanceStat> AffectedStats =
new Dictionary<BlueprintStatEffect, PerformanceStat>();
private double _time;
private float _deltaTime;
private Dictionary<Guid, Zone> _zones = new Dictionary<Guid, Zone>();
@ -158,118 +155,20 @@ public class ItemManager
return 0;
}
public PerformanceStat GetAffectedStat(BlueprintData blueprint, BlueprintStatEffect effect)
{
// We've already cached this effect's stat, return it directly
if (AffectedStats.ContainsKey(effect)) return AffectedStats[effect];
// Get the data for the item the blueprint is for, return null if not found or not equippable
var blueprintItem = ItemData.Get<EquippableItemData>(blueprint.Item);
if (blueprintItem == null)
{
_logger($"Attempted to get stat effect but Blueprint {blueprint.ID} is not for an equippable item!");
return AffectedStats[effect] = null;
}
// Get the first behavior of the type specified in the blueprint stat effect, return null if not found
var effectObject = effect.StatReference.Target == blueprintItem.Name ? (object) blueprintItem :
blueprintItem.Behaviors.FirstOrDefault(b => b.GetType().Name == effect.StatReference.Target);
if (effectObject == null)
{
_logger($"Attempted to get stat effect for Blueprint {blueprint.ID} but stat references missing behavior \"{effect.StatReference.Target}\"!");
return AffectedStats[effect] = null;
}
// Get the first field in the behavior matching the name specified in the stat effect, return null if not found
var type = effectObject.GetType();
var field = type.GetField(effect.StatReference.Stat);
if (field == null)
{
_logger($"Attempted to get stat effect for Blueprint {blueprint.ID} but object {effect.StatReference.Target} does not have a stat named \"{effect.StatReference.Stat}\"!");
return AffectedStats[effect] = null;
}
// Finally we've confirmed the stat effect is valid, return the affected stat
return AffectedStats[effect] = field.GetValue(effectObject) as PerformanceStat;
}
private readonly Dictionary<CraftedItemInstance, float> ItemQuality = new Dictionary<CraftedItemInstance, float>();
public float CompoundQuality(CraftedItemInstance item)
{
if (ItemQuality.ContainsKey(item)) return ItemQuality[item];
var quality = item.Quality;
var craftedIngredients = item.Ingredients.Where(i => i is CraftedItemInstance).ToArray();
if (craftedIngredients.Length > 0)
{
var ingredientQualityWeight = ItemData.Get<CraftedItemData>(item.Data).IngredientQualityWeight;
quality = quality * (1 - ingredientQualityWeight) +
craftedIngredients.Cast<CraftedItemInstance>().Average(CompoundQuality) * ingredientQualityWeight;
}
ItemQuality[item] = quality;
return ItemQuality[item];
}
private readonly Dictionary<(PerformanceStat stat, EquippableItem item), float> StatQuality = new Dictionary<(PerformanceStat stat, EquippableItem item), float>();
// Determine quality of either the item itself or the specific ingredient this stat depends on
public float Quality(PerformanceStat stat, EquippableItem item)
{
if (StatQuality.ContainsKey((stat, item)))
return StatQuality[(stat, item)];
var quality = CalcQuality(stat, item);
StatQuality[(stat, item)] = quality;
return quality;
}
private float CalcQuality(PerformanceStat stat, EquippableItem item)
{
var itemData = GetData(item);
var blueprint = ItemData.Get<BlueprintData>(item.Blueprint);
var activeEffects = blueprint.StatEffects.Where(x => GetAffectedStat(blueprint, x) == stat).ToArray();
float quality;
if (!activeEffects.Any())
quality = CompoundQuality(item);
else
{
var ingredients = item.Ingredients.Where(i => activeEffects.Any(e => e.Ingredient == i.Data)).ToArray();
var distinctIngredients = ingredients.Select(i => i.Data).Distinct();
if(distinctIngredients.Count() != activeEffects.Length)
{
_logger($"Item {itemData.Name} does not have the ingredients specified by the stat effects of its blueprint!");
return 0;
}
float sum = 0;
foreach (var i in ingredients)
{
if (i is CraftedItemInstance ci)
sum += CompoundQuality(ci);
else _logger($"Blueprint stat effect for item {itemData.Name} specifies invalid (non crafted) ingredient!");
}
quality = sum / ingredients.Length;
}
return quality;
}
// Returns stat when not equipped
public float Evaluate(PerformanceStat stat, EquippableItem item)
{
var quality = pow(Quality(stat, item), stat.QualityExponent);
var result = lerp(stat.Min, stat.Max, quality);
if (float.IsNaN(result))
return stat.Min;
var data = GetData(item);
var quality = pow(item.Quality, stat.QualityExponent);
var durabilityExponent = lerp(
GameplaySettings.DurabilityQualityMin,
GameplaySettings.DurabilityQualityMax,
pow(item.Quality, GameplaySettings.DurabilityQualityExponent));
var durability = pow(item.Durability / data.Durability, durabilityExponent * stat.DurabilityExponentMultiplier);
var result = lerp(stat.Min, stat.Max, quality * durability);
if (float.IsNaN(result)) throw new InvalidOperationException("Performance Stat evaluating as NaN: input data is invalid!");
return result;
}
public int GetPrice(CraftedItemInstance item)
@ -317,57 +216,10 @@ public class ItemManager
{
if (item == null)
{
_logger("Attempted to create crafted item instance using missing or incorrect item id!");
_logger("Attempted to create crafted item instance using missing or incorrect item data!");
return null;
}
var blueprint = ItemData.GetAll<BlueprintData>().FirstOrDefault(b => b.Item == item.ID);
if (blueprint == null)
{
_logger("Attempted to create crafted item instance which has no blueprint!");
return null;
}
bool invalidIngredientFound = false;
ItemData invalidIngredient = null;
var ingredients = new List<ItemInstance>();
foreach (var ingredient in blueprint.Ingredients)
{
var itemData = ItemData.Get<ItemData>(ingredient.Key);
if (itemData is SimpleCommodityData simpleIngredientData)
{
var itemInstance = CreateInstance(simpleIngredientData, ingredient.Value);
if(itemInstance == null)
{
invalidIngredientFound = true;
invalidIngredient = itemData;
}
else ingredients.Add(itemInstance);
}
else
{
var craftedIngredientData = ItemData.Get<CraftedItemData>(ingredient.Key);
for (int i = 0; i < ingredient.Value; i++)
{
var itemInstance = CreateInstance(craftedIngredientData);
if (itemInstance == null)
{
invalidIngredientFound = true;
invalidIngredient = itemData;
break;
}
ingredients.Add(itemInstance);
}
}
}
if (invalidIngredientFound)
{
_logger($"Unable to create crafted item ingredient: {invalidIngredient?.Name??"null"} for item {item.Name}");
}
var quality = Random.NextFloat();
var tier = GameplaySettings.Tiers[0];
foreach (var t in GameplaySettings.Tiers)
@ -381,10 +233,7 @@ public class ItemManager
var newGear = new EquippableItem
{
Data = item.ID,
Ingredients = ingredients,
Quality = tier.Quality,
Blueprint = blueprint.ID,
Name = $"{item.Name}"
Quality = tier.Quality
};
newGear.Durability = equippableItemData.Durability;
return newGear;
@ -393,10 +242,7 @@ public class ItemManager
var newCommodity = new CompoundCommodity
{
Data = item.ID,
Ingredients = ingredients,
Quality = tier.Quality,
Blueprint = blueprint.ID,
Name = $"{item.Name}"
Quality = tier.Quality
};
return newCommodity;
}

View file

@ -1,33 +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 MessagePack;
using Newtonsoft.Json;
[RethinkTable("Items"), Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class LoadoutData : DatabaseEntry, INamedEntry
{
[InspectableField, JsonProperty("name"), Key(1)]
public string Name;
[InspectableDatabaseLink(typeof(HullData)), JsonProperty("hull"), Key(2)]
public Guid Hull;
[JsonProperty("items"), Key(3)]
public List<Guid> Gear = new List<Guid>();
[InspectableDatabaseLink(typeof(SimpleCommodityData)), JsonProperty("simpleCargo"), Key(4)]
public Dictionary<Guid, int> SimpleCargo = new Dictionary<Guid, int>();
[InspectableDatabaseLink(typeof(CraftedItemData)), JsonProperty("compoundCargo"), Key(5)]
public Dictionary<Guid, int> CompoundCargo = new Dictionary<Guid, int>();
[IgnoreMember] public string EntryName
{
get => Name;
set => Name = value;
}
}

View file

@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: 897e13bb0462456b800522cd213bf70d
timeCreated: 1591829121

View file

@ -135,6 +135,12 @@ public class GameplaySettings
public EntitySettings DefaultEntitySettings;
public RarityTier[] Tiers;
public ExponentialLerp QualityPriceModifier;
public float DurabilityQualityExponent = 2;
public float DurabilityQualityMin = 2;
public float DurabilityQualityMax = .25f;
public float ThermalQualityExponent = 2;
public float ThermalQualityMin = 2;
public float ThermalQualityMax = .25f;
public float DefaultShutdownPerformance = .25f;
public float SevereHeatstrokeRiskThreshold = .25f;
public float WormholeDepth = 1000;

View file

@ -300,7 +300,7 @@ public class Ship : Entity
{
var exitLerp = (_wormholeAnimationProgress - ItemManager.GameplaySettings.WormholeExitCurveStart) /
(1 - ItemManager.GameplaySettings.WormholeExitCurveStart);
exitLerp = AetheriaMath.Smoothstep(exitLerp); // Square the interpolation variable to produce curve with zero slope at start
exitLerp = AetheriaMath.Smootherstep(exitLerp); // Square the interpolation variable to produce curve with zero slope at start
Position.xz = _wormholePosition + normalize(_wormholeExitVelocity) * exitLerp * ItemManager.GameplaySettings.WormholeExitRadius;
Rotation = quaternion.LookRotation(
lerp(float3(0, 1, 0), forward, exitLerp),
@ -326,7 +326,7 @@ public class Ship : Entity
if (_wormholeAnimationProgress < 1 - ItemManager.GameplaySettings.WormholeExitCurveStart)
{
var enterLerp = _wormholeAnimationProgress / (1 - ItemManager.GameplaySettings.WormholeExitCurveStart);
enterLerp = AetheriaMath.Smoothstep(enterLerp); // Square the interpolation variable to produce curve with zero slope at vertical
enterLerp = AetheriaMath.Smootherstep(enterLerp); // Square the interpolation variable to produce curve with zero slope at vertical
Position.xz = lerp(_wormholeEntryPosition, _wormholePosition, enterLerp);
Rotation = quaternion.LookRotation(
lerp(forward, float3(0, -1, 0), enterLerp),

View file

@ -1,438 +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;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Layout.Layered;
using NaughtyAttributes;
using TMPro;
using UnityEngine;
using Random = UnityEngine.Random;
using Unity.Mathematics;
using static Unity.Mathematics.math;
public class TechTreeMsagl : MonoBehaviour
{
[Section("Assets")]
public string IconsPath;
public Prototype Ring;
public Prototype Tech;
public Prototype RadialLink;
public Prototype Arrow;
[Section("UI Links")]
public PropertiesPanel PropertiesPanel;
[Section("Graph Generation")]
public bool TestMode;
public int TechCount = 50;
public int SeedTechs = 5;
public int RollingWindowSize = 50;
public bool Radial;
public float MultipleDependencyProbability;
public int DependencyDepth;
public int DependencyAncestorDepth;
[Section("Layout")]
public PackingMethod PackingMethod;
[Section("Radial")]
public int Sections;
public float PaddingRadians;
public int StartTier = 3;
public float Scale = 1;
public int LinkPoints = 16;
public int LinkDepth = 5;
public float LinkTargetDistance = .75f;
public int RingDepth = 6;
public float ArrowDepth = 3;
public float LayerDistance;
[Section("Colors")]
public float Saturation = .95f;
public float HueMin = 0;
public float HueMax = 1;
public float Brightness = 1;
public float RingInnerSaturation;
public float RingOuterSaturation;
public float RingInnerBrightness;
public float RingOuterBrightness;
public int RingColorKeys;
public float FillOpacity = .25f;
public float GlowOpacity = .5f;
public Material TechFillMaterial;
public Material TechGlowMaterial;
public Material TechArrowMaterial;
public Material TechLinkMaterial;
public ItemManager Context;
private List<Prototype> _ringInstances = new List<Prototype>();
private List<Prototype> _techInstances = new List<Prototype>();
private List<Prototype> _linkInstances = new List<Prototype>();
private List<Prototype> _arrowInstances = new List<Prototype>();
private Texture2D[] _icons;
public BlueprintData[] Blueprints { get; set; }
void Start()
{
if(TestMode)
Initialize();
}
public void Initialize()
{
_icons = Resources.LoadAll<Texture2D>(IconsPath);
}
void Update()
{
if(TestMode && Input.GetKeyDown(KeyCode.Space))
GenerateTechs();
}
Node NewNode(object data) => new Node(new Ellipse(1,1,new Point()), data);
List<Node> GetRegion(GeometryGraph graph, Node node, int depth, int maxAncestorDistance)
{
Node ancestor = node;
int actualDepth = 0;
while (actualDepth < depth)
{
var edge = graph.Edges.FirstOrDefault(e => e.Target == ancestor);
if (edge == null) break;
var next = edge.Source;
if (next == null)
break;
ancestor = next;
actualDepth++;
}
var skipGenerations = actualDepth - maxAncestorDistance;
var region = new List<Node>();
Node[] children = {ancestor};
for (int i = 0; i < actualDepth - 1; i++)
{
children = children.SelectMany(n => graph.Edges.Where(e => e.Source == n).Select(e => e.Target)).ToArray();
if(i >= skipGenerations)
region.AddRange(children);
}
return region;
}
public void GenerateTechs()
{
foreach (var instance in _ringInstances) instance.ReturnToPool();
_ringInstances.Clear();
foreach (var instance in _techInstances) instance.ReturnToPool();
_techInstances.Clear();
foreach (var instance in _linkInstances) instance.ReturnToPool();
_linkInstances.Clear();
foreach (var instance in _arrowInstances) instance.ReturnToPool();
_arrowInstances.Clear();
var graph = new GeometryGraph();
var settings = new SugiyamaLayoutSettings();
if (TestMode)
{
for (int i = 0; i < TechCount; i++)
{
var node = NewNode(i);
graph.Nodes.Add(node);
if(i>SeedTechs) graph.Edges.Add(new Edge(graph.Nodes[Random.Range(max(0,i-RollingWindowSize),i-1)], node));
}
foreach (var vertex in graph.Nodes.Where(v=>!graph.Edges.Any(e=>e.Source==v||e.Target==v)))
{
graph.Edges.Add(new Edge(vertex, graph.Nodes[Random.Range(0,TechCount-1)]));
}
}
else
{
var nodeMap = new Dictionary<BlueprintData, Node>();
foreach (var blueprint in Blueprints)
{
var node = NewNode(blueprint);
nodeMap[blueprint] = node;
graph.Nodes.Add(node);
}
foreach (var targetBlueprint in Blueprints)
{
foreach (var sourceBlueprint in Blueprints.Where(sb =>
targetBlueprint.Dependencies.Any(dep => sb.ID == dep)))
{
var edge = new Edge(nodeMap[sourceBlueprint], nodeMap[targetBlueprint]);
graph.Edges.Add(edge);
var splitName = sourceBlueprint.Name.Split(' ');
if (splitName.Length > 1)
{
var nameStart = string.Join(" ", splitName.Take(splitName.Length - 1));
if(targetBlueprint.Name.StartsWith(nameStart))
edge.Weight *= 10;
}
}
}
}
settings.BrandesThreshold = 9999;
var islands = graph.GetClusteredConnectedComponents();
var islandMap =
graph.Nodes.ToDictionary(n => n, n => islands.Find(c => c.Nodes.Any(cn => cn.UserData == n)));
if (TestMode)
{
foreach (var island in islands)
{
foreach (var node in island.Nodes)
{
var region = GetRegion(island, node, DependencyAncestorDepth, DependencyDepth);
while (Random.value < MultipleDependencyProbability && region.Count > 0)
{
var dependency = region[Random.Range(0,region.Count)];
graph.Edges.Add(new Edge(dependency.UserData as Node, node.UserData as Node));
region.Remove(dependency);
}
}
}
}
var islandsBySize = islands.OrderByDescending(i => i.Nodes.Count);
var largestIsland = islandsBySize.First();
foreach (var island in islandsBySize.Skip(1))
settings.VerticalConstraints.SameLayerConstraints.Insert(new Tuple<Node, Node>(
largestIsland.Nodes[Random.Range(0,largestIsland.Nodes.Count)].UserData as Node, island.Nodes[Random.Range(0,island.Nodes.Count)].UserData as Node));
settings.PackingMethod = PackingMethod;
settings.Transformation = PlaneTransformation.Rotation(PI);
var layout = new LayeredLayout(graph, settings);
layout.Run();
var positions = graph.Nodes.ToDictionary(n => n, n => (float2) n.Center);
var islandCenters = islands.ToDictionary(i => i,
i => i.Nodes.Aggregate(float2(0, 0), (total, v) => total + positions[v.UserData as Node]) / i.Nodes.Count);
Rect bounds = Rect.MinMaxRect(
positions.Values.Min(v=>v.x),
positions.Values.Min(v=>v.y),
positions.Values.Max(v=>v.x),
positions.Values.Max(v=>v.y));
var tiers =
Mathf.RoundToInt(graph.Nodes.Max(n => Rect.PointToNormalized(bounds, n.Center).y) /
graph.Nodes.Min(n =>
{
var normalized = Rect.PointToNormalized(bounds, n.Center);
return normalized.y > .001f ? normalized.y : 1;
}));
// var islandsBySize = islands.OrderByDescending(i => i.Nodes.Count);
// var largestIsland = islandsBySize.First();
// foreach(var island in islandsBySize.Skip(1))
// settings.AddSameLayerNeighbors(largestIsland.Nodes.RandomElement().UserData as Node, island.Nodes.RandomElement().UserData as Node);
//
// layout = new LayeredLayout(graph, settings);
// layout.Run();
positions = graph.Nodes.ToDictionary(n => n, n => (float2) n.Center);
islandCenters = islands.ToDictionary(i => i,
i => i.Nodes.Aggregate(float2(0, 0), (total, v) => total + positions[v.UserData as Node]) / i.Nodes.Count);
bounds = Rect.MinMaxRect(
positions.Values.Min(v=>v.x),
positions.Values.Min(v=>v.y),
positions.Values.Max(v=>v.x),
positions.Values.Max(v=>v.y));
Debug.Log($"Generated {tiers} tiers of techs!");
var islandColors = islandCenters.ToDictionary(
i=>i.Key,
i=>Color.HSVToRGB(lerp(HueMin, HueMax, Rect.PointToNormalized(bounds, i.Value).x), Saturation, Brightness));
var islandFillMaterials = islandColors.ToDictionary(i => i.Key, i =>
{
var mat = new Material(TechFillMaterial);
var col = i.Value;
col.a = FillOpacity;
mat.SetColor("_TintColor", col);
return mat;
});
var islandGlowMaterials = islandColors.ToDictionary(i => i.Key, i =>
{
var mat = new Material(TechGlowMaterial);
var col = i.Value;
col.a = GlowOpacity;
mat.SetColor("_TintColor", col);
return mat;
});
var islandArrowMaterials = islandColors.ToDictionary(i => i.Key, i =>
{
var mat = new Material(TechArrowMaterial);
var col = i.Value;
col.a = 1;
mat.SetColor("_TintColor", col);
return mat;
});
var islandLinkMaterials = islandColors.ToDictionary(i => i.Key, i =>
{
var mat = new Material(TechLinkMaterial);
var col = i.Value;
col.a = 1;
mat.SetColor("_TintColor", col);
return mat;
});
if(Radial)
positions = positions.ToDictionary(
kvp => kvp.Key,
kvp =>
{
var normalized = Rect.PointToNormalized(bounds, kvp.Value);
var rads = normalized.x * (PI * 2 - PaddingRadians) + PaddingRadians / 2;
return float2(sin(rads), -cos(rads)) * ((normalized.y * tiers + StartTier + .5f) * LayerDistance) * Scale;
});
else
positions = positions.ToDictionary(
kvp => kvp.Key,
kvp =>
{
var normalized = Rect.PointToNormalized(bounds, kvp.Value);
return float2(
normalized.x * LayerDistance * tiers * (bounds.width / bounds.height),
(normalized.y * tiers / 2 + StartTier + .5f) * LayerDistance);
});
foreach (var vertex in graph.Nodes.Where(positions.ContainsKey))
{
var tech = Tech.Instantiate<TechNode>();
tech.transform.position = (Vector2) positions[vertex];
tech.Label.text = $"{(TestMode ? ((int) vertex.UserData).ToString() : ((BlueprintData) vertex.UserData).ID.ToString().Substring(0,2))}";
var gradient = tech.Label.colorGradient;
gradient.bottomLeft = gradient.bottomRight = islandColors[islandMap[vertex]];
tech.Label.colorGradient = gradient;
tech.Icon.material.SetTexture("_MainTex", _icons[Random.Range(0,_icons.Length-1)]);
tech.Fill.material = islandFillMaterials[islandMap[vertex]];
tech.Glow.material = islandGlowMaterials[islandMap[vertex]];
if (!TestMode)
tech.Fill.GetComponent<ClickableCollider>().OnClick += (collider, data) =>
{
PropertiesPanel.Clear();
var blueprint = (BlueprintData) vertex.UserData;
PropertiesPanel.Title.text = blueprint.Name;
PropertiesPanel.AddProperty("Research Time", () => $"{blueprint.ResearchTime:0.##} MH");
PropertiesPanel.AddProperty("Produces", () => $"{Context.ItemData.Get<ItemData>(blueprint.Item).Name}");
PropertiesPanel.AddProperty("Production Quality", () => $"{Mathf.RoundToInt(blueprint.Quality * 100)}%");
PropertiesPanel.AddProperty("Production Time", () => $"{blueprint.ProductionTime:0.##} MH");
var ingredientsList = PropertiesPanel.AddList("Ingredients");
foreach (var ingredient in blueprint.Ingredients)
{
var ingredientData = Context.ItemData.Get<ItemData>(ingredient.Key);
ingredientsList.AddProperty(ingredientData.Name, () => ingredient.Value.ToString());
}
ingredientsList.SetExpanded(true, true);
var dependenciesList = PropertiesPanel.AddList("Dependencies");
foreach (var dependency in blueprint.Dependencies)
{
var dependencyBlueprint = Context.ItemData.Get<BlueprintData>(dependency);
dependenciesList.AddProperty(dependencyBlueprint.Name);
}
dependenciesList.SetExpanded(true, true);
var descendantsList = PropertiesPanel.AddList("Descendants");
foreach (var descendant in Blueprints.Where(bp => bp.Dependencies.Any(dep => blueprint.ID == dep)))
{
descendantsList.AddProperty(descendant.Name);
}
descendantsList.SetExpanded(true, true);
};
_techInstances.Add(tech.GetComponent<Prototype>());
}
foreach (var edge in graph.Edges)
{
var link = RadialLink.Instantiate<LineRenderer>();
link.material = islandLinkMaterials[islandMap[edge.Source]];
link.positionCount = LinkPoints;
var p1r = length(positions[edge.Source]);
var p2r = length(positions[edge.Target]);
var p1a = (atan2(positions[edge.Source].y, positions[edge.Source].x) + PI * 2.5f) % (PI * 2);
var p2a = (atan2(positions[edge.Target].y, positions[edge.Target].x) + PI * 2.5f) % (PI * 2);
var p1 = float2(sin(p1a) * p1r, -cos(p1a) * p1r);
var p2 = float2(sin(p2a) * p2r, -cos(p2a) * p2r);
var dist = length(p2 - p1);
var distProp = (dist - LinkTargetDistance) / dist;
var dir = new float2();
var lastPos = new float2();
link.SetPositions(Enumerable.Range(0,LinkPoints).Select(i=>
{
var lerp = (float) i / (LinkPoints-1) * distProp;
var angle = math.lerp(p1a, p2a, (lerp));
var radius = math.lerp(p1r, p2r, lerp);
var pos = Radial ? float2(sin(angle) * radius, -cos(angle) * radius) : math.lerp(positions[edge.Source], positions[edge.Target], lerp);
dir = normalize(pos - lastPos);
lastPos = pos;
return (Vector3) float3(lastPos, LinkDepth);
}).ToArray());
_linkInstances.Add(link.GetComponent<Prototype>());
var arrow = Arrow.Instantiate<TechArrow>();
arrow.transform.position = new Vector3(lastPos.x, lastPos.y, ArrowDepth);
arrow.transform.rotation = Quaternion.Euler(0,0,atan2(dir.y, dir.x) * Mathf.Rad2Deg);
arrow.Icon.material = islandArrowMaterials[islandMap[edge.Source]];
_arrowInstances.Add(arrow.GetComponent<Prototype>());
}
if (Radial)
{
for (int i = 1; i <= tiers; i++)
{
var ring = Ring.Instantiate<LineRenderer>();
var ringPositions = new Vector3[Sections];
for (int s = 0; s < Sections; s++)
{
var rads = ((float) s / (Sections-1)) * (PI * 2 - PaddingRadians) + PaddingRadians / 2;
ringPositions[s] = new Vector3(sin(rads), -cos(rads), 0) * ((i + StartTier) * (LayerDistance) * Scale);
ringPositions[s].z = RingDepth;
}
ring.positionCount = Sections;
ring.SetPositions(ringPositions);
var tierLerp = (float) i / (tiers - 1);
ring.colorGradient = new Gradient
{
alphaKeys = new []{new GradientAlphaKey(1,0), new GradientAlphaKey(1,1)},
colorKeys = Enumerable.Range(0,RingColorKeys).Select(x=>
{
var ringLerp = (float) x / (RingColorKeys - 1);
return new GradientColorKey(
Color.HSVToRGB(HueMin + (HueMax - HueMin) * ringLerp,
lerp(RingInnerSaturation, RingOuterSaturation, tierLerp),
lerp(RingInnerBrightness, RingOuterBrightness, tierLerp)), ringLerp);
}).ToArray()
};
_ringInstances.Add(ring.GetComponent<Prototype>());
}
}
}
}

View file

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

View file

@ -379,7 +379,7 @@ public class PropertiesPanel : MonoBehaviour
{
var tier = entity.ItemManager.GetTier(gear);
Title.text =
$"<color=#{ColorUtility.ToHtmlStringRGB(tier.tier.Color.ToColor())}>{gear.Name}</color><smallcaps><size=60%> ({tier.tier.Name}{new string('+', tier.upgrades)})";
$"<color=#{ColorUtility.ToHtmlStringRGB(tier.tier.Color.ToColor())}>{data.Name}</color><smallcaps><size=60%> ({tier.tier.Name}{new string('+', tier.upgrades)})";
var gearData = Context.GetData(gear);
AddProperty("Durability", () =>
$"{gear.Durability.SignificantDigits(Context.GameplaySettings.SignificantDigits)}/{gearData.Durability.SignificantDigits(Context.GameplaySettings.SignificantDigits)}");