Context Menus & Progress Bars

We now have a context menu UI for in-game actions, right click on an item to activate
Database view has a progress bar (finally!)
Data structures for Megacorps and loadouts
Towing task complete? needs testing
This commit is contained in:
hyperion51 2020-05-10 00:16:33 +01:00
commit c24c155673
93 changed files with 1410 additions and 324 deletions

View file

@ -176,6 +176,8 @@ public class DatabaseInspector : EditorWindow
{
if(inspectable is InspectablePrefabAttribute)
field.SetValue(obj, InspectGameObject(field.Name.SplitCamelCase(), (string) value));
else if(inspectable is InspectableTextureAttribute)
field.SetValue(obj, InspectTexture(field.Name.SplitCamelCase(), (string) value));
else
field.SetValue(obj, Inspect(field.Name.SplitCamelCase(), (string) value, inspectable is InspectableTextAttribute));
}
@ -269,7 +271,7 @@ public class DatabaseInspector : EditorWindow
using (var h = new HorizontalScope(_list.ListItemStyle))
{
GUILayout.Label($"Add new Stat Effect", GUILayout.ExpandWidth(true));
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))
@ -554,13 +556,11 @@ public class DatabaseInspector : EditorWindow
return value;
}
else
using (var h = new HorizontalScope())
{
using (var h = new HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
return Popup(value, enumOptions);
}
GUILayout.Label(label, GUILayout.Width(width));
return Popup(value, enumOptions);
}
}
@ -573,6 +573,15 @@ public class DatabaseInspector : EditorWindow
}
}
public string InspectTexture(string label, string value)
{
using (var h = new HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(width));
return AssetDatabase.GetAssetPath(ObjectField(AssetDatabase.LoadAssetAtPath<Texture2D>(value), typeof(Texture2D), false));
}
}
public GameObject Inspect(string label, GameObject value)
{
using (var h = new HorizontalScope())
@ -977,117 +986,115 @@ public class DatabaseInspector : EditorWindow
}
#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
#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.Items.Count < hardpoints.Length)
loadout.Items.AddRange(Enumerable.Repeat(Guid.Empty, hardpoints.Length - loadout.Items.Count));
Space();
using (var h = new HorizontalScope())
{
GUILayout.Label($"Equipped Items: {loadout.Items.Sum(i=>((ItemData) DatabaseCache.Get(i))?.Size ?? 0)}/{loadoutHull.Capacity.Min}", EditorStyles.boldLabel);
GUILayout.Label($"Mass: {loadout.Items.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.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}\"");
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.Items[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.Items[itemIndex] = Guid.Empty;
}
}
}
}
Space();
LabelField("Cargo", EditorStyles.boldLabel);
using (var v = new VerticalScope(GUI.skin.box))
{
if (v.rect.Contains(current.mousePosition) &&
(currentEventType == EventType.DragUpdated || currentEventType == EventType.DragPerform))
{
var guid = (Guid) DragAndDrop.GetGenericData("Item");
var dragItem = DatabaseCache.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);
GUI.changed = true;
}
}
if(itemIndex == loadout.Items.Count)
GUILayout.Label("Nothing Here!");
for (; itemIndex < loadout.Items.Count; itemIndex++)
{
var loadoutItem = DatabaseCache.Get(loadout.Items[itemIndex]) as ItemData;
using (var h = new HorizontalScope(_list.ListItemStyle))
{
GUILayout.Label(loadoutItem?.Name ?? "Invalid Item");
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.Items.RemoveAt(itemIndex--);
}
}
}
}
}
#endregion
if (EditorGUI.EndChangeCheck())
{

View file

@ -17,7 +17,6 @@ public class DatabaseListView : EditorWindow
public GUIStyle SelectedStyle;
public static RethinkDB R = RethinkDB.R;
private Connection _connection;
private DatabaseCache _databaseCache;
private bool[] _gearFoldouts;
@ -36,6 +35,7 @@ public class DatabaseListView : EditorWindow
private string _connectionString;
private const float LineHeight = 20;
private Vector2 _view;
private RethinkQueryStatus _queryStatus;
public Color LabelColor => EditorGUIUtility.isProSkin ? Color.white : Color.black;
@ -143,7 +143,7 @@ public class DatabaseListView : EditorWindow
if (GUILayout.Button("Connect"))
{
EditorPrefs.SetString("RethinkDB.URL", _connectionString);
_connection = RethinkConnection.RethinkConnect(_databaseCache, _connectionString);
_queryStatus = RethinkConnection.RethinkConnect(_databaseCache, _connectionString);
}
}
using (var h = new HorizontalScope())
@ -151,7 +151,7 @@ public class DatabaseListView : EditorWindow
if (GUILayout.Button("Connect All"))
{
EditorPrefs.SetString("RethinkDB.URL", _connectionString);
_connection = RethinkConnection.RethinkConnect(_databaseCache, _connectionString, true, false);
_queryStatus = RethinkConnection.RethinkConnect(_databaseCache, _connectionString, true, false);
}
if (GUILayout.Button("Save"))
@ -159,7 +159,16 @@ public class DatabaseListView : EditorWindow
_databaseCache.Save(new DirectoryInfo(Application.dataPath).Parent.FullName);
}
}
if (_queryStatus != null && _queryStatus.RetrievedItems < _queryStatus.GalaxyEntries + _queryStatus.ItemsEntries)
{
var progressRect = GetControlRect(false, 20);
EditorGUI.ProgressBar(progressRect, (float)_queryStatus.RetrievedItems/(_queryStatus.GalaxyEntries + _queryStatus.ItemsEntries), "Sync Progress");
}
GUILayout.Space(5);
// if(GUILayout.Button("Log Cache Count"))
// Debug.Log($"Cache contains {_databaseCache.AllEntries.Count()} elements");
Action<DatabaseEntry> select = item =>
{

View file

@ -14,7 +14,7 @@ public static class RethinkConnection
{
public static RethinkDB R = RethinkDB.R;
public static Connection RethinkConnect(DatabaseCache cache, string connectionString, bool syncLocalChanges = true, bool filterGalaxyData = true)
public static RethinkQueryStatus RethinkConnect(DatabaseCache cache, string connectionString, bool syncLocalChanges = true, bool filterGalaxyData = true)
{
// Add Unity.Mathematics serialization support to RethinkDB Driver
//Converter.Serializer.Converters.Add(new MathJsonConverter());
@ -72,9 +72,16 @@ public static class RethinkConnection
};
}
var status = new RethinkQueryStatus();
// Get all item data from RethinkDB
Task.Run(async () =>
{
status.ItemsEntries = R
.Db("Aetheria")
.Table("Items")
.Count().RunAtom<int>(connection);
var result = await R
.Db("Aetheria")
.Table("Items")
@ -82,8 +89,9 @@ public static class RethinkConnection
while (await result.MoveNextAsync())
{
var entry = result.Current;
Debug.Log($"Received Items entry from RethinkDB: {entry.GetType()} {(entry as INamedEntry)?.EntryName ?? ""}:{entry.ID}");
//Debug.Log($"Received Items entry from RethinkDB: {entry.GetType()} {(entry as INamedEntry)?.EntryName ?? ""}:{entry.ID}");
cache.Add(entry, true);
status.RetrievedItems++;
}
}).WrapErrors();
@ -94,15 +102,24 @@ public static class RethinkConnection
.Db("Aetheria")
.Table("Galaxy");
if (filterGalaxyData)
operation = ((Table)operation).Filter(o =>
o["$type"] == typeof(GalaxyMapLayerData).Name || o["$type"] == typeof(GlobalData).Name);
{
var filter = ((Table) operation).Filter(o =>
o["$type"] == typeof(GalaxyMapLayerData).Name ||
o["$type"] == typeof(GlobalData).Name ||
o["$type"] == typeof(MegaCorporation).Name);
status.GalaxyEntries = filter.Count().RunAtom<int>(connection);
operation = filter;
}
else status.GalaxyEntries = ((Table) operation).Count().RunAtom<int>(connection);
var result = await operation
.RunCursorAsync<DatabaseEntry>(connection);
while (await result.MoveNextAsync())
{
var entry = result.Current;
Debug.Log($"Received Galaxy entry from RethinkDB: {entry.GetType()} {(entry as INamedEntry)?.EntryName ?? ""}:{entry.ID}");
//Debug.Log($"Received Galaxy entry from RethinkDB: {entry.GetType()} {(entry as INamedEntry)?.EntryName ?? ""}:{entry.ID}");
cache.Add(entry, true);
status.RetrievedItems++;
}
}).WrapErrors();
@ -132,6 +149,13 @@ public static class RethinkConnection
Debug.Log(R.Now().Run<DateTime>(connection).ToString() as string);
});
return connection;
return status;
}
}
public class RethinkQueryStatus
{
public int RetrievedItems;
public int GalaxyEntries;
public int ItemsEntries;
}

