AI State Machine First Pass

Implemented first pass on code-driven state machine logic for flexible AI agents
This commit is contained in:
Reinier Vens 2021-02-11 03:14:20 +00:00
commit 8d4bd04891
26 changed files with 489 additions and 137 deletions

View file

@ -1450,6 +1450,10 @@
<e p="ChargeEffectManager.cs" t="Include" />
<e p="ConstantLaser.cs" t="Include" />
<e p="ConstantLaserManager.cs" t="Include" />
<e p="ConstantLightning.cs" t="Include" />
<e p="ConstantLightningManager.cs" t="Include" />
<e p="ConstantParticleWeapon.cs" t="Include" />
<e p="ConstantParticleWeaponManager.cs" t="Include" />
<e p="ConstantWeaponEffectManager.cs" t="Include" />
<e p="GuidedProjectile.cs" t="Include" />
<e p="GuidedProjectileManager.cs" t="Include" />
@ -1460,6 +1464,8 @@
<e p="LaserManager.cs" t="Include" />
<e p="Lightning.cs" t="Include" />
<e p="LightningGunManager.cs" t="Include" />
<e p="Mine.cs" t="Include" />
<e p="MineManager.cs" t="Include" />
<e p="ParticleChargeEffect.cs" t="Include" />
<e p="Projectile.cs" t="Include" />
<e p="ProjectileManager.cs" t="Include" />

View file

@ -86,7 +86,7 @@ Material:
- _Mode: 0
- _OcclusionStrength: 1
- _Parallax: 0.02
- _Scale: 5.181433
- _Scale: 2.7104213
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1

View file

@ -4567,6 +4567,7 @@ MonoBehaviour:
m_Script: {fileID: 11500000, guid: 78aa0b8ec7594a7438f13757228e3500, type: 3}
m_Name:
m_EditorClassIdentifier:
ConfirmationDialog: {fileID: 0}
Flip: 1
Settings: {fileID: 11400000, guid: cd2344e2001a37544aab0960c164d4ff, type: 2}
GameManager: {fileID: 1009503729}
@ -28397,6 +28398,7 @@ MonoBehaviour:
m_Script: {fileID: 11500000, guid: 78aa0b8ec7594a7438f13757228e3500, type: 3}
m_Name:
m_EditorClassIdentifier:
ConfirmationDialog: {fileID: 0}
Flip: 0
Settings: {fileID: 11400000, guid: cd2344e2001a37544aab0960c164d4ff, type: 2}
GameManager: {fileID: 1009503729}

View file

