Control Modules & Job System

Agent behaviors are no longer hard coded but instead created by equippable control modules
Game Context has a job system which assigns appropriate tasks to drone control modules
This commit is contained in:
hyperion51 2020-05-07 03:53:54 +01:00
commit ab8aa5fb9a
27 changed files with 480 additions and 190 deletions

View file

@ -1,7 +1,30 @@
using System.Collections;
using System.Collections.Generic;
using Unity.Mathematics;
using static Unity.Mathematics.math;
public abstract class AgentBehavior
{
public abstract void Update(float delta);
protected float ThrustInput(float2 deltaV) =>
saturate( // Input must be normalized
pow( // Apply specificity as exponent to dot product to control how specific the direction needs to be
saturate( // Discard negative dot product (we're facing away from desired direction)
dot(normalize(Entity.Direction), normalize(deltaV))), // Cosine of angle between direction and deltaV
ControllerData.ThrustSpecificity)
* length(deltaV) * ControllerData.ThrustSensitivity);
protected float TurningInput(float2 deltaV) => clamp(-Entity.Direction.AngleDiff(deltaV) * ControllerData.TurningSensitivity, -1, 1);
protected ControllerData ControllerData;
protected GameContext Context;
protected Entity Entity;
public AgentBehavior(GameContext context, Entity entity, ControllerData controllerData)
{
Context = context;
Entity = entity;
ControllerData = controllerData;
}
}

View file

@ -1,64 +1,64 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using static Unity.Mathematics.math;
using Random = Unity.Mathematics.Random;
public class AgentController
{
public Guid Entity { get; }
public EntityAgent EntityAgent { get; }
public GameContext Context { get; }
public Guid Zone { get; set; }
private Locomotion _locomotion;
private VelocityMatch _velocityMatch;
private Random _random = new Random((uint) (DateTime.Now.Ticks%uint.MaxValue));
private Guid _targetOrbit;
public AgentController(GameContext context, Guid zone, Guid entity)
{
Entity = entity;
Zone = zone;
Context = context;
EntityAgent = new EntityAgent(context, entity, zone, Guid.Empty);
_locomotion = new Locomotion(context, entity);
_velocityMatch = new VelocityMatch(context, entity);
_velocityMatch.OnMatch += () =>
{
EntityAgent.CurrentBehavior = _locomotion;
RandomTarget();
};
EntityAgent.CurrentBehavior = _locomotion;
RandomTarget();
}
public void Update(float delta)
{
EntityAgent.Update(delta);
// Context.Log(
// $"Agent Mode: {EntityAgent.CurrentBehavior.GetType()} " +
// $"Agent Distance: {distance} " +
// $"Turnaround Distance: {_stoppingDistance + _turnaroundDistance} " +
// $"Objective: {_objective.Key.ID.ToString().Substring(0, 8)}");
var entity = Context.Cache.Get<Entity>(Entity);
if (EntityAgent.CurrentBehavior == _locomotion)
{
var orbitData = Context.Cache.Get<OrbitData>(_targetOrbit);
_velocityMatch.TargetOrbit = _targetOrbit;
var matchDistanceTime = _velocityMatch.MatchDistanceTime;
_locomotion.Objective = Context.GetOrbitPosition(_targetOrbit) + Context.GetOrbitVelocity(_targetOrbit) * matchDistanceTime.y;
var distance = length(_locomotion.Objective - entity.Position);
if (distance < matchDistanceTime.x)
EntityAgent.CurrentBehavior = _velocityMatch;
}
}
private void RandomTarget()
{
var entities = Context.ZonePlanets[Zone];
_targetOrbit = Context.Cache.Get<PlanetData>(entities[_random.NextInt(entities.Length)]).Orbit;
}
}
// using System;
// using System.Collections;
// using System.Collections.Generic;
// using System.Linq;
// using static Unity.Mathematics.math;
// using Random = Unity.Mathematics.Random;
//
// public class AgentController
// {
// public Guid Entity { get; }
// public EntityAgent EntityAgent { get; }
// public GameContext Context { get; }
// public Guid Zone { get; set; }
//
// private Locomotion _locomotion;
// private VelocityMatch _velocityMatch;
// private Random _random = new Random((uint) (DateTime.Now.Ticks%uint.MaxValue));
// private Guid _targetOrbit;
//
// public AgentController(GameContext context, Guid zone, Guid entity)
// {
// Entity = entity;
// Zone = zone;
// Context = context;
// EntityAgent = new EntityAgent(context, entity, zone, Guid.Empty);
// _locomotion = new Locomotion(context, entity);
// _velocityMatch = new VelocityMatch(context, entity);
// _velocityMatch.OnMatch += () =>
// {
// EntityAgent.CurrentBehavior = _locomotion;
// RandomTarget();
// };
// EntityAgent.CurrentBehavior = _locomotion;
// RandomTarget();
// }
//
// public void Update(float delta)
// {
// EntityAgent.Update(delta);
// // Context.Log(
// // $"Agent Mode: {EntityAgent.CurrentBehavior.GetType()} " +
// // $"Agent Distance: {distance} " +
// // $"Turnaround Distance: {_stoppingDistance + _turnaroundDistance} " +
// // $"Objective: {_objective.Key.ID.ToString().Substring(0, 8)}");
// var entity = Context.Cache.Get<Entity>(Entity);
//
// if (EntityAgent.CurrentBehavior == _locomotion)
// {
// var orbitData = Context.Cache.Get<OrbitData>(_targetOrbit);
// _velocityMatch.TargetOrbit = _targetOrbit;
// var matchDistanceTime = _velocityMatch.MatchDistanceTime;
// _locomotion.Objective = Context.GetOrbitPosition(_targetOrbit) + Context.GetOrbitVelocity(_targetOrbit) * matchDistanceTime.y;
// var distance = length(_locomotion.Objective - entity.Position);
// if (distance < matchDistanceTime.x)
// EntityAgent.CurrentBehavior = _velocityMatch;
// }
// }
//
// private void RandomTarget()
// {
// var entities = Context.ZonePlanets[Zone];
// _targetOrbit = Context.Cache.Get<PlanetData>(entities[_random.NextInt(entities.Length)]).Orbit;
// }
// }