View file

@ -17,7 +17,7 @@ public abstract class AgentTask : DatabaseEntry
[JsonProperty("zone"), Key(2)]
public Guid Zone;
[JsonProperty("assignedEntity"), Key(3)]
[JsonProperty("reserved"), Key(3)]
public bool Reserved;
[IgnoreMember] public abstract TaskType Type { get; }

View file

@ -12,15 +12,19 @@ public class StationTowing : AgentTask
[IgnoreMember] public override TaskType Type => TaskType.Tow;
[JsonProperty("station"), Key(4)]
private Guid _station;
public Guid Station;
[JsonProperty("targetOrbit"), Key(5)]
private Guid _targetOrbit;
[JsonProperty("orbitParent"), Key(5)]
public Guid OrbitParent;
[JsonProperty("orbitDistance"), Key(6)]
public float OrbitDistance;
public StationTowing(Guid zone, Guid station, Guid targetOrbit)
public StationTowing(Guid zone, Guid station, Guid orbitParent, float orbitDistance)
{
Zone = zone;
_station = station;
_targetOrbit = targetOrbit;
Station = station;
OrbitParent = orbitParent;
OrbitDistance = orbitDistance;
}
}

View file

@ -8,7 +8,7 @@ using static Unity.Mathematics.math;
public class VelocityMatch : AgentBehavior
{
public event Action OnMatch;
public Guid TargetOrbit;
public float2 TargetVelocity;
private Thruster _thrust;
private Turning _turning;
private const float TargetThreshold = .1f;
@ -21,12 +21,17 @@ public class VelocityMatch : AgentBehavior
_thrust = Entity.Axes.Keys.FirstOrDefault(x => x is Thruster) as Thruster;
_turning = Entity.Axes.Keys.FirstOrDefault(x => x is Turning) as Turning;
}
public void Clear()
{
OnMatch = null;
}
public override void Update(float delta)
{
if (TargetOrbit != Guid.Empty && _thrust != null && _turning != null)
if (_thrust != null && _turning != null)
{
var deltaV = _context.GetOrbitVelocity(TargetOrbit) - Entity.Velocity;
var deltaV = TargetVelocity - Entity.Velocity;
if(length(deltaV) < TargetThreshold)
OnMatch?.Invoke();
Entity.Axes[_turning] = TurningInput(deltaV);
@ -39,7 +44,7 @@ public class VelocityMatch : AgentBehavior
get
{
var velocity = length(Entity.Velocity);
var deltaV = _context.GetOrbitVelocity(TargetOrbit) - Entity.Velocity;
var deltaV = TargetVelocity - Entity.Velocity;
var stoppingTime = length(deltaV) / (_thrust.Thrust / Entity.Mass);
var stoppingDistance = stoppingTime * (velocity / 2);

View file

@ -53,6 +53,9 @@ public class InspectableTextAttribute : InspectableFieldAttribute { }
[AttributeUsage(AttributeTargets.Field)]
public class InspectablePrefabAttribute : InspectableFieldAttribute { }
[AttributeUsage(AttributeTargets.Field)]
public class InspectableTextureAttribute : InspectableFieldAttribute { }
[AttributeUsage(AttributeTargets.Field)]
public class TemperatureInspectableAttribute : InspectableFieldAttribute { }

View file

@ -36,8 +36,9 @@ public interface IPersistentBehavior//<T> where T : IBehavior
public interface IController
{
bool Available { get; }
TaskType JobType { get; }
void AssignTask(Guid task);
TaskType TaskType { get; }
Guid Zone { get; }
void AssignTask(Guid task, List<SimplifiedZoneData> path);
}
[MessagePackObject,

View file

@ -1,4 +1,5 @@
using System.Collections;
using System;
using System.Collections;
using System.Collections.Generic;
using MessagePack;
using Newtonsoft.Json;
@ -19,7 +20,25 @@ public abstract class ControllerData : BehaviorData
public float TangentSensitivity = 4;
}
// public abstract class Controller
// public abstract class Controller : IController
// {
// public abstract bool Available { get; }
// public abstract TaskType TaskType { get; }
// public Guid Zone { get; }
//
// private GameContext _context;
// private Entity _entity;
// private Guid _task;
// private List<SimplifiedZoneData> _path;
//
// public Controller(GameContext context, Entity entity)
// {
//
// }
//
// public void AssignTask(Guid task, List<SimplifiedZoneData> path)
// {
// _task = task;
// _path = path;
// }
// }

View file

@ -20,8 +20,9 @@ public class PatrolControllerData : ControllerData
public class PatrolController : IBehavior, IController
{
public TaskType JobType => TaskType.Tow;
public TaskType TaskType => TaskType.Tow;
public bool Available => false;
public Guid Zone => _entity.Zone;
public BehaviorData Data => _data;
private PatrolControllerData _data;
@ -55,7 +56,7 @@ public class PatrolController : IBehavior, IController
RandomTarget();
}
public void AssignTask(Guid task)
public void AssignTask(Guid task, List<SimplifiedZoneData> path)
{
throw new NotImplementedException();
}

View file

@ -1,8 +1,11 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[MessagePackObject, JsonObject(MemberSerialization.OptIn), EntityTypeRestriction(HullType.Ship)]
public class TowingControllerData : ControllerData
@ -15,8 +18,9 @@ public class TowingControllerData : ControllerData
public class TowingController : IBehavior, IPersistentBehavior, IController
{
public TaskType JobType => TaskType.Tow;
public TaskType TaskType => TaskType.Tow;
public bool Available => _towingTask != Guid.Empty;
public Guid Zone => _entity.Zone;
public BehaviorData Data => _data;
private TowingControllerData _data;
@ -24,6 +28,11 @@ public class TowingController : IBehavior, IPersistentBehavior, IController
private Entity _entity;
private Gear _item;
private Guid _towingTask;
private List<SimplifiedZoneData> _path;
private TowingPhase _towingPhase = TowingPhase.Pickup;
private MovementPhase _movementPhase = MovementPhase.Locomotion;
private Locomotion _locomotion;
private VelocityMatch _velocityMatch;
public TowingController(GameContext context, TowingControllerData data, Entity entity, Gear item)
{
@ -35,11 +44,81 @@ public class TowingController : IBehavior, IPersistentBehavior, IController
public void Initialize()
{
_locomotion = new Locomotion(_context, _entity, _data);
_velocityMatch = new VelocityMatch(_context, _entity, _data);
}
public void Update(float delta)
{
if (_path.Any())
{
_locomotion.Update(delta);
if (length(_entity.Position - _locomotion.Objective) < _context.GlobalData.WarpDistance)
{
_context.Warp(_entity, _path[0].ZoneID);
_path.RemoveAt(0);
if(_path.Any())
SetWormholeDestination();
}
}
else
{
var towingTask = _context.Cache.Get<StationTowing>(_towingTask);
var destination = float2(0);
var velocity = float2(0);
if (_towingPhase == TowingPhase.Pickup)
{
destination = _context.ZoneEntities[_entity.Zone][towingTask.Station].Position;
velocity = _context.ZoneEntities[_entity.Zone][towingTask.Station].Velocity;
}
else
{
var orbitParent = _context.GetOrbitPosition(towingTask.OrbitParent);
var parentToUs = _entity.Position - orbitParent;
var nearestPointInOrbit = orbitParent + normalize(parentToUs) * towingTask.OrbitDistance;
destination = nearestPointInOrbit;
velocity = _context.GetOrbitVelocity(towingTask.OrbitParent);
}
_velocityMatch.TargetVelocity = velocity;
if (_movementPhase == MovementPhase.Locomotion)
{
var matchDistanceTime = _velocityMatch.MatchDistanceTime;
_locomotion.Objective = destination + velocity * matchDistanceTime.y;
_locomotion.Update(delta);
var distance = length(destination - _entity.Position);
if (distance < matchDistanceTime.x)
{
_movementPhase = MovementPhase.Slowdown;
_velocityMatch.Clear();
if (_towingPhase == TowingPhase.Pickup)
_velocityMatch.OnMatch += () =>
{
var target = _context.ZoneEntities[_entity.Zone][towingTask.Station];
_entity.Children.Add(towingTask.Station);
target.Parent = _entity.ID;
_towingPhase = TowingPhase.Delivery;
_movementPhase = MovementPhase.Locomotion;
};
else
_velocityMatch.OnMatch += () =>
{
var orbit = _context.CreateOrbit(towingTask.OrbitParent, _entity.Position);
var target = _context.ZoneEntities[_entity.Zone][towingTask.Station] as OrbitalEntity;
_entity.Children.Remove(towingTask.Station);
target.Parent = Guid.Empty;
target.OrbitData = orbit.ID;
};
}
}
else
{
_velocityMatch.Update(delta);
}
}
}
public PersistentBehaviorData Store()
@ -56,9 +135,18 @@ public class TowingController : IBehavior, IPersistentBehavior, IController
_towingTask = towingControllerPersistence.TowingTask;
}
public void AssignTask(Guid task)
public void AssignTask(Guid task, List<SimplifiedZoneData> path)
{
_towingTask = task;
_path = path;
_path.RemoveAt(0);
if(_path.Any())
SetWormholeDestination();
}
private void SetWormholeDestination()
{
_locomotion.Objective = _context.WormholePosition(_entity.Zone, _path[0].ZoneID);
}
}
@ -67,3 +155,15 @@ public class TowingControllerPersistence : PersistentBehaviorData
[JsonProperty("towingTask"), Key(0)]
public Guid TowingTask;
}
public enum TowingPhase
{
Pickup,
Delivery
}
public enum MovementPhase
{
Locomotion,
Slowdown
}

View file

@ -31,13 +31,13 @@ public interface INamedEntry
Union(10, typeof(ZoneData)),
Union(11, typeof(Player)),
Union(12, typeof(Corporation)),
Union(13, typeof(ShipData)),
Union(13, typeof(MegaCorporation)),
Union(14, typeof(StationData)),
Union(15, typeof(OrbitData)),
Union(16, typeof(PlanetData)),
Union(17, typeof(PersonalityAttribute)),
Union(18, typeof(AgentTask)),
// Union(17, typeof(ShipData)),
Union(19, typeof(LoadoutData)),
JsonObject(MemberSerialization.OptIn), JsonConverter(typeof(JsonKnownTypesConverter<DatabaseEntry>))]
//[Union(21, typeof(ContractData))]
//[Union(22, typeof(Station))]
@ -81,8 +81,43 @@ public class Corporation : DatabaseEntry, INamedEntry
}
}
[RethinkTable("Galaxy"), MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class ShipData : DatabaseEntry
[RethinkTable("Galaxy"), Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class MegaCorporation : DatabaseEntry, INamedEntry
{
[InspectableField, JsonProperty("name"), Key(1)]
public string Name;
[InspectableTexture, JsonProperty("logo"), Key(2)]
public string Logo;
[InspectableDatabaseLink(typeof(PersonalityAttribute)), JsonProperty("initialFleet"), Key(3)]
public Dictionary<Guid, float> Personality = new Dictionary<Guid, float>();
[InspectableDatabaseLink(typeof(LoadoutData)), JsonProperty("initialFleet"), Key(4)]
public Dictionary<Guid, int> InitialFleet = new Dictionary<Guid, int>();
[IgnoreMember] public string EntryName
{
get => Name;
set => Name = value;
}
}
[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> Items = new List<Guid>();
[IgnoreMember] public string EntryName
{
get => Name;
set => Name = value;
}
}

View file

@ -6,6 +6,7 @@ using Unity.Mathematics;
using static Unity.Mathematics.math;
using float2 = Unity.Mathematics.float2;
using Random = Unity.Mathematics.Random;
using JM.LinqFaster;
public class GameContext
{
@ -14,6 +15,7 @@ public class GameContext
public Dictionary<Guid, Dictionary<Guid, Entity>> ZoneEntities = new Dictionary<Guid, Dictionary<Guid, Entity>>();
public Dictionary<string, GalaxyMapLayerData> MapLayers = new Dictionary<string, GalaxyMapLayerData>();
public Dictionary<Guid, List<IController>> CorporationControllers = new Dictionary<Guid, List<IController>>();
public Dictionary<Guid, SimplifiedZoneData> GalaxyZones;
private Action<string> _logger;
@ -23,14 +25,29 @@ public class GameContext
private double _time;
private float _deltaTime;
private GlobalData _globalData;
private HashSet<Guid> _loadedZones = new HashSet<Guid>();
private HashSet<Guid> _orbits = new HashSet<Guid>();
private Dictionary<Guid, float2> _orbitVelocities = new Dictionary<Guid, float2>();
private Dictionary<Guid, float2> _orbitPositions = new Dictionary<Guid, float2>();
private Dictionary<Guid, float2> _previousOrbitPositions = new Dictionary<Guid, float2>();
private Guid _forceLoadZone;
public GlobalData GlobalData => _globalData ?? (_globalData = Cache.GetAll<GlobalData>().FirstOrDefault());
public DatabaseCache Cache { get; }
public Guid ForceLoadZone
{
get => _forceLoadZone;
set
{
if(_forceLoadZone != Guid.Empty && ZoneEntities[_forceLoadZone].Count == 0)
UnloadZone(_forceLoadZone);
_forceLoadZone = value;
if(!_loadedZones.Contains(_forceLoadZone))
LoadZone(_forceLoadZone);
}
}
public double Time
{
get => _time;
@ -68,24 +85,6 @@ public class GameContext
_logger(s);
}
public IEnumerable<Entity> GetEntities(Guid zone)
{
return ZoneEntities[zone].Values;
}
public void InitializeZone(Guid zoneID)
{
var zoneData = Cache.Get<ZoneData>(zoneID);
foreach (var orbit in zoneData.Orbits) _orbits.Add(orbit);
// TODO: Associate planets with stored entities for planetary colonies
ZonePlanets[zoneID] = zoneData.Planets;
// TODO: Load stored entities
ZoneEntities[zoneID] = new Dictionary<Guid, Entity>();
}
public void Update()
{
_previousOrbitPositions = _orbitPositions;
@ -101,22 +100,33 @@ public class GameContext
foreach (var corporation in Cache.GetAll<Corporation>())
{
foreach (var taskController in corporation.Tasks
foreach (var tasks in corporation.Tasks
.Select(id => Cache.Get<AgentTask>(id)) // Fetch the tasks from the database cache
.Where(task => task.Reserved == false) // Filter out tasks that have already been reserved
.GroupBy(task => task.Type) // Group tasks by job type
.Where(grouping =>
CorporationControllers[corporation.ID] // Filter out groupings with no available controller
.Any(controller => controller.Available && controller.JobType == grouping.Key))
.Select(grouping => grouping // Pair each task in remaining groupings with available controllers
.OrderByDescending(task => task.Priority) // Sort by priority, highest first
.Zip(CorporationControllers[corporation.ID]
.Where(controller => controller.Available && controller.JobType == grouping.Key),
(task, controller) => new {task, controller}))
.SelectMany(x => x)) // Flatten groupings
.Where(task => !task.Reserved) // Filter out tasks that have already been reserved
.GroupBy(task => task.Type)) // Group tasks by type
{
taskController.task.Reserved = true;
taskController.controller.AssignTask(taskController.task.ID);
// Create a list of available controllers for this task type
var availableControllers = CorporationControllers[corporation.ID]
.Where(controller => controller.TaskType == tasks.Key && controller.Available).ToList();
// Iterate over the highest priority tasks for which controllers are available
foreach (var task in tasks.OrderByDescending(task => task.Priority).Take(availableControllers.Count))
{
// Find the nearest controller for this task
IController nearestController = availableControllers[0];
List<SimplifiedZoneData> nearestControllerPath = FindPath(GalaxyZones[availableControllers.First().Zone], GalaxyZones[task.Zone], true);
foreach (var controller in availableControllers.Skip(1))
{
var path = FindPath(GalaxyZones[controller.Zone], GalaxyZones[task.Zone], true);
if (path.Count < nearestControllerPath.Count)
{
nearestControllerPath = path;
nearestController = controller;
}
}
task.Reserved = true;
nearestController.AssignTask(task.ID, nearestControllerPath);
}
}
}
@ -127,11 +137,57 @@ public class GameContext
}
}
public IEnumerable<Entity> GetEntities(Guid zone)
{
return ZoneEntities[zone].Values;
}
public void LoadZone(Guid zone)
{
var zoneData = Cache.Get<ZoneData>(zone);
_loadedZones.Add(zone);
foreach (var orbit in zoneData.Orbits) _orbits.Add(orbit);
// TODO: Associate planets with stored entities for planetary colonies
ZonePlanets[zone] = zoneData.Planets;
// TODO: Load stored entities
ZoneEntities[zone] = new Dictionary<Guid, Entity>();
}
public void UnloadZone(Guid zone)
{
var zoneData = Cache.Get<ZoneData>(zone);
foreach (var orbit in zoneData.Orbits) _orbits.Remove(orbit);
_loadedZones.Remove(zone);
ZoneEntities.Remove(zone);
ZonePlanets.Remove(zone);
foreach (var orbit in zoneData.Orbits) _orbits.Remove(orbit);
}
public void Warp(Entity entity, Guid targetZone)
{
if (length(entity.Position - WormholePosition(entity.Zone, targetZone)) < GlobalData.WarpDistance)
{
var sourceZone = entity.Zone;
// Remove entity from source zone
ZoneEntities[sourceZone].Remove(entity.ID);
// Unload source zone if empty and unobserved
if(ForceLoadZone != sourceZone && ZoneEntities[sourceZone].Count == 0)
UnloadZone(sourceZone);
// Load target zone if not yet loaded
if(!_loadedZones.Contains(targetZone))
LoadZone(targetZone);
entity.Zone = targetZone;
entity.Position = WormholePosition(targetZone, sourceZone);
ZoneEntities[targetZone][entity.ID] = entity;
}
}
// Determine orbital position recursively, caching parent positions to avoid repeated calculations
@ -145,7 +201,7 @@ public class GameContext
{
var orbitData = Cache.Get<OrbitData>(orbit);
_orbitPositions[orbit] = GetOrbitPosition(orbitData.Parent) + (orbitData.Period < .01f ? float2.zero :
OrbitData.Evaluate((float) (Time / -orbitData.Period * GlobalData.OrbitSpeedMultiplier + orbitData.Phase)) *
OrbitData.Evaluate((float) frac(Time / -orbitData.Period * GlobalData.OrbitSpeedMultiplier + orbitData.Phase)) *
orbitData.Distance);
}
@ -162,6 +218,35 @@ public class GameContext
{
return _orbitVelocities.ContainsKey(orbit) ? _orbitVelocities[orbit] : float2.zero;
}
public OrbitData CreateOrbit(Guid parent, float2 position)
{
var parentOrbit = Cache.Get<OrbitData>(parent);
var parentPosition = GetOrbitPosition(parent);
var delta = position - parentPosition;
var distance = length(delta);
var period = OrbitalPeriod(distance);
var phase = atan2(delta.y, delta.x) / (PI * 2);
var storedPhase = (float) frac(Time / -period * GlobalData.OrbitSpeedMultiplier - phase);
var orbit = new OrbitData
{
Context = this,
Distance = distance,
ID = Guid.NewGuid(),
Parent = parent,
Period = period,
Phase = storedPhase,
Zone = parentOrbit.Zone
};
Cache.Add(orbit);
return orbit;
}
public float OrbitalPeriod(float distance)
{
return pow(distance, GlobalData.OrbitPeriodExponent) * GlobalData.OrbitPeriodMultiplier;
}
// public int ItemTier(CraftedItemData itemData)
// {
@ -389,4 +474,37 @@ public class GameContext
Cache.Add(newCommodity);
return newCommodity;
}
class DijkstraNode
{
public float Cost;
public DijkstraNode Parent;
public SimplifiedZoneData Zone;
}
public List<SimplifiedZoneData> FindPath(SimplifiedZoneData source, SimplifiedZoneData target, bool bestFirst = false)
{
SortedList<float,DijkstraNode> members = new SortedList<float,DijkstraNode>{{0,new DijkstraNode{Zone = source}}};
List<DijkstraNode> searched = new List<DijkstraNode>();
while (true)
{
var s = members.FirstOrDefault(m => !searched.Contains(m.Value)).Value; // Lowest cost unsearched node
if (s == null) return null; // No vertices left unsearched
if (s.Zone == target) // We found the path
{
Stack<DijkstraNode> path = new Stack<DijkstraNode>(); // Since we start at the end, use a LIFO collection
path.Push(s);
while(path.Peek().Parent!=null) // Keep pushing until we reach the start, which has no parent
path.Push(path.Peek().Parent);
return path.Select(dv => dv.Zone).ToList();
}
// For each adjacent star (filter already visited zones unless heuristic is in use)
foreach (var dijkstraStar in s.Zone.Links.WhereSelectF(i => !bestFirst || members.All(m => m.Value.Zone != GalaxyZones[i]),
// Cost is parent cost plus distance
i => new DijkstraNode {Parent = s, Zone = GalaxyZones[i], Cost = s.Cost + length(s.Zone.Position - GalaxyZones[i].Position)}))
// Add new member to list, sorted by cost plus optional heuristic
members.Add(bestFirst ? dijkstraStar.Cost + length(dijkstraStar.Zone.Position - target.Position) : dijkstraStar.Cost, dijkstraStar);
searched.Add(s);
}
}
}