@ -17,6 +17,7 @@ using UnityEngine.InputSystem;
using UnityEngine.UI;
using static Unity.Mathematics.math;
using float2 = Unity.Mathematics.float2;
using Random = UnityEngine.Random;
public class ActionGameManager : MonoBehaviour
{
@ -48,20 +49,21 @@ public class ActionGameManager : MonoBehaviour
// private CinemachineComposer _composer;
private DirectoryInfo _filePath;
private DirectoryInfo _presetPath;
private DirectoryInfo _loadoutPath;
private bool _editMode;
private float _time;
private AetheriaInput _input;
private int _zoomLevelIndex;
public List<EntityPack> Loadouts { get; set; } = new List<EntityPack>();
// private ShipInput _shipInput;
private List<Agent> _shipAgents = new List<Agent>();
private IDisposable _shipTargetSubscription;
private float2 _shipYawPitch;
private float3 _viewDirection;
private (HardpointData[] hardpoints, Transform[] barrels, PlaceUIElementWorldspace crosshair)[] _articulationGroups;
private (LockWeapon targetLock, PlaceUIElementWorldspace indicator, Rotate spin)[] _lockingIndicators;
public List<Ship> PlayerShips { get; } = new List<Ship>();
public List<Entity> PlayerEntities { get; } = new List<Entity>();
public EquippedDockingBay DockingBay { get; private set; }
public Entity DockedEntity { get; private set; }
@ -69,6 +71,7 @@ public class ActionGameManager : MonoBehaviour
public DatabaseCache ItemData { get; private set; }
public ItemManager ItemManager { get; private set; }
public Zone Zone { get; private set; }
public List<EntityPack> Loadouts { get; } = new List<EntityPack>();
private readonly (float2 direction, string name)[] _directions = {
(float2(0, 1), "Front"),
@ -79,7 +82,7 @@ public class ActionGameManager : MonoBehaviour
public void SaveLoadout(EntityPack pack)
{
File.WriteAllBytes(Path.Combine(_presetPath.FullName, $"{pack.Name}.preset"), MessagePackSerializer.Serialize(pack));
File.WriteAllBytes(Path.Combine(_loadoutPath.FullName, $"{pack.Name}.preset"), MessagePackSerializer.Serialize(pack));
}
void Start()
@ -90,12 +93,12 @@ public class ActionGameManager : MonoBehaviour
ConsoleController.MessageReceiver = this;
_filePath = new DirectoryInfo(Application.dataPath).Parent.CreateSubdirectory("GameData");
_presetPath = _filePath.CreateSubdirectory("Presets");
_loadoutPath = _filePath.CreateSubdirectory("Loadouts");
ItemData = new DatabaseCache();
ItemData.Load(_filePath.FullName);
ItemManager = new ItemManager(ItemData, Settings.GameplaySettings, Debug.Log);
Loadouts.AddRange(_presetPath.EnumerateFiles("*.preset")
Loadouts.AddRange(_loadoutPath.EnumerateFiles("*.preset")
.Select(fi => MessagePackSerializer.Deserialize<EntityPack>(File.ReadAllBytes(fi.FullName))));
var zoneFile = Path.Combine(_filePath.FullName, "Home.zone");
@ -112,6 +115,7 @@ public class ActionGameManager : MonoBehaviour
);
Zone = new Zone(Settings.PlanetSettings, zonePack);
Zone.Log = s => Debug.Log($"Zone: {s}");
SectorRenderer.ItemManager = ItemManager;
SectorRenderer.LoadZone(Zone);
@ -353,38 +357,34 @@ public class ActionGameManager : MonoBehaviour
var dockingBay = ItemManager.CreateInstance(dockingBayData, 1, 1) as EquippableItem;
station.TryEquip(dockingBay);
station.Active = true;
var reactorData = ItemData.GetAll<GearData>().First(x => x.HardpointType == HardpointType.Reactor && x.Shape.Height == 2);
var radiatorData = ItemData.GetAll<GearData>().First(x => x.Name == "Long Radiator");
var autocannonData = ItemData.GetAll<GearData>().First(x => x.Name == "Autocannon");
var ammoData = ItemData.GetAll<SimpleCommodityData>().First(x => x.Name == "Autocannon Ammo");
var turretType = ItemData.GetAll<HullData>().First(x=>x.HullType==HullType.Turret);
var controlModuleData = ItemData.GetAll<GearData>().First(x => x.Name == "Murder Module");
var cargo1Data = ItemData.GetAll<CargoBayData>().First(x => x.Name == "Cargo Bay 1x1");
var turretLoadout = Loadouts.First(x => x.Name == "Turret");
for(int i=0; i<5; i++)
for(int i=0; i<3; i++)
{
var turretParent = Zone.PlanetInstances.Values.OrderByDescending(p => p.BodyData.Mass.Value).ElementAt(5+i);
var turretParentOrbit = turretParent.Orbit.Data.ID;
var turretParentPos = Zone.GetOrbitPosition(turretParentOrbit);
var turretPos = turretParentPos + ItemManager.Random.NextFloat2Direction() * turretParent.GravityWellRadius.Value * .25f;
var turretOrbit = Zone.CreateOrbit(turretParentOrbit, turretPos);
var turret = new OrbitalEntity(ItemManager, Zone, ItemManager.CreateInstance(turretType, 0, 1) as EquippableItem, turretOrbit.ID);
turret.TryEquip(ItemManager.CreateInstance(reactorData, .5f, 1) as EquippableItem);
turret.TryEquip(ItemManager.CreateInstance(radiatorData, .5f, 1) as EquippableItem);
turret.TryEquip(ItemManager.CreateInstance(radiatorData, .5f, 1) as EquippableItem);
turret.TryEquip(ItemManager.CreateInstance(controlModuleData, .5f, 1) as EquippableItem);
turret.TryEquip(ItemManager.CreateInstance(autocannonData, .5f, 1) as EquippableItem);
turret.TryEquip(ItemManager.CreateInstance(autocannonData, .5f, 1) as EquippableItem);
turret.TryEquip(ItemManager.CreateInstance(cargo1Data, .5f, 1) as EquippableItem);
turret.CargoBays.First().TryStore(ItemManager.CreateInstance(ammoData, 400));
foreach (var v in turretType.Shape.Coordinates)
turret.HullConductivity[v.x, v.y] = bool2(true);
turret.Active = true;
Zone.Entities.Add(turret);
var planet = Zone.PlanetInstances.Values.OrderByDescending(p => p.BodyData.Mass.Value).ElementAt(4+i);
var planetOrbit = planet.Orbit.Data.ID;
var planetPos = Zone.GetOrbitPosition(planetOrbit);
for (int j = 0; j < 2; j++)
{
var pos = planetPos + ItemManager.Random.NextFloat2Direction() * planet.GravityWellRadius.Value * (.1f + .1f * j);
var orbit = Zone.CreateOrbit(planetOrbit, pos);
var turret = EntityPack.Unpack(ItemManager, Zone, turretLoadout, orbit.ID, true);
turret.Active = true;
Zone.Entities.Add(turret);
}
}
var enemyShipLoadout = Loadouts.First(x => ((HullData) ItemManager.GetData(x.Hull)).HullType == HullType.Ship);
var enemyShip = EntityPack.Unpack(ItemManager, Zone, enemyShipLoadout, true);
enemyShip.Active = true;
Zone.Entities.Add(enemyShip);
var agent = new Agent(enemyShip);
var task = new PatrolOrbitsTask();
task.Circuit = Zone.Orbits.OrderBy(_ => Random.value).Take(4).Select(x => x.Key).ToArray();
agent.Task = task;
_shipAgents.Add(agent);
DockedEntity = station;
DockingBay = station.DockingBays.First();
DockCamera.enabled = true;
@ -544,25 +544,20 @@ public class ActionGameManager : MonoBehaviour
{
foreach (var bay in CurrentShip.Parent.DockingBays)
{
if (PlayerShips.Contains(bay.DockedShip)) yield return bay;
if (PlayerEntities.Contains(bay.DockedShip)) yield return bay;
}
}
}
public IEnumerable<Ship> AvailableShips()
public IEnumerable<Entity> AvailableEntities()
{
if (CurrentShip != null)
{
if (CurrentShip.Parent != null)
if(DockedEntity != null)
foreach (var entity in PlayerEntities)
{
foreach (var ship in PlayerShips)
{
if (CurrentShip.Parent.Children.Contains(ship)) yield return ship;
}
if (DockedEntity.Children.Contains(entity)) yield return entity;
}
else
yield return CurrentShip;
}
else if (CurrentShip != null)
yield return CurrentShip;
}
void Update()
@ -580,6 +575,8 @@ public class ActionGameManager : MonoBehaviour
CurrentShip.MovementDirection = _input.Player.Move.ReadValue<Vector2>();
}
}
foreach(var agent in _shipAgents)
agent.Update(Time.deltaTime);
Zone.Update(_time, Time.deltaTime);
SectorRenderer.Time = _time;
}

View file

