Skip to content

Commit

Permalink
Merge pull request #61 from InvalidArgument3/roidnetworking-narrowing…
Browse files Browse the repository at this point in the history
…downthecause

queueing attempt, anti natural grav
  • Loading branch information
InvalidArgument3 authored Jun 17, 2024
2 parents ad336a0 + d330e34 commit c0e9fda
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@
using Invalid.DynamicRoids;
using Sandbox.Game.Entities;



public class AsteroidZone
{
public Vector3D Center { get; set; }
Expand All @@ -31,9 +29,6 @@ public bool IsPointInZone(Vector3D point)
}
}




public class AsteroidSpawner
{
public List<AsteroidEntity> _asteroids;
Expand All @@ -43,14 +38,18 @@ public class AsteroidSpawner
private List<AsteroidState> _despawnedAsteroids = new List<AsteroidState>();
private List<AsteroidNetworkMessage> _networkMessages = new List<AsteroidNetworkMessage>();
private Dictionary<long, AsteroidZone> playerZones = new Dictionary<long, AsteroidZone>();

private Dictionary<long, PlayerMovementData> playerMovementData = new Dictionary<long, PlayerMovementData>();
private Queue<AsteroidEntity> gravityCheckQueue = new Queue<AsteroidEntity>();
private const int GravityChecksPerTick = 1;

private Queue<AsteroidEntity> _updateQueue = new Queue<AsteroidEntity>();
private const int UpdatesPerTick = 50; // Adjust this number based on performance needs

private class PlayerMovementData
{
public Vector3D LastPosition { get; set; }
public DateTime LastUpdateTime { get; set; }
public double Speed { get; set; } // Added to store the calculated speed
public double Speed { get; set; }
}

public void Init(int seed)
Expand All @@ -63,6 +62,12 @@ public void Init(int seed)
_worldLoadTime = DateTime.UtcNow;
rand = new Random(seed);
AsteroidSettings.Seed = seed;

// Add all asteroids to the update queue
foreach (var asteroid in _asteroids)
{
_updateQueue.Enqueue(asteroid);
}
}

public void SaveAsteroidState()
Expand All @@ -75,7 +80,7 @@ public void SaveAsteroidState()
Position = asteroid.PositionComp.GetPosition(),
Size = asteroid.Size,
Type = asteroid.Type,
EntityId = asteroid.EntityId // Save unique ID
EntityId = asteroid.EntityId
}).ToList();

asteroidStates.AddRange(_despawnedAsteroids);
Expand All @@ -85,6 +90,13 @@ public void SaveAsteroidState()
{
writer.Write(stateBytes, 0, stateBytes.Length);
}

// Ensure the update queue is saved as well
_updateQueue.Clear();
foreach (var asteroid in _asteroids)
{
_updateQueue.Enqueue(asteroid);
}
}

public void LoadAsteroidState()
Expand All @@ -109,13 +121,19 @@ public void LoadAsteroidState()
if (_asteroids.Any(a => a.EntityId == state.EntityId))
{
Log.Info($"Skipping duplicate asteroid with ID {state.EntityId}");
continue; // Skip duplicates
continue;
}

var asteroid = AsteroidEntity.CreateAsteroid(state.Position, state.Size, Vector3D.Zero, state.Type);
asteroid.EntityId = state.EntityId; // Assign the saved ID
asteroid.EntityId = state.EntityId;
_asteroids.Add(asteroid);
MyEntities.Add(asteroid);

// Add to gravity check queue
gravityCheckQueue.Enqueue(asteroid);

// Add to update queue
_updateQueue.Enqueue(asteroid);
}
}
}
Expand Down Expand Up @@ -144,14 +162,17 @@ private void LoadAsteroidsInRange(Vector3D playerPosition, AsteroidZone zone)
respawnedPositions.Add(state.Position);

var asteroid = AsteroidEntity.CreateAsteroid(state.Position, state.Size, Vector3D.Zero, state.Type);
asteroid.EntityId = state.EntityId; // Assign the saved ID
asteroid.EntityId = state.EntityId;
_asteroids.Add(asteroid);