View file

@ -94,13 +94,13 @@ public class GalaxyRequestMessage : Message
[MessagePackObject]
public class GalaxyResponseMessage : Message
{
[Key(0)] public GalaxyResponseZone[] Zones;
[Key(0)] public SimplifiedZoneData[] Zones;
[Key(1)] public GalaxyMapLayerData StarDensity;
[Key(2)] public GlobalData GlobalData;
}
[MessagePackObject]
public class GalaxyResponseZone
public class SimplifiedZoneData
{
[Key(0)] public Guid ZoneID;
[Key(1)] public Guid[] Links;

View file

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: f577b52edee2c39429e13166dc0fddc2
guid: 8a827381b8571114091cd0fc9c0ebd1f
folderAsset: yes
DefaultImporter:
externalObjects: {}

View file

@ -7,18 +7,21 @@ using float2 = Unity.Mathematics.float2;
public class OrbitalEntity : Entity
{
private Guid _orbitData;
public Guid OrbitData;
public OrbitalEntity(GameContext context, Guid hull, IEnumerable<Guid> items, IEnumerable<Guid> cargo, Guid orbit, Guid zone) : base(context, hull, items, cargo, zone)
{
_orbitData = orbit;
OrbitData = orbit;
}
public override void Update(float delta)
{
var newPosition = Context.GetOrbitPosition(_orbitData);
Velocity = (newPosition - Position) / delta;
Position = newPosition;
if (OrbitData != Guid.Empty)
{
Velocity = Context.GetOrbitVelocity(OrbitData);
Position = Context.GetOrbitPosition(OrbitData);
}
base.Update(delta);
}
}

View file

@ -123,7 +123,7 @@ public class OrbitData : DatabaseEntry
public static float2 Evaluate(float phase)
{
phase *= (PI * 2);
phase *= PI * 2;
return new float2(sin(phase), cos(phase));
}
}

