Initial ARPG Port
ARPG scene assets from old project are now correctly visualizing sectors generated by ZoneGenerator and updated by GameContext
This commit is contained in:
parent
1e2b474fc1
commit
d12d7c5c45
379 changed files with 42700 additions and 7253 deletions
|
|
@ -56,7 +56,7 @@ public interface IController
|
|||
{
|
||||
bool Available { get; }
|
||||
TaskType TaskType { get; }
|
||||
Guid Zone { get; }
|
||||
Zone Zone { get; }
|
||||
void AssignTask(Guid task);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ public abstract class ControllerBase : IBehavior, IController, IInitializableBeh
|
|||
protected Guid HomeEntity => (_entity as Ship)?.HomeEntity ?? Guid.Empty;
|
||||
public bool Available => _spaceworthy && Task == Guid.Empty;
|
||||
public abstract TaskType TaskType { get; }
|
||||
public Guid Zone => _entity.Zone;
|
||||
public Zone Zone => _entity.Zone;
|
||||
public BehaviorData Data => _controllerData;
|
||||
|
||||
protected Locomotion Locomotion;
|
||||
|
|
@ -182,7 +182,7 @@ public abstract class ControllerBase : IBehavior, IController, IInitializableBeh
|
|||
_context.SetParent(_entity, homeEntity);
|
||||
onFinish?.Invoke();
|
||||
});
|
||||
else MoveTo(homeEntity.Zone, () => MoveTo(homeEntity, true, () =>
|
||||
else MoveTo(homeEntity.Zone.Data.ID, () => MoveTo(homeEntity, true, () =>
|
||||
{
|
||||
_context.SetParent(_entity, homeEntity);
|
||||
onFinish?.Invoke();
|
||||
|
|
@ -228,14 +228,14 @@ public abstract class ControllerBase : IBehavior, IController, IInitializableBeh
|
|||
|
||||
public void MoveTo(Guid zone, Action onFinish = null)
|
||||
{
|
||||
var path = _context.FindPath(_context.GalaxyZones[Zone], _context.GalaxyZones[zone]);
|
||||
var path = _context.FindPath(_context.GalaxyZones[Zone.Data.ID], _context.GalaxyZones[zone]);
|
||||
|
||||
void OnNextZone()
|
||||
{
|
||||
path.RemoveAt(0);
|
||||
if (path.Count > 0)
|
||||
{
|
||||
MoveTo(_context.WormholePosition(_entity.Zone, Path[0].ZoneID), false, OnNextZone);
|
||||
MoveTo(Zone.WormholePosition(Path[0].ZoneID), false, OnNextZone);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
|
|
|||
|
|
@ -66,7 +66,7 @@ public class HaulingController : ControllerBase, IBehavior, IPersistentBehavior
|
|||
void OnPickup()
|
||||
{
|
||||
var haulingTask = _context.Cache.Get<HaulingTask>(Task);
|
||||
var target = _context.ZoneEntities[_entity.Zone][haulingTask.Origin] as OrbitalEntity;
|
||||
var target = Zone.Entities[haulingTask.Origin] as OrbitalEntity;
|
||||
|
||||
_context.SetParent(_entity, target);
|
||||
var itemData = _context.Cache.Get<ItemData>(haulingTask.ItemType);
|
||||
|
|
@ -101,7 +101,7 @@ public class HaulingController : ControllerBase, IBehavior, IPersistentBehavior
|
|||
|
||||
var target = _context.Cache.Get<Entity>(haulingTask.Target);
|
||||
|
||||
MoveTo(target.Zone, OnTargetZoneArrival);
|
||||
MoveTo(target.Zone.Data.ID, OnTargetZoneArrival);
|
||||
}
|
||||
|
||||
void OnTargetZoneArrival()
|
||||
|
|
@ -114,7 +114,7 @@ public class HaulingController : ControllerBase, IBehavior, IPersistentBehavior
|
|||
void OnDelivery()
|
||||
{
|
||||
var haulingTask = _context.Cache.Get<HaulingTask>(Task);
|
||||
var target = _context.ZoneEntities[_entity.Zone][haulingTask.Target] as OrbitalEntity;
|
||||
var target = Zone.Entities[haulingTask.Target] as OrbitalEntity;
|
||||
|
||||
_context.SetParent(_entity, target);
|
||||
|
||||
|
|
|
|||
|
|
@ -61,22 +61,22 @@ public class MiningController : ControllerBase, IBehavior, IPersistentBehavior,
|
|||
{
|
||||
if (_entity.OccupiedCapacity < _entity.Capacity - 1)
|
||||
{
|
||||
var asteroidTransform = _context.GetAsteroidTransform(miningTask.Asteroids, _asteroid);
|
||||
var asteroidTransform = Zone.GetAsteroidTransform(miningTask.Asteroids, _asteroid);
|
||||
if (length(_entity.Position - asteroidTransform.xy) - asteroidTransform.w > _miningTool.Range)
|
||||
{
|
||||
_entity.SetMessage("Moving to target asteroid.");
|
||||
MoveTo(() => _context.GetAsteroidTransform(miningTask.Asteroids, _asteroid).xy,
|
||||
() => _context.GetAsteroidVelocity(miningTask.Asteroids, _asteroid));
|
||||
MoveTo(() => Zone.GetAsteroidTransform(miningTask.Asteroids, _asteroid).xy,
|
||||
() => Zone.GetAsteroidVelocity(miningTask.Asteroids, _asteroid));
|
||||
_toolSwitch.Activated = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_context.AsteroidExists(miningTask.Asteroids, _asteroid))
|
||||
if (Zone.AsteroidExists(miningTask.Asteroids, _asteroid))
|
||||
{
|
||||
_miningTool.AsteroidBelt = miningTask.Asteroids;
|
||||
_miningTool.Asteroid = _asteroid;
|
||||
_toolSwitch.Activated = true;
|
||||
Aim.Objective = _context.GetAsteroidTransform(miningTask.Asteroids, _asteroid).xy;
|
||||
Aim.Objective = Zone.GetAsteroidTransform(miningTask.Asteroids, _asteroid).xy;
|
||||
Aim.Update(delta);
|
||||
}
|
||||
else NextAsteroid();
|
||||
|
|
@ -119,7 +119,7 @@ public class MiningController : ControllerBase, IBehavior, IPersistentBehavior,
|
|||
private void NextAsteroid()
|
||||
{
|
||||
var miningTask = _context.Cache.Get<Mining>(Task);
|
||||
_asteroid = _context.NearestAsteroid(miningTask.Asteroids, _entity.Position);
|
||||
_asteroid = Zone.NearestAsteroid(miningTask.Asteroids, _entity.Position);
|
||||
_entity.SetMessage("Selecting new asteroid.");
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -51,12 +51,12 @@ public class MiningTool : IBehavior
|
|||
public bool Update(float delta)
|
||||
{
|
||||
Range = Context.Evaluate(_data.Range, Item, Entity);
|
||||
var asteroidTransform = Context.GetAsteroidTransform(AsteroidBelt, Asteroid);
|
||||
var asteroidTransform = Entity.Zone.GetAsteroidTransform(AsteroidBelt, Asteroid);
|
||||
if (AsteroidBelt != Guid.Empty &&
|
||||
Context.AsteroidExists(AsteroidBelt, Asteroid) &&
|
||||
Entity.Zone.AsteroidExists(AsteroidBelt, Asteroid) &&
|
||||
length(Entity.Position - asteroidTransform.xy) - asteroidTransform.w < Range)
|
||||
{
|
||||
Context.MineAsteroid(
|
||||
Entity.Zone.MineAsteroid(
|
||||
Entity,
|
||||
AsteroidBelt,
|
||||
Asteroid,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
using Unity.Mathematics;
|
||||
|
|
@ -19,7 +20,7 @@ public class PatrolController : IBehavior, IController, IInitializableBehavior
|
|||
{
|
||||
public TaskType TaskType => TaskType.None;
|
||||
public bool Available => false;
|
||||
public Guid Zone => _entity.Zone;
|
||||
public Zone Zone => _entity.Zone;
|
||||
public BehaviorData Data => _data;
|
||||
|
||||
private PatrolControllerData _data;
|
||||
|
|
@ -45,7 +46,7 @@ public class PatrolController : IBehavior, IController, IInitializableBehavior
|
|||
|
||||
public bool Update(float delta)
|
||||
{
|
||||
_locomotion.Objective = _context.GetOrbitPosition(_targetOrbit);
|
||||
_locomotion.Objective = Zone.GetOrbitPosition(_targetOrbit);
|
||||
_locomotion.Update(delta);
|
||||
|
||||
if(length(_entity.Position - _locomotion.Objective) < _data.TargetDistance)
|
||||
|
|
@ -61,7 +62,6 @@ public class PatrolController : IBehavior, IController, IInitializableBehavior
|
|||
|
||||
private void RandomTarget()
|
||||
{
|
||||
var entities = _context.ZonePlanets[_entity.Zone];
|
||||
_targetOrbit = _context.Cache.Get<PlanetData>(entities[_context.Random.NextInt(entities.Length)]).Orbit;
|
||||
_targetOrbit = Zone.Planets.Keys.ToArray()[_context.Random.NextInt(Zone.Planets.Count)];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -66,11 +66,11 @@ public class ResourceScanner : IBehavior, IAlwaysUpdatedBehavior
|
|||
var planetData = Context.Cache.Get<PlanetData>(ScanTarget);
|
||||
if (planetData != null)
|
||||
{
|
||||
if (planetData.Belt)
|
||||
if (planetData is AsteroidBeltData beltData)
|
||||
{
|
||||
if(Asteroid > -1 &&
|
||||
Asteroid < planetData.Asteroids.Length &&
|
||||
length(Entity.Position - Context.GetAsteroidTransform(ScanTarget, Asteroid).xy) < Range)
|
||||
Asteroid < beltData.Asteroids.Length &&
|
||||
length(Entity.Position - Entity.Zone.GetAsteroidTransform(ScanTarget, Asteroid).xy) < Range)
|
||||
{
|
||||
_scanTime += delta;
|
||||
if (_scanTime > ScanDuration)
|
||||
|
|
@ -83,7 +83,7 @@ public class ResourceScanner : IBehavior, IAlwaysUpdatedBehavior
|
|||
}
|
||||
else
|
||||
{
|
||||
if(length(Entity.Position - Context.GetOrbitPosition(planetData.Orbit)) < Range)
|
||||
if(length(Entity.Position - Entity.Zone.GetOrbitPosition(planetData.Orbit)) < Range)
|
||||
{
|
||||
_scanTime += delta;
|
||||
if (_scanTime > ScanDuration)
|
||||
|
|
|
|||
|
|
@ -35,6 +35,11 @@ public class StatModifier : IBehavior, IInitializableBehavior, IDisposableBehavi
|
|||
public BehaviorData Data => _data;
|
||||
|
||||
private PerformanceStat[] _stats;
|
||||
|
||||
private static Type[] _statObjects;
|
||||
|
||||
private static Type[] StatObjects => _statObjects ?? (_statObjects = typeof(BehaviorData).GetAllChildClasses()
|
||||
.Concat(typeof(EquippableItemData).GetAllChildClasses()).ToArray());
|
||||
|
||||
public StatModifier(GameContext context, StatModifierData data, Entity entity, Gear item)
|
||||
{
|
||||
|
|
@ -46,7 +51,7 @@ public class StatModifier : IBehavior, IInitializableBehavior, IDisposableBehavi
|
|||
|
||||
public void Initialize()
|
||||
{
|
||||
var targetType = Context.StatObjects.FirstOrDefault(so => so.Name == _data.Stat.Target);
|
||||
var targetType = StatObjects.FirstOrDefault(so => so.Name == _data.Stat.Target);
|
||||
if (targetType != null)
|
||||
{
|
||||
var statField = targetType.GetFields()
|
||||
|
|
|
|||
|
|
@ -111,30 +111,30 @@ public class SurveyController : ControllerBase, IBehavior, IPersistentBehavior,
|
|||
private void NextPlanet()
|
||||
{
|
||||
var surveyTask = _context.Cache.Get<Survey>(Task);
|
||||
var planets = surveyTask.Planets.Select(id => _context.Cache.Get<PlanetData>(id));
|
||||
var planets = surveyTask.Planets.Select(id => Zone.Planets[id]);
|
||||
var nearestPlanet = planets.MinBy(p => lengthsq(_entity.Position - GetPosition(p)));
|
||||
_asteroid = nearestPlanet.Belt ? _context.NearestAsteroid(nearestPlanet.ID, _entity.Position) : -1;
|
||||
_asteroid = nearestPlanet is AsteroidBeltData ? Zone.NearestAsteroid(nearestPlanet.ID, _entity.Position) : -1;
|
||||
_targetPlanet = nearestPlanet.ID;
|
||||
}
|
||||
|
||||
private float2 GetPosition(PlanetData planet, int asteroid = -1)
|
||||
{
|
||||
if (planet.Belt)
|
||||
if (planet is AsteroidBeltData)
|
||||
{
|
||||
if(asteroid == -1) asteroid = _context.NearestAsteroid(planet.ID, _entity.Position);
|
||||
return _context.GetAsteroidTransform(planet.ID, asteroid).xy;
|
||||
if(asteroid == -1) asteroid = Zone.NearestAsteroid(planet.ID, _entity.Position);
|
||||
return Zone.GetAsteroidTransform(planet.ID, asteroid).xy;
|
||||
}
|
||||
return _context.GetOrbitPosition(planet.Orbit);
|
||||
return Zone.GetOrbitPosition(planet.Orbit);
|
||||
}
|
||||
|
||||
private float2 GetVelocity(PlanetData planet, int asteroid = -1)
|
||||
{
|
||||
if (planet.Belt)
|
||||
if (planet is AsteroidBeltData)
|
||||
{
|
||||
if(asteroid == -1) asteroid = _context.NearestAsteroid(planet.ID, _entity.Position);
|
||||
return _context.GetAsteroidVelocity(planet.ID, asteroid);
|
||||
if(asteroid == -1) asteroid = Zone.NearestAsteroid(planet.ID, _entity.Position);
|
||||
return Zone.GetAsteroidVelocity(planet.ID, asteroid);
|
||||
}
|
||||
return _context.GetOrbitVelocity(planet.Orbit);
|
||||
return Zone.GetOrbitVelocity(planet.Orbit);
|
||||
}
|
||||
|
||||
public PersistentBehaviorData Store()
|
||||
|
|
|
|||
|
|
@ -61,7 +61,7 @@ public class TowingController : ControllerBase, IBehavior, IPersistentBehavior
|
|||
void OnPickup()
|
||||
{
|
||||
var towingTask = _context.Cache.Get<StationTowing>(Task);
|
||||
var target = _context.ZoneEntities[_entity.Zone][towingTask.Station] as OrbitalEntity;
|
||||
var target = Zone.Entities[towingTask.Station] as OrbitalEntity;
|
||||
|
||||
_context.SetParent(target, _entity);
|
||||
|
||||
|
|
@ -69,22 +69,22 @@ public class TowingController : ControllerBase, IBehavior, IPersistentBehavior
|
|||
|
||||
MoveTo(() =>
|
||||
{
|
||||
var orbitParent = _context.GetOrbitPosition(towingTask.OrbitParent);
|
||||
var orbitParent = Zone.GetOrbitPosition(towingTask.OrbitParent);
|
||||
var parentToUs = _entity.Position - orbitParent;
|
||||
return orbitParent + normalize(parentToUs) * towingTask.OrbitDistance;
|
||||
}, () => _context.GetOrbitVelocity(towingTask.OrbitParent), OnDelivery);
|
||||
}, () => Zone.GetOrbitVelocity(towingTask.OrbitParent), OnDelivery);
|
||||
}
|
||||
|
||||
void OnDelivery()
|
||||
{
|
||||
var towingTask = _context.Cache.Get<StationTowing>(Task);
|
||||
var target = _context.ZoneEntities[_entity.Zone][towingTask.Station] as OrbitalEntity;
|
||||
var target = Zone.Entities[towingTask.Station] as OrbitalEntity;
|
||||
|
||||
_context.RemoveParent(target);
|
||||
|
||||
_entity.SetMessage("Target delivered. Returning Home.");
|
||||
|
||||
var orbit = _context.CreateOrbit(towingTask.Zone, towingTask.OrbitParent, _entity.Position);
|
||||
var orbit = Zone.CreateOrbit(towingTask.OrbitParent, _entity.Position);
|
||||
target.OrbitData = orbit.ID;
|
||||
|
||||
FinishTask();
|
||||
|
|
|
|||
|
|
@ -57,13 +57,13 @@ public class WanderController : ControllerBase, IBehavior
|
|||
{
|
||||
if (WanderTarget == WanderTarget.Planets)
|
||||
{
|
||||
var planets = _context.ZonePlanets[_entity.Zone];
|
||||
var randomPlanet = _context.Cache.Get<PlanetData>(planets[_context.Random.NextInt(planets.Length)]);
|
||||
MoveTo(() => _context.GetOrbitPosition(randomPlanet.Orbit), () => _context.GetOrbitVelocity(randomPlanet.Orbit));
|
||||
var planets = Zone.Planets.Values.ToArray();
|
||||
var randomPlanet = planets[_context.Random.NextInt(planets.Length)];
|
||||
MoveTo(() => Zone.GetOrbitPosition(randomPlanet.Orbit), () => Zone.GetOrbitVelocity(randomPlanet.Orbit));
|
||||
}
|
||||
else if (WanderTarget == WanderTarget.Orbitals)
|
||||
{
|
||||
var entities = _context.ZoneEntities[_entity.Zone].Values.ToArray();
|
||||
var entities = Zone.Entities.Values.ToArray();
|
||||
var randomEntity = entities[_context.Random.NextInt(entities.Length)];
|
||||
MoveTo(randomEntity, true, () =>
|
||||
{
|
||||
|
|
|
|||
|
|
@ -42,6 +42,9 @@ public interface INamedEntry
|
|||
Union(22, typeof(StationTowing)),
|
||||
Union(23, typeof(Survey)),
|
||||
Union(24, typeof(HaulingTask)),
|
||||
Union(25, typeof(AsteroidBeltData)),
|
||||
Union(26, typeof(GasGiantData)),
|
||||
Union(27, typeof(SunData)),
|
||||
JsonObject(MemberSerialization.OptIn), JsonConverter(typeof(JsonKnownTypesConverter<DatabaseEntry>))]
|
||||
//[Union(21, typeof(ContractData))]
|
||||
//[Union(22, typeof(Station))]
|
||||
|
|
|
|||
|
|
@ -89,7 +89,7 @@ public abstract class Entity : DatabaseEntry, IMessagePackSerializationCallbackR
|
|||
}
|
||||
//public List<IncompleteItem> IncompleteCargo = new List<IncompleteItem>();
|
||||
|
||||
[IgnoreMember] public Guid Zone;
|
||||
[IgnoreMember] public Zone Zone;
|
||||
[IgnoreMember] public List<Hardpoint> Hardpoints;
|
||||
[IgnoreMember] public readonly Dictionary<object, float> VisibilitySources = new Dictionary<object, float>();
|
||||
[IgnoreMember] public readonly Dictionary<string, float> Messages = new Dictionary<string, float>();
|
||||
|
|
@ -138,7 +138,7 @@ public abstract class Entity : DatabaseEntry, IMessagePackSerializationCallbackR
|
|||
}
|
||||
|
||||
|
||||
public Entity(GameContext context, Guid hull, IEnumerable<Guid> gear, IEnumerable<Guid> cargo, Guid zone, Guid corporation)
|
||||
public Entity(GameContext context, Guid hull, IEnumerable<Guid> gear, IEnumerable<Guid> cargo, Zone zone, Guid corporation)
|
||||
{
|
||||
Context = context;
|
||||
Zone = zone;
|
||||
|
|
|
|||
22
Assets/Scripts/ServerShared/ExponentialCurve.cs
Normal file
22
Assets/Scripts/ServerShared/ExponentialCurve.cs
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
using Unity.Mathematics;
|
||||
using static Unity.Mathematics.math;
|
||||
|
||||
[Serializable, MessagePackObject, JsonObject]
|
||||
public class ExponentialCurve
|
||||
{
|
||||
[JsonProperty("exponent"), Key(0)]
|
||||
public float Exponent;
|
||||
|
||||
[JsonProperty("multiplier"), Key(1)]
|
||||
public float Multiplier;
|
||||
|
||||
[JsonProperty("constant"), Key(2)]
|
||||
public float Constant;
|
||||
|
||||
public float Evaluate(float value) => Multiplier * pow(value, Exponent) + Constant;
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/ExponentialCurve.cs.meta
Normal file
11
Assets/Scripts/ServerShared/ExponentialCurve.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 8e3680eb7ef815d4d8babd7bd3ae2276
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -12,9 +12,8 @@ using float4 = Unity.Mathematics.float4;
|
|||
public class GameContext
|
||||
{
|
||||
public Random Random = new Random((uint) (DateTime.Now.Ticks%uint.MaxValue));
|
||||
public Dictionary<Guid, Guid[]> ZonePlanets = new Dictionary<Guid, Guid[]>();
|
||||
public Dictionary<Guid, Dictionary<Guid, Entity>> ZoneEntities = new Dictionary<Guid, Dictionary<Guid, Entity>>();
|
||||
public Dictionary<string, GalaxyMapLayerData> MapLayers = new Dictionary<string, GalaxyMapLayerData>();
|
||||
public SimpleCommodityData[] Resources;
|
||||
public Dictionary<Guid, List<IController>> CorporationControllers = new Dictionary<Guid, List<IController>>();
|
||||
public Dictionary<Guid, SimplifiedZoneData> GalaxyZones;
|
||||
|
||||
|
|
@ -26,37 +25,24 @@ 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 Dictionary<Guid, float4[]> _asteroidTransforms = new Dictionary<Guid, float4[]>(); // x, y, rotation, scale
|
||||
private Dictionary<Guid, float4[]> _previousAsteroidTransforms = new Dictionary<Guid, float4[]>(); // x, y, rotation, scale
|
||||
private Dictionary<(Guid, int), float> _asteroidRespawnTimers = new Dictionary<(Guid, int), float>();
|
||||
private Dictionary<(Guid, int), float> _asteroidDamage = new Dictionary<(Guid, int), float>();
|
||||
private Dictionary<(Guid, Guid, int), float> _asteroidMiningAccumulator = new Dictionary<(Guid, Guid, int), float>();
|
||||
private Guid _forceLoadZone;
|
||||
private Type[] _statObjects;
|
||||
private Dictionary<Guid, Zone> _zones = new Dictionary<Guid, Zone>();
|
||||
// private Guid _forceLoadZone;
|
||||
|
||||
public GlobalData GlobalData => _globalData ?? (_globalData = Cache.GetAll<GlobalData>().FirstOrDefault());
|
||||
public DatabaseCache Cache { get; }
|
||||
|
||||
public Type[] StatObjects => _statObjects ?? (_statObjects = typeof(BehaviorData).GetAllChildClasses()
|
||||
.Concat(typeof(EquippableItemData).GetAllChildClasses()).ToArray());
|
||||
|
||||
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 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
|
||||
{
|
||||
|
|
@ -69,18 +55,13 @@ public class GameContext
|
|||
}
|
||||
}
|
||||
|
||||
public float2 WormholePosition(Guid zone, Guid other)
|
||||
{
|
||||
var zoneData = Cache.Get<ZoneData>(zone);
|
||||
var direction = Cache.Get<ZoneData>(other).Position - zoneData.Position;
|
||||
return normalize(direction) * zoneData.Radius * .95f;
|
||||
}
|
||||
|
||||
// private readonly Dictionary<CraftedItemData, int> Tier = new Dictionary<CraftedItemData, int>();
|
||||
|
||||
public GameContext(DatabaseCache cache, Action<string> logger)
|
||||
{
|
||||
Cache = cache;
|
||||
MapLayers = cache.GetAll<GalaxyMapLayerData>().ToDictionary(ml => ml.Name);
|
||||
Resources = cache.GetAll<SimpleCommodityData>().Where(i => i.ResourceDensity.Any()).ToArray();
|
||||
_logger = logger;
|
||||
// var globalData = Cache.GetAll<GlobalData>().FirstOrDefault();
|
||||
// if (globalData == null)
|
||||
|
|
@ -97,20 +78,9 @@ public class GameContext
|
|||
|
||||
public void Update()
|
||||
{
|
||||
_previousOrbitPositions = _orbitPositions;
|
||||
_orbitPositions = new Dictionary<Guid, float2>(_orbits.Count);
|
||||
foreach(var zone in _zones.Values)
|
||||
zone.Update(_deltaTime);
|
||||
|
||||
foreach(var orbit in _orbits)
|
||||
{
|
||||
_orbitPositions[orbit] = GetOrbitPosition(orbit);
|
||||
_orbitVelocities[orbit] = _previousOrbitPositions.ContainsKey(orbit)
|
||||
? (_orbitPositions[orbit] - _previousOrbitPositions[orbit]) / _deltaTime
|
||||
: float2.zero;
|
||||
}
|
||||
|
||||
foreach (var asteroids in _asteroidTransforms.Keys)
|
||||
UpdateAsteroidTransforms(asteroids);
|
||||
|
||||
foreach (var corporation in Cache.GetAll<Corporation>())
|
||||
{
|
||||
foreach (var tasks in corporation.Tasks
|
||||
|
|
@ -127,10 +97,10 @@ public class GameContext
|
|||
{
|
||||
// Find the nearest controller for this task
|
||||
IController nearestController = availableControllers[0];
|
||||
List<SimplifiedZoneData> nearestControllerPath = FindPath(GalaxyZones[availableControllers.First().Zone], GalaxyZones[task.Zone], true);
|
||||
List<SimplifiedZoneData> nearestControllerPath = FindPath(GalaxyZones[availableControllers.First().Zone.Data.ID], GalaxyZones[task.Zone], true);
|
||||
foreach (var controller in availableControllers.Skip(1))
|
||||
{
|
||||
var path = FindPath(GalaxyZones[controller.Zone], GalaxyZones[task.Zone], true);
|
||||
var path = FindPath(GalaxyZones[controller.Zone.Data.ID], GalaxyZones[task.Zone], true);
|
||||
if (path.Count < nearestControllerPath.Count)
|
||||
{
|
||||
nearestControllerPath = path;
|
||||
|
|
@ -143,208 +113,53 @@ public class GameContext
|
|||
}
|
||||
}
|
||||
|
||||
foreach (var kvp in ZoneEntities)
|
||||
{
|
||||
foreach (var entity in kvp.Value.Values) entity.Update(_deltaTime);
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<Entity> GetEntities(Guid zone)
|
||||
public Zone GetZone(Guid zone)
|
||||
{
|
||||
return ZoneEntities[zone].Values;
|
||||
if (_zones.ContainsKey(zone)) return _zones[zone];
|
||||
|
||||
// var zoneData = Cache.Get<ZoneData>(zone);
|
||||
// if (zoneData == null) throw new ArgumentException("Zone parameter is not a valid zone ID!", nameof(zone));
|
||||
//
|
||||
// return GetZone(zoneData);
|
||||
return null;
|
||||
}
|
||||
|
||||
public void LoadZone(Guid zone)
|
||||
public Zone GetZone(ZonePack zonePack)
|
||||
{
|
||||
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;
|
||||
|
||||
foreach (var belt in zoneData.Planets
|
||||
.Select(id => Cache.Get<PlanetData>(id))
|
||||
.Where(p => p.Belt))
|
||||
{
|
||||
_asteroidTransforms[belt.ID] = new float4[belt.Asteroids.Length];
|
||||
_previousAsteroidTransforms[belt.ID] = new float4[belt.Asteroids.Length];
|
||||
}
|
||||
|
||||
// TODO: Load stored entities
|
||||
ZoneEntities[zone] = new Dictionary<Guid, Entity>();
|
||||
var z = new Zone(this, zonePack);
|
||||
_zones.Add(zonePack.Data.ID, z);
|
||||
return z;
|
||||
}
|
||||
|
||||
public void UnloadZone(Guid zone)
|
||||
{
|
||||
var zoneData = Cache.Get<ZoneData>(zone);
|
||||
|
||||
_loadedZones.Remove(zone);
|
||||
ZoneEntities.Remove(zone);
|
||||
ZonePlanets.Remove(zone);
|
||||
foreach (var orbit in zoneData.Orbits) _orbits.Remove(orbit);
|
||||
foreach (var belt in zoneData.Planets
|
||||
.Select(id => Cache.Get<PlanetData>(id))
|
||||
.Where(p => p.Belt))
|
||||
{
|
||||
_asteroidTransforms.Remove(belt.ID);
|
||||
_previousAsteroidTransforms.Remove(belt.ID);
|
||||
}
|
||||
_zones.Remove(zone);
|
||||
}
|
||||
|
||||
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
|
||||
public float2 GetOrbitPosition(Guid orbit)
|
||||
{
|
||||
// Root orbit is fixed at center
|
||||
if(orbit==Guid.Empty)
|
||||
return float2.zero;
|
||||
|
||||
if (!_orbitPositions.ContainsKey(orbit))
|
||||
{
|
||||
var orbitData = Cache.Get<OrbitData>(orbit);
|
||||
float2 pos = float2.zero;
|
||||
if (orbitData.Period > .01f)
|
||||
{
|
||||
var phase = (float) frac(Time / orbitData.Period * GlobalData.OrbitSpeedMultiplier);
|
||||
pos = OrbitData.Evaluate(frac(phase + orbitData.Phase)) * orbitData.Distance;
|
||||
}
|
||||
|
||||
_orbitPositions[orbit] = GetOrbitPosition(orbitData.Parent) + pos;
|
||||
}
|
||||
|
||||
var position = _orbitPositions[orbit];
|
||||
if (float.IsNaN(position.x))
|
||||
{
|
||||
Log("Orbit position is NaN, something went very wrong!");
|
||||
return float2.zero;
|
||||
}
|
||||
return _orbitPositions[orbit];
|
||||
}
|
||||
|
||||
public float2 GetOrbitVelocity(Guid orbit)
|
||||
{
|
||||
return _orbitVelocities.ContainsKey(orbit) ? _orbitVelocities[orbit] : float2.zero;
|
||||
}
|
||||
|
||||
public int NearestAsteroid(Guid planetDataID, float2 position)
|
||||
{
|
||||
var planetData = Cache.Get<PlanetData>(planetDataID);
|
||||
|
||||
var asteroidPositions = GetAsteroidTransforms(planetDataID);
|
||||
|
||||
int nearest = 0;
|
||||
float nearestDistance = Single.MaxValue;
|
||||
for (int i = 0; i < planetData.Asteroids.Length; i++)
|
||||
{
|
||||
var dist = lengthsq(asteroidPositions[i].xy - position);
|
||||
if (AsteroidExists(planetDataID, i) && dist < nearestDistance)
|
||||
{
|
||||
nearest = i;
|
||||
nearestDistance = dist;
|
||||
}
|
||||
}
|
||||
|
||||
return nearest;
|
||||
}
|
||||
|
||||
public bool AsteroidExists(Guid planetDataID, int asteroid) =>
|
||||
!_asteroidRespawnTimers.ContainsKey((planetDataID, asteroid));
|
||||
|
||||
public float2 GetAsteroidVelocity(Guid planetDataID, int asteroid)
|
||||
{
|
||||
return (_asteroidTransforms[planetDataID][asteroid].xy - _previousAsteroidTransforms[planetDataID][asteroid].xy) / _deltaTime;
|
||||
}
|
||||
|
||||
public float4 GetAsteroidTransform(Guid planetDataID, int asteroid)
|
||||
{
|
||||
return _asteroidTransforms[planetDataID][asteroid];
|
||||
}
|
||||
|
||||
public float4[] GetAsteroidTransforms(Guid planetDataID)
|
||||
{
|
||||
return _asteroidTransforms[planetDataID];
|
||||
}
|
||||
|
||||
private void UpdateAsteroidTransforms(Guid planetDataID)
|
||||
{
|
||||
var planetData = Cache.Get<PlanetData>(planetDataID);
|
||||
|
||||
Array.Copy(_asteroidTransforms[planetDataID], _previousAsteroidTransforms[planetDataID], planetData.Asteroids.Length);
|
||||
|
||||
var orbitData = Cache.Get<OrbitData>(planetData.Orbit);
|
||||
var orbitPosition = GetOrbitPosition(orbitData.Parent);
|
||||
for (var i = 0; i < planetData.Asteroids.Length; i++)
|
||||
{
|
||||
var size = planetData.Asteroids[i].Size;
|
||||
if(_asteroidRespawnTimers.ContainsKey((planetDataID, i))) size = 0;
|
||||
else if (_asteroidDamage.ContainsKey((planetDataID, i)))
|
||||
{
|
||||
var hpLerp = unlerp(GlobalData.AsteroidSizeMin, GlobalData.AsteroidSizeMax, size);
|
||||
var asteroidHitpoints = lerp(GlobalData.AsteroidHitpointsMin, GlobalData.AsteroidHitpointsMax, pow(hpLerp, GlobalData.AsteroidHitpointsPower));
|
||||
var sizeLerp = (asteroidHitpoints - _asteroidDamage[(planetDataID, i)]) / asteroidHitpoints;
|
||||
size = lerp(GlobalData.AsteroidSizeMin, size, sizeLerp);
|
||||
}
|
||||
|
||||
_asteroidTransforms[planetDataID][i] = float4(
|
||||
OrbitData.Evaluate((float) frac(Time / OrbitalPeriod(planetData.Asteroids[i].Distance) * GlobalData.OrbitSpeedMultiplier +
|
||||
planetData.Asteroids[i].Phase)) * planetData.Asteroids[i].Distance + orbitPosition,
|
||||
(float) (Time * planetData.Asteroids[i].RotationSpeed % 360.0), size);
|
||||
}
|
||||
}
|
||||
|
||||
public OrbitData CreateOrbit(Guid zone, Guid parent, float2 position)
|
||||
{
|
||||
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 currentPhase = frac(Time / period * GlobalData.OrbitSpeedMultiplier);
|
||||
var storedPhase = (float) frac(phase - currentPhase);
|
||||
|
||||
var orbit = new OrbitData
|
||||
{
|
||||
Context = this,
|
||||
Distance = distance,
|
||||
Parent = parent,
|
||||
Period = period,
|
||||
Phase = storedPhase,
|
||||
Zone = zone
|
||||
};
|
||||
Cache.Add(orbit);
|
||||
_orbits.Add(orbit.ID);
|
||||
return orbit;
|
||||
}
|
||||
|
||||
public float OrbitalPeriod(float distance)
|
||||
{
|
||||
return pow(distance, GlobalData.OrbitPeriodExponent) * GlobalData.OrbitPeriodMultiplier;
|
||||
}
|
||||
// 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;
|
||||
// }
|
||||
// }
|
||||
|
||||
public void PlaceMegas()
|
||||
{
|
||||
|
|
@ -368,28 +183,28 @@ public class GameContext
|
|||
mega.HomeZone = zone.ID;
|
||||
}
|
||||
break;
|
||||
case MegaPlacementType.Planets:
|
||||
foreach (var mega in megaPlacement)
|
||||
{
|
||||
var zone = availableZones
|
||||
.MaxBy(z => z.Planets.Length);
|
||||
availableZones.Remove(zone);
|
||||
mega.HomeZone = zone.ID;
|
||||
}
|
||||
break;
|
||||
case MegaPlacementType.Resources:
|
||||
foreach (var mega in megaPlacement)
|
||||
{
|
||||
var zone = availableZones
|
||||
.MaxBy(z => z.Planets
|
||||
.SelectMany(id=>Cache.Get<PlanetData>(id).Resources
|
||||
.Select(r=>r.Key))
|
||||
.Distinct()
|
||||
.Count());
|
||||
availableZones.Remove(zone);
|
||||
mega.HomeZone = zone.ID;
|
||||
}
|
||||
break;
|
||||
// case MegaPlacementType.Planets:
|
||||
// foreach (var mega in megaPlacement)
|
||||
// {
|
||||
// var zone = availableZones
|
||||
// .MaxBy(z => z.Planets.Length);
|
||||
// availableZones.Remove(zone);
|
||||
// mega.HomeZone = zone.ID;
|
||||
// }
|
||||
// break;
|
||||
// case MegaPlacementType.Resources:
|
||||
// foreach (var mega in megaPlacement)
|
||||
// {
|
||||
// var zone = availableZones
|
||||
// .MaxBy(z => z.Planets
|
||||
// .SelectMany(id=>Cache.Get<PlanetData>(id).Resources
|
||||
// .Select(r=>r.Key))
|
||||
// .Distinct()
|
||||
// .Count());
|
||||
// availableZones.Remove(zone);
|
||||
// mega.HomeZone = zone.ID;
|
||||
// }
|
||||
// break;
|
||||
case MegaPlacementType.Connected:
|
||||
foreach (var mega in megaPlacement)
|
||||
{
|
||||
|
|
@ -623,7 +438,7 @@ public class GameContext
|
|||
return result;
|
||||
}
|
||||
|
||||
public Entity CreateEntity(Guid zone, Guid corporation, Guid loadout)
|
||||
public Entity CreateEntity(Guid zoneID, Guid corporation, Guid loadout)
|
||||
{
|
||||
if (!(Cache.Get(loadout) is LoadoutData loadoutData))
|
||||
{
|
||||
|
|
@ -637,7 +452,7 @@ public class GameContext
|
|||
return null;
|
||||
}
|
||||
|
||||
if (!(Cache.Get(zone) is ZoneData zoneData))
|
||||
if (!(Cache.Get(zoneID) is ZoneData zoneData))
|
||||
{
|
||||
_logger("Attempted to spawn entity with invalid zone ID");
|
||||
return null;
|
||||
|
|
@ -703,9 +518,8 @@ public class GameContext
|
|||
if(hull==null)
|
||||
return null;
|
||||
|
||||
// Load target zone if not yet loaded
|
||||
if (!_loadedZones.Contains(zone))
|
||||
LoadZone(zone);
|
||||
// Get target zone
|
||||
var zone = _zones[zoneID];
|
||||
|
||||
if (hullData.HullType == HullType.Ship)
|
||||
{
|
||||
|
|
@ -722,15 +536,12 @@ public class GameContext
|
|||
{
|
||||
Context = this,
|
||||
Distance = distance,
|
||||
Parent = _orbits
|
||||
.Select(id => Cache.Get<OrbitData>(id))
|
||||
.First(orbitData => orbitData.Zone == zone && orbitData.Parent == Guid.Empty).ID,
|
||||
Period = OrbitalPeriod(distance),
|
||||
Phase = Random.NextFloat(),
|
||||
Zone = zone
|
||||
Parent = zone.Orbits.Values.Select(o=>o.Data)
|
||||
.First(orbitData => orbitData.Parent == Guid.Empty).ID,
|
||||
Period = _globalData.OrbitalPeriod(distance),
|
||||
Phase = Random.NextFloat()
|
||||
};
|
||||
Cache.Add(orbit);
|
||||
_orbits.Add(orbit.ID);
|
||||
zone.AddOrbit(orbit);
|
||||
|
||||
var entity = new OrbitalEntity(this, hull.ID, gear.Select(g => g.ID),
|
||||
cargo.Select(c => c.ID).Concat(simpleCargo.Select(c => c.ID)), orbit.ID, zone, corporation)
|
||||
|
|
@ -745,14 +556,14 @@ public class GameContext
|
|||
entity.Personality[attribute.Key] = attribute.Value;
|
||||
Cache.Add(entity);
|
||||
|
||||
ZoneEntities[zone][entity.ID] = entity;
|
||||
zone.Entities[entity.ID] = entity;
|
||||
return entity;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public Ship CreateShip(Guid hull, IEnumerable<Guid> gear, IEnumerable<Guid> cargo, Guid zone, Guid corporation, Guid homeEntity, string typeName)
|
||||
public Ship CreateShip(Guid hull, IEnumerable<Guid> gear, IEnumerable<Guid> cargo, Zone zone, Guid corporation, Guid homeEntity, string typeName)
|
||||
{
|
||||
|
||||
var ship = new Ship(this, hull, gear, cargo, zone, corporation)
|
||||
|
|
@ -762,7 +573,7 @@ public class GameContext
|
|||
};
|
||||
Cache.Add(ship);
|
||||
|
||||
ZoneEntities[zone][ship.ID] = ship;
|
||||
zone.Entities[ship.ID] = ship;
|
||||
return ship;
|
||||
}
|
||||
|
||||
|
|
@ -920,46 +731,6 @@ public class GameContext
|
|||
child.Parent = Guid.Empty;
|
||||
}
|
||||
|
||||
public void MineAsteroid(Entity miner, Guid asteroidBelt, int asteroid, float damage, float efficiency, float penetration)
|
||||
{
|
||||
var planetData = Cache.Get<PlanetData>(asteroidBelt);
|
||||
var asteroidTransform = GetAsteroidTransform(asteroidBelt, asteroid);
|
||||
var hpLerp = unlerp(GlobalData.AsteroidSizeMin, GlobalData.AsteroidSizeMax, asteroidTransform.w);
|
||||
var asteroidHitpoints = lerp(GlobalData.AsteroidHitpointsMin, GlobalData.AsteroidHitpointsMax, pow(hpLerp, GlobalData.AsteroidHitpointsPower));
|
||||
|
||||
if (!_asteroidDamage.ContainsKey((asteroidBelt, asteroid)))
|
||||
_asteroidDamage[(asteroidBelt, asteroid)] = 0;
|
||||
_asteroidDamage[(asteroidBelt, asteroid)] = _asteroidDamage[(asteroidBelt, asteroid)] + damage;
|
||||
|
||||
if (!_asteroidMiningAccumulator.ContainsKey((asteroidBelt, miner.ID, asteroid)))
|
||||
_asteroidMiningAccumulator[(asteroidBelt, miner.ID, asteroid)] = 0;
|
||||
_asteroidMiningAccumulator[(asteroidBelt, miner.ID, asteroid)] = _asteroidMiningAccumulator[(asteroidBelt, miner.ID, asteroid)] + damage;
|
||||
|
||||
if (_asteroidDamage[(asteroidBelt, asteroid)] > asteroidHitpoints)
|
||||
{
|
||||
_asteroidRespawnTimers[(asteroidBelt, asteroid)] =
|
||||
lerp(GlobalData.AsteroidRespawnMin, GlobalData.AsteroidRespawnMax, hpLerp);
|
||||
_asteroidDamage.Remove((asteroidBelt, asteroid));
|
||||
_asteroidMiningAccumulator.Remove((asteroidBelt, miner.ID, asteroid));
|
||||
return;
|
||||
}
|
||||
|
||||
var resourceCount = planetData.Resources.Sum(x => x.Value);
|
||||
var resource = planetData.Resources.MaxBy(x => pow(x.Value, 1f / penetration) * Random.NextFloat());
|
||||
if (efficiency * Random.NextFloat() * _asteroidMiningAccumulator[(asteroidBelt, miner.ID, asteroid)] * resourceCount / GlobalData.MiningDifficulty > 1 && miner.OccupiedCapacity < miner.Capacity - 1)
|
||||
{
|
||||
_asteroidMiningAccumulator.Remove((asteroidBelt, miner.ID, asteroid));
|
||||
var newSimpleCommodity = new SimpleCommodity
|
||||
{
|
||||
Context = this,
|
||||
Data = resource.Key,
|
||||
Quantity = 1
|
||||
};
|
||||
Cache.Add(newSimpleCommodity);
|
||||
miner.AddCargo(newSimpleCommodity);
|
||||
}
|
||||
}
|
||||
|
||||
// public bool MoveCargo(Entity source, Entity target, ItemInstance item, int quantity = int.MaxValue)
|
||||
// {
|
||||
// if (item is CraftedItemInstance craftedItemInstance)
|
||||
|
|
|
|||
|
|
@ -171,6 +171,11 @@ public class GlobalData : DatabaseEntry
|
|||
{
|
||||
return pow(mass, 1 / RadiusPower);
|
||||
}
|
||||
|
||||
public float OrbitalPeriod(float distance)
|
||||
{
|
||||
return pow(distance, OrbitPeriodExponent) * OrbitPeriodMultiplier;
|
||||
}
|
||||
}
|
||||
|
||||
[Inspectable, Serializable, RethinkTable("Galaxy"), MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ public class OrbitalEntity : Entity
|
|||
{
|
||||
public Guid OrbitData;
|
||||
|
||||
public OrbitalEntity(GameContext context, Guid hull, IEnumerable<Guid> gear, IEnumerable<Guid> cargo, Guid orbit, Guid zone, Guid corporation) : base(context, hull, gear, cargo, zone, corporation)
|
||||
public OrbitalEntity(GameContext context, Guid hull, IEnumerable<Guid> gear, IEnumerable<Guid> cargo, Guid orbit, Zone zone, Guid corporation) : base(context, hull, gear, cargo, zone, corporation)
|
||||
{
|
||||
OrbitData = orbit;
|
||||
}
|
||||
|
|
@ -18,8 +18,8 @@ public class OrbitalEntity : Entity
|
|||
{
|
||||
if (OrbitData != Guid.Empty)
|
||||
{
|
||||
Position = Context.GetOrbitPosition(OrbitData);
|
||||
Velocity = Context.GetOrbitVelocity(OrbitData);
|
||||
Position = Zone.GetOrbitPosition(OrbitData);
|
||||
Velocity = Zone.GetOrbitVelocity(OrbitData);
|
||||
}
|
||||
|
||||
base.Update(delta);
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ public class Ship : Entity
|
|||
[JsonProperty("homeEntity"), Key(19)]
|
||||
public Guid HomeEntity;
|
||||
|
||||
public Ship(GameContext context, Guid hull, IEnumerable<Guid> gear, IEnumerable<Guid> cargo, Guid zone, Guid corporation) : base(context, hull, gear, cargo, zone, corporation)
|
||||
public Ship(GameContext context, Guid hull, IEnumerable<Guid> gear, IEnumerable<Guid> cargo, Zone zone, Guid corporation) : base(context, hull, gear, cargo, zone, corporation)
|
||||
{
|
||||
}
|
||||
|
||||
|
|
|
|||
280
Assets/Scripts/ServerShared/Zone.cs
Normal file
280
Assets/Scripts/ServerShared/Zone.cs
Normal file
|
|
@ -0,0 +1,280 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Unity.Mathematics;
|
||||
using static Unity.Mathematics.math;
|
||||
using float2 = Unity.Mathematics.float2;
|
||||
|
||||
public class Zone
|
||||
{
|
||||
//public HashSet<Guid> Planets = new HashSet<Guid>();
|
||||
public Dictionary<Guid, Entity> Entities = new Dictionary<Guid, Entity>();
|
||||
//public Dictionary<Guid, OrbitData> Orbits = new Dictionary<Guid, OrbitData>();
|
||||
public Dictionary<Guid, PlanetData> Planets = new Dictionary<Guid, PlanetData>();
|
||||
|
||||
public Dictionary<Guid, Orbit> Orbits = new Dictionary<Guid, Orbit>();
|
||||
public Dictionary<Guid, AsteroidBelt> AsteroidBelts = new Dictionary<Guid, AsteroidBelt>();
|
||||
|
||||
private HashSet<Guid> _updatedOrbits;
|
||||
|
||||
private GameContext _context;
|
||||
|
||||
public ZoneData Data { get; }
|
||||
|
||||
public Zone(GameContext context, ZonePack pack)
|
||||
{
|
||||
Data = pack.Data;
|
||||
_context = context;
|
||||
|
||||
foreach (var orbit in pack.Orbits)
|
||||
{
|
||||
Orbits.Add(orbit.ID, new Orbit(orbit));
|
||||
}
|
||||
foreach (var planet in pack.Planets) Planets.Add(planet.ID, planet);
|
||||
foreach (var entity in pack.Entities) Entities.Add(entity.ID, entity);
|
||||
|
||||
foreach (var belt in pack.Planets.Where(p => p is AsteroidBeltData).Cast<AsteroidBeltData>())
|
||||
AsteroidBelts[belt.ID] = new AsteroidBelt(belt.Asteroids.Length);
|
||||
|
||||
// TODO: Associate planets with stored entities for planetary colonies
|
||||
}
|
||||
|
||||
public ZonePack Pack()
|
||||
{
|
||||
return new ZonePack
|
||||
{
|
||||
Data = Data,
|
||||
Entities = Entities.Values.ToList(),
|
||||
Orbits = Orbits.Values.Select(o=>o.Data).ToList(),
|
||||
Planets = Planets.Values.ToList()
|
||||
};
|
||||
}
|
||||
|
||||
public void AddOrbit(OrbitData orbit)
|
||||
{
|
||||
Orbits.Add(orbit.ID, new Orbit(orbit));
|
||||
}
|
||||
|
||||
public void Update(float deltaTime)
|
||||
{
|
||||
_updatedOrbits = new HashSet<Guid>();
|
||||
foreach (var orbit in Orbits)
|
||||
{
|
||||
orbit.Value.PreviousPosition = orbit.Value.Position;
|
||||
orbit.Value.Position = GetOrbitPosition(orbit.Key);
|
||||
orbit.Value.Velocity = (orbit.Value.Position - orbit.Value.PreviousPosition) / deltaTime;
|
||||
}
|
||||
|
||||
foreach (var asteroids in AsteroidBelts.Keys)
|
||||
UpdateAsteroidTransforms(asteroids);
|
||||
|
||||
foreach (var entity in Entities.Values) entity.Update(deltaTime);
|
||||
}
|
||||
|
||||
public float2 WormholePosition(Guid target)
|
||||
{
|
||||
var direction = _context.Cache.Get<ZoneData>(target).Position - Data.Position;
|
||||
return normalize(direction) * Data.Radius * .95f;
|
||||
}
|
||||
|
||||
// Determine orbital position recursively, caching parent positions to avoid repeated calculations
|
||||
public float2 GetOrbitPosition(Guid orbit)
|
||||
{
|
||||
// Root orbit is fixed at center
|
||||
if(orbit==Guid.Empty)
|
||||
return float2.zero;
|
||||
|
||||
if (!_updatedOrbits.Contains(orbit))
|
||||
{
|
||||
var orbitData = Orbits[orbit].Data;
|
||||
float2 pos = float2.zero;
|
||||
if (orbitData.Period > .01f)
|
||||
{
|
||||
var phase = (float) frac(_context.Time / orbitData.Period * _context.GlobalData.OrbitSpeedMultiplier);
|
||||
pos = OrbitData.Evaluate(frac(phase + orbitData.Phase)) * orbitData.Distance;
|
||||
|
||||
if (float.IsNaN(pos.x))
|
||||
{
|
||||
_context.Log("Orbit position is NaN, something went very wrong!");
|
||||
pos = float2.zero;
|
||||
}
|
||||
}
|
||||
|
||||
_updatedOrbits.Add(orbit);
|
||||
return GetOrbitPosition(orbitData.Parent) + pos;
|
||||
}
|
||||
|
||||
return Orbits[orbit].Position;
|
||||
}
|
||||
|
||||
public float2 GetOrbitVelocity(Guid orbit)
|
||||
{
|
||||
if (Orbits.ContainsKey(orbit))
|
||||
return Orbits[orbit].Velocity;
|
||||
return float2.zero;
|
||||
}
|
||||
|
||||
public int NearestAsteroid(Guid planetDataID, float2 position)
|
||||
{
|
||||
var beltData = Planets[planetDataID] as AsteroidBeltData;
|
||||
|
||||
var asteroidPositions = GetAsteroidTransforms(planetDataID);
|
||||
|
||||
int nearest = 0;
|
||||
float nearestDistance = Single.MaxValue;
|
||||
for (int i = 0; i < beltData.Asteroids.Length; i++)
|
||||
{
|
||||
var dist = lengthsq(asteroidPositions[i].xy - position);
|
||||
if (AsteroidExists(planetDataID, i) && dist < nearestDistance)
|
||||
{
|
||||
nearest = i;
|
||||
nearestDistance = dist;
|
||||
}
|
||||
}
|
||||
|
||||
return nearest;
|
||||
}
|
||||
|
||||
public bool AsteroidExists(Guid planetDataID, int asteroid) => ((AsteroidBeltData) Planets[planetDataID]).Asteroids.Length > asteroid && asteroid >= 0;
|
||||
|
||||
public float2 GetAsteroidVelocity(Guid planetDataID, int asteroid)
|
||||
{
|
||||
return (AsteroidBelts[planetDataID].Transforms[asteroid].xy - AsteroidBelts[planetDataID].PreviousTransforms[asteroid].xy);
|
||||
}
|
||||
|
||||
public float4 GetAsteroidTransform(Guid planetDataID, int asteroid)
|
||||
{
|
||||
return AsteroidBelts[planetDataID].Transforms[asteroid];
|
||||
}
|
||||
|
||||
public float4[] GetAsteroidTransforms(Guid planetDataID)
|
||||
{
|
||||
return AsteroidBelts[planetDataID].Transforms;
|
||||
}
|
||||
|
||||
private void UpdateAsteroidTransforms(Guid planetDataID)
|
||||
{
|
||||
var beltData = Planets[planetDataID] as AsteroidBeltData;
|
||||
|
||||
var belt = AsteroidBelts[planetDataID];
|
||||
|
||||
Array.Copy(belt.Transforms, belt.PreviousTransforms, beltData.Asteroids.Length);
|
||||
|
||||
var orbitData = Orbits[beltData.Orbit].Data;
|
||||
var orbitPosition = GetOrbitPosition(orbitData.Parent);
|
||||
for (var i = 0; i < beltData.Asteroids.Length; i++)
|
||||
{
|
||||
var size = beltData.Asteroids[i].Size;
|
||||
if(belt.RespawnTimers.ContainsKey(i)) size = 0;
|
||||
else if (belt.Damage.ContainsKey(i))
|
||||
{
|
||||
var hpLerp = unlerp(_context.GlobalData.AsteroidSizeMin, _context.GlobalData.AsteroidSizeMax, size);
|
||||
var asteroidHitpoints = lerp(_context.GlobalData.AsteroidHitpointsMin, _context.GlobalData.AsteroidHitpointsMax, pow(hpLerp, _context.GlobalData.AsteroidHitpointsPower));
|
||||
var sizeLerp = (asteroidHitpoints - belt.Damage[i]) / asteroidHitpoints;
|
||||
size = lerp(_context.GlobalData.AsteroidSizeMin, size, sizeLerp);
|
||||
}
|
||||
|
||||
belt.Transforms[i] = float4(
|
||||
OrbitData.Evaluate((float) frac(_context.Time / _context.GlobalData.OrbitalPeriod(beltData.Asteroids[i].Distance) * _context.GlobalData.OrbitSpeedMultiplier +
|
||||
beltData.Asteroids[i].Phase)) * beltData.Asteroids[i].Distance + orbitPosition,
|
||||
(float) (_context.Time * beltData.Asteroids[i].RotationSpeed % 360.0), size);
|
||||
}
|
||||
}
|
||||
|
||||
public OrbitData CreateOrbit(Guid parent, float2 position)
|
||||
{
|
||||
var parentPosition = GetOrbitPosition(parent);
|
||||
var delta = position - parentPosition;
|
||||
var distance = length(delta);
|
||||
var period = _context.GlobalData.OrbitalPeriod(distance);
|
||||
var phase = atan2(delta.y, delta.x) / (PI * 2);
|
||||
var currentPhase = frac(_context.Time / period * _context.GlobalData.OrbitSpeedMultiplier);
|
||||
var storedPhase = (float) frac(phase - currentPhase);
|
||||
|
||||
var orbit = new OrbitData
|
||||
{
|
||||
Context = _context,
|
||||
Distance = distance,
|
||||
Parent = parent,
|
||||
Period = period,
|
||||
Phase = storedPhase
|
||||
};
|
||||
Orbits.Add(orbit.ID, new Orbit(orbit));
|
||||
return orbit;
|
||||
}
|
||||
|
||||
public void MineAsteroid(Entity miner, Guid asteroidBelt, int asteroid, float damage, float efficiency, float penetration)
|
||||
{
|
||||
var planetData = Planets[asteroidBelt];
|
||||
var belt = AsteroidBelts[asteroidBelt];
|
||||
var asteroidTransform = belt.Transforms[asteroid];
|
||||
var hpLerp = unlerp(_context.GlobalData.AsteroidSizeMin, _context.GlobalData.AsteroidSizeMax, asteroidTransform.w);
|
||||
var asteroidHitpoints = lerp(_context.GlobalData.AsteroidHitpointsMin, _context.GlobalData.AsteroidHitpointsMax, pow(hpLerp, _context.GlobalData.AsteroidHitpointsPower));
|
||||
|
||||
if (!belt.Damage.ContainsKey(asteroid))
|
||||
belt.Damage[asteroid] = 0;
|
||||
belt.Damage[asteroid] = belt.Damage[asteroid] + damage;
|
||||
|
||||
if (!belt.MiningAccumulator.ContainsKey((miner.ID, asteroid)))
|
||||
belt.MiningAccumulator[(miner.ID, asteroid)] = 0;
|
||||
belt.MiningAccumulator[(miner.ID, asteroid)] = belt.MiningAccumulator[(miner.ID, asteroid)] + damage;
|
||||
|
||||
if (belt.Damage[asteroid] > asteroidHitpoints)
|
||||
{
|
||||
belt.RespawnTimers[asteroid] =
|
||||
lerp(_context.GlobalData.AsteroidRespawnMin, _context.GlobalData.AsteroidRespawnMax, hpLerp);
|
||||
belt.Damage.Remove(asteroid);
|
||||
belt.MiningAccumulator.Remove((miner.ID, asteroid));
|
||||
return;
|
||||
}
|
||||
|
||||
var resourceCount = planetData.Resources.Sum(x => x.Value);
|
||||
var resource = planetData.Resources.MaxBy(x => pow(x.Value, 1f / penetration) * _context.Random.NextFloat());
|
||||
if (efficiency * _context.Random.NextFloat() * belt.MiningAccumulator[(miner.ID, asteroid)] * resourceCount / _context.GlobalData.MiningDifficulty > 1 && miner.OccupiedCapacity < miner.Capacity - 1)
|
||||
{
|
||||
belt.MiningAccumulator.Remove((miner.ID, asteroid));
|
||||
var newSimpleCommodity = new SimpleCommodity
|
||||
{
|
||||
Context = _context,
|
||||
Data = resource.Key,
|
||||
Quantity = 1
|
||||
};
|
||||
_context.Cache.Add(newSimpleCommodity);
|
||||
miner.AddCargo(newSimpleCommodity);
|
||||
}
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return Data.ID.GetHashCode();
|
||||
}
|
||||
}
|
||||
|
||||
public class AsteroidBelt
|
||||
{
|
||||
public float4[] Transforms; // x, y, rotation, scale
|
||||
public float4[] PreviousTransforms; // x, y, rotation, scale
|
||||
public Dictionary<int, float> RespawnTimers = new Dictionary<int, float>();
|
||||
public Dictionary<int, float> Damage = new Dictionary<int, float>();
|
||||
public Dictionary<(Guid, int), float> MiningAccumulator = new Dictionary<(Guid, int), float>();
|
||||
|
||||
public AsteroidBelt(int count)
|
||||
{
|
||||
Transforms = new float4[count];
|
||||
PreviousTransforms = new float4[count];
|
||||
}
|
||||
}
|
||||
|
||||
public class Orbit
|
||||
{
|
||||
public OrbitData Data { get; }
|
||||
public float2 Velocity = float2.zero;
|
||||
public float2 Position = float2.zero;
|
||||
public float2 PreviousPosition = float2.zero;
|
||||
|
||||
public Orbit(OrbitData data)
|
||||
{
|
||||
Data = data;
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Zone.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Zone.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: dde69e76badd79c4c8d73cf89be4f0e8
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -4,6 +4,7 @@ using System.Collections.Generic;
|
|||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
using Unity.Mathematics;
|
||||
using UnityEngine;
|
||||
using static Unity.Mathematics.math;
|
||||
|
||||
[RethinkTable("Galaxy"), MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
|
|
@ -21,17 +22,17 @@ public class ZoneData : DatabaseEntry, INamedEntry
|
|||
[JsonProperty("mass"), Key(4)]
|
||||
public float Mass = 10000;
|
||||
|
||||
[JsonProperty("visited"), Key(5)]
|
||||
public bool Visited;
|
||||
// [JsonProperty("visited"), Key(5)]
|
||||
// public bool Visited;
|
||||
|
||||
[JsonProperty("wormholes"), Key(6)]
|
||||
[JsonProperty("wormholes"), Key(5)]
|
||||
public List<Guid> Wormholes = new List<Guid>();
|
||||
|
||||
[JsonProperty("planets"), Key(7)]
|
||||
public Guid[] Planets;// = new List<Guid>();
|
||||
|
||||
[JsonProperty("orbits"), Key(8)]
|
||||
public List<Guid> Orbits = new List<Guid>();
|
||||
// [JsonProperty("planets"), Key(7)]
|
||||
// public Guid[] Planets;// = new List<Guid>();
|
||||
//
|
||||
// [JsonProperty("orbits"), Key(8)]
|
||||
// public List<Guid> Orbits = new List<Guid>();
|
||||
|
||||
[IgnoreMember] public string EntryName
|
||||
{
|
||||
|
|
@ -40,6 +41,28 @@ public class ZoneData : DatabaseEntry, INamedEntry
|
|||
}
|
||||
}
|
||||
|
||||
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
public class ZonePack : INamedEntry
|
||||
{
|
||||
[JsonProperty("data"), Key(0)]
|
||||
public ZoneData Data;
|
||||
|
||||
[JsonProperty("planets"), Key(1)]
|
||||
public List<PlanetData> Planets = new List<PlanetData>();
|
||||
|
||||
[JsonProperty("orbits"), Key(2)]
|
||||
public List<OrbitData> Orbits = new List<OrbitData>();
|
||||
|
||||
[JsonProperty("entities"), Key(3)]
|
||||
public List<Entity> Entities = new List<Entity>();
|
||||
|
||||
[IgnoreMember] public string EntryName
|
||||
{
|
||||
get => Data.Name;
|
||||
set => Data.Name = value;
|
||||
}
|
||||
}
|
||||
|
||||
// [RethinkTable("Galaxy"), MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
// public class StationData : DatabaseEntry, INamedEntry
|
||||
// {
|
||||
|
|
@ -72,7 +95,11 @@ public class ZoneData : DatabaseEntry, INamedEntry
|
|||
// }
|
||||
// }
|
||||
|
||||
[RethinkTable("Galaxy"), MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
[MessagePackObject,
|
||||
JsonObject(MemberSerialization.OptIn),
|
||||
Union(1, typeof(AsteroidBeltData)),
|
||||
Union(2, typeof(GasGiantData)),
|
||||
Union(3, typeof(SunData))]
|
||||
public class PlanetData : DatabaseEntry, INamedEntry
|
||||
{
|
||||
[JsonProperty("name"), Key(1)]
|
||||
|
|
@ -84,20 +111,14 @@ public class PlanetData : DatabaseEntry, INamedEntry
|
|||
[JsonProperty("mass"), Key(3)]
|
||||
public float Mass;
|
||||
|
||||
[JsonProperty("zone"), Key(4)]
|
||||
public Guid Zone;
|
||||
|
||||
[JsonProperty("belt"), Key(5)]
|
||||
public bool Belt;
|
||||
|
||||
[JsonProperty("resources"), Key(6)]
|
||||
[JsonProperty("resources"), Key(4)]
|
||||
public Dictionary<Guid, float> Resources = new Dictionary<Guid, float>();
|
||||
|
||||
[JsonProperty("asteroids"), Key(7)]
|
||||
public Asteroid[] Asteroids; // Distance, Phase, Size, RotationSpeed
|
||||
|
||||
// [JsonProperty("radius")] [Key(5)]
|
||||
// public float GravityRadius;
|
||||
[JsonProperty("radiusMul")] [Key(5)]
|
||||
public float GravityRadiusMultiplier = 1;
|
||||
|
||||
[JsonProperty("depthMul")] [Key(6)]
|
||||
public float GravityDepthMultiplier = 1;
|
||||
|
||||
[IgnoreMember] public string EntryName
|
||||
{
|
||||
|
|
@ -106,6 +127,45 @@ public class PlanetData : DatabaseEntry, INamedEntry
|
|||
}
|
||||
}
|
||||
|
||||
public class AsteroidBeltData : PlanetData
|
||||
{
|
||||
[JsonProperty("asteroids"), Key(7)]
|
||||
public Asteroid[] Asteroids;
|
||||
}
|
||||
|
||||
public class GasGiantData : PlanetData
|
||||
{
|
||||
[JsonProperty("firstOffsetDomainRotationSpeed"), Key(7)]
|
||||
public float FirstOffsetDomainRotationSpeed;
|
||||
|
||||
[JsonProperty("firstOffsetRotationSpeed"), Key(8)]
|
||||
public float FirstOffsetRotationSpeed;
|
||||
|
||||
[JsonProperty("secondOffsetDomainRotationSpeed"), Key(9)]
|
||||
public float SecondOffsetDomainRotationSpeed;
|
||||
|
||||
[JsonProperty("secondOffsetRotationSpeed"), Key(10)]
|
||||
public float SecondOffsetRotationSpeed;
|
||||
|
||||
[JsonProperty("albedoRotationSpeed"), Key(11)]
|
||||
public float AlbedoRotationSpeed;
|
||||
|
||||
[JsonProperty("materialOverrides"), Key(12)]
|
||||
public List<string> MaterialOverrides = new List<string>();
|
||||
|
||||
[JsonProperty("colors"), Key(13)]
|
||||
public Gradient Colors;
|
||||
}
|
||||
|
||||
public class SunData : GasGiantData
|
||||
{
|
||||
[JsonProperty("lightColor"), Key(17)]
|
||||
public Color LightColor;
|
||||
|
||||
[JsonProperty("fogTintColor"), Key(18)]
|
||||
public Color FogTintColor;
|
||||
}
|
||||
|
||||
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
public class Asteroid
|
||||
{
|
||||
|
|
@ -115,7 +175,7 @@ public class Asteroid
|
|||
public float RotationSpeed;
|
||||
}
|
||||
|
||||
[RethinkTable("Galaxy"), MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
public class OrbitData : DatabaseEntry
|
||||
{
|
||||
[JsonProperty("parent"), Key(1)]
|
||||
|
|
@ -130,9 +190,6 @@ public class OrbitData : DatabaseEntry
|
|||
[JsonProperty("period"), Key(4)]
|
||||
public float Period;
|
||||
|
||||
[JsonProperty("zone"), Key(5)]
|
||||
public Guid Zone;
|
||||
|
||||
public static float2 Evaluate(float phase)
|
||||
{
|
||||
phase *= PI * 2;
|
||||
|
|
|
|||
|
|
@ -5,21 +5,33 @@ using System.Globalization;
|
|||
using System.Linq;
|
||||
using MessagePack;
|
||||
using Unity.Mathematics;
|
||||
using UnityEngine;
|
||||
using static Unity.Mathematics.math;
|
||||
using Random = Unity.Mathematics.Random;
|
||||
|
||||
public class ZoneGenerator
|
||||
{
|
||||
|
||||
public static void GenerateZone(
|
||||
public static ZonePack GenerateZone(
|
||||
GameContext context,
|
||||
ZoneData zone,
|
||||
string name,
|
||||
float2 position,
|
||||
IEnumerable<GalaxyMapLayerData> mapLayers,
|
||||
IEnumerable<SimpleCommodityData> resources,
|
||||
out OrbitData[] orbitData,
|
||||
out PlanetData[] planetsData)
|
||||
float mass = 0,
|
||||
float radius = 0)
|
||||
{
|
||||
var zoneRadius = context.Random.NextPowerDistribution(
|
||||
var zone = new ZoneData
|
||||
{
|
||||
Name = name,
|
||||
Position = position
|
||||
};
|
||||
|
||||
var pack = new ZonePack
|
||||
{
|
||||
Data = zone
|
||||
};
|
||||
|
||||
var zoneRadius = radius != 0 ? radius : context.Random.NextPowerDistribution(
|
||||
context.GlobalData.MinimumZoneRadius,
|
||||
context.GlobalData.MaximumZoneRadius,
|
||||
context.GlobalData.ZoneRadiusExponent,
|
||||
|
|
@ -31,7 +43,7 @@ public class ZoneGenerator
|
|||
.Evaluate(zone.Position, context.GlobalData)));
|
||||
zone.Radius = zoneRadius;
|
||||
|
||||
var zoneMass = context.Random.NextPowerDistribution(
|
||||
var zoneMass = mass != 0 ? mass : context.Random.NextPowerDistribution(
|
||||
context.GlobalData.MinimumZoneMass,
|
||||
context.GlobalData.MaximumZoneMass,
|
||||
context.GlobalData.ZoneMassExponent,
|
||||
|
|
@ -48,26 +60,25 @@ public class ZoneGenerator
|
|||
var planets = GenerateEntities(context, zone, zoneMass, zoneRadius);
|
||||
|
||||
// Create collections to map between zone generator output and database entries
|
||||
var orbitMap = new Dictionary<Planet, OrbitData>();
|
||||
var orbitInverseMap = new Dictionary<OrbitData, Planet>();
|
||||
var orbitMap = new Dictionary<GeneratorPlanet, OrbitData>();
|
||||
var orbitInverseMap = new Dictionary<OrbitData, GeneratorPlanet>();
|
||||
|
||||
// Create orbit database entries
|
||||
orbitData = planets.Select(planet =>
|
||||
pack.Orbits = planets.Select(planet =>
|
||||
{
|
||||
var data = new OrbitData
|
||||
{
|
||||
Distance = planet.Distance,
|
||||
Period = planet.Period,
|
||||
Phase = planet.Phase,
|
||||
Zone = zone.ID
|
||||
Phase = planet.Phase
|
||||
};
|
||||
orbitMap[planet] = data;
|
||||
orbitInverseMap[data] = planet;
|
||||
return data;
|
||||
}).ToArray();
|
||||
}).ToList();
|
||||
|
||||
// Link OrbitData parents to database GUIDs
|
||||
foreach (var data in orbitData)
|
||||
foreach (var data in pack.Orbits)
|
||||
data.Parent = orbitInverseMap[data].Parent != null
|
||||
? orbitMap[orbitInverseMap[data].Parent].ID
|
||||
: Guid.Empty;
|
||||
|
|
@ -75,34 +86,50 @@ public class ZoneGenerator
|
|||
// Cache resource densities
|
||||
var resourceMaps = mapLayers.ToDictionary(m => m.ID, m => m.Evaluate(zone.Position, context.GlobalData));
|
||||
|
||||
planetsData = planets.Where(p=>!p.Empty).Select(planet =>
|
||||
pack.Planets = planets.Where(p=>!p.Empty).Select(planet =>
|
||||
{
|
||||
Dictionary<Guid, float> dictionary = new Dictionary<Guid, float>();
|
||||
Dictionary<Guid, float> planetResources = new Dictionary<Guid, float>();
|
||||
BodyType bodyType = planet.Belt ? BodyType.Asteroid :
|
||||
planet.Mass > context.GlobalData.SunMass ? BodyType.Sun :
|
||||
planet.Mass > context.GlobalData.GasGiantMass ? BodyType.GasGiant :
|
||||
planet.Mass > context.GlobalData.PlanetMass ? BodyType.Planet : BodyType.Planetoid;
|
||||
|
||||
foreach (var r in resources)
|
||||
{
|
||||
var bodyType = (planet.Belt ? BodyType.Asteroid :
|
||||
planet.Mass > context.GlobalData.SunMass ? BodyType.Sun :
|
||||
planet.Mass > context.GlobalData.GasGiantMass ? BodyType.GasGiant :
|
||||
planet.Mass > context.GlobalData.PlanetMass ? BodyType.Planet : BodyType.Planetoid);
|
||||
if ((bodyType & r.ResourceBodyType) != 0)
|
||||
{
|
||||
float quantity = ResourceValue(r, context, r.ResourceDensity.Aggregate(1f, (m, rdm) => m * resourceMaps[rdm]));
|
||||
if (r.Floor < quantity) dictionary.Add(r.ID, quantity);
|
||||
if (r.Floor < quantity) planetResources.Add(r.ID, quantity);
|
||||
}
|
||||
}
|
||||
|
||||
var planetData = new PlanetData
|
||||
{
|
||||
Mass = planet.Mass,
|
||||
Orbit = orbitMap[planet].ID,
|
||||
Zone = zone.ID,
|
||||
Belt = planet.Belt,
|
||||
Resources = dictionary
|
||||
};
|
||||
PlanetData planetData;
|
||||
switch (bodyType)
|
||||
{
|
||||
case BodyType.Asteroid:
|
||||
planetData = new AsteroidBeltData();
|
||||
break;
|
||||
case BodyType.Planetoid:
|
||||
case BodyType.Planet:
|
||||
planetData = new PlanetData();
|
||||
break;
|
||||
case BodyType.GasGiant:
|
||||
planetData = new GasGiantData();
|
||||
break;
|
||||
case BodyType.Sun:
|
||||
planetData = new SunData();
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException();
|
||||
}
|
||||
|
||||
planetData.Mass = planet.Mass;
|
||||
planetData.Orbit = orbitMap[planet].ID;
|
||||
planetData.Resources = planetResources;
|
||||
planetData.Name = planetData.ID.ToString().Substring(0, 8);
|
||||
if (planet.Belt)
|
||||
if (planetData is AsteroidBeltData beltData)
|
||||
{
|
||||
planetData.Asteroids =
|
||||
beltData.Asteroids =
|
||||
Enumerable.Range(0, (int) (pow(planetData.Mass, context.GlobalData.BeltMassExponent) / context.GlobalData.BeltMassRatio * orbitMap[planet].Distance))
|
||||
.Select(_ => new Asteroid
|
||||
{
|
||||
|
|
@ -114,11 +141,27 @@ public class ZoneGenerator
|
|||
RotationSpeed = context.Random.NextFloat() * context.GlobalData.AsteroidRotationSpeed
|
||||
}).ToArray();
|
||||
}
|
||||
else if (planetData is GasGiantData gas)
|
||||
{
|
||||
var grad = new Gradient();
|
||||
var times = Enumerable.Range(0, 5).Select(i => (float) i / 4).ToArray();
|
||||
grad.alphaKeys = times.Select(f => new GradientAlphaKey(1, f)).ToArray();
|
||||
grad.colorKeys = times.Select(f => new GradientColorKey(UnityEngine.Random.ColorHSV(), f)).ToArray();
|
||||
gas.Colors = grad;
|
||||
gas.AlbedoRotationSpeed = 1;
|
||||
gas.FirstOffsetRotationSpeed = 1;
|
||||
gas.FirstOffsetDomainRotationSpeed = 1;
|
||||
gas.SecondOffsetRotationSpeed = 1;
|
||||
gas.SecondOffsetDomainRotationSpeed = 1;
|
||||
if (planetData is SunData sun)
|
||||
{
|
||||
sun.FogTintColor = sun.LightColor = UnityEngine.Random.ColorHSV();
|
||||
}
|
||||
}
|
||||
return planetData;
|
||||
}).ToArray();
|
||||
}).ToList();
|
||||
|
||||
zone.Planets = planetsData.Select(pd => pd.ID).ToArray();
|
||||
zone.Orbits = orbitData.Select(od => od.ID).ToList();
|
||||
return pack;
|
||||
}
|
||||
|
||||
static float ResourceValue(SimpleCommodityData resource, GameContext context, float density)
|
||||
|
|
@ -127,15 +170,15 @@ public class ZoneGenerator
|
|||
1 / lerp(context.GlobalData.ResourceDensityMinimum, context.GlobalData.ResourceDensityMaximum, density));
|
||||
}
|
||||
|
||||
public static Planet[] GenerateEntities(GameContext context, ZoneData data, float mass, float radius)
|
||||
public static GeneratorPlanet[] GenerateEntities(GameContext context, ZoneData data, float mass, float radius)
|
||||
{
|
||||
var random = new Random();
|
||||
random.InitState(unchecked((uint)data.Name.GetHashCode()));
|
||||
|
||||
var root = new Planet
|
||||
var root = new GeneratorPlanet
|
||||
{
|
||||
Context = context,
|
||||
Mass = mass,
|
||||
Mass = mass,
|
||||
ChildDistanceMaximum = radius * .75f,
|
||||
ChildDistanceMinimum = context.GlobalData.PlanetRadius(mass)
|
||||
};
|
||||
|
|
@ -194,7 +237,7 @@ public class ZoneGenerator
|
|||
? root.AllPlanets().Where(p => p != root && p.Parent != root && p.Mass > context.GlobalData.SatelliteCreationMassFloor)
|
||||
: root.AllPlanets().Where(p => p != root && p.Mass > context.GlobalData.SatelliteCreationMassFloor);
|
||||
|
||||
var binaries = new List<Planet>();
|
||||
var binaries = new List<GeneratorPlanet>();
|
||||
foreach (var planet in satelliteCandidates)
|
||||
{
|
||||
// There's a chance of generating satellites for each qualified planet
|
||||
|
|
@ -233,7 +276,7 @@ public class ZoneGenerator
|
|||
// All orbiting bodies are referred to here as "Planets"
|
||||
// This goes back to the original etymology for the word planet, which is traveler,
|
||||
// Because they were objects we observed to move in the sky instead of remaining fixed like the stars
|
||||
public class Planet
|
||||
public class GeneratorPlanet
|
||||
{
|
||||
public GameContext Context;
|
||||
public float Distance;
|
||||
|
|
@ -244,11 +287,11 @@ public class Planet
|
|||
public float ChildDistanceMaximum;
|
||||
public bool Empty = false;
|
||||
public bool Belt = false;
|
||||
public List<Planet> Children = new List<Planet>(); // Planets orbiting this one are referred to as children
|
||||
public Planet Parent;
|
||||
public List<GeneratorPlanet> Children = new List<GeneratorPlanet>(); // Planets orbiting this one are referred to as children
|
||||
public GeneratorPlanet Parent;
|
||||
|
||||
// Recursively gather all planets in the hierarchy
|
||||
public IEnumerable<Planet> AllPlanets()
|
||||
public IEnumerable<GeneratorPlanet> AllPlanets()
|
||||
{
|
||||
return new[]{this}.Concat(Children.SelectMany(c=>c.AllPlanets()));
|
||||
}
|
||||
|
|
@ -283,7 +326,7 @@ public class Planet
|
|||
|
||||
for (int i = 0; i < vertices; i++)
|
||||
{
|
||||
var child = new Planet
|
||||
var child = new GeneratorPlanet
|
||||
{
|
||||
Context = Context,
|
||||
Parent = this,
|
||||
|
|
@ -293,7 +336,7 @@ public class Planet
|
|||
ChildDistanceMaximum = (i % 2 == 0 ? p0ChildDist : p1ChildDist)
|
||||
};
|
||||
child.ChildDistanceMinimum = Context.GlobalData.PlanetRadius(child.Mass) * 2;
|
||||
child.Period = Context.OrbitalPeriod(child.Distance);
|
||||
child.Period = Context.GlobalData.OrbitalPeriod(child.Distance);
|
||||
Children.Add(child);
|
||||
}
|
||||
|
||||
|
|
@ -346,7 +389,7 @@ public class Planet
|
|||
// Only instantiate children above the mass floor
|
||||
if (masses[i] > Context.GlobalData.MassFloor)
|
||||
{
|
||||
var child = new Planet
|
||||
var child = new GeneratorPlanet
|
||||
{
|
||||
Context = Context,
|
||||
Parent = this,
|
||||
|
|
@ -354,7 +397,7 @@ public class Planet
|
|||
Distance = distances[i],
|
||||
Phase = Context.Random.NextFloat()
|
||||
};
|
||||
child.Period = Context.OrbitalPeriod(child.Distance);
|
||||
child.Period = Context.GlobalData.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],
|
||||
|
|
|
|||
Loading…
Reference in a new issue