Skip to content

Commit

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

attempt at fixing client logging (it didnt work)
  • Loading branch information
InvalidArgument3 authored Jun 19, 2024
2 parents 80678dc + dab3fa0 commit fb9af2f
Show file tree
Hide file tree
Showing 4 changed files with 120 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,8 @@ public void SplitAsteroid()
if (!MyAPIGateway.Session.IsServer)
return;

Log.ServerInfo($"Splitting asteroid with ID {EntityId}, Size: {Size}");

int splits = MainSession.I.Rand.Next(2, 5);

if (splits > Size)
Expand All @@ -383,12 +385,15 @@ public void SplitAsteroid()
{
int dropAmount = GetRandomDropAmount(Type);
MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(dropAmount, newObject), PositionComp.GetPosition() + RandVector() * Size, Vector3D.Forward, Vector3D.Up, Physics);
Log.ServerInfo($"Spawned {dropAmount} of {Type} at {PositionComp.GetPosition() + RandVector() * Size}");
}

var removalMessage = new AsteroidNetworkMessage(PositionComp.GetPosition(), Size, Vector3D.Zero, Vector3D.Zero, Type, false, EntityId, true, false, Quaternion.Identity);
var removalMessageBytes = MyAPIGateway.Utilities.SerializeToBinary(removalMessage);
MyAPIGateway.Multiplayer.SendMessageToOthers(32000, removalMessageBytes);

Log.ServerInfo($"Sent removal message for asteroid with ID {EntityId}");

MainSession.I._spawner._asteroids.Remove(this);
Close();
return;
Expand All @@ -409,6 +414,8 @@ public void SplitAsteroid()

MainSession.I._spawner._asteroids.Add(subChunk);

Log.ServerInfo($"Created sub-chunk asteroid with ID {subChunk.EntityId} at {newPos}");

var message = new AsteroidNetworkMessage(newPos, newSize, newVelocity, newAngularVelocity, Type, true, subChunk.EntityId, false, true, newRotation);
var messageBytes = MyAPIGateway.Utilities.SerializeToBinary(message);
MyAPIGateway.Multiplayer.SendMessageToOthers(32000, messageBytes);
Expand All @@ -418,45 +425,60 @@ public void SplitAsteroid()
var finalRemovalMessageBytes = MyAPIGateway.Utilities.SerializeToBinary(finalRemovalMessage);
MyAPIGateway.Multiplayer.SendMessageToOthers(32000, finalRemovalMessageBytes);

Log.ServerInfo($"Sent final removal message for asteroid with ID {EntityId}");

MainSession.I._spawner._asteroids.Remove(this);
Close();
}