View file

@ -274,7 +274,7 @@ public class Planet
ChildDistanceMaximum = (i % 2 == 0 ? p0ChildDist : p1ChildDist)
};
child.ChildDistanceMinimum = Context.GlobalData.PlanetRadius(child.Mass) * 2;
child.Period = pow(child.Distance, Context.GlobalData.OrbitPeriodExponent) * Context.GlobalData.OrbitPeriodMultiplier;
child.Period = Context.OrbitalPeriod(child.Distance);
Children.Add(child);
}
@ -335,7 +335,7 @@ public class Planet
Distance = distances[i],
Phase = Context.Random.NextFloat()
};
child.Period = pow(child.Distance, Context.GlobalData.OrbitPeriodExponent) * Context.GlobalData.OrbitPeriodMultiplier;
child.Period = Context.OrbitalPeriod(child.Distance);
child.ChildDistanceMinimum = Context.GlobalData.PlanetRadius(child.Mass) * 2;
// Maximum child distance of child is the smallest distance to either of its neighbors
child.ChildDistanceMaximum = min(i == 0 ? child.Distance - ChildDistanceMinimum : child.Distance - distances[i - 1],

View file

@ -8,6 +8,7 @@ using RethinkDb.Driver.Net;
using TMPro;
using UnityEngine;
using Unity.Mathematics;
using UnityEngine.EventSystems;
using static Unity.Mathematics.math;
using float2 = Unity.Mathematics.float2;
using Random = UnityEngine.Random;
@ -25,6 +26,7 @@ public class StrategyGameManager : MonoBehaviour
public MeshRenderer ZoneBoundary;
public ClickRaycaster ClickRaycaster;
public ReadOnlyPropertiesPanel PropertiesPanel;
public ContextMenu ContextMenu;
[Section("Tab Links")]
public TabGroup PrimaryTabGroup;
@ -65,7 +67,6 @@ public class StrategyGameManager : MonoBehaviour
private Guid _populatedZone;
private Guid _selectedZone;
private GalaxyZone _selectedGalaxyZone;
private Dictionary<Guid, GalaxyResponseZone> _galaxyResponseZones;
private Dictionary<Guid, GalaxyZone> _galaxyZoneObjects = new Dictionary<Guid, GalaxyZone>();
private Dictionary<Guid, ZoneObject> _zoneObjects = new Dictionary<Guid, ZoneObject>(); // Key is Orbit
private Dictionary<Guid, AsteroidBelt> _zoneBelts = new Dictionary<Guid, AsteroidBelt>();
@ -90,8 +91,8 @@ public class StrategyGameManager : MonoBehaviour
_context = new GameContext(_cache, Debug.Log);
TechTree.Context = _context;
_context.MapLayers = _cache.GetAll<GalaxyMapLayerData>().ToDictionary(ml => ml.Name);
_galaxyResponseZones = _cache.GetAll<ZoneData>()
.ToDictionary(z => z.ID, z => new GalaxyResponseZone
_context.GalaxyZones = _cache.GetAll<ZoneData>()
.ToDictionary(z => z.ID, z => new SimplifiedZoneData
{
Links = z.Wormholes.ToArray(),
Name = z.Name,
@ -110,7 +111,7 @@ public class StrategyGameManager : MonoBehaviour
// Listen for the server's galaxy description
CultClient.AddMessageListener<GalaxyResponseMessage>(galaxy =>
{
_galaxyResponseZones = galaxy.Zones.ToDictionary(z => z.ZoneID);
_context.GalaxyZones = galaxy.Zones.ToDictionary(z => z.ZoneID);
_cache.Add(galaxy.GlobalData, true);
_context = new GameContext(_cache, Debug.Log);
TechTree.Context = _context;
@ -178,6 +179,7 @@ public class StrategyGameManager : MonoBehaviour
ClickRaycaster.OnClickMiss += () =>
{
ContextMenu.gameObject.SetActive(false);
if (_currentTab == GalaxyTabButton) PopulateGalaxyProperties();
else if (_currentTab == ZoneTabButton) PopulateZoneProperties(_populatedZone);
else if (_currentTab == TechTabButton) PopulateTechProperties();
@ -189,7 +191,7 @@ public class StrategyGameManager : MonoBehaviour
PropertiesPanel.Clear();
PropertiesPanel.Title.text = _context.GlobalData.GalaxyName;
PropertiesPanel.AddSection("Galaxy");
PropertiesPanel.AddProperty("Sectors", $"{_galaxyResponseZones.Count}");
PropertiesPanel.AddProperty("Sectors", $"{_context.GalaxyZones.Count}");
}
private void PopulateZoneProperties(Guid zone)
@ -281,7 +283,7 @@ public class StrategyGameManager : MonoBehaviour
// var zones = _galaxyResponse.Zones.ToDictionary(z=>z.ZoneID);
var linkedZones = new List<Guid>();
foreach (var zone in _galaxyResponseZones.Values)
foreach (var zone in _context.GalaxyZones.Values)
{
linkedZones.Add(zone.ZoneID);
var instance = GalaxyZonePrototype.Instantiate<Transform>();
@ -314,7 +316,7 @@ public class StrategyGameManager : MonoBehaviour
foreach (var linkedZone in zone.Links.Where(l=>!linkedZones.Contains(l)))
{
var link = GalaxyZoneLinkPrototype.Instantiate<Transform>();
var diff = _galaxyResponseZones[linkedZone].Position - zone.Position;
var diff = _context.GalaxyZones[linkedZone].Position - zone.Position;
link.position = instance.position + Vector3.forward*.1f;
link.rotation = Quaternion.Euler(0,0,atan2(diff.y, diff.x) * Mathf.Rad2Deg);
link.localScale = new Vector3(length(diff) * GalaxyScale, 1, 1);
@ -356,9 +358,6 @@ public class StrategyGameManager : MonoBehaviour
_zoneBelts.Clear();
foreach (var ship in _zoneShips.Values) Destroy(ship.gameObject);
_zoneShips.Clear();
if(_populatedZone!=Guid.Empty)
_context.UnloadZone(_populatedZone);
_populatedZone = _selectedZone;
@ -368,8 +367,8 @@ public class StrategyGameManager : MonoBehaviour
{
GenerateZone(_populatedZone);
}
_context.InitializeZone(_populatedZone);
_context.ForceLoadZone = _populatedZone;
float zoneDepth = 0;
@ -396,18 +395,29 @@ public class StrategyGameManager : MonoBehaviour
PlanetoidSprite);
planetObject.Icon.GetComponent<ClickableCollider>().OnClick += (collider, data) =>
{
PropertiesPanel.Clear();
PropertiesPanel.Title.text = planetData.Name;
PropertiesPanel.AddSection(planetData.Mass > _context.GlobalData.SunMass ? "Star" :
planetData.Mass > _context.GlobalData.GasGiantMass ? "Gas Giant" :
planetData.Mass > _context.GlobalData.PlanetMass ? "Planet" :
"Planetoid");
PropertiesPanel.AddProperty("Mass", $"{planetData.Mass}");
PropertiesPanel.AddList("Resources", planetData.Resources.Select(resource =>
if (data.button == PointerEventData.InputButton.Left)
{
var itemData = _context.Cache.Get<SimpleCommodityData>(resource.Key);
return new Tuple<string, string>(itemData.Name, $"{resource.Value:0}");
}));
PropertiesPanel.Clear();
PropertiesPanel.Title.text = planetData.Name;
PropertiesPanel.AddSection(planetData.Mass > _context.GlobalData.SunMass ? "Star" :
planetData.Mass > _context.GlobalData.GasGiantMass ? "Gas Giant" :
planetData.Mass > _context.GlobalData.PlanetMass ? "Planet" :
"Planetoid");
PropertiesPanel.AddProperty("Mass", $"{planetData.Mass}");
PropertiesPanel.AddList("Resources", planetData.Resources.Select(resource =>
{
var itemData = _context.Cache.Get<SimpleCommodityData>(resource.Key);
return new Tuple<string, string>(itemData.Name, $"{resource.Value:0}");
}));
}
else if (data.button == PointerEventData.InputButton.Right)
{
ContextMenu.gameObject.SetActive(true);
ContextMenu.SetOptions(new []
{
("Test Option", (Action) (() => Debug.Log("Test Option Selected")))
});
}
};
}
else
@ -418,15 +428,22 @@ public class StrategyGameManager : MonoBehaviour
_zoneBelts[_cache.Get<OrbitData>(planetData.Orbit).Parent] = belt;
beltObject.GetComponent<ClickableCollider>().OnClick += (_, data) =>
{
PropertiesPanel.Clear();
PropertiesPanel.Title.text = planetData.Name;
PropertiesPanel.AddSection("Asteroid Belt");
PropertiesPanel.AddProperty("Mass", $"{planetData.Mass}");
PropertiesPanel.AddList("Resources", planetData.Resources.Select(resource =>
if (data.button == PointerEventData.InputButton.Left)
{
var itemData = _context.Cache.Get<SimpleCommodityData>(resource.Key);
return new Tuple<string, string>(itemData.Name, $"{resource.Value:0}");
}));
PropertiesPanel.Clear();
PropertiesPanel.Title.text = planetData.Name;
PropertiesPanel.AddSection("Asteroid Belt");
PropertiesPanel.AddProperty("Mass", $"{planetData.Mass}");
PropertiesPanel.AddList("Resources", planetData.Resources.Select(resource =>
{
var itemData = _context.Cache.Get<SimpleCommodityData>(resource.Key);
return new Tuple<string, string>(itemData.Name, $"{resource.Value:0}");
}));
}
else if (data.button == PointerEventData.InputButton.Right)
{
}
};
}
}
@ -438,7 +455,7 @@ public class StrategyGameManager : MonoBehaviour
foreach (var wormhole in zoneData.Wormholes)
{
var otherZone = _galaxyResponseZones[wormhole];
var otherZone = _context.GalaxyZones[wormhole];
var wormholeObject = Instantiate(ZoneObjectPrefab, ZoneRoot);
_wormholes.Add(wormholeObject);
wormholeObject.transform.position = (Vector2) (_context.WormholePosition(zoneData.ID, wormhole) * ZoneSizeScale);
@ -548,7 +565,7 @@ public class StrategyGameManager : MonoBehaviour
if(_populatedZone!=Guid.Empty)
_context.UnloadZone(_populatedZone);
_cache.Delete(zoneData);
_galaxyResponseZones.Remove(zoneData.ID);
_context.GalaxyZones.Remove(zoneData.ID);
var newZone = zoneData.Copy();
newZone.ID = Guid.NewGuid();
@ -563,7 +580,7 @@ public class StrategyGameManager : MonoBehaviour
}
newZone.Wormholes = linkedZones.Select(z => z.ID).ToList();
var zone = _galaxyResponseZones[newZone.ID] = new GalaxyResponseZone
var zone = _context.GalaxyZones[newZone.ID] = new SimplifiedZoneData
{
Links = newZone.Wormholes.ToArray(),
Name = newZone.Name,
@ -675,8 +692,8 @@ public class AsteroidBelt
{
var rotation = Quaternion.Euler(0, 0, (float) (_context.Time * _data.Asteroids[i].w % 360.0));
var position = (Vector3) (Vector2)
OrbitData.Evaluate((float) (_context.Time / -pow(_data.Asteroids[i].x, _context.GlobalData.OrbitPeriodExponent) * _context.GlobalData.OrbitPeriodMultiplier) *
_context.GlobalData.OrbitSpeedMultiplier + _data.Asteroids[i].y) * (_data.Asteroids[i].x * _zoneScale);
OrbitData.Evaluate((float) frac(_context.Time / -_context.OrbitalPeriod(_data.Asteroids[i].x) *
_context.GlobalData.OrbitSpeedMultiplier + _data.Asteroids[i].y)) * (_data.Asteroids[i].x * _zoneScale);
_vertices[i * 4] = rotation * new Vector3(-_data.Asteroids[i].z,-_data.Asteroids[i].z,0) + position;
_vertices[i * 4 + 1] = rotation * new Vector3(-_data.Asteroids[i].z,_data.Asteroids[i].z,0) + position;
_vertices[i * 4 + 2] = rotation * new Vector3(_data.Asteroids[i].z,_data.Asteroids[i].z,0) + position;

View file

@ -0,0 +1,47 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class ContextMenu : MonoBehaviour
{
public Canvas Canvas;
public RectTransform OptionPrefab;
public RectTransform ContentRoot;
public float OptionHeight;
public float PaddingHeight;
private List<GameObject> _options = new List<GameObject>();
public void SetOptions(IEnumerable<(string text, Action action)> options)
{
var rect = transform as RectTransform;
var pivot = rect.pivot;
pivot.x = Input.mousePosition.x > Screen.width - rect.sizeDelta.x * Canvas.scaleFactor ? 1 : 0;
pivot.y = Input.mousePosition.y < (PaddingHeight + options.Count() * OptionHeight) * Canvas.scaleFactor ? 0 : 1;
rect.pivot = pivot;
rect.position = Input.mousePosition;
// Destroy previous options
foreach(var option in _options)
Destroy(option);
_options.Clear();
foreach (var option in options)
{
var optionButton = Instantiate(OptionPrefab, ContentRoot);
optionButton.GetComponentInChildren<TextMeshProUGUI>().text = option.text;
optionButton.GetComponent<Button>().onClick.AddListener(() =>
{
option.action();
gameObject.SetActive(false);
});
_options.Add(optionButton.gameObject);
}
}
}

View file

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