View file

@ -9,14 +9,21 @@ using UnityEngine;
[MessagePackObject,
Union(0, typeof(StationTowing)),
JsonObject(MemberSerialization.OptIn), JsonConverter(typeof(JsonKnownTypesConverter<DatabaseEntry>))]
public abstract class AgentTask
public abstract class AgentTask : DatabaseEntry
{
[IgnoreMember] public abstract AgentJob JobType { get; }
[JsonProperty("id"), Key(0)] public int Priority;
[JsonProperty("zone"), Key(1)] public Guid Zone;
[JsonProperty("priority"), Key(1)]
public int Priority;
[JsonProperty("zone"), Key(2)]
public Guid Zone;
[JsonProperty("assignedEntity"), Key(3)]
public bool Reserved;
[IgnoreMember] public abstract TaskType Type { get; }
}
public enum AgentJob
public enum TaskType
{
Mine,
Haul,

View file

@ -11,30 +11,45 @@ public class Locomotion : AgentBehavior
private const float Sensitivity = 1;
private const float TangentSensitivity = 2;
private GameContext _context;
private Guid _entity;
private IAnalogBehavior _thrust;
private IAnalogBehavior _turning;
private Thruster _thrust;
private Turning _turning;
private VelocityLimit _velocityLimit;
public Locomotion(GameContext context, Guid entity)
public Locomotion(GameContext context, Entity entity, ControllerData controllerData) : base(context, entity, controllerData)
{
_context = context;
_entity = entity;
var entityObject = _context.Cache.Get<Entity>(_entity);
_thrust = entityObject.Axes.Keys.FirstOrDefault(x => x is Thruster);
_turning = entityObject.Axes.Keys.FirstOrDefault(x => x is Turning);
_velocityLimit = Entity.GetBehaviors<VelocityLimit>().FirstOrDefault();
_thrust = Entity.Axes.Keys.FirstOrDefault(x => x is Thruster) as Thruster;
_turning = Entity.Axes.Keys.FirstOrDefault(x => x is Turning) as Turning;
}
public override void Update(float delta)
{
var entity = _context.Cache.Get<Entity>(_entity);
if (_thrust != null && _turning != null)
{
float2 diff = Objective - entity.Position;
float2 tangential = entity.Velocity - dot(normalize(diff), normalize(entity.Velocity)) * entity.Velocity;
float angleDiff = entity.Direction.AngleDiff(normalize(diff) - tangential * TangentSensitivity);
entity.Axes[_turning] = clamp(-angleDiff * Sensitivity, -1, 1);
entity.Axes[_thrust] = 1;
float2 diff = Objective - Entity.Position;
// We want to go top speed in the direction of our target
var topSpeed = _velocityLimit?.Limit ?? 1000;
float2 desiredVelocity = normalize(diff) * topSpeed;
var accelerationTime = length(desiredVelocity - Entity.Velocity) / (_thrust.Thrust / Entity.Mass);
var accelerationDistance = accelerationTime * length((desiredVelocity + Entity.Velocity) / 2);
// We do not have enough space to get to full speed, use approximate maneuvering
if (accelerationDistance > length(diff))
{
float2 tangential = Entity.Velocity - dot(normalize(diff), normalize(Entity.Velocity)) * Entity.Velocity;
float2 adjustedDirection = normalize(diff) - tangential * TangentSensitivity;
Entity.Axes[_turning] = TurningInput(adjustedDirection);
Entity.Axes[_thrust] = 1;
}
// We have plenty of space, use exact maneuvering
else
{
var deltaV = desiredVelocity - Entity.Velocity;
Entity.Axes[_turning] = TurningInput(deltaV);
Entity.Axes[_thrust] = ThrustInput(deltaV);
}
}
}
}