@ -3,7 +3,7 @@ using System.Collections.Generic;
using Unity.Mathematics;
using static Unity.Mathematics.math;
public class AetheriaMath
public static class AetheriaMath
{
//first-order intercept using absolute target position
public static float3 FirstOrderIntercept

View file

@ -2,10 +2,15 @@
* 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 RethinkDb.Driver.Ast;
using UniRx;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using float2 = Unity.Mathematics.float2;
public abstract class AgentBehavior
{
@ -32,3 +37,167 @@ public abstract class AgentBehavior
ControllerData = controllerData;
}
}
public class Agent
{
private BaseState _rootState;
private BaseState _currentState;
private Dictionary<BaseState, List<StateTransition>> _stateTransitions = new Dictionary<BaseState, List<StateTransition>>();
public AgentTask Task { get; set; }
public Ship Ship { get; }
public ItemManager ItemManager { get; }
public GameplaySettings Settings { get; }
public Agent(Ship ship)
{
Ship = ship;
ItemManager = Ship.ItemManager;
Settings = Ship.ItemManager.GameplaySettings;
_rootState = _currentState = new BaseState(this);
var patrolState = new PatrolOrbitsState(this);
AddTransition(_rootState, patrolState,
() => Task is PatrolOrbitsTask,
() => patrolState.Task = Task as PatrolOrbitsTask);
var patrolMoveState = new MoveToOrbitState(this);
AddTransition(patrolState, patrolMoveState,
() => true,
() => patrolMoveState.Orbit = patrolState.CurrentTarget);
AddTransition(patrolMoveState, patrolState,
() => patrolMoveState.Distance < 10,
() => patrolState.NextTarget());
}
public void AddTransition(BaseState source, BaseState targetState, Func<bool> condition, Action onTransition = null)
{
if(!_stateTransitions.ContainsKey(source))
_stateTransitions[source] = new List<StateTransition>();
_stateTransitions[source].Add(new StateTransition(targetState, condition, onTransition));
}
public void Transition(BaseState targetState, Action onTransition = null)
{
_currentState.OnExitState();
_currentState = targetState;
onTransition?.Invoke();
_currentState.OnEnterState();
}
public void Update(float delta)
{
_currentState.Update(delta);
foreach (var transition in _stateTransitions[_currentState])
if (transition.Condition())
{
Transition(transition.TargetState, transition.OnTransition);
break;
}
}
public class StateTransition
{
public StateTransition(BaseState targetState, Func<bool> condition, Action onTransition)
{
TargetState = targetState;
Condition = condition;
OnTransition = onTransition;
}
public BaseState TargetState { get; }
public Func<bool> Condition { get; }
public Action OnTransition { get; }
}
}
public class BaseState
{
protected Agent _agent;
public BaseState(Agent agent)
{
_agent = agent;
}
public virtual void Update(float delta){}
public virtual void OnEnterState(){}
public virtual void OnExitState(){}
}
public abstract class MoveToState : BaseState
{
private const float FORWARD_DELTA_THRESHOLD = 20;
private const float THRUST_DELTA_THRESHOLD = 1;
private VelocityLimit _velocityLimit;
protected abstract float2 TargetPosition { get; }
public float Distance { get; private set; }
protected MoveToState(Agent agent) : base(agent)
{
_velocityLimit = agent.Ship.GetBehavior<VelocityLimit>();
}
public override void Update(float delta)
{
var diff = TargetPosition - _agent.Ship.Position.xz;
var dir = normalize(diff);
Distance = length(diff);
// We want to go top speed in the direction of our target
var topSpeed = _velocityLimit?.Limit ?? 100;
var desiredVelocity = dir * topSpeed;
var deltaV = desiredVelocity - _agent.Ship.Velocity;
var deltaVMag = length(deltaV);
var deltaVDirection = normalize(deltaV);
// If Delta V is above the threshold, direct the ship towards the delta and use only main thrusters
if (deltaVMag > FORWARD_DELTA_THRESHOLD)
{
_agent.Ship.LookDirection = float3(deltaVDirection.x, 0, deltaVDirection.y);
_agent.Ship.MovementDirection = float2(0, pow(dot(_agent.Ship.Direction, deltaVDirection), 2));
}
// If Delta V is low, direct the ship towards the target and use all thrusters
else if(deltaVMag > THRUST_DELTA_THRESHOLD)
{
var right = _agent.Ship.Direction.Rotate(ItemRotation.Clockwise);
_agent.Ship.LookDirection = float3(dir.x, 0, dir.y);
_agent.Ship.MovementDirection = float2(dot(right, deltaVDirection), dot(_agent.Ship.Direction, deltaVDirection));
}
else
{
_agent.Ship.LookDirection = float3(dir.x, 0, dir.y);
_agent.Ship.MovementDirection = float2.zero;
}
}
}
public class MoveToEntityState : MoveToState
{
public Entity TargetEntity { get; set; }
protected override float2 TargetPosition => TargetEntity?.Position.xz ?? float2.zero;
public MoveToEntityState(Agent agent) : base(agent) { }
}
public class MoveToOrbitState : MoveToState
{
public Guid Orbit { get; set; }
public MoveToOrbitState(Agent agent) : base(agent) { }
protected override float2 TargetPosition => _agent.Ship.Zone.GetOrbitPosition(Orbit);
}
public class PatrolOrbitsState : BaseState
{
public PatrolOrbitsTask Task;
public Guid CurrentTarget
{
get => Task.Circuit[_currentTargetIndex];
}
private int _currentTargetIndex;
public void NextTarget()
{
_currentTargetIndex++;
_currentTargetIndex %= Task.Circuit.Length;
}
public PatrolOrbitsState(Agent agent) : base(agent) { }
}

View file

@ -39,3 +39,9 @@ public enum TaskType
Attack,
Explore
}
public class PatrolOrbitsTask : AgentTask
{
public override TaskType Type => TaskType.Defend;
public Guid[] Circuit;
}

View file

@ -32,7 +32,7 @@ public class Locomotion : AgentBehavior
var diff = Objective - Entity.Position.xz;
// We want to go top speed in the direction of our target
var topSpeed = _velocityLimit?.Limit ?? 1000;
var topSpeed = _velocityLimit?.Limit ?? 100;
float2 desiredVelocity = normalize(diff) * topSpeed;
var accelerationTime = length(desiredVelocity - Entity.Velocity) / (_thrust / Entity.Mass);

View file