private int GetRandomDropAmount(AsteroidType type)
{
int dropAmount = 0;
switch (type)
{
case AsteroidType.Ice:
return MainSession.I.Rand.Next(AsteroidSettings.IceDropRange[0], AsteroidSettings.IceDropRange[1]);
dropAmount = MainSession.I.Rand.Next(AsteroidSettings.IceDropRange[0], AsteroidSettings.IceDropRange[1]);
break;
case AsteroidType.Stone:
return MainSession.I.Rand.Next(AsteroidSettings.StoneDropRange[0], AsteroidSettings.StoneDropRange[1]);
dropAmount = MainSession.I.Rand.Next(AsteroidSettings.StoneDropRange[0], AsteroidSettings.StoneDropRange[1]);
break;
case AsteroidType.Iron:
return MainSession.I.Rand.Next(AsteroidSettings.IronDropRange[0], AsteroidSettings.IronDropRange[1]);
dropAmount = MainSession.I.Rand.Next(AsteroidSettings.IronDropRange[0], AsteroidSettings.IronDropRange[1]);
break;
case AsteroidType.Nickel:
return MainSession.I.Rand.Next(AsteroidSettings.NickelDropRange[0], AsteroidSettings.NickelDropRange[1]);
dropAmount = MainSession.I.Rand.Next(AsteroidSettings.NickelDropRange[0], AsteroidSettings.NickelDropRange[1]);
break;
case AsteroidType.Cobalt:
return MainSession.I.Rand.Next(AsteroidSettings.CobaltDropRange[0], AsteroidSettings.CobaltDropRange[1]);
dropAmount = MainSession.I.Rand.Next(AsteroidSettings.CobaltDropRange[0], AsteroidSettings.CobaltDropRange[1]);
break;
case AsteroidType.Magnesium:
return MainSession.I.Rand.Next(AsteroidSettings.MagnesiumDropRange[0], AsteroidSettings.MagnesiumDropRange[1]);
dropAmount = MainSession.I.Rand.Next(AsteroidSettings.MagnesiumDropRange[0], AsteroidSettings.MagnesiumDropRange[1]);
break;
case AsteroidType.Silicon:
return MainSession.I.Rand.Next(AsteroidSettings.SiliconDropRange[0], AsteroidSettings.SiliconDropRange[1]);
dropAmount = MainSession.I.Rand.Next(AsteroidSettings.SiliconDropRange[0], AsteroidSettings.SiliconDropRange[1]);
break;
case AsteroidType.Silver:
return MainSession.I.Rand.Next(AsteroidSettings.SilverDropRange[0], AsteroidSettings.SilverDropRange[1]);
dropAmount = MainSession.I.Rand.Next(AsteroidSettings.SilverDropRange[0], AsteroidSettings.SilverDropRange[1]);
break;
case AsteroidType.Gold:
return MainSession.I.Rand.Next(AsteroidSettings.GoldDropRange[0], AsteroidSettings.GoldDropRange[1]);
dropAmount = MainSession.I.Rand.Next(AsteroidSettings.GoldDropRange[0], AsteroidSettings.GoldDropRange[1]);
break;
case AsteroidType.Platinum:
return MainSession.I.Rand.Next(AsteroidSettings.PlatinumDropRange[0], AsteroidSettings.PlatinumDropRange[1]);
dropAmount = MainSession.I.Rand.Next(AsteroidSettings.PlatinumDropRange[0], AsteroidSettings.PlatinumDropRange[1]);
break;
case AsteroidType.Uraninite:
return MainSession.I.Rand.Next(AsteroidSettings.UraniniteDropRange[0], AsteroidSettings.UraniniteDropRange[1]);
default:
return 0;
dropAmount = MainSession.I.Rand.Next(AsteroidSettings.UraniniteDropRange[0], AsteroidSettings.UraniniteDropRange[1]);
break;
}
Log.ServerInfo($"Generated drop amount for {type}: {dropAmount}");
return dropAmount;
}

public void OnDestroy()
{
try
{
Log.ServerInfo($"OnDestroy called for asteroid with ID {EntityId}");
SplitAsteroid();
}
catch (Exception ex)
Expand Down Expand Up @@ -519,6 +541,8 @@ private void CreatePhysics()
MyAPIGateway.Physics.CreateSpherePhysics(settings, radius);
Physics.Enabled = true;
Physics.Activate();

Log.ServerInfo($"Physics created for asteroid with ID {EntityId}, Mass: {mass}, Radius: {radius}");
}

private Vector3D RandVector()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ private class PlayerMovementData
public double Speed { get; set; }
}

private int _spawnIntervalTimer = 0;
private int _updateIntervalTimer = 0;
private int _logUpdateTimer = 0;
private int totalSpawnAttempts = 0;

public void Init(int seed)
{
if (!MyAPIGateway.Session.IsServer)
Expand Down Expand Up @@ -338,9 +343,6 @@ public void UpdateZones()
playerZones = updatedZones;
}

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

public void UpdateTick()
{
if (!MyAPIGateway.Session.IsServer) return;
Expand Down Expand Up @@ -375,6 +377,16 @@ public void UpdateTick()
_spawnIntervalTimer = AsteroidSettings.SpawnInterval;
}

if (_logUpdateTimer > 0)
{
_logUpdateTimer--;
}
else
{
Log.Info($"All zones spawn attempt complete. Total spawn attempts: {totalSpawnAttempts}, New total asteroid count: {_asteroids.Count}");
_logUpdateTimer = 5; // Log every 5 updates, adjust as necessary
}

