projectiles

This commit is contained in:
dingo
2026-01-18 00:17:06 -05:00
parent 4e189613fb
commit 6e14f6faa1
17 changed files with 4981 additions and 51 deletions
+250 -5
View File
@@ -89,6 +89,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler
DungeonOpCodes.DUNGEON_INPUT_PICKUP,
DungeonOpCodes.DUNGEON_INPUT_CHEST,
DungeonOpCodes.DUNGEON_INPUT_PORTAL,
DungeonOpCodes.DUNGEON_INPUT_FIRE_PROJECTILE,
DungeonOpCodes.INVENTORY_REQUEST,
DungeonOpCodes.EQUIP_ITEM,
DungeonOpCodes.UNEQUIP_ITEM,
@@ -327,6 +328,10 @@ public sealed partial class DungeonHandler : IClientMessageHandler
await HandlePortalUse(connection, session, payload, ct);
break;
case DungeonOpCodes.DUNGEON_INPUT_FIRE_PROJECTILE:
await HandleFireProjectile(connection, session, payload, ct);
break;
case DungeonOpCodes.INVENTORY_REQUEST:
await HandleInventoryRequest(connection, session, ct);
break;
@@ -997,6 +1002,236 @@ public sealed partial class DungeonHandler : IClientMessageHandler
}
}
/// <summary>
/// Handle projectile firing - validates weapon, consumes ammunition, creates projectile
/// </summary>
private async Task HandleFireProjectile(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
if (session.PlayerInstance == null) return;
if (session.State != PlayerState.InDungeon || !session.CurrentDungeonId.HasValue) return;
if (!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) return;
var input = _ser.Deserialize<FireProjectileInput>(payload);
var player = session.PlayerInstance;
// Normalize direction vector
float magnitude = MathF.Sqrt(input.DirectionX * input.DirectionX + input.DirectionY * input.DirectionY);
if (magnitude < 0.01f) return; // Invalid direction
float dirX = input.DirectionX / magnitude;
float dirY = input.DirectionY / magnitude;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Get equipped weapon
var weaponItemId = session.Character.EquippedWeapon;
if (!weaponItemId.HasValue) return;
var weaponItem = await db.DungeonCharacterItems
.Include(i => i.ItemDefinition)
.FirstOrDefaultAsync(i => i.Id == weaponItemId.Value, ct);
if (weaponItem?.ItemDefinition == null) return;
var weapon = weaponItem.ItemDefinition;
// Handle throwable weapons (consume from inventory)
if (weapon.IsThrowable)
{
await HandleThrowableProjectile(session, dungeon, weapon, dirX, dirY, ct);
return;
}
// Handle ranged weapons (require ammunition)
if (!weapon.RequiresAmmunition || weapon.ProjectileSpeed <= 0) return;
// Get ammunition from quiver
var ammo = await ConsumeAmmunitionFromQuiver(session, weapon.AmmunitionType, db, ct);
if (ammo == null)
{
// No ammo available - could send error message to client
_log.LogDebug("Player {Name} tried to fire {Weapon} but has no {AmmoType} ammunition",
session.Character.Name, weapon.Name, weapon.AmmunitionType);
return;
}
// Calculate damage (STR 30% + DEX 70%)
int weaponDamage = Random.Shared.Next(weapon.MinDamage, weapon.MaxDamage + 1);
int ammoDamage = Random.Shared.Next(ammo.MinDamage, ammo.MaxDamage + 1);
int baseDamage = weaponDamage + ammoDamage;
float statModifier = (session.Character.Strength * 0.3f + session.Character.Dexterity * 0.7f);
float statBonus = baseDamage * (statModifier / 100f);
int totalDamage = (int)(baseDamage + statBonus);
// Create projectile
var projectile = new ProjectileInstance
{
Id = dungeon.Simulation.GetNextProjectileId(),
SourceType = ProjectileSource.Player,
SourcePlayerId = session.CharacterId,
X = player.X,
Y = player.Y,
VelocityX = dirX * weapon.ProjectileSpeed,
VelocityY = dirY * weapon.ProjectileSpeed,
Speed = weapon.ProjectileSpeed,
Damage = totalDamage,
DamageTypeKey = weapon.DamageTypeKey,
MaxRange = weapon.ProjectileRange,
DistanceTraveled = 0,
AmmunitionItemDefinitionId = ammo.Id,
RecoveryChance = ammo.ArrowRecoveryChance,
CanHitMobs = true,
CanHitPlayers = false, // TODO: PvP support
SpriteKey = ammo.SpritePath ?? "projectile_arrow"
};
dungeon.Simulation.Projectiles.TryAdd(projectile.Id, projectile);
// Broadcast projectile spawned
foreach (var dungeonPlayer in dungeon.Simulation.Players.Values)
{
var playerSession = _playerSessions.Values.FirstOrDefault(p => p.CharacterId == dungeonPlayer.CharacterId);
if (playerSession != null)
{
_ = SendAsync(playerSession.Connection, DungeonOpCodes.EVENT_PROJECTILE_SPAWNED, new
{
id = projectile.Id,
sourceType = "player",
sourceId = session.CharacterId,
x = projectile.X,
y = projectile.Y,
vx = projectile.VelocityX,
vy = projectile.VelocityY,
sprite = projectile.SpriteKey
}, CancellationToken.None);
}
}
_log.LogDebug("Player {Name} fired projectile with {Weapon} using {Ammo} for {Damage} damage",
session.Character.Name, weapon.Name, ammo.Name, totalDamage);
}
private async Task HandleThrowableProjectile(DungeonPlayerSession session, DungeonInstance dungeon, DungeonItemDefinition weapon, float dirX, float dirY, CancellationToken ct)
{
// Throwables consume from inventory
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var throwableStack = await db.DungeonCharacterItems
.FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId &&
i.ItemDefinitionId == weapon.Id &&
i.Quantity > 0, ct);
if (throwableStack == null) return;
// Consume one
throwableStack.Quantity--;
if (throwableStack.Quantity <= 0)
{
db.DungeonCharacterItems.Remove(throwableStack);
}
await db.SaveChangesAsync(ct);
// Calculate damage
int baseDamage = Random.Shared.Next(weapon.MinDamage, weapon.MaxDamage + 1);
float statModifier = (session.Character.Strength * 0.3f + session.Character.Dexterity * 0.7f);
float statBonus = baseDamage * (statModifier / 100f);
int totalDamage = (int)(baseDamage + statBonus);
// Create projectile
var projectile = new ProjectileInstance
{
Id = dungeon.Simulation.GetNextProjectileId(),
SourceType = ProjectileSource.Player,
SourcePlayerId = session.CharacterId,
X = session.PlayerInstance!.X,
Y = session.PlayerInstance.Y,
VelocityX = dirX * weapon.ProjectileSpeed,
VelocityY = dirY * weapon.ProjectileSpeed,
Speed = weapon.ProjectileSpeed,
Damage = totalDamage,
DamageTypeKey = weapon.DamageTypeKey,
MaxRange = weapon.ProjectileRange,
DistanceTraveled = 0,
AmmunitionItemDefinitionId = weapon.Id,
RecoveryChance = weapon.ArrowRecoveryChance,
CanHitMobs = true,
CanHitPlayers = false,
SpriteKey = weapon.SpritePath ?? "projectile_knife"
};
dungeon.Simulation.Projectiles.TryAdd(projectile.Id, projectile);
foreach (var dungeonPlayer in dungeon.Simulation.Players.Values)
{
var playerSession = _playerSessions.Values.FirstOrDefault(p => p.CharacterId == dungeonPlayer.CharacterId);
if (playerSession != null)
{
_ = SendAsync(playerSession.Connection, DungeonOpCodes.EVENT_PROJECTILE_SPAWNED, new
{
id = projectile.Id,
sourceType = "player",
sourceId = session.CharacterId,
x = projectile.X,
y = projectile.Y,
vx = projectile.VelocityX,
vy = projectile.VelocityY,
sprite = projectile.SpriteKey
}, CancellationToken.None);
}
}
}
private async Task<DungeonItemDefinition?> ConsumeAmmunitionFromQuiver(DungeonPlayerSession session, string? ammoType, GameDbContext db, CancellationToken ct)
{
if (string.IsNullOrEmpty(ammoType)) return null;
var quiverItemId = session.Character.EquippedQuiver;
if (!quiverItemId.HasValue) return null;
var quiverItem = await db.DungeonCharacterItems
.Include(i => i.ItemDefinition)
.FirstOrDefaultAsync(i => i.Id == quiverItemId.Value, ct);
if (quiverItem?.ItemDefinition == null) return null;
// Check if it's a quiver container
if (quiverItem.ItemDefinition.QuiverCapacity > 0)
{
// Quiver container - find ammunition in slots
var ammoSlot = await db.DungeonQuiverAmmoSlots
.Include(s => s.ItemDefinition)
.Where(s => s.QuiverCharacterItemId == quiverItemId.Value && s.Quantity > 0)
.OrderBy(s => s.SlotIndex)
.FirstOrDefaultAsync(ct);
if (ammoSlot?.ItemDefinition == null) return null;
// Consume one
ammoSlot.Quantity--;
await db.SaveChangesAsync(ct);
return ammoSlot.ItemDefinition;
}
else
{
// Direct ammo equip (stack of arrows in quiver slot)
if (quiverItem.Quantity <= 0) return null;
quiverItem.Quantity--;
if (quiverItem.Quantity <= 0)
{
// Unequip when empty
session.Character.EquippedQuiver = null;
db.DungeonCharacterItems.Remove(quiverItem);
}
await db.SaveChangesAsync(ct);
return quiverItem.ItemDefinition;
}
}
/// <summary>
/// Handle portal use - instant extraction when player clicks/walks into portal
/// </summary>
@@ -2965,8 +3200,10 @@ public sealed partial class DungeonHandler : IClientMessageHandler
DungeonEquipmentSlot.Legs => "legs",
DungeonEquipmentSlot.Boots => "boots",
DungeonEquipmentSlot.Gloves => "gloves",
DungeonEquipmentSlot.Accessory1 => "ring1",
DungeonEquipmentSlot.Accessory2 => "ring2",
DungeonEquipmentSlot.Necklace => "necklace",
DungeonEquipmentSlot.Ring1 => "ring1",
DungeonEquipmentSlot.Ring2 => "ring2",
DungeonEquipmentSlot.Quiver => "quiver",
_ => "unknown"
};
@@ -3126,8 +3363,10 @@ public sealed partial class DungeonHandler : IClientMessageHandler
"legs" => DungeonEquipmentSlot.Legs,
"boots" => DungeonEquipmentSlot.Boots,
"gloves" => DungeonEquipmentSlot.Gloves,
"ring1" => DungeonEquipmentSlot.Accessory1,
"ring2" => DungeonEquipmentSlot.Accessory2,
"necklace" => DungeonEquipmentSlot.Necklace,
"ring1" => DungeonEquipmentSlot.Ring1,
"ring2" => DungeonEquipmentSlot.Ring2,
"quiver" => DungeonEquipmentSlot.Quiver,
_ => (DungeonEquipmentSlot?)null
};
@@ -3265,7 +3504,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler
{
ItemType.Weapon => item.EquipSlot ?? DungeonEquipmentSlot.MainHand,
ItemType.Armor => item.EquipSlot ?? DungeonEquipmentSlot.Chest,
ItemType.Accessory => DungeonEquipmentSlot.Accessory1,
ItemType.Accessory => DungeonEquipmentSlot.Ring1, // Default to Ring1, but check if already equipped
_ => null
};
}
@@ -4295,4 +4534,10 @@ public class StashWithdrawRequest
public int Quantity { get; set; } = 1;
}
public class FireProjectileInput
{
public float DirectionX { get; set; }
public float DirectionY { get; set; }
}
#endregion
+109 -27
View File
@@ -488,6 +488,7 @@ public partial class DungeonSimulation
var projectile = new ProjectileInstance
{
Id = GetNextProjectileId(),
SourceType = ProjectileSource.Mob,
SourceMobId = mob.Id,
AbilityId = ability.Id,
X = mob.X,
@@ -498,9 +499,11 @@ public partial class DungeonSimulation
Damage = ability.BaseDamage,
DamageTypeKey = ability.DamageTypeKey,
AoeRadius = ability.AoeRadius,
SpriteKey = ability.ProjectileSprite ?? "projectile_default"
SpriteKey = ability.ProjectileSprite ?? "projectile_default",
CanHitPlayers = true,
CanHitMobs = false
};
// Calculate direction
float dx = target.X - mob.X;
float dy = target.Y - mob.Y;
@@ -510,56 +513,135 @@ public partial class DungeonSimulation
projectile.VelocityX = (dx / dist) * ability.ProjectileSpeed;
projectile.VelocityY = (dy / dist) * ability.ProjectileSpeed;
}
Projectiles[projectile.Id] = projectile;
}
private void UpdateProjectiles()
{
var toRemove = new List<int>();
foreach (var projectile in Projectiles.Values)
{
// Move projectile
projectile.X += projectile.VelocityX * TickDelta;
projectile.Y += projectile.VelocityY * TickDelta;
projectile.DistanceTraveled += MathF.Sqrt(
projectile.VelocityX * projectile.VelocityX +
projectile.VelocityX * projectile.VelocityX +
projectile.VelocityY * projectile.VelocityY) * TickDelta;
// Check max range
if (projectile.DistanceTraveled > 500)
if (projectile.MaxRange > 0 && projectile.DistanceTraveled > projectile.MaxRange)
{
toRemove.Add(projectile.Id);
continue;
}
// Check collision with players
foreach (var player in Players.Values.Where(p => p.IsAlive))
// Handle player projectiles hitting mobs
if (projectile.SourceType == ProjectileSource.Player && projectile.CanHitMobs)
{
if (Distance(projectile.X, projectile.Y, player.X, player.Y) < 20)
foreach (var mob in Mobs.Values.Where(m => m.IsAlive))
{
// Hit!
if (projectile.AoeRadius > 0)
if (Distance(projectile.X, projectile.Y, mob.X, mob.Y) < 20)
{
// AOE explosion
ProcessAoeAbilityAtLocation(projectile, projectile.X, projectile.Y);
}
else
{
// Single target
if (Mobs.TryGetValue(projectile.SourceMobId, out var sourceMob))
// Get player instance for damage calculation
PlayerInstance? sourcePlayer = null;
if (Players.TryGetValue(projectile.SourcePlayerId, out var playerInst))
{
var result = CombatCalculator.CalculateMobToPlayerDamage(
sourceMob, player, projectile.DamageTypeKey, projectile.Damage, player.Resistances);
ApplyDamageToPlayer(sourceMob, player, result.FinalDamage, projectile.DamageTypeKey, result.WasResisted, result.WasWeakness);
sourcePlayer = playerInst;
}
// Apply damage with resistances
int finalDamage = projectile.Damage;
if (sourcePlayer != null)
{
var result = CombatCalculator.CalculatePlayerToMobDamage(
sourcePlayer, mob, projectile.DamageTypeKey, projectile.Damage);
finalDamage = result.FinalDamage;
_pendingDamageEvents.Add(new DamageEvent
{
SourceType = EntityType.Player,
SourceId = (int)sourcePlayer.CharacterId,
TargetType = EntityType.Mob,
TargetId = mob.Id,
Damage = result.FinalDamage,
DamageTypeKey = projectile.DamageTypeKey,
WasResisted = result.WasResisted,
WasWeakness = result.WasWeakness
});
}
else
{
// Fallback if player not found (they disconnected)
_pendingDamageEvents.Add(new DamageEvent
{
SourceType = EntityType.Player,
SourceId = (int)projectile.SourcePlayerId,
TargetType = EntityType.Mob,
TargetId = mob.Id,
Damage = projectile.Damage,
DamageTypeKey = projectile.DamageTypeKey
});
}
mob.Health -= finalDamage;
// Try to recover ammunition
// TODO: Implement arrow recovery - add to LootService or mob's carried items
// For now, skip recovery - will implement in loot system integration
// Check if mob died
if (mob.Health <= 0 && mob.IsAlive)
{
mob.IsAlive = false;
_pendingDeathEvents.Add(new DeathEvent
{
EntityType = EntityType.Mob,
EntityId = mob.Id,
EntityName = mob.Name,
KillerType = EntityType.Player,
KillerId = (int)projectile.SourcePlayerId,
KillerName = sourcePlayer?.CharacterName ?? "Unknown",
XpReward = 0 // Will be calculated in handler
});
}
toRemove.Add(projectile.Id);
break;
}
toRemove.Add(projectile.Id);
break;
}
}
// Handle mob projectiles hitting players
if (projectile.SourceType == ProjectileSource.Mob && projectile.CanHitPlayers)
{
foreach (var player in Players.Values.Where(p => p.IsAlive))
{
if (Distance(projectile.X, projectile.Y, player.X, player.Y) < 20)
{
// Hit!
if (projectile.AoeRadius > 0)
{
// AOE explosion
ProcessAoeAbilityAtLocation(projectile, projectile.X, projectile.Y);
}
else
{
// Single target
if (Mobs.TryGetValue(projectile.SourceMobId, out var sourceMob))
{
var result = CombatCalculator.CalculateMobToPlayerDamage(
sourceMob, player, projectile.DamageTypeKey, projectile.Damage, player.Resistances);
ApplyDamageToPlayer(sourceMob, player, result.FinalDamage, projectile.DamageTypeKey, result.WasResisted, result.WasWeakness);
}
}
toRemove.Add(projectile.Id);
break;
}
}
}
// Check wall collision
if (!CanMoveTo(projectile.X, projectile.Y))
{
@@ -570,7 +652,7 @@ public partial class DungeonSimulation
toRemove.Add(projectile.Id);
}
}
foreach (var id in toRemove)
{
Projectiles.TryRemove(id, out _);
+39 -7
View File
@@ -1,31 +1,63 @@
namespace GameServer.Dungeon;
public enum ProjectileSource
{
Mob,
Player
}
/// <summary>
/// A projectile in flight
/// </summary>
public class ProjectileInstance
{
public int Id { get; set; }
public int SourceMobId { get; set; }
public int AbilityId { get; set; }
// Source tracking
public ProjectileSource SourceType { get; set; }
public int SourceMobId { get; set; } // Used when SourceType = Mob
public ulong SourcePlayerId { get; set; } // Used when SourceType = Player
public int AbilityId { get; set; } // For mob abilities
public float X { get; set; }
public float Y { get; set; }
public float VelocityX { get; set; }
public float VelocityY { get; set; }
public float Speed { get; set; }
public float TargetX { get; set; }
public float TargetY { get; set; }
public int Damage { get; set; }
public string DamageTypeKey { get; set; } = "physical";
public float AoeRadius { get; set; }
public float DistanceTraveled { get; set; }
public float MaxRange { get; set; } = 500f;
public string SpriteKey { get; set; } = "projectile_default";
// Player projectile properties
/// <summary>
/// Item definition ID of the ammunition used (for recovery)
/// Null if not recoverable (mob projectiles, throwables that don't recover)
/// </summary>
public int? AmmunitionItemDefinitionId { get; set; }
/// <summary>
/// Recovery chance (0.0 to 1.0) for this specific projectile
/// </summary>
public float RecoveryChance { get; set; } = 0.05f;
/// <summary>
/// Whether this projectile can hit players (for PvP)
/// </summary>
public bool CanHitPlayers { get; set; } = false;
/// <summary>
/// Whether this projectile can hit mobs
/// </summary>
public bool CanHitMobs { get; set; } = true;
}
/// <summary>