@ -9,40 +9,40 @@ using static Unity.Mathematics.math;
[InspectableField, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class ChargedWeaponData : InstantWeaponData
{
[InspectableField, JsonProperty("chargeTime"), Key(19), RuntimeInspectable]
[InspectableField, JsonProperty("chargeTime"), Key(21), RuntimeInspectable]
public PerformanceStat ChargeTime = new PerformanceStat();
[InspectableField, JsonProperty("chargeEnergy"), Key(20), RuntimeInspectable]
[InspectableField, JsonProperty("chargeEnergy"), Key(22), RuntimeInspectable]
public PerformanceStat ChargeEnergy = new PerformanceStat();
[InspectableField, JsonProperty("chargeHeat"), Key(21), RuntimeInspectable]
[InspectableField, JsonProperty("chargeHeat"), Key(23), RuntimeInspectable]
public PerformanceStat ChargeHeat = new PerformanceStat();
[InspectableField, JsonProperty("canFireEarly"), Key(22)]
[InspectableField, JsonProperty("canFireEarly"), Key(24)]
public bool CanFireEarly;
[InspectableField, JsonProperty("failureCharge"), Key(23)]
[InspectableField, JsonProperty("failureCharge"), Key(25)]
public float FailureCharge;
[InspectableField, JsonProperty("failureDamage"), Key(24)]
[InspectableField, JsonProperty("failureDamage"), Key(26)]
public float FailureDamage = 1;
[InspectableField, JsonProperty("chargeDamage"), Key(25)]
[InspectableField, JsonProperty("chargeDamage"), Key(27)]
public float ChargeFiringDamageMultiplier = 1;
[InspectableField, JsonProperty("chargeSpread"), Key(26)]
[InspectableField, JsonProperty("chargeSpread"), Key(28)]
public float ChargeFiringSpreadMultiplier = 1;
[InspectableField, JsonProperty("chargeBurstCount"), Key(27)]
[InspectableField, JsonProperty("chargeBurstCount"), Key(29)]
public float ChargeFiringBurstCountMultiplier = 1;
[InspectableField, JsonProperty("chargeVisibility"), Key(28)]
[InspectableField, JsonProperty("chargeVisibility"), Key(30)]
public float ChargeFiringVisibilityMultiplier = 1;
[InspectableField, JsonProperty("chargeVelocity"), Key(29)]
[InspectableField, JsonProperty("chargeVelocity"), Key(31)]
public float ChargeFiringVelocityMultiplier = 1;
[InspectableField, JsonProperty("chargeHeatMul"), Key(30)]
[InspectableField, JsonProperty("chargeHeatMul"), Key(32)]
public float ChargeFiringHeatMultiplier = 1;
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)
@ -131,7 +131,7 @@ public class ChargedWeapon : InstantWeapon
public override void Activate()
{
if(!_coolingDown)
if(!_charging && !_coolingDown)
{
OnStartCharging?.Invoke();
_charging = true;

View file

@ -11,7 +11,7 @@ using static Unity.Mathematics.math;
[InspectableField, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class ConstantWeaponData : WeaponData
{
[InspectablePrefab, JsonProperty("ammoInterval"), Key(15)]
[InspectablePrefab, JsonProperty("ammoInterval"), Key(17)]
public float AmmoInterval = 1;
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)
@ -112,7 +112,7 @@ public class ConstantWeapon : Weapon, IProgressBehavior
public override void Activate()
{
if(!_reloading)
if(!_firing && !_reloading)
{
_firing = true;
OnStartFiring?.Invoke();

View file

@ -9,16 +9,16 @@ using static Unity.Mathematics.math;
[InspectableField, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class InstantWeaponData : WeaponData
{
[InspectableField, JsonProperty("count"), Key(15)]
[InspectableField, JsonProperty("count"), Key(17)]
public PerformanceStat Count = new PerformanceStat();
[InspectableField, JsonProperty("burstTime"), Key(16)]
[InspectableField, JsonProperty("burstTime"), Key(18)]
public PerformanceStat BurstTime = new PerformanceStat();
[InspectableField, JsonProperty("cooldown"), Key(17), RuntimeInspectable]
[InspectableField, JsonProperty("cooldown"), Key(19), RuntimeInspectable]
public PerformanceStat Cooldown = new PerformanceStat();
[InspectablePrefab, JsonProperty("ammoInterval"), Key(18)]
[InspectablePrefab, JsonProperty("ammoInterval"), Key(20)]
public bool SingleAmmoBurst;
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)

View file

@ -9,22 +9,22 @@ using Unity.Mathematics;
[InspectableField, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class LauncherData : LockWeaponData
{
[InspectableAnimationCurve, JsonProperty("guidance"), Key(24)]
[InspectableAnimationCurve, JsonProperty("guidance"), Key(26)]
public float4[] GuidanceCurve;
[InspectableAnimationCurve, JsonProperty("thrustCurve"), Key(25)]
[InspectableAnimationCurve, JsonProperty("thrustCurve"), Key(27)]
public float4[] ThrustCurve;
[InspectableAnimationCurve, JsonProperty("liftCurve"), Key(26)]
[InspectableAnimationCurve, JsonProperty("liftCurve"), Key(28)]
public float4[] LiftCurve;
[InspectableField, JsonProperty("thrust"), Key(27)]
[InspectableField, JsonProperty("thrust"), Key(29)]
public PerformanceStat Thrust = new PerformanceStat();
[InspectableField, JsonProperty("frequency"), Key(28)]
[InspectableField, JsonProperty("frequency"), Key(30)]
public float DodgeFrequency;
[InspectableField, JsonProperty("missileSpeed"), Key(29), RuntimeInspectable]
[InspectableField, JsonProperty("missileSpeed"), Key(31), RuntimeInspectable]
public PerformanceStat MissileVelocity = new PerformanceStat();
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)
@ -36,22 +36,22 @@ public class LauncherData : LockWeaponData
[InspectableField, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class GuidedWeaponData : InstantWeaponData
{
[InspectableAnimationCurve, JsonProperty("guidance"), Key(24)]
[InspectableAnimationCurve, JsonProperty("guidance"), Key(21)]
public float4[] GuidanceCurve;
[InspectableAnimationCurve, JsonProperty("thrustCurve"), Key(25)]
[InspectableAnimationCurve, JsonProperty("thrustCurve"), Key(22)]
public float4[] ThrustCurve;
[InspectableAnimationCurve, JsonProperty("liftCurve"), Key(26)]
[InspectableAnimationCurve, JsonProperty("liftCurve"), Key(23)]
public float4[] LiftCurve;
[InspectableField, JsonProperty("thrust"), Key(27)]
[InspectableField, JsonProperty("thrust"), Key(24)]
public PerformanceStat Thrust = new PerformanceStat();
[InspectableField, JsonProperty("frequency"), Key(28)]
[InspectableField, JsonProperty("frequency"), Key(25)]
public float DodgeFrequency;
[InspectableField, JsonProperty("missileSpeed"), Key(29), RuntimeInspectable]
[InspectableField, JsonProperty("missileSpeed"), Key(26), RuntimeInspectable]
public PerformanceStat MissileVelocity = new PerformanceStat();
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)

View file

@ -9,19 +9,19 @@ using static Unity.Mathematics.math;
[InspectableField, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class LockWeaponData : InstantWeaponData
{
[InspectableField, JsonProperty("speed"), Key(19), RuntimeInspectable]
[InspectableField, JsonProperty("speed"), Key(21), RuntimeInspectable]
public PerformanceStat LockSpeed = new PerformanceStat();
[InspectableField, JsonProperty("sensorImpact"), Key(20)]
[InspectableField, JsonProperty("sensorImpact"), Key(22)]
public PerformanceStat SensorImpact = new PerformanceStat();
[InspectableField, JsonProperty("threshold"), Key(21), RuntimeInspectable]
[InspectableField, JsonProperty("threshold"), Key(23), RuntimeInspectable]
public PerformanceStat LockAngle = new PerformanceStat();
[InspectableField, JsonProperty("directionImpact"), Key(22)]
[InspectableField, JsonProperty("directionImpact"), Key(24)]
public PerformanceStat DirectionImpact = new PerformanceStat();
[InspectableField, JsonProperty("decay"), Key(23)]
[InspectableField, JsonProperty("decay"), Key(25)]
public PerformanceStat Decay = new PerformanceStat();
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)

View file

@ -4,12 +4,17 @@
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[InspectableField, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class SensorData : BehaviorData
{
[InspectableField, JsonProperty("sensitivity"), Key(3), RuntimeInspectable]
public PerformanceStat Sensitivity = new PerformanceStat();
[InspectableField, JsonProperty("sensitivityCurve"), Key(4), RuntimeInspectable]
public float4[] SensitivityCurve;
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)
{
@ -38,6 +43,21 @@ public class Sensor : IBehavior
public bool Execute(float delta)
{
// TODO: Handle Active Detection / Visibility From Reflected Radiance
var hardpoint = Entity.Hardpoints[Item.Position.x, Item.Position.y];
var forward = Entity.HardpointTransforms.ContainsKey(hardpoint) ?
normalize(Entity.HardpointTransforms[hardpoint].direction.xz) :
Entity.Direction;
foreach (var entity in Entity.Zone.Entities)
{
var diff = entity.Position.xz - Entity.Position.xz;
var angle = acos(dot(forward, normalize(diff)));
var dist = length(diff);
Entity.EntityInfoGathered[entity] +=
entity.Visibility *
Context.Evaluate(_data.Sensitivity, Item.EquippableItem, Entity) *
_data.SensitivityCurve.Evaluate(angle / PI) *
delta / dist;
}
return true;
// var ship = Hardpoint.Ship.Ship.transform;
// var contacts =

View file

@ -7,6 +7,7 @@ using System.Collections.Generic;
using System.Linq;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
[Union(0, typeof(InstantWeaponData)),
Union(1, typeof(LauncherData)),
@ -27,34 +28,40 @@ public abstract class WeaponData : BehaviorData
[RangedFloatInspectable(0,1), JsonProperty("damageSpread"), Key(4)]
public PerformanceStat DamageSpread = new PerformanceStat();
[InspectableField, JsonProperty("range"), Key(5), RuntimeInspectable]
[InspectableField, JsonProperty("minRange"), Key(5), RuntimeInspectable]
public PerformanceStat MinRange = new PerformanceStat();
[InspectableField, JsonProperty("range"), Key(6), RuntimeInspectable]
public PerformanceStat Range = new PerformanceStat();
[InspectableAnimationCurve, JsonProperty("damageRange"), Key(7), RuntimeInspectable]
public float4[] DamageCurve;
[InspectablePrefab, JsonProperty("effect"), Key(6)]
[InspectablePrefab, JsonProperty("effect"), Key(8)]
public string EffectPrefab;
[InspectablePrefab, JsonProperty("energy"), Key(7), RuntimeInspectable]
[InspectablePrefab, JsonProperty("energy"), Key(9), RuntimeInspectable]
public PerformanceStat Energy = new PerformanceStat();
[InspectablePrefab, JsonProperty("heat"), Key(8), RuntimeInspectable]
[InspectablePrefab, JsonProperty("heat"), Key(10), RuntimeInspectable]
public PerformanceStat Heat = new PerformanceStat();
[InspectablePrefab, JsonProperty("visibility"), Key(9), RuntimeInspectable]
[InspectablePrefab, JsonProperty("visibility"), Key(11), RuntimeInspectable]
public PerformanceStat Visibility = new PerformanceStat();
[InspectableDatabaseLink(typeof(SimpleCommodityData)), JsonProperty("ammo"), Key(10), RuntimeInspectable]
[InspectableDatabaseLink(typeof(SimpleCommodityData)), JsonProperty("ammo"), Key(12), RuntimeInspectable]
public Guid AmmoType;
[InspectablePrefab, JsonProperty("magSize"), Key(11)]
[InspectablePrefab, JsonProperty("magSize"), Key(13)]
public int MagazineSize;
[InspectablePrefab, JsonProperty("reloadTime"), Key(12)]
[InspectablePrefab, JsonProperty("reloadTime"), Key(14)]
public float ReloadTime = 1;
[InspectablePrefab, JsonProperty("spread"), Key(13)]
[InspectablePrefab, JsonProperty("spread"), Key(15)]
public PerformanceStat Spread = new PerformanceStat();
[InspectableField, JsonProperty("velocity"), Key(14)]
[InspectableField, JsonProperty("velocity"), Key(16)]
public PerformanceStat Velocity = new PerformanceStat();
}
@ -73,6 +80,7 @@ public abstract class Weapon : IActivatedBehavior
public float Damage { get; protected set; }
public float Penetration { get; protected set; }
public float DamageSpread { get; protected set; }
public float MinRange { get; protected set; }
public float Range { get; protected set; }
public float Energy { get; protected set; }
public float Heat { get; protected set; }
@ -103,6 +111,7 @@ public abstract class Weapon : IActivatedBehavior
Damage = Context.Evaluate(_data.Damage, Item.EquippableItem, Entity);
Penetration = Context.Evaluate(_data.Penetration, Item.EquippableItem, Entity);
DamageSpread = Context.Evaluate(_data.DamageSpread, Item.EquippableItem, Entity);
MinRange = Context.Evaluate(_data.MinRange, Item.EquippableItem, Entity);
Range = Context.Evaluate(_data.Range, Item.EquippableItem, Entity);
Energy = Context.Evaluate(_data.Energy, Item.EquippableItem, Entity);
Heat = Context.Evaluate(_data.Heat, Item.EquippableItem, Entity);

View file

@ -48,18 +48,9 @@ public class MegaCorporation : DatabaseEntry, INamedEntry
[InspectableDatabaseLink(typeof(PersonalityAttribute)), JsonProperty("personality"), Key(4)]
public Dictionary<Guid, float> Personality = new Dictionary<Guid, float>();
[InspectableDatabaseLink(typeof(LoadoutData)), JsonProperty("initialFleet"), Key(5)]
public Dictionary<Guid, int> InitialFleet = new Dictionary<Guid, int>();
[InspectableDatabaseLink(typeof(BlueprintData)), JsonProperty("initialTechs"), Key(6)]
public List<Guid> InitialTechnologies = new List<Guid>();
[JsonProperty("parent"), Key(7)]
public Guid HomeZone;
[InspectableField, JsonProperty("placement"), Key(8)]
public MegaPlacementType PlacementType;
[InspectableField, JsonProperty("hostile"), Key(5)]
public bool PlayerHostile;
[IgnoreMember] public string EntryName
{

View file

@ -21,6 +21,7 @@ using int2 = Unity.Mathematics.int2;
public abstract class Entity
{
public Zone Zone;
public MegaCorporation Faction;
public EquippableItem Hull;
public float3 Position;
@ -50,6 +51,7 @@ public abstract class Entity
public readonly Dictionary<string, float> Messages = new Dictionary<string, float>();
public readonly Dictionary<object, float> VisibilitySources = new Dictionary<object, float>();
public readonly Dictionary<Entity, float> EntityInfoGathered = new Dictionary<Entity, float>();
public readonly Dictionary<HardpointData, (float3 position, float3 direction)> HardpointTransforms =
new Dictionary<HardpointData, (float3 position, float3 direction)>();
@ -63,8 +65,19 @@ public abstract class Entity
public float[,] MaxArmor;
private EquippedItem[] _orderedEquipment;
private List<Weapon> _weapons = new List<Weapon>();
private List<Weapon> _weaponsInRange = new List<Weapon>();
protected bool _active;
public IEnumerable<Weapon> Weapons
{
get => _weapons;
}
public IEnumerable<Weapon> WeaponsInRange
{
get => _weaponsInRange;
}
public float MaxTemp { get; private set; }
public float MinTemp { get; private set; }
public ItemManager ItemManager { get; }
@ -246,6 +259,9 @@ public abstract class Entity
GearOccupancy[i.x, i.y] = null;
}
Mass -= itemData.Mass;
foreach (var b in item.Behaviors)
if (b is Weapon weapon)
_weapons.Add(weapon);
return item.EquippableItem;
}
@ -397,6 +413,9 @@ public abstract class Entity
{
equippedItem = new EquippedItem(ItemManager, item, hullCoord, this);
Equipment.Add(equippedItem);
foreach (var b in equippedItem.Behaviors)
if (b is Weapon weapon)
_weapons.Add(weapon);
}
foreach (var i in itemData.Shape.Coordinates)
@ -537,6 +556,15 @@ public abstract class Entity
public virtual void Update(float delta)
{
var hullData = ItemManager.GetData(Hull) as HullData;
_weaponsInRange.Clear();
if (Target.Value != null)
{
var dist = length(Position - Target.Value.Position);
foreach (var w in _weapons)
if (w.MinRange < dist && dist < w.Range)
_weaponsInRange.Add(w);
}
foreach (var v in VisibilitySources.Keys.ToArray())
{

View file

@ -111,5 +111,9 @@ public class GameplaySettings
public float TorqueFloor;
public float TorqueMultiplier;
public float VisibilityDecay;
public float TargetInfoDecay;
public float TargetDetectionInfoThreshold;
public float TargetArmorInfoThreshold;
public float TargetGearInfoThreshold;
public float ConvergenceMinimumDistance;
}

View file

@ -9,6 +9,7 @@ using System.Linq;
using System.Reflection;
using MessagePack;
using Newtonsoft.Json;
using UniRx;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using quaternion = Unity.Mathematics.quaternion;
@ -26,28 +27,127 @@ public class Ship : Entity
public float2 MovementDirection;
private Thruster[] _allThrusters;
private Thruster[] _forwardThrusters;
private Thruster[] _reverseThrusters;
private Thruster[] _rightThrusters;
private Thruster[] _leftThrusters;
private Thruster[] _clockwiseThrusters;
private Thruster[] _counterClockwiseThrusters;
private HashSet<Thruster> _forwardThrusters;
private HashSet<Thruster> _reverseThrusters;
private HashSet<Thruster> _rightThrusters;
private HashSet<Thruster> _leftThrusters;
private HashSet<Thruster> _clockwiseThrusters;
private HashSet<Thruster> _counterClockwiseThrusters;
public float ForwardThrust { get; private set; }
public float ReverseThrust { get; private set; }
public float LeftStrafeThrust { get; private set; }
public float RightStrafeThrust { get; private set; }
public float ClockwiseTorque { get; private set; }
public float CounterClockwiseTorque { get; private set; }
public quaternion Rotation { get; private set; }
protected override void OnActivate()
{
_allThrusters = GetBehaviors<Thruster>().ToArray();
_forwardThrusters = _allThrusters.Where(x => x.Item.EquippableItem.Rotation == ItemRotation.Reversed).ToArray();
_reverseThrusters = _allThrusters.Where(x => x.Item.EquippableItem.Rotation == ItemRotation.None).ToArray();
_rightThrusters = _allThrusters.Where(x => x.Item.EquippableItem.Rotation == ItemRotation.CounterClockwise).ToArray();
_leftThrusters = _allThrusters.Where(x => x.Item.EquippableItem.Rotation == ItemRotation.Clockwise).ToArray();
_counterClockwiseThrusters = _allThrusters.Where(x => x.Torque < -ItemManager.GameplaySettings.TorqueFloor).ToArray();
_clockwiseThrusters = _allThrusters.Where(x => x.Torque > ItemManager.GameplaySettings.TorqueFloor).ToArray();
_forwardThrusters = new HashSet<Thruster>(_allThrusters
.Where(x => x.Item.EquippableItem.Rotation == ItemRotation.Reversed));
RecalculateForwardThrust();
_reverseThrusters = new HashSet<Thruster>(_allThrusters
.Where(x => x.Item.EquippableItem.Rotation == ItemRotation.None));
RecalculateReverseThrust();
_rightThrusters = new HashSet<Thruster>(_allThrusters
.Where(x => x.Item.EquippableItem.Rotation == ItemRotation.CounterClockwise));
RecalculateRightStrafeThrust();
_leftThrusters = new HashSet<Thruster>(_allThrusters
.Where(x => x.Item.EquippableItem.Rotation == ItemRotation.Clockwise));
RecalculateLeftStrafeThrust();
_counterClockwiseThrusters = new HashSet<Thruster>(_allThrusters
.Where(x => x.Torque < -ItemManager.GameplaySettings.TorqueFloor));
RecalculateCounterClockwiseTorque();
_clockwiseThrusters = new HashSet<Thruster>(_allThrusters
.Where(x => x.Torque > ItemManager.GameplaySettings.TorqueFloor));
RecalculateClockwiseTorque();
}
public Ship(ItemManager itemManager, Zone zone, EquippableItem hull) : base(itemManager, zone, hull)
{
ItemDamage.Subscribe(x =>
{
if (Hardpoints[x.item.Position.x, x.item.Position.y]?.Type == HardpointType.Thruster)
{
foreach (var behavior in x.item.Behaviors)
{
if (behavior is Thruster thruster)
{
if(_forwardThrusters.Contains(thruster)) RecalculateForwardThrust();
if(_reverseThrusters.Contains(thruster)) RecalculateReverseThrust();
if(_rightThrusters.Contains(thruster)) RecalculateRightStrafeThrust();
if(_leftThrusters.Contains(thruster)) RecalculateLeftStrafeThrust();
if(_clockwiseThrusters.Contains(thruster)) RecalculateClockwiseTorque();
if(_counterClockwiseThrusters.Contains(thruster)) RecalculateCounterClockwiseTorque();
}
}
if(x.item.EquippableItem.Rotation == ItemRotation.Reversed)
RecalculateForwardThrust();
}
});
}
private void RecalculateForwardThrust()
{
ForwardThrust = 0;
foreach (var thruster in _forwardThrusters)
{
ForwardThrust += thruster.Thrust;
}
}
private void RecalculateReverseThrust()
{
ReverseThrust = 0;
foreach (var thruster in _reverseThrusters)
{
ReverseThrust += thruster.Thrust;
}
}
private void RecalculateLeftStrafeThrust()
{
LeftStrafeThrust = 0;
foreach (var thruster in _leftThrusters)
{
LeftStrafeThrust += thruster.Thrust;
}
}
private void RecalculateRightStrafeThrust()
{
RightStrafeThrust = 0;
foreach (var thruster in _rightThrusters)
{
RightStrafeThrust += thruster.Thrust;
}
}
private void RecalculateClockwiseTorque()
{
ClockwiseTorque = 0;
foreach (var thruster in _clockwiseThrusters)
{
ClockwiseTorque += thruster.Torque;
}
}
private void RecalculateCounterClockwiseTorque()
{
CounterClockwiseTorque = 0;
foreach (var thruster in _counterClockwiseThrusters)
{
CounterClockwiseTorque -= thruster.Torque;
}
}
public override void Update(float delta)

View file

@ -16,6 +16,7 @@ using Random = Unity.Mathematics.Random;
public class Zone
{
public Action<string> Log;
//public HashSet<Guid> Planets = new HashSet<Guid>();
public ReactiveCollection<Entity> Entities = new ReactiveCollection<Entity>();
//public Dictionary<Guid, OrbitData> Orbits = new Dictionary<Guid, OrbitData>();
@ -24,10 +25,10 @@ public class Zone
public Dictionary<Guid, Orbit> Orbits = new Dictionary<Guid, Orbit>();
public Dictionary<Guid, AsteroidBelt> AsteroidBelts = new Dictionary<Guid, AsteroidBelt>();
public PlanetSettings Settings;
private HashSet<Guid> _updatedOrbits = new HashSet<Guid>();
public PlanetSettings Settings;
private float _time;
private Random _random;
@ -121,6 +122,11 @@ public class Zone
// Root orbit is fixed at origin
if(orbitID==Guid.Empty)
return float2.zero;
if (!Orbits.ContainsKey(orbitID))
{
Log?.Invoke("Requested orbit is not part of this zone!");
return float2.zero;
}
if (!_updatedOrbits.Contains(orbitID))
{

View file

@ -19,6 +19,7 @@ using int2 = Unity.Mathematics.int2;
public class InventoryPanel : MonoBehaviour
{
public ConfirmationDialog ConfirmationDialog;
public bool Flip;
public GameSettings Settings;
public ActionGameManager GameManager;
@ -100,9 +101,18 @@ public class InventoryPanel : MonoBehaviour
{
if (_displayedEntity != GameManager.CurrentShip)
{
GameManager.CurrentShip = (Ship) _displayedEntity;
GameManager.DockingBay.DockedShip = (Ship) _displayedEntity;
Current.targetGraphic.color = ToggleEnabledColor;
if(_displayedEntity is Ship ship)
{
GameManager.CurrentShip = ship;
GameManager.DockingBay.DockedShip = ship;
Current.targetGraphic.color = ToggleEnabledColor;
}
else
{
ConfirmationDialog.Clear();
ConfirmationDialog.Title.text = "Can't select entity, you can only pilot a ship!";
ConfirmationDialog.Show();
}
}
});
}
@ -111,18 +121,18 @@ public class InventoryPanel : MonoBehaviour
Dropdown.onClick.AddListener(() =>
{
ContextMenu.Clear();
foreach (var ship in GameManager.AvailableShips())
foreach (var entity in GameManager.AvailableEntities())
{
if (ship.CargoBays.Any())
if (entity.CargoBays.Any())
{
var options = ship.CargoBays
var options = entity.CargoBays
.Where(bay => bay != _displayedCargo)
.Select<EquippedCargoBay, (string text, Action action, bool enabled)>((bay, index) =>
($"Bay {index}", () => Display(bay), true));
if(ship != _displayedEntity) options = options.Prepend(("Equipment", () => Display(ship), true));
ContextMenu.AddDropdown(ship.Name, options);
if(entity != _displayedEntity) options = options.Prepend(("Equipment", () => Display(entity), true));
ContextMenu.AddDropdown(entity.Name, options);
}
else if(ship != _displayedEntity) ContextMenu.AddOption(ship.Name, () => Display(ship));
else if(entity != _displayedEntity) ContextMenu.AddOption(entity.Name, () => Display(entity));
}
if(GameManager.DockingBay!=null && _displayedCargo!=GameManager.DockingBay)
@ -143,7 +153,7 @@ public class InventoryPanel : MonoBehaviour
{
var ship = EntityPack.Unpack(GameManager.ItemManager, GameManager.Zone, pack, true);
ship.SetParent(GameManager.DockedEntity);
GameManager.PlayerShips.Add(ship);
GameManager.PlayerEntities.Add(ship);
GameManager.Credits -= pack.Price(GameManager.ItemManager);
GameManager.CurrentShip = ship;
GameManager.DockingBay.DockedShip = ship;

View file

@ -272,7 +272,7 @@ public class TradeMenu : MonoBehaviour
data => () =>
{
if (data is HullData)
return GameManager.PlayerShips.Count(s => s.Hull.Data == data.ID && s.Parent == GameManager.CurrentShip.Parent).ToString();
return GameManager.PlayerEntities.Count(s => s.Hull.Data == data.ID && s.Parent == GameManager.DockedEntity).ToString();
if(data is SimpleCommodityData)
return (_targetCargo.ItemsOfType.ContainsKey(data.ID) ? _targetCargo.ItemsOfType[data.ID].Cast<SimpleCommodity>().Sum(s=>s.Quantity) : 0).ToString();
return (_targetCargo.ItemsOfType.ContainsKey(data.ID) ? _targetCargo.ItemsOfType[data.ID].Count : 0).ToString();
@ -280,7 +280,7 @@ public class TradeMenu : MonoBehaviour
data =>
{
if (data is HullData)
return GameManager.PlayerShips.Count(s => s.Hull.Data == data.ID && s.Parent == GameManager.CurrentShip.Parent);
return GameManager.PlayerEntities.Count(s => s.Hull.Data == data.ID && s.Parent == GameManager.DockedEntity);
if(data is SimpleCommodityData)
return _targetCargo.ItemsOfType.ContainsKey(data.ID) ? _targetCargo.ItemsOfType[data.ID].Cast<SimpleCommodity>().Sum(s=>s.Quantity) : 0;
return _targetCargo.ItemsOfType.ContainsKey(data.ID) ? _targetCargo.ItemsOfType[data.ID].Count : 0;
@ -355,9 +355,13 @@ public class TradeMenu : MonoBehaviour
{
if (data.Price < GameManager.Credits)
{
var ship = new Ship(GameManager.ItemManager, GameManager.Zone, GameManager.ItemManager.CreateInstance(data, .1f, 1) as EquippableItem);
ship.SetParent(GameManager.CurrentShip.Parent);
GameManager.PlayerShips.Add(ship);
var hull = GameManager.ItemManager.CreateInstance(data, .1f, 1) as EquippableItem;
Entity entity;
if(data.HullType==HullType.Ship)
entity = new Ship(GameManager.ItemManager, GameManager.Zone, hull);
else entity = new OrbitalEntity(GameManager.ItemManager, GameManager.Zone, hull, Guid.Empty);
entity.SetParent(GameManager.DockedEntity);
GameManager.PlayerEntities.Add(entity);
GameManager.Credits -= data.Price;
}
@ -444,7 +448,7 @@ public class TradeMenu : MonoBehaviour
_targetCargo = GameManager.DockingBay;
TargetCargoLabel.text = "Docking Bay";
});
foreach (var ship in GameManager.CurrentShip.Parent.Children.Where(GameManager.PlayerShips.Contains))
foreach (var ship in GameManager.CurrentShip.Parent.Children.Where(GameManager.PlayerEntities.Contains))
{
foreach (var bay in ship.CargoBays.Select((bay, index) => (bay, index)))
ContextMenu.AddOption($"{ship.Name} Bay {bay.index}",

Binary file not shown.

Binary file not shown.

Binary file not shown.