View file

@ -4,21 +4,23 @@ using System.Collections.Generic;
using JsonKnownTypes;
using MessagePack;
using Newtonsoft.Json;
using UnityEngine;
[MessagePackObject,
JsonObject(MemberSerialization.OptIn), JsonConverter(typeof(JsonKnownTypesConverter<DatabaseEntry>))]
public class StationTowing : AgentTask
{
[IgnoreMember] public override AgentJob JobType => AgentJob.Tow;
[IgnoreMember] public override TaskType Type => TaskType.Tow;
private Guid _entity;
[JsonProperty("station"), Key(4)]
private Guid _station;
[JsonProperty("targetOrbit"), Key(5)]
private Guid _targetOrbit;
public StationTowing(Guid zone, Guid entity, Guid targetOrbit)
public StationTowing(Guid zone, Guid station, Guid targetOrbit)
{
Zone = zone;
_entity = entity;
_station = station;
_targetOrbit = targetOrbit;
}
}

View file

@ -9,35 +9,28 @@ public class VelocityMatch : AgentBehavior
{
public event Action OnMatch;
public Guid TargetOrbit;
private Guid _entity;
private IAnalogBehavior _thrust;
private IAnalogBehavior _turning;
private const float TurningSensitivity = 1;
private const float ThrustSensitivity = 1;
private Thruster _thrust;
private Turning _turning;
private const float TargetThreshold = .1f;
private GameContext _context;
public VelocityMatch(GameContext context, Guid entity)
public VelocityMatch(GameContext context, Entity entity, ControllerData controllerData) : base(context, entity, controllerData)
{
_context = context;
_entity = entity;
var entityObject = _context.Cache.Get<Entity>(_entity);
_thrust = entityObject.Axes.Keys.FirstOrDefault(x => x is Thruster);
_turning = entityObject.Axes.Keys.FirstOrDefault(x => x is Turning);
_thrust = Entity.Axes.Keys.FirstOrDefault(x => x is Thruster) as Thruster;
_turning = Entity.Axes.Keys.FirstOrDefault(x => x is Turning) as Turning;
}
public override void Update(float delta)
{
var entity = _context.Cache.Get<Entity>(_entity);
if (TargetOrbit != Guid.Empty && _thrust != null && _turning != null)
{
var deltaV = _context.GetOrbitVelocity(TargetOrbit) - entity.Velocity;
var deltaV = _context.GetOrbitVelocity(TargetOrbit) - Entity.Velocity;
if(length(deltaV) < TargetThreshold)
OnMatch?.Invoke();
var angleDiff = entity.Direction.AngleDiff(deltaV);
entity.Axes[_turning] = clamp(-angleDiff * TurningSensitivity, -1, 1);
entity.Axes[_thrust] = saturate(length(pow(saturate(dot(normalize(entity.Direction),normalize(deltaV))), 8)*length(deltaV))*ThrustSensitivity);
Entity.Axes[_turning] = TurningInput(deltaV);
Entity.Axes[_thrust] = ThrustInput(deltaV);
}
}
@ -45,15 +38,14 @@ public class VelocityMatch : AgentBehavior
{
get
{
var entity = _context.Cache.Get<Entity>(_entity);
var velocity = length(entity.Velocity);
var deltaV = _context.GetOrbitVelocity(TargetOrbit) - entity.Velocity;
var velocity = length(Entity.Velocity);
var deltaV = _context.GetOrbitVelocity(TargetOrbit) - Entity.Velocity;
var stoppingTime = length(deltaV) / (_context.Evaluate((_thrust.Data as ThrusterData).Thrust, _thrust.Item, entity) / entity.Mass);
var stoppingTime = length(deltaV) / (_thrust.Thrust / Entity.Mass);
var stoppingDistance = stoppingTime * (velocity / 2);
var angleDiff = entity.Direction.AngleDiff(deltaV);
var turnaroundTime = angleDiff / (_context.Evaluate((_turning.Data as TurningData).Torque, _turning.Item, entity) / entity.Mass);
var angleDiff = Entity.Direction.AngleDiff(deltaV);
var turnaroundTime = angleDiff / (_turning.Torque / Entity.Mass);
var turnaroundDistance = turnaroundTime * velocity;
return float2(stoppingDistance + turnaroundDistance, stoppingTime + turnaroundTime);