foreach (var player in players)
{
Vector3D playerPosition = player.GetPosition();
Expand Down Expand Up @@ -510,8 +522,6 @@ private void ProcessGravityCheckQueue()

public void SpawnAsteroids(List<AsteroidZone> zones)
{
int totalSpawnAttempts = 0;

if (AsteroidSettings.MaxAsteroidCount == 0)
{
Log.Info("Asteroid spawning is disabled.");
Expand Down
65 changes: 53 additions & 12 deletions Dynamic Asteroids/Data/Scripts/DynamicAsteroids/Log.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Timers;
using DynamicAsteroids;
using Sandbox.ModAPI;

Expand All @@ -9,31 +11,51 @@ internal class Log
{
private static Log I;
private readonly TextWriter _writer;
private static List<string> _logBuffer = new List<string>();
private static Timer _logTimer;

private Log()
{
MyAPIGateway.Utilities.DeleteFileInGlobalStorage("DynamicAsteroids.log");
_writer = MyAPIGateway.Utilities.WriteFileInGlobalStorage("DynamicAsteroids.log");
var logFileName = MyAPIGateway.Session.IsServer ? "DynamicAsteroids_Server.log" : "DynamicAsteroids_Client.log";
MyAPIGateway.Utilities.DeleteFileInGlobalStorage(logFileName);
_writer = MyAPIGateway.Utilities.WriteFileInGlobalStorage(logFileName);
_writer.WriteLine($" Dynamic Asteroids - {(MyAPIGateway.Session.IsServer ? "Server" : "Client")} Debug Log\n===========================================\n");
_writer.WriteLine($"{DateTime.UtcNow:HH:mm:ss}: Logger initialized for {(MyAPIGateway.Session.IsServer ? "Server" : "Client")}");
_writer.Flush();

_logTimer = new Timer(5000); // Set the interval to 5 seconds
_logTimer.Elapsed += FlushLogs;
_logTimer.Start();
}

public static void Info(string message)
{
if (AsteroidSettings.EnableLogging)
I?._Log(message);
I?._BufferLog(message);
}

public static void ServerInfo(string message)
{
if (AsteroidSettings.EnableLogging && MyAPIGateway.Session.IsServer)
I?._BufferLog("Server: " + message);
}

public static void ClientInfo(string message)
{
if (AsteroidSettings.EnableLogging && !MyAPIGateway.Session.IsServer)
I?._BufferLog("Client: " + message);
}

public static void Warning(string message)
{
if (AsteroidSettings.EnableLogging)
I?._Log("WARNING: " + message);
I?._BufferLog("WARNING: " + message);
}

public static void Exception(Exception ex, Type callingType, string prefix = "")
{
if (AsteroidSettings.EnableLogging)
I?._LogException(ex, callingType, prefix);
I?._BufferLogException(ex, callingType, prefix);
}

public static void Init()
Expand All @@ -47,28 +69,47 @@ public static void Close()
if (I != null)
{
Info("Closing log writer.");
FlushLogs(null, null);
I._writer.Close();
}

I = null;
}

private void _Log(string message)
private void _BufferLog(string message)
{
_writer.WriteLine($"{DateTime.UtcNow:HH:mm:ss}: {message}");
_writer.Flush();
lock (_logBuffer)
{
_logBuffer.Add($"{DateTime.UtcNow:HH:mm:ss}: {message}");
}
}

private void _LogException(Exception ex, Type callingType, string prefix = "")
private void _BufferLogException(Exception ex, Type callingType, string prefix = "")
{
if (ex == null)
{
_Log("Null exception! CallingType: " + callingType.FullName);
_BufferLog("Null exception! CallingType: " + callingType.FullName);
return;
}

_Log(prefix + $"Exception in {callingType.FullName}! {ex.Message}\n{ex.StackTrace}\n{ex.InnerException}");
_BufferLog(prefix + $"Exception in {callingType.FullName}! {ex.Message}\n{ex.StackTrace}\n{ex.InnerException}");
MyAPIGateway.Utilities.ShowNotification($"{ex.GetType().Name} in Dynamic Asteroids! Check logs for more info.", 10000, "Red");
}

private static void FlushLogs(object sender, ElapsedEventArgs e)
{
lock (_logBuffer)
{
if (_logBuffer.Count > 0)
{
foreach (var log in _logBuffer)
{
I?._writer.WriteLine(log);
}
_logBuffer.Clear();
I?._writer.Flush();
}
}
}
}
}
}
27 changes: 15 additions & 12 deletions Dynamic Asteroids/Data/Scripts/DynamicAsteroids/MainSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ public class MainSession : MySessionComponentBase
public override void LoadData()
{
I = this;
Log.Init();
Log.Init(); // Ensure this is called on both server and client
Log.Info("Log initialized in LoadData method.");

AsteroidSettings.LoadSettings(); // Load settings from the config file

try
Expand Down Expand Up @@ -160,7 +162,7 @@ public override void UpdateAfterSimulation()
}
else
{
Log.Info($"Server: Sending network messages, asteroid count: {_spawner._asteroids.Count}");
Log.ServerInfo($"Sending network messages, asteroid count: {_spawner._asteroids.Count}");
_spawner.SendNetworkMessages();
_networkMessageTimer = AsteroidSettings.NetworkMessageInterval;
}
Expand All @@ -176,6 +178,7 @@ public override void UpdateAfterSimulation()
string rotationString = $"({angularVelocity.X:F2}, {angularVelocity.Y:F2}, {angularVelocity.Z:F2})";
string message = $"Nearest Asteroid: {nearestAsteroid.EntityId} ({nearestAsteroid.Type})\nRotation: {rotationString}";
if (AsteroidSettings.EnableLogging) MyAPIGateway.Utilities.ShowNotification(message, 1000 / 60);
Log.ClientInfo(message);
}
}

Expand All @@ -187,7 +190,7 @@ public override void UpdateAfterSimulation()
var velocity = MyAPIGateway.Session.Player?.Character?.Physics?.LinearVelocity ?? Vector3D.Zero;
AsteroidType type = DetermineAsteroidType();
AsteroidEntity.CreateAsteroid(position, Rand.Next(50), velocity, type);
Log.Info($"Asteroid created at {position} with velocity {velocity}");
Log.ClientInfo($"Asteroid created at {position} with velocity {velocity}");
}
}
}
Expand All @@ -203,38 +206,38 @@ private void OnMessageReceived(byte[] message)
{
if (message == null || message.Length == 0)
{
Log.Info("Received empty or null message, skipping processing.");
Log.ClientInfo("Received empty or null message, skipping processing.");
return;
}

Log.Info($"Client: Received message of {message.Length} bytes");
Log.ClientInfo($"Received message of {message.Length} bytes");
var asteroidMessage = MyAPIGateway.Utilities.SerializeFromBinary<AsteroidNetworkMessage>(message);

if (asteroidMessage.IsRemoval)
{
var asteroid = MyEntities.GetEntityById(asteroidMessage.EntityId) as AsteroidEntity;
if (asteroid != null)
{
Log.Info($"Client: Removing asteroid with ID {asteroidMessage.EntityId}");
Log.ClientInfo($"Removing asteroid with ID {asteroidMessage.EntityId}");
MyEntities.Remove(asteroid);
asteroid.Close();
Log.Info($"Client: Removed asteroid with ID {asteroidMessage.EntityId}");
Log.ClientInfo($"Removed asteroid with ID {asteroidMessage.EntityId}");
}
else
{
Log.Info($"Client: Failed to find asteroid with ID {asteroidMessage.EntityId} for removal");
Log.ClientInfo($"Failed to find asteroid with ID {asteroidMessage.EntityId} for removal");
}
}
else
{
var existingAsteroid = MyEntities.GetEntityById(asteroidMessage.EntityId) as AsteroidEntity;
if (existingAsteroid != null)
{
Log.Info($"Client: Asteroid with ID {asteroidMessage.EntityId} already exists, skipping creation");
Log.ClientInfo($"Asteroid with ID {asteroidMessage.EntityId} already exists, skipping creation");
}
else
{
Log.Info($"Client: Creating asteroid with provided details");
Log.ClientInfo($"Creating asteroid with provided details");
var asteroid = AsteroidEntity.CreateAsteroid(
asteroidMessage.GetPosition(),
asteroidMessage.Size,
Expand All @@ -247,11 +250,11 @@ private void OnMessageReceived(byte[] message)
{
asteroid.Physics.AngularVelocity = asteroidMessage.GetAngularVelocity();
MyEntities.Add(asteroid);
Log.Info($"Client: Created asteroid with ID {asteroid.EntityId}");
Log.ClientInfo($"Created asteroid with ID {asteroid.EntityId}");
}
else
{
Log.Info($"Client: Failed to create asteroid with ID {asteroidMessage.EntityId}");
Log.ClientInfo($"Failed to create asteroid with ID {asteroidMessage.EntityId}");
}
}
}
Expand Down

0 comments on commit fb9af2f

Please sign in to comment.