var message = new AsteroidNetworkMessage(state.Position, state.Size, Vector3D.Zero, Vector3D.Zero, state.Type, false, asteroid.EntityId, false, true, Quaternion.Identity);
var messageBytes = MyAPIGateway.Utilities.SerializeToBinary(message);
MyAPIGateway.Multiplayer.SendMessageToOthers(32000, messageBytes);

_despawnedAsteroids.Remove(state);

// Add to gravity check queue
gravityCheckQueue.Enqueue(asteroid);
}
}

Expand Down Expand Up @@ -219,6 +240,7 @@ public void AssignZonesToPlayers()

playerZones = updatedZones;
}

public void MergeZones()
{
List<AsteroidZone> mergedZones = new List<AsteroidZone>();
Expand All @@ -234,7 +256,6 @@ public void MergeZones()

if (distance <= combinedRadius)
{
// Merge the zones by updating the center and radius of the merged zone
Vector3D newCenter = (zone.Center + mergedZone.Center) / 2;
double newRadius = Math.Max(zone.Radius, mergedZone.Radius) + distance / 2;
mergedZone.Center = newCenter;
Expand All @@ -247,12 +268,10 @@ public void MergeZones()

if (!merged)
{
// If the zone couldn't be merged with any existing merged zones, add it as a new merged zone
mergedZones.Add(new AsteroidZone(zone.Center, zone.Radius) { AsteroidCount = zone.AsteroidCount });
}
}

// Update the playerZones dictionary with the merged zones
playerZones.Clear();
List<IMyPlayer> players = new List<IMyPlayer>();
MyAPIGateway.Players.GetPlayers(players);
Expand Down Expand Up @@ -318,6 +337,7 @@ public void UpdateZones()

playerZones = updatedZones;
}

private int _spawnIntervalTimer = 0;
private int _updateIntervalTimer = 0;

Expand All @@ -340,7 +360,7 @@ public void UpdateTick()
}
else
{
UpdateAsteroids(playerZones.Values.ToList());
ProcessAsteroidUpdates();
_updateIntervalTimer = AsteroidSettings.UpdateInterval;
}

Expand All @@ -364,6 +384,8 @@ public void UpdateTick()
}
}

ProcessGravityCheckQueue();

if (AsteroidSettings.EnableLogging)
MyAPIGateway.Utilities.ShowNotification($"Active Asteroids: {_asteroids.Count}", 1000 / 60);
}
Expand All @@ -373,6 +395,46 @@ public void UpdateTick()
}
}

private void ProcessAsteroidUpdates()
{
int updatesProcessed = 0;

while (updatesProcessed < UpdatesPerTick && _updateQueue.Count > 0)
{
var asteroid = _updateQueue.Dequeue();

// Perform the update logic for the asteroid here
UpdateAsteroid(asteroid);

// Re-enqueue the asteroid for future updates
_updateQueue.Enqueue(asteroid);

updatesProcessed++;
}
}

private void UpdateAsteroid(AsteroidEntity asteroid)
{
// Implement the actual update logic for an individual asteroid here
}

private void ProcessGravityCheckQueue()
{
for (int i = 0; i < GravityChecksPerTick && gravityCheckQueue.Count > 0; i++)
{
var asteroid = gravityCheckQueue.Dequeue();
if (IsInNaturalGravity(asteroid.PositionComp.GetPosition()))
{
RemoveAsteroid(asteroid);
}
else
{
// Re-enqueue if still valid
gravityCheckQueue.Enqueue(asteroid);
}
}
}

private void UpdateAsteroids(List<AsteroidZone> zones)
{
Log.Info($"Updating asteroids. Total asteroids: {_asteroids.Count}, Total zones: {zones.Count}");
Expand Down Expand Up @@ -401,7 +463,6 @@ private void UpdateAsteroids(List<AsteroidZone> zones)
}
else if (currentZone != null)
{
// Ensure the asteroid is counted in the correct zone
foreach (var zone in zones)
{
if (zone != currentZone && zone.IsPointInZone(asteroid.PositionComp.GetPosition()))
Expand All @@ -411,6 +472,9 @@ private void UpdateAsteroids(List<AsteroidZone> zones)
}
currentZone.AsteroidCount++;
}

// Add to gravity check queue
gravityCheckQueue.Enqueue(asteroid);
}

Log.Info($"Update complete. Removed asteroids: {removedCount}, Remaining asteroids: {_asteroids.Count}");
Expand All @@ -435,14 +499,13 @@ public void SpawnAsteroids(List<AsteroidZone> zones)
List<Vector3D> skippedPositions = new List<Vector3D>();
List<Vector3D> spawnedPositions = new List<Vector3D>();

UpdatePlayerMovementData(); // Update player movement data
UpdatePlayerMovementData();

foreach (var zone in zones)
{
int asteroidsSpawned = 0;
int zoneSpawnAttempts = 0;

// Check if any player in the zone is moving too fast
bool skipSpawning = false;
List<IMyPlayer> players = new List<IMyPlayer>();
MyAPIGateway.Players.GetPlayers(players);
Expand Down Expand Up @@ -494,7 +557,6 @@ public void SpawnAsteroids(List<AsteroidZone> zones)
continue;
}

// Check max asteroid count before actually adding a new asteroid
if (AsteroidSettings.MaxAsteroidCount != -1 && _asteroids.Count >= AsteroidSettings.MaxAsteroidCount)
{
Log.Warning($"Maximum asteroid count of {AsteroidSettings.MaxAsteroidCount} reached. No more asteroids will be spawned until existing ones are removed.");
Expand All @@ -518,6 +580,9 @@ public void SpawnAsteroids(List<AsteroidZone> zones)
var message = new AsteroidNetworkMessage(newPosition, size, newVelocity, Vector3D.Zero, type, false, asteroid.EntityId, false, true, rotation);
_networkMessages.Add(message);
asteroidsSpawned++;

// Add to gravity check queue
gravityCheckQueue.Enqueue(asteroid);
}
}

Expand Down Expand Up @@ -576,6 +641,11 @@ private void UpdatePlayerMovementData()

private bool IsValidSpawnPosition(Vector3D position, List<AsteroidZone> zones)
{
if (AsteroidSettings.IgnorePlanets && IsInNaturalGravity(position))
{
return false;
}

foreach (var zone in zones)
{
if (zone.IsPointInZone(position) &&
Expand All @@ -587,6 +657,13 @@ private bool IsValidSpawnPosition(Vector3D position, List<AsteroidZone> zones)
return false;
}

private bool IsInNaturalGravity(Vector3D position)
{
float naturalGravityInterference;
Vector3 gravity = MyAPIGateway.Physics.CalculateNaturalGravityAt(position, out naturalGravityInterference);
return gravity.LengthSquared() > 0;
}

public void SendNetworkMessages()
{
if (_networkMessages.Count == 0) return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public static class AsteroidSettings
public static double MinDistanceFromVanillaAsteroids = 1000;
public static double MinDistanceFromPlayer = 3000;
public static int Seed = 69420;
public static bool IgnorePlanets = true;
public static double IceWeight = 99;
public static double StoneWeight = 0.5;
public static double IronWeight = 0.25;
Expand Down Expand Up @@ -153,6 +154,7 @@ public static void SaveSettings()
writer.WriteLine($"MinDistanceFromVanillaAsteroids={MinDistanceFromVanillaAsteroids}");
writer.WriteLine($"MinDistanceFromPlayer={MinDistanceFromPlayer}");
writer.WriteLine($"Seed={Seed}");
writer.WriteLine($"IgnorePlanets={IgnorePlanets}");

writer.WriteLine("[Weights]");
writer.WriteLine($"IceWeight={IceWeight}");
Expand Down Expand Up @@ -291,6 +293,9 @@ public static void LoadSettings()
case "Seed":
Seed = int.Parse(value);
break;
case "IgnorePlanets":
IgnorePlanets = bool.Parse(value);
break;
case "IceWeight":
IceWeight = double.Parse(value);
break;
Expand Down

0 comments on commit c0e9fda

Please sign in to comment.