import { Component } from "../ecs/components.js"; import { itemDefinition } from "../../../shared/definitions/items.js"; import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js"; import { mobDefinition, isTownGuardMob } from "../../../shared/definitions/mobs.js"; import { mobCanFightType, mobCanFight, mobMeleeAttackProfile, mobSkillLevels, mobIsAggressive, mobAggroRangeTiles, mobIsBoss } from "../../../shared/definitions/mobCombat.js"; import { combatLevelFromSkills, mobAggressionLevel, playerOutlevelsMobAggression } from "../../../shared/combat/combatLevel.js"; import { chunkPeaceAggressionImmunity } from "../../../shared/navigation/chunkPresence.js"; import { skullAttractsTownGuards } from "../../../shared/combat/skull.js"; import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js"; import { spellDefinition, spellMinMagicLevel } from "../../../shared/definitions/spells.js"; import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js"; import { mobDamageAffinities } from "../../../shared/combat/magic.js"; import { AttackType } from "../../../shared/definitions/attackTypes.js"; import { isMagicStaffEquipped, firstFavoriteAttackSpellId } from "../../../shared/combat/maxHit.js"; import { canCastSpell } from "../../../shared/spells/state.js"; import { effectiveHitSkillInDarkness, aggroDistanceMultiplier } from "../../../shared/combat/darkness.js"; import { entityLightAtTile, tileCombatLight01, tileIndexLocal } from "../../../shared/lighting/combatLight.js"; import { blockLightSourcesNearTile } from "../../../shared/lighting/blockLights.js"; import { dynamicDarknessAtTile, dynamicLightAtTile, rayReaches } from "../../../shared/lighting/raycast.js"; import { LightOcclusion } from "../../../shared/definitions/tiles.js"; import { tileLightOcclusionAt } from "../../../shared/lighting/chunkOcclusion.js"; import { spellLightsForDynamicLighting } from "../spells/lights.js"; import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js"; import { effectiveSkillLevel, equipmentBonusesFromSlots } from "../../../shared/equipment/stats.js"; import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js"; import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS, SPELL_COOLDOWN_MS } from "../../../shared/spells/constants.js"; import { markHealthDamaged, PASSIVE_HP_REGEN_DELAY_MS, PASSIVE_HP_REGEN_PER_SECOND } from "../../../shared/combat/passiveRegen.js"; import { publicEntityView } from "../ecs/serialize.js"; import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js"; import { chunkBoundsAround, findPath } from "../navigation/astar.js"; import { tileToChunk } from "../world/coordinates.js"; import { findPathToNearestGoal } from "../../../shared/navigation/bfs.js"; import { withCombatBackstepCost } from "../../../shared/navigation/combatPathCost.js"; import { CHUNK_SIZE, GAIT, VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js"; import { stackQuantity, insertStack } from "../../../shared/items/inventory.js"; import { placeOrMergeGroundStack, bagView } from "../items/bags.js"; import { resolveItemDualTint } from "../../../shared/render/tint.js"; import { essenceItemIdForElement } from "../../../shared/definitions/essenceItems.js"; import { castMobAttackSpell } from "../spells/mobCast.js"; import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js"; import { scheduleSpawnerRespawn } from "../simulation/spawners.js"; import { passiveHpRegenMultiplier, attackerToHitRng, enemyToHitRngAgainst, hitSkillBonus, jewelryDamageAffinities, mergeAffinities, damageReflectFraction, autoLootOnKill, ignoresNonBossAggro, JADEITE_FAIRY_RESPAWN_MS } from "../../../shared/equipment/jewelryEffects.js"; export function chebyshev (ax, ay, bx, by) { return Math.max(Math.abs(ax - bx), Math.abs(ay - by)); } /** Creatures run while closing; they walk the last two tiles (and when standing to attack). */ export const COMBAT_CHASE_RUN_TILES = 2; function creatureCanRun (world, handle) { const stamina = world.ecs.get(handle, Component.stamina); if (!stamina) { return true; } return Number(stamina.current) > 0; } function isCombatCreature (world, handle) { return !!world.ecs.get(handle, Component.creature) && !world.ecs.get(handle, Component.character); } function syncCreatureChaseGait (world, handle, dist, chasing) { if (!isCombatCreature(world, handle)) { return; } const movement = world.ecs.get(handle, Component.movement); if (!movement) { return; } if (chasing && dist > COMBAT_CHASE_RUN_TILES && creatureCanRun(world, handle)) { movement.gait = GAIT.run; } else { movement.gait = GAIT.walk; } } function dropCombatTarget (world, entity) { entity.combat.targetEntityId = null; syncCreatureChaseGait(world, entity.handle, 0, false); } /** Euclidean (hemelsbreed) distance from spawn origin for combat leash. */ export function spawnOriginDistance (position, origin) { const ox = Number.isInteger(origin?.originTileX) ? origin.originTileX : (position.tileX | 0); const oy = Number.isInteger(origin?.originTileY) ? origin.originTileY : (position.tileY | 0); return Math.hypot((position.tileX | 0) - ox, (position.tileY | 0) - oy); } /** Break chase at max(3× wander, wander + spell/ranged combat range) from the spawner. */ export function combatLeashLimit (wanderRangeTiles) { const wander = Math.max(0, wanderRangeTiles | 0); return Math.max(wander * 3, wander + COMBAT_RANGE_TILES); } function creatureWithinWanderHome (world, handle, position) { const origin = world.ecs.get(handle, Component.spawnOrigin); if (!origin) { return true; } const range = Math.max(0, origin.wanderRangeTiles | 0); const ox = Number.isInteger(origin.originTileX) ? origin.originTileX : (position.tileX | 0); const oy = Number.isInteger(origin.originTileY) ? origin.originTileY : (position.tileY | 0); const chebyshevHome = Math.max( Math.abs((position.tileX | 0) - ox), Math.abs((position.tileY | 0) - oy) ); return chebyshevHome <= range; } /** * Spawner creatures break combat beyond their leash (euclidean). * Ambient mobs without spawnOrigin are not leashed. */ function creatureShouldBreakCombatLeash (world, handle, position) { if (!isCombatCreature(world, handle)) { return false; } if (world.ecs.get(handle, Component.summon)) { return false; } const origin = world.ecs.get(handle, Component.spawnOrigin); if (!origin) { return false; } const range = Math.max(0, origin.wanderRangeTiles | 0); return spawnOriginDistance(position, origin) > combatLeashLimit(range); } function beginCombatLeashReturn (world, entity) { const combat = entity.combat; combat.targetEntityId = null; combat.leashing = true; combat.seekCover = false; combat.fleeFrom = null; clearCombatApproachPath(world.ecs, entity.handle); syncCreatureChaseGait(world, entity.handle, 0, false); } function clearLeashingIfHome (world, entity) { const combat = entity.combat; if (!combat?.leashing) { return; } if (creatureWithinWanderHome(world, entity.handle, entity.position)) { combat.leashing = false; } } /** * Stop everyone who was attacking / auto-casting at `targetEntityId` * (melee engage, spell repeat, pending cast, approach path). */ export function clearAttackersTargeting (ecs, targetEntityId) { const targetId = targetEntityId | 0; if (!targetId) { return; } for (const entity of ecs.query(Component.combat)) { if (entity.combat.targetEntityId !== targetId) { continue; } entity.combat.targetEntityId = null; entity.combat.seekCover = false; entity.combat.fleeFrom = null; clearCombatApproachPath(ecs, entity.handle); } for (const entity of ecs.query(Component.spellcasting)) { const casting = entity.spellcasting; if (!casting) { continue; } const pendingTarget = casting.pendingCast?.targetEntityId; const hitting = casting.repeatTargetEntityId === targetId || (pendingTarget != null && (pendingTarget | 0) === targetId); if (!hitting) { continue; } casting.repeatSpellId = null; casting.repeatTargetEntityId = null; casting.repeatTileX = null; casting.repeatTileY = null; casting.pendingCast = null; clearCombatApproachPath(ecs, entity.handle); } } export function attackProfileOf (ecs, handle) { const creature = ecs.get(handle, Component.creature); const level = creatureLevel(ecs, handle); const equipment = ecs.get(handle, Component.equipment); const weapon = equipment?.slots?.weapon; if (weapon?.itemId != null) { const attack = itemDefinition(weapon.itemId)?.equipment?.attack; if (attack) { const profile = { ...attack }; if (creature) { profile.mobAttackSkill = level; } return profile; } } if (creature) { const def = mobDefinition(creature.mobTypeId); if (mobCanFightType(creature.mobTypeId)) { return mobMeleeAttackProfile(def, level); } } return { ...UNARMED_ATTACK }; } function creatureLevel (ecs, handle) { const creature = ecs.get(handle, Component.creature); if (!creature) { return 1; } if (creature.level != null) { return Math.max(1, creature.level | 0 || 1); } const origin = ecs.get(handle, Component.spawnOrigin); if (origin?.level != null) { return Math.max(1, origin.level | 0 || 1); } const def = mobDefinition(creature.mobTypeId); return Math.max(1, def?.attackSkill | 0 || 1); } export function weaponEquipmentKind (ecs, handle) { const equipment = ecs.get(handle, Component.equipment); const weapon = equipment?.slots?.weapon; if (!weapon?.itemId) { return null; } return itemDefinition(weapon.itemId)?.equipment?.kind ?? null; } export function ensureMobCombat (ecs, entityId) { const handle = ecs.handleOf(entityId); if (handle == null) { return false; } const creature = ecs.get(handle, Component.creature); if (!creature || !mobCanFightType(creature.mobTypeId)) { return false; } const def = mobDefinition(creature.mobTypeId); const level = creatureLevel(ecs, handle); if (!ecs.get(handle, Component.combat)) { ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0, seekCover: false, fleeFrom: null }); } if (!ecs.get(handle, Component.skills)) { ecs.add(handle, Component.skills, { levels: mobSkillLevels(def, level) }); } return true; } /** Spawner Passive: take hits but do not enter combat / retaliate. Aggressive overrides. */ export function entityIsPassive (ecs, handle) { const origin = ecs.get(handle, Component.spawnOrigin); if (!origin?.passive) { return false; } if (origin.aggressive) { return false; } return true; } function attackerSkillLevel (skills, profile, skillId) { if (profile.mobAttackSkill != null) { return profile.mobAttackSkill; } return skillLevel(skills, skillId); } function defenderSkillLevel (skills, skillId, equipment = null, settings = null) { const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots, settings) : {}; return effectiveSkillLevel(skills, skillId, bonuses); } function playerCombatLevels (ecs, handle, profile, settings = null) { const skills = ecs.get(handle, Component.skills); const equipment = ecs.get(handle, Component.equipment); const bonuses = equipmentBonusesFromSlots(equipment?.slots, settings); const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now()); bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0); bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0); return { hitLevel: effectiveSkillLevel(skills, profile.hitSkillId ?? SkillId.unarmed, bonuses) + hitSkillBonus(equipment), damageLevel: effectiveSkillLevel(skills, profile.damageSkillId ?? SkillId.strength, bonuses), agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses), defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses) }; } export function isUntargetable (ecs, handle) { if (ecs.has(handle, Component.dead)) { return true; } const creature = ecs.get(handle, Component.creature); if (!creature) { return false; } return !!mobDefinition(creature.mobTypeId)?.untargetable; } /** Stop active combat / cast / path activity when a player dies. * Auto-cast preference is kept so respawn + re-cast can resume repeating. */ export function silenceDeadPlayer (ecs, handle) { if (handle == null) { return; } const entityId = ecs.entityIdOf(handle); if (entityId != null) { clearEngage(ecs, entityId); } const path = ecs.get(handle, Component.path); if (path) { path.tiles = []; } const follow = ecs.get(handle, Component.follow); if (follow) { follow.targetEntityId = null; follow.trail = []; } const casting = ecs.get(handle, Component.spellcasting); if (casting) { casting.armedSpellId = null; casting.repeatSpellId = null; casting.repeatTargetEntityId = null; casting.repeatTileX = null; casting.repeatTileY = null; casting.pendingCast = null; } } /** * Player is mid click-order (walk / harvest) — do not auto-retaliate or * cancel that order when a mob swings. */ export function playerBusyWithClickOrder (ecs, handle) { if (handle == null) { return false; } if (ecs.has(handle, Component.gather)) { return true; } const path = ecs.get(handle, Component.path); return !!(path?.tiles?.length); } /** * Staff with a favorited attack spell → entity auto-cast at the attacker; * otherwise melee engage. Returns true when a response was started. */ /** * Staff + favorite entity attack spell: arm auto-cast at the target instead of melee engage. * Used by click-Attack and auto-retaliate so casters hold spell range. */ export function tryArmStaffSpellAttack (ecs, playerId, targetEntityId) { const handle = ecs.handleOf(playerId); if (handle == null) { return false; } const equipment = ecs.get(handle, Component.equipment); const spells = ecs.get(handle, Component.spells); const skills = ecs.get(handle, Component.skills); let casting = ecs.get(handle, Component.spellcasting); if (!casting && spells) { casting = ecs.add(handle, Component.spellcasting, { armedSpellId: null, repeatSpellId: null, repeatTargetEntityId: null, repeatTileX: null, repeatTileY: null, nextCastAt: 0, pendingCast: null }); } if (!(isMagicStaffEquipped(equipment?.slots) && casting && spells && skills)) { return false; } const spellId = firstFavoriteAttackSpellId(spells); const def = spellId ? spellDefinition(spellId) : null; if ( !( spellId && def?.target === "entity" && def.autoRepeat && canCastSpell(skills, spells, spellId).ok ) ) { return false; } casting.repeatSpellId = spellId; casting.repeatTargetEntityId = targetEntityId | 0; casting.repeatTileX = null; casting.repeatTileY = null; casting.pendingCast = null; const combat = ecs.get(handle, Component.combat); if (combat) { combat.targetEntityId = null; } const path = ecs.get(handle, Component.path); if (path) { path.tiles = []; } return true; } export function maybePlayerRetaliate (world, playerId, attackerId, now = Date.now()) { const ecs = world.ecs; const handle = ecs.handleOf(playerId); if (handle == null || ecs.has(handle, Component.dead)) { return false; } if (playerBusyWithClickOrder(ecs, handle)) { return false; } if (isSpellCombatBusy(ecs, handle)) { return false; } const follow = ecs.get(handle, Component.follow); if (follow) { follow.targetEntityId = null; follow.trail = []; } if (ecs.has(handle, Component.gather)) { ecs.remove(handle, Component.gather); } if (tryArmStaffSpellAttack(ecs, playerId, attackerId)) { return true; } return engageTarget(ecs, playerId, attackerId, now); } export function engageTarget (ecs, attackerId, targetId, now = Date.now()) { const handle = ecs.handleOf(attackerId); if (handle == null) { return false; } if (ecs.has(handle, Component.dead)) { return false; } const targetHandle = ecs.handleOf(targetId); if (targetHandle != null && ecs.has(targetHandle, Component.dead)) { return false; } // Spell auto-cast / pending cast is already the active combat form. if (isSpellCombatBusy(ecs, handle)) { return false; } let combat = ecs.get(handle, Component.combat); if (!combat) { combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0, seekCover: false, fleeFrom: null }); } const targetChanged = combat.targetEntityId !== targetId; combat.targetEntityId = targetId; combat.leashing = false; if (targetChanged) { // New engage (or switch): allow an immediate swing; keep cadence if already on this target. combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now); const path = ecs.get(handle, Component.path); if (path) { path.tiles = []; } } return true; } /** Melee mobs shot by player ranged/spells prefer cover while closing. */ export function markSeekCover (ecs, entityId) { const handle = ecs.handleOf(entityId); const combat = handle != null ? ecs.get(handle, Component.combat) : null; if (combat) { combat.seekCover = true; } } /** * Flee-on-hit mobs (fairies) path away from the hit source until far enough, * then stop fleeing until the next successful hit. */ export function markFleeOnHit (world, targetId, attackerId) { const ecs = world.ecs; const targetHandle = ecs.handleOf(targetId); if (targetHandle == null) { return; } const creature = ecs.get(targetHandle, Component.creature); if (!creature || ecs.get(targetHandle, Component.character)) { return; } // Companion summons (jadeite fairy, shade) stay in the fight. if (ecs.get(targetHandle, Component.summon)) { return; } const fleeDist = mobDefinition(creature.mobTypeId)?.fleeOnHitTiles | 0; if (fleeDist <= 0) { return; } if (!ensureMobCombat(ecs, targetId)) { return; } const combat = ecs.get(targetHandle, Component.combat); const targetPos = ecs.get(targetHandle, Component.position); const attackerHandle = ecs.handleOf(attackerId); const attackerPos = attackerHandle != null ? ecs.get(attackerHandle, Component.position) : null; if (!combat || !targetPos || !attackerPos) { return; } if (chebyshev(targetPos.tileX, targetPos.tileY, attackerPos.tileX, attackerPos.tileY) >= fleeDist) { combat.fleeFrom = null; return; } combat.fleeFrom = { tileX: attackerPos.tileX, tileY: attackerPos.tileY, minDist: fleeDist }; const path = ecs.get(targetHandle, Component.path); if (path) { path.tiles = []; } } /** Pending cast or entity-spell auto-repeat — physical combat must not run. */ export function isSpellCombatBusy (ecs, handle) { const casting = ecs.get(handle, Component.spellcasting); if (!casting) { return false; } if (casting.pendingCast) { return true; } if (!casting.repeatSpellId) { return false; } const def = spellDefinition(casting.repeatSpellId); return def?.target === "entity"; } function clearSpellCombatState (ecs, handle) { const casting = ecs.get(handle, Component.spellcasting); if (!casting) { return; } casting.repeatSpellId = null; casting.repeatTargetEntityId = null; casting.repeatTileX = null; casting.repeatTileY = null; casting.pendingCast = null; } export function clearEngage (ecs, entityId) { const handle = ecs.handleOf(entityId); const combat = handle != null ? ecs.get(handle, Component.combat) : null; if (combat) { combat.targetEntityId = null; combat.seekCover = false; combat.fleeFrom = null; } } export function hasCombatLineOfSight (world, fromX, fromY, toX, toY, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const isClear = world.isClearForRangedAttack ? (x, y) => world.isClearForRangedAttack(x, y, dim) : (x, y) => world.isEnterable(x, y, dim); return rayReaches(fromX, fromY, toX, toY, isClear); } function lightOcclusionAtWorld (world, x, y, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const data = world.chunkData?.(tileToChunk(x), tileToChunk(y), dim); if (!data) { return LightOcclusion.clear; } const index = tileIndexLocal(x, y); if (Array.isArray(data.occlusion) && data.occlusion.length > index) { return data.occlusion[index] | 0; } const localX = ((x % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE; const localY = ((y % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE; return tileLightOcclusionAt(data.grounds, data.blocks, localX, localY); } /** * Target-tile lighting 0–1 for combat. * Block lights (torches, …) use live occlusion so passage-open doors let light through; * entity/spell lights layer on top (same compositing as client inner 3×3). */ export function tileLightAt (world, tileX, tileY, now = Date.now(), dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const occlusionAt = (x, y) => lightOcclusionAtWorld(world, x, y, dim); const blockSources = blockLightSourcesNearTile( (chunkX, chunkY) => world.chunkData?.(chunkX, chunkY, dim), tileX, tileY ); const blockLit = dynamicLightAtTile(tileX, tileY, blockSources, occlusionAt); const entity = entityLightAtTile(world.ecs, Component, tileX, tileY, now); const { lights, darks } = spellLightsForDynamicLighting(world.spellLights, now, dim); const spellLight = dynamicLightAtTile(tileX, tileY, lights, occlusionAt); const spellDark = dynamicDarknessAtTile(tileX, tileY, darks, occlusionAt); const worldTime = world.worldTime?.(now); return tileCombatLight01({ bakedLight01: blockLit, entityLight01: entity, spellLight01: spellLight, spellDark01: spellDark, worldHour: worldTime?.hour ?? 12, nightDarkness: world.settings?.nightDarkness ?? 0.72 }); } function arrowStackInOffhand (equipment) { const stack = equipment?.slots?.offhand; if (!stack) { return null; } const def = itemDefinition(stack.itemId); if (def?.equipment?.kind !== EquipmentKind.arrowAmmo) { return null; } return stack; } /** Physical attack type, or tipped-arrow element for ranged shots. */ function resolveAttackDamageType (ecs, attackerHandle, profile) { if (attackerHandle != null && profile?.mode === "ranged") { const stack = arrowStackInOffhand(ecs.get(attackerHandle, Component.equipment)); if (stack?.instance?.kind === "tipped-arrow" && stack.instance.element) { return stack.instance.element; } } return profile?.attackType ?? AttackType.blunt; } function consumeArrow (ecs, handle) { const equipment = ecs.get(handle, Component.equipment); const stack = arrowStackInOffhand(equipment); if (!stack || stackQuantity(stack.quantity) <= 0) { return false; } if (stackQuantity(stack.quantity) <= 1) { equipment.slots.offhand = null; } else { stack.quantity = stackQuantity(stack.quantity) - 1; } return true; } /** Fixed `quantity`, or inclusive `quantityMin`/`quantityMax` range (default 1). */ function rollDropQuantity (drop) { if (drop.quantityMin != null || drop.quantityMax != null) { const min = Math.max(0, Math.floor(Number(drop.quantityMin ?? 1))); const max = Math.max(min, Math.floor(Number(drop.quantityMax ?? min))); return min + Math.floor(Math.random() * (max - min + 1)); } return Math.max(1, Math.floor(Number(drop.quantity ?? 1))); } function spawnMobDrops (world, targetHandle, tileX, tileY, now, attackerId = null) { const creature = world.ecs.get(targetHandle, Component.creature); if (!creature) { return []; } // Summons (e.g. Shade spell) never drop loot — only wild / spawner mobs. if (world.ecs.get(targetHandle, Component.summon)) { return []; } const def = mobDefinition(creature.mobTypeId); const mobName = entityCombatDisplayName(world.ecs, targetHandle) || def?.displayName || "a creature"; let killerName = "someone"; if (attackerId != null) { const attackerHandle = world.ecs.handleOf(attackerId); if (attackerHandle != null) { killerName = entityCombatDisplayName(world.ecs, attackerHandle) || "someone"; } } const origin = lootOrigin(mobName, killerName); const events = []; const spawnOrigin = world.ecs.get(targetHandle, Component.spawnOrigin); const customDrops = Array.isArray(spawnOrigin?.drops) ? spawnOrigin.drops : []; /** Spawner loot picker replaces the mob's default table when any lines are set. */ const dropTable = [ ...(customDrops.length > 0 ? customDrops : (def?.drops ?? [])) ]; if (creature.element && (def?.essenceDropChance ?? 0) > 0) { const essenceId = essenceItemIdForElement(creature.element); if (essenceId) { dropTable.push({ itemId: essenceId, chance: def.essenceDropChance }); } } for (const drop of dropTable) { if (Math.random() > (drop.chance ?? 1)) { continue; } const quantity = rollDropQuantity(drop); if (quantity <= 0) { continue; } const stack = attachOrigins({ itemId: drop.itemId, quantity, origins: [{ origin, quantity }] }); if (tryAutoLootToKiller(world, attackerId, stack, events)) { continue; } const targetPos = world.ecs.get(targetHandle, Component.position); const placed = placeOrMergeGroundStack(world, { tileX, tileY, dimensionId: normalizeDimensionId(targetPos?.dimensionId ?? OVERWORLD_ID), stack, now, source: "mob-drop" }); events.push(...placed.events); } return events; } function tryAutoLootToKiller (world, attackerId, stack, events) { if (attackerId == null) { return false; } const attackerHandle = world.ecs.handleOf(attackerId); if (attackerHandle == null) { return false; } const equipment = world.ecs.get(attackerHandle, Component.equipment); if (!autoLootOnKill(equipment)) { return false; } const inventory = world.ecs.get(attackerHandle, Component.inventory); const character = world.ecs.get(attackerHandle, Component.character); const def = itemDefinition(stack.itemId); if (!inventory || !character || !def) { return false; } const inserted = insertStack(inventory.slots, stack, def); if (!inserted.ok || (inserted.remainder | 0) > 0) { return false; } inventory.slots = inserted.slots; events.push({ type: "inventory", characterId: character.characterId, ...bagView(world.ecs, attackerHandle) }); return true; } function entityCombatDisplayName (ecs, handle) { const appearance = ecs.get(handle, Component.appearance); const fromAppearance = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim(); if (fromAppearance) { return fromAppearance; } const creature = ecs.get(handle, Component.creature); if (creature?.mobTypeId) { const def = mobDefinition(creature.mobTypeId); if (def?.displayName) { return def.displayName; } } return null; } function projectileDualTintFromAttacker (ecs, handle) { const equipment = ecs.get(handle, Component.equipment); const stack = arrowStackInOffhand(equipment); if (!stack) { return null; } return resolveItemDualTint(stack, itemDefinition(stack.itemId)); } function projectileSpriteFromAttacker (ecs, handle) { const equipment = ecs.get(handle, Component.equipment); const stack = arrowStackInOffhand(equipment); if (stack?.instance?.kind === "tipped-arrow") { return "fx:projectile:arrow-tipped"; } return "fx:projectile:arrow"; } function publicDualTint (dualTint) { if (!dualTint) { return null; } return { shaftTint: dualTint.shaft, tipTint: dualTint.tip, ...(dualTint.coat ? { coatTint: dualTint.coat } : {}) }; } function missProjectileTile (targetTileX, targetTileY, rng = Math.random) { const angle = rng() * Math.PI * 2; const dist = rng(); return { tileX: Math.round(targetTileX + Math.cos(angle) * dist), tileY: Math.round(targetTileY + Math.sin(angle) * dist) }; } /** * Aggressive mobs auto-engage the nearest player or town guard within aggro range * when they have line of sight. Town guards auto-engage aggressive creatures and * players whose skull tint has started lerping toward red. * Does nothing while already engaged. */ export function stepAggression (world, now = Date.now()) { for (const entity of world.ecs.query(Component.creature, Component.position)) { if (!world.chunkIsSimulating?.( entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID )) { continue; } const def = mobDefinition(entity.creature.mobTypeId); if (world.ecs.get(entity.handle, Component.summon)) { continue; } const origin = world.ecs.get(entity.handle, Component.spawnOrigin); const townGuard = !!origin?.townGuard || isTownGuardMob(entity.creature.mobTypeId); const aggressive = origin ? !!origin.aggressive : mobIsAggressive(def); if ((!aggressive && !townGuard) || !mobCanFight(def)) { continue; } if (world.ecs.has(entity.handle, Component.dead)) { continue; } const health = world.ecs.get(entity.handle, Component.health); if (health && health.current <= 0) { continue; } const combat = world.ecs.get(entity.handle, Component.combat); clearLeashingIfHome(world, { combat, handle: entity.handle, position: entity.position }); if (combat?.leashing) { continue; } if (combat?.targetEntityId != null) { continue; } const range = mobAggroRangeTiles(def); const bestId = townGuard ? pickAggressionTargetForTownGuard(world, entity, range) : pickAggressionTargetPlayerOrGuard(world, entity, range, now); if (bestId == null) { continue; } if (!ensureMobCombat(world.ecs, entity.entityId)) { continue; } engageTarget(world.ecs, entity.entityId, bestId, now); } } function creatureIsAggressiveHostile (world, handle, creature) { if (!creature || world.ecs.get(handle, Component.character)) { return false; } if (world.ecs.get(handle, Component.summon)) { return false; } const origin = world.ecs.get(handle, Component.spawnOrigin); if (origin?.townGuard || isTownGuardMob(creature.mobTypeId)) { return false; } if (origin) { return !!origin.aggressive; } return mobIsAggressive(mobDefinition(creature.mobTypeId)); } function entityIsTownGuard (world, handle, creature) { if (!creature || world.ecs.get(handle, Component.character)) { return false; } const origin = world.ecs.get(handle, Component.spawnOrigin); return !!origin?.townGuard || isTownGuardMob(creature.mobTypeId); } /** Nearest living player or town guard in range with LOS. */ function pickAggressionTargetPlayerOrGuard (world, entity, range, now = Date.now()) { let bestId = null; let bestDist = Infinity; for (const player of world.ecs.query(Component.character, Component.position)) { if (playerIgnoresAggressiveMob(world, entity, player.handle, now)) { continue; } const dist = considerAggressionCandidate(world, entity, player.handle, player.entityId, player.position, range); if (dist != null && dist < bestDist) { bestDist = dist; bestId = player.entityId; } } for (const other of world.ecs.query(Component.creature, Component.position)) { if (other.entityId === entity.entityId) { continue; } if (!entityIsTownGuard(world, other.handle, other.creature)) { continue; } const dist = considerAggressionCandidate(world, entity, other.handle, other.entityId, other.position, range); if (dist != null && dist < bestDist) { bestDist = dist; bestId = other.entityId; } } return bestId; } /** Non-boss aggressive mobs skip players who outlevel them or have chunk peace. */ function playerIgnoresAggressiveMob (world, mobEntity, playerHandle, now) { const def = mobDefinition(mobEntity.creature.mobTypeId); if (mobIsBoss(def)) { return false; } const playerEquipment = world.ecs.get(playerHandle, Component.equipment); if (ignoresNonBossAggro(playerEquipment)) { return true; } const skills = world.ecs.get(playerHandle, Component.skills); if (!skills) { return false; } const playerLevel = combatLevelFromSkills(skills); const origin = world.ecs.get(mobEntity.handle, Component.spawnOrigin); const mobLevel = mobAggressionLevel(mobEntity.creature, origin, def); if (playerOutlevelsMobAggression(playerLevel, mobLevel)) { return true; } const presence = world.ecs.get(playerHandle, Component.chunkPresence); const pos = world.ecs.get(playerHandle, Component.position); if (!presence || !pos) { return false; } return chunkPeaceAggressionImmunity( presence, pos.tileX, pos.tileY, pos.dimensionId ?? OVERWORLD_ID, now, tileToChunk ); } /** * Nearest aggressive hostile creature or red-lerping skulled player in range * with LOS (for town guards). */ function pickAggressionTargetForTownGuard (world, entity, range) { let bestId = null; let bestDist = Infinity; for (const other of world.ecs.query(Component.creature, Component.position)) { if (other.entityId === entity.entityId) { continue; } if (!creatureIsAggressiveHostile(world, other.handle, other.creature)) { continue; } if (!mobCanFight(mobDefinition(other.creature.mobTypeId))) { continue; } const dist = considerAggressionCandidate(world, entity, other.handle, other.entityId, other.position, range); if (dist != null && dist < bestDist) { bestDist = dist; bestId = other.entityId; } } for (const player of world.ecs.query(Component.character, Component.position)) { if (!skullAttractsTownGuards(player.character?.skullValue, world.settings)) { continue; } const dist = considerAggressionCandidate(world, entity, player.handle, player.entityId, player.position, range); if (dist != null && dist < bestDist) { bestDist = dist; bestId = player.entityId; } } return bestId; } /** * @returns {number|null} Chebyshev distance if a valid aggro candidate, else null. */ function considerAggressionCandidate (world, attacker, targetHandle, targetEntityId, targetPos, range) { if (world.ecs.has(targetHandle, Component.dead)) { return null; } const health = world.ecs.get(targetHandle, Component.health); if (health && health.current <= 0) { return null; } const attackerDim = normalizeDimensionId(attacker.position.dimensionId ?? OVERWORLD_ID); const targetDim = normalizeDimensionId(targetPos.dimensionId ?? OVERWORLD_ID); if (attackerDim !== targetDim) { return null; } const dist = chebyshev( attacker.position.tileX, attacker.position.tileY, targetPos.tileX, targetPos.tileY ); if (dist < 1 || dist > range) { return null; } let effectiveDist = dist; if (dist > 1) { const light = tileLightAt(world, targetPos.tileX, targetPos.tileY, Date.now(), attackerDim); effectiveDist = dist * aggroDistanceMultiplier(light); } if (effectiveDist > range) { return null; } if (!hasCombatLineOfSight( world, attacker.position.tileX, attacker.position.tileY, targetPos.tileX, targetPos.tileY, attackerDim )) { return null; } return dist; } /** Local entity handle or a nearby ghost snapshot for cross-worker combat. */ export function resolveCombatTarget (world, targetId) { const handle = world.ecs.handleOf(targetId); if (handle != null) { const pos = world.ecs.get(handle, Component.position); if (!pos) { return null; } if (isUntargetable(world.ecs, handle)) { return null; } return { local: true, handle, pos, health: world.ecs.get(handle, Component.health) }; } const ghost = world.ghosts?.get?.(targetId); if (!ghost || ghost.untargetable) { return null; } const health = ghost.health != null ? { current: ghost.health, max: ghost.maxHealth ?? ghost.health } : null; return { local: false, handle: null, pos: { tileX: ghost.tileX, tileY: ghost.tileY, dimensionId: normalizeDimensionId(ghost.dimensionId ?? OVERWORLD_ID) }, health }; } function attackerCombatLevels (ecs, attackerHandle, profile, settings = null) { const attackerCharacter = ecs.get(attackerHandle, Component.character); if (attackerCharacter) { return playerCombatLevels(ecs, attackerHandle, profile, settings); } const skills = ecs.get(attackerHandle, Component.skills); const equipment = ecs.get(attackerHandle, Component.equipment); const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots, settings) : {}; const hitSkillId = profile.hitSkillId ?? SkillId.unarmed; const damageSkillId = profile.damageSkillId ?? SkillId.strength; const baseHit = attackerSkillLevel(skills, profile, hitSkillId); const baseDamage = attackerSkillLevel(skills, profile, damageSkillId); return { hitLevel: Math.max(1, baseHit + (bonuses[hitSkillId] ?? 0)), damageLevel: Math.max(1, baseDamage + (bonuses[damageSkillId] ?? 0)), agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses), defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses) }; } export function stepPassiveHealthRegen (world, now = Date.now(), dt = 1 / 20) { const events = []; for (const entity of world.ecs.query(Component.health, Component.position)) { const { handle, entityId, health, position, character } = entity; if (world.ecs.has(handle, Component.dead)) { continue; } if (!world.chunkIsSimulating?.( position.tileX, position.tileY, position.dimensionId ?? OVERWORLD_ID )) { continue; } if ((health.current | 0) >= (health.max | 0)) { continue; } const lastDamageAt = health.lastDamageAt ?? 0; if (now - lastDamageAt < PASSIVE_HP_REGEN_DELAY_MS) { continue; } const beforeInt = health.current | 0; const equipment = world.ecs.get(handle, Component.equipment); const regenMult = passiveHpRegenMultiplier(equipment); health.current = Math.min( health.max | 0, (Number(health.current) || 0) + PASSIVE_HP_REGEN_PER_SECOND * regenMult * dt ); if ((health.current | 0) === beforeInt) { continue; } if (character) { syncPlayerHealth(world.ecs, handle); } const view = publicEntityView(world.ecs, entityId); if (!view) { continue; } events.push({ type: "entity-health", entityId, ...(character ? { characterId: character.characterId } : {}), health: view.health, maxHealth: view.maxHealth, tileX: view.tileX, tileY: view.tileY }); } return events; } export function stepCombat (world, now = Date.now()) { const events = []; for (const entity of world.ecs.query(Component.combat, Component.position)) { if (world.ecs.has(entity.handle, Component.dead)) { dropCombatTarget(world, entity); continue; } if (!world.chunkIsSimulating?.( entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID )) { continue; } const combat = entity.combat; clearLeashingIfHome(world, entity); if (combat.leashing) { combat.targetEntityId = null; syncCreatureChaseGait(world, entity.handle, 0, false); continue; } const targetId = combat.targetEntityId; if (targetId == null) { continue; } const target = resolveCombatTarget(world, targetId); if (!target) { dropCombatTarget(world, entity); continue; } if (target.health && target.health.current <= 0) { dropCombatTarget(world, entity); continue; } if (creatureShouldBreakCombatLeash(world, entity.handle, entity.position)) { beginCombatLeashReturn(world, entity); continue; } // One combat form at a time: spell cast / auto-cast wins over melee & archery. if (isSpellCombatBusy(world.ecs, entity.handle)) { continue; } if (combat.fleeFrom) { const flee = combat.fleeFrom; const minDist = Math.max(1, flee.minDist | 0 || 2); const fleeDist = chebyshev( entity.position.tileX, entity.position.tileY, flee.tileX, flee.tileY ); if (fleeDist >= minDist) { combat.fleeFrom = null; clearCombatApproachPath(world.ecs, entity.handle); } else { queueFleeFromHitSource(world, entity.entityId, entity.handle, entity.position, flee, minDist); continue; } } const profile = attackProfileOf(world.ecs, entity.handle); const targetPos = target.pos; const isCreature = isCombatCreature(world, entity.handle); const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY); if (profile.mode === "ranged") { const maxRange = profile.rangeTiles | 0 || COMBAT_RANGE_TILES; const equipment = world.ecs.get(entity.handle, Component.equipment); const hasArrows = isCreature || (arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0); const inRange = dist >= 1 && dist <= maxRange && hasCombatLineOfSight( world, entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY, entity.position.dimensionId ?? OVERWORLD_ID ); if (!inRange || !hasArrows) { if (inRange && !hasArrows && now >= (combat.nextSwingAt || 0) && world.ecs.get(entity.handle, Component.character)) { combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200); events.push({ type: "combat-no-arrows", attackerId: entity.entityId, sessionId: world.ecs.get(entity.handle, Component.networkIdentity)?.sessionId ?? null }); } syncCreatureChaseGait(world, entity.handle, dist, true); queueRangedApproach(world, entity.entityId, entity.handle, entity.position, targetPos, maxRange); continue; } syncCreatureChaseGait(world, entity.handle, dist, false); clearCombatApproachPath(world.ecs, entity.handle); if (now < (combat.nextSwingAt || 0)) { continue; } combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200); clearSpellCombatState(world.ecs, entity.handle); events.push(...resolveRangedShot(world, entity.entityId, targetId, profile, now, targetPos)); continue; } if (profile.mode !== "melee") { continue; } const canSwing = dist === 1 && world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY); const attackSpells = isCreature ? eligibleMobAttackSpells(world.ecs, entity.handle) : []; const preferSpell = isCreature && !!mobDefinition(world.ecs.get(entity.handle, Component.creature)?.mobTypeId)?.preferSpellAttack; const shouldCast = isCreature && attackSpells.length > 0 && (!canSwing || preferSpell); if (shouldCast) { const inSpellRange = dist >= 1 && dist <= COMBAT_RANGE_TILES && hasCombatLineOfSight( world, entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY, entity.position.dimensionId ?? OVERWORLD_ID ); if (!inSpellRange) { syncCreatureChaseGait(world, entity.handle, dist, true); queueStandInRangeApproach( world, entity.entityId, entity.handle, entity.position, targetPos.tileX, targetPos.tileY, COMBAT_RANGE_TILES, 1 ); continue; } syncCreatureChaseGait(world, entity.handle, dist, false); clearCombatApproachPath(world.ecs, entity.handle); if (now < (combat.nextSwingAt || 0)) { continue; } const picked = pickMobAttackSpell(attackSpells); if (!picked) { combat.nextSwingAt = now + SPELL_COOLDOWN_MS; continue; } combat.nextSwingAt = now + SPELL_COOLDOWN_MS; events.push(...castMobAttackSpell(world, entity.entityId, targetId, picked.spellId, now)); continue; } if (!canSwing) { syncCreatureChaseGait(world, entity.handle, dist, true); queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos); continue; } syncCreatureChaseGait(world, entity.handle, dist, false); clearCombatApproachPath(world.ecs, entity.handle); const attackerHealth = world.ecs.get(entity.handle, Component.health); if (attackerHealth && attackerHealth.current <= 0) { continue; } if ((combat.nextSwingAt || 0) > now) { continue; } combat.nextSwingAt = now + (profile.cooldownMs || 800); clearSpellCombatState(world.ecs, entity.handle); events.push(...resolveMeleeSwing(world, entity.entityId, targetId, profile, now)); } return events; } function eligibleMobAttackSpells (ecs, handle) { const spells = ecs.get(handle, Component.spells); if (!spells?.known?.length) { return []; } const level = creatureLevel(ecs, handle); const chances = spells.castChances ?? {}; const out = []; for (const spellId of spells.known) { const def = spellDefinition(spellId); if (!def || def.target !== "entity") { continue; } const minLevel = spellMinMagicLevel(def); if (level < minLevel) { continue; } const chance = Math.max(0, Math.min(100, Number(chances[spellId]) || 0)) | 0; if (chance <= 0) { continue; } out.push({ spellId, chance }); } return out; } function pickMobAttackSpell (spells) { if (!spells.length) { return null; } const pick = spells[Math.floor(Math.random() * spells.length)]; if ((Math.random() * 100) >= pick.chance) { return null; } return pick; } function clearCombatApproachPath (ecs, handle) { const path = ecs.get(handle, Component.path); if (path?.tiles?.length) { path.tiles = []; } } function combatTileKey (tileX, tileY) { return `${tileX},${tileY}`; } /** Tiles claimed by other combatants fighting the same target (position, next step, path goal). */ function collectCombatAllyReservations (world, entityId, targetEntityId) { const reserved = new Set(); if (targetEntityId == null) { return reserved; } for (const entity of world.ecs.query(Component.combat, Component.position)) { if (entity.entityId === entityId) { continue; } if (entity.combat.targetEntityId !== targetEntityId) { continue; } reserved.add(combatTileKey(entity.position.tileX, entity.position.tileY)); const allyPath = world.ecs.get(entity.handle, Component.path); if (!allyPath?.tiles?.length) { continue; } const next = allyPath.tiles[0]; if (next) { reserved.add(combatTileKey(next.x, next.y)); } const dest = allyPath.tiles[allyPath.tiles.length - 1]; if (dest) { reserved.add(combatTileKey(dest.x, dest.y)); } } return reserved; } function combatGoalPreference (entityId, tileX, tileY) { return ((tileX * 73856093) ^ (tileY * 19349663) ^ (entityId * 83492791)) >>> 0; } /** Cost multiplier for tiles the threat can currently shoot. */ const COVER_EXPOSED_STEP_COST = 5; function mobHasRangedRetaliation (world, handle) { const profile = attackProfileOf(world.ecs, handle); if (profile?.mode === "ranged") { return true; } return eligibleMobAttackSpells(world.ecs, handle).length > 0; } /** Melee-only creatures closing after a player ranged/spell hit. */ function shouldSeekCoverApproach (world, handle) { if (world.ecs.get(handle, Component.character)) { return false; } if (!world.ecs.get(handle, Component.creature)) { return false; } const combat = world.ecs.get(handle, Component.combat); if (!combat?.seekCover) { return false; } return !mobHasRangedRetaliation(world, handle); } /** Double cost for stepping back onto the tile just left while chasing. */ function combatApproachStepCost (position, baseCost = null) { const prevX = position?.prevTileX; const prevY = position?.prevTileY; return (x, y) => withCombatBackstepCost( baseCost ? baseCost(x, y) : 1, x, y, prevX, prevY ); } function coverStepCost (world, threatPos, goalX, goalY, x, y) { // Final adjacent step is always in LOS — don't punish the last lunge. if (x === goalX && y === goalY) { return 1; } if (hasCombatLineOfSight( world, threatPos.tileX, threatPos.tileY, x, y, threatPos.dimensionId ?? OVERWORLD_ID )) { return COVER_EXPOSED_STEP_COST; } return 1; } function pathCoverScore (world, threatPos, tiles) { let score = 0; for (const step of tiles) { score += hasCombatLineOfSight( world, threatPos.tileX, threatPos.tileY, step.x, step.y, threatPos.dimensionId ?? OVERWORLD_ID ) ? COVER_EXPOSED_STEP_COST : 1; } return score; } function listAdjacentMeleeGoals (world, entityId, position, targetPos, reserved) { const dirs = [ { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 }, { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 } ]; const goals = []; for (const dir of dirs) { const x = targetPos.tileX + dir.x; const y = targetPos.tileY + dir.y; const isHere = x === position.tileX && y === position.tileY; const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true; const key = combatTileKey(x, y); if (reserved?.has(key) && !(isHere && aloneHere)) { continue; } const clear = world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y); if (!clear && !isHere) { continue; } if (isHere && !aloneHere) { continue; } goals.push({ x, y }); } return goals; } function findCoverMeleeApproachPath (world, entityId, handle, position, targetPos, reserved) { const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); const preferVertical = !!world.ecs.get(handle, Component.character); const isWalkable = (x, y, goal) => { if (x === goal.x && y === goal.y) { return world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y); } return world.pathWalkableFor?.(entityId, x, y) ?? world.walkableFor(entityId, x, y, { softDoorRequirements: true }); }; let bestTiles = null; let bestScore = Infinity; let bestPref = Infinity; for (const goal of listAdjacentMeleeGoals(world, entityId, position, targetPos, reserved)) { if (goal.x === position.tileX && goal.y === position.tileY) { return []; } const tiles = findPath( position.tileX, position.tileY, goal.x, goal.y, (x, y) => isWalkable(x, y, goal), bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, { preferVertical, stepCost: combatApproachStepCost( position, (x, y) => coverStepCost(world, targetPos, goal.x, goal.y, x, y) ) } ); if (!tiles.length) { continue; } const score = pathCoverScore(world, targetPos, tiles); const pref = combatGoalPreference(entityId, goal.x, goal.y); if (score < bestScore || (score === bestScore && pref < bestPref)) { bestScore = score; bestPref = pref; bestTiles = tiles; } } return bestTiles; } /** Duck behind the nearest tile the threat cannot shoot when melee approach is impossible. */ function queueFleeToCover (world, entityId, handle, position, threatPos) { let path = world.ecs.get(handle, Component.path); if (!path) { path = world.ecs.add(handle, Component.path, { tiles: [] }); } const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); const isWalkable = (x, y) => world.pathWalkableFor?.(entityId, x, y) ?? world.walkableFor(entityId, x, y, { softDoorRequirements: true }); const isGoal = (x, y) => { if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y))) { return false; } if (chebyshev(x, y, threatPos.tileX, threatPos.tileY) < 1) { return false; } return !hasCombatLineOfSight( world, threatPos.tileX, threatPos.tileY, x, y, threatPos.dimensionId ?? OVERWORLD_ID ); }; if (isGoal(position.tileX, position.tileY)) { path.tiles = []; return; } const tiles = findPathToNearestGoal( position.tileX, position.tileY, isGoal, isWalkable, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY ); if (!tiles.length) { path.tiles = []; return; } path.tiles = tiles; const movement = world.ecs.get(handle, Component.movement); if (movement) { movement.walkCarry = 0; } } /** Path to the nearest standable tile at least `minDist` from the hit source. */ function queueFleeFromHitSource (world, entityId, handle, position, source, minDist) { if (world.frozen?.has?.(entityId)) { return; } let path = world.ecs.get(handle, Component.path); if (!path) { path = world.ecs.add(handle, Component.path, { tiles: [] }); } const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true; if ( aloneHere && chebyshev(position.tileX, position.tileY, source.tileX, source.tileY) >= minDist ) { path.tiles = []; return; } const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); const isWalkable = (x, y) => world.pathWalkableFor?.(entityId, x, y) ?? world.walkableFor(entityId, x, y, { softDoorRequirements: true }); const isGoal = (x, y) => { if (chebyshev(x, y, source.tileX, source.tileY) < minDist) { return false; } return world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y); }; if (isGoal(position.tileX, position.tileY) && aloneHere) { path.tiles = []; return; } const dest = path.tiles?.length ? path.tiles[path.tiles.length - 1] : null; if ( dest && isGoal(dest.x, dest.y) && path.tiles.every((step) => isWalkable(step.x, step.y)) ) { return; } const tiles = findPathToNearestGoal( position.tileX, position.tileY, isGoal, isWalkable, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY ); if (!tiles.length) { path.tiles = []; return; } path.tiles = tiles; const movement = world.ecs.get(handle, Component.movement); if (movement) { movement.walkCarry = 0; } } export function queueMeleeApproach (world, entityId, handle, position, targetPos) { if (world.frozen?.has?.(entityId)) { return; } let path = world.ecs.get(handle, Component.path); if (!path) { path = world.ecs.add(handle, Component.path, { tiles: [] }); } const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true; if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) === 1 && aloneHere) { path.tiles = []; return; } const combat = world.ecs.get(handle, Component.combat); const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null); const seekCover = shouldSeekCoverApproach(world, handle); if (seekCover) { const coverTiles = findCoverMeleeApproachPath( world, entityId, handle, position, targetPos, reserved ); if (coverTiles) { if (!coverTiles.length) { path.tiles = []; return; } const goal = coverTiles[coverTiles.length - 1]; if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved)) { return; } path.tiles = coverTiles; const movement = world.ecs.get(handle, Component.movement); if (movement) { movement.walkCarry = 0; } return; } queueFleeToCover(world, entityId, handle, position, targetPos); return; } const goal = bestAdjacentGoal(world, entityId, position, targetPos, reserved); if (!goal) { path.tiles = []; return; } if (goal.x === position.tileX && goal.y === position.tileY) { path.tiles = []; return; } if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved)) { return; } const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); const preferVertical = !!world.ecs.get(handle, Component.character); const tiles = findPath( position.tileX, position.tileY, goal.x, goal.y, (x, y) => { if (x === goal.x && y === goal.y) { return world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y); } return world.pathWalkableFor?.(entityId, x, y) ?? world.walkableFor(entityId, x, y, { softDoorRequirements: true }); }, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, { preferVertical, stepCost: combatApproachStepCost(position) } ); if (!tiles.length) { path.tiles = []; return; } path.tiles = tiles; const movement = world.ecs.get(handle, Component.movement); if (movement) { movement.walkCarry = 0; } } /** * Path toward the nearest reachable tile from which `targetTile` is in Chebyshev range with LOS. * Goal is chosen by BFS flood from the actor (shortest walk), not min Chebyshev (which biases top-left). * @param {number} minStandDist Minimum stand-off from target (0 = may stand on target tile). */ export function queueStandInRangeApproach ( world, entityId, handle, position, targetTileX, targetTileY, maxRange, minStandDist = 1 ) { if (world.frozen?.has?.(entityId)) { return; } let path = world.ecs.get(handle, Component.path); if (!path) { path = world.ecs.add(handle, Component.path, { tiles: [] }); } const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY); const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true; const dimensionId = position.dimensionId ?? OVERWORLD_ID; if ( distToTarget <= maxRange && distToTarget >= minStandDist && aloneHere && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY, dimensionId) ) { path.tiles = []; return; } const combat = world.ecs.get(handle, Component.combat); const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null); const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); const isWalkable = (x, y) => world.pathWalkableFor?.(entityId, x, y) ?? world.walkableFor(entityId, x, y, { softDoorRequirements: true }); const isGoal = (x, y) => { const standOff = chebyshev(x, y, targetTileX, targetTileY); if (standOff < minStandDist || standOff > maxRange) { return false; } if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y))) { return false; } const key = combatTileKey(x, y); if (reserved.has(key) && !(x === position.tileX && y === position.tileY)) { return false; } return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY, dimensionId); }; const tiles = findPathToNearestGoal( position.tileX, position.tileY, isGoal, isWalkable, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, { stepCost: combatApproachStepCost(position) } ); if (!tiles.length) { path.tiles = []; return; } const bestGoal = tiles[tiles.length - 1]; if (path.tiles?.length && !standInRangePathStale( world, entityId, path, bestGoal, targetTileX, targetTileY, maxRange, minStandDist, reserved, position )) { return; } path.tiles = tiles; const movement = world.ecs.get(handle, Component.movement); if (movement) { movement.walkCarry = 0; } } function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange) { queueStandInRangeApproach( world, entityId, handle, position, targetPos.tileX, targetPos.tileY, maxRange, 1 ); } export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos) { const events = []; const attackerHandle = world.ecs.handleOf(attackerId); if (attackerHandle == null) { return events; } const from = world.ecs.get(attackerHandle, Component.position); if (!from || !targetPos) { return events; } const isCreature = !!world.ecs.get(attackerHandle, Component.creature) && !world.ecs.get(attackerHandle, Component.character); const arrowTint = projectileDualTintFromAttacker(world.ecs, attackerHandle); const arrowSprite = projectileSpriteFromAttacker(world.ecs, attackerHandle); const tipElement = (() => { const stack = arrowStackInOffhand(world.ecs.get(attackerHandle, Component.equipment)); return stack?.instance?.kind === "tipped-arrow" ? stack.instance.element : null; })(); if (!isCreature && !consumeArrow(world.ecs, attackerHandle)) { return events; } const character = world.ecs.get(attackerHandle, Component.character); if (character?.characterId != null) { events.push({ type: "inventory", characterId: character.characterId, ...bagView(world.ecs, attackerHandle) }); } const shotProfile = tipElement ? { ...profile, attackType: tipElement } : profile; const snapshot = { tileX: targetPos.tileX, tileY: targetPos.tileY, dimensionId: normalizeDimensionId(from.dimensionId ?? targetPos.dimensionId ?? OVERWORLD_ID) }; const target = resolveCombatTarget(world, targetId); if (!target) { return events; } if (!target.local) { events.push({ type: "remote-ranged-resolve", attackerId, targetId, profile: shotProfile, attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, shotProfile, world.settings), attackerIsPlayer: !!world.ecs.get(attackerHandle, Component.character), now, tileX: snapshot.tileX, tileY: snapshot.tileY, fromTileX: from.tileX, fromTileY: from.tileY, sprite: arrowSprite, dimensionId: normalizeDimensionId(from.dimensionId ?? targetPos.dimensionId ?? OVERWORLD_ID), ...(publicDualTint(arrowTint) ?? {}) }); return events; } const hitEvents = applyLocalMeleeHit( world, attackerId, targetId, attackerHandle, target.handle, shotProfile, now, snapshot ); const outcome = hitEvents.find((e) => e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block"); let endX = snapshot.tileX; let endY = snapshot.tileY; if (outcome?.type === "combat-miss") { const miss = missProjectileTile(snapshot.tileX, snapshot.tileY); endX = miss.tileX; endY = miss.tileY; } else { const currentPos = world.ecs.get(target.handle, Component.position); if (currentPos) { endX = currentPos.tileX; endY = currentPos.tileY; } } events.push({ type: "combat-projectile", attackerId, targetId, fromTileX: from.tileX, fromTileY: from.tileY, tileX: endX, tileY: endY, durationMs: RANGED_PROJECTILE_MS, trackTarget: outcome?.type !== "combat-miss", sprite: arrowSprite, dimensionId: normalizeDimensionId(from.dimensionId ?? OVERWORLD_ID), ...(publicDualTint(arrowTint) ?? {}) }); return events.concat(hitEvents); } function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist, reserved, position) { const dest = path.tiles[path.tiles.length - 1]; if (dest.x !== goal.x || dest.y !== goal.y) { return true; } const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY); if (standOff < minStandDist || standOff > maxRange) { return true; } if (!hasCombatLineOfSight( world, dest.x, dest.y, targetTileX, targetTileY, position.dimensionId ?? OVERWORLD_ID )) { return true; } if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true)) { return true; } const destKey = combatTileKey(dest.x, dest.y); if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY)) { return true; } const next = path.tiles[0]; if (!next) { return true; } if (!world.walkableFor(entityId, next.x, next.y)) { return true; } return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true); } function meleePathStale (world, entityId, position, targetPos, path, goal, reserved) { const dest = path.tiles[path.tiles.length - 1]; if (dest.x !== goal.x || dest.y !== goal.y) { return true; } if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1) { return true; } if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true)) { return true; } const destKey = combatTileKey(dest.x, dest.y); if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY)) { return true; } const next = path.tiles[0]; if (!next) { return true; } if (!world.walkableFor(entityId, next.x, next.y)) { return true; } return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true); } function bestAdjacentGoal (world, entityId, position, targetPos, reserved = null) { const dirs = [ { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 }, { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 } ]; let best = null; let bestDist = Infinity; let bestPref = Infinity; for (const dir of dirs) { const x = targetPos.tileX + dir.x; const y = targetPos.tileY + dir.y; const isHere = x === position.tileX && y === position.tileY; const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true; const key = combatTileKey(x, y); if (reserved?.has(key) && !(isHere && aloneHere)) { continue; } const clear = world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y); if (!clear && !isHere) { continue; } if (isHere && !aloneHere) { continue; } const dist = chebyshev(position.tileX, position.tileY, x, y); const pref = combatGoalPreference(entityId, x, y); if (dist < bestDist || (dist === bestDist && pref < bestPref)) { bestDist = dist; bestPref = pref; best = { x, y }; } } return best; } export function resolveMeleeSwing (world, attackerId, targetId, profile, now = Date.now()) { const events = []; const attackerHandle = world.ecs.handleOf(attackerId); if (attackerHandle == null) { return events; } const target = resolveCombatTarget(world, targetId); if (!target) { return events; } const from = world.ecs.get(attackerHandle, Component.position); const to = target.pos; if (!from || !to) { return events; } if (chebyshev(from.tileX, from.tileY, to.tileX, to.tileY) !== 1) { return events; } if (world.isClearStanding && !world.isClearStanding(attackerId, from.tileX, from.tileY)) { return events; } events.push({ type: "combat-swing", attackerId, targetId, tileX: to.tileX, tileY: to.tileY, fromTileX: from.tileX, fromTileY: from.tileY, dimensionId: normalizeDimensionId(from.dimensionId ?? to.dimensionId ?? OVERWORLD_ID) }); if (!target.local) { const attackerCharacter = world.ecs.get(attackerHandle, Component.character); events.push({ type: "remote-melee-resolve", attackerId, targetId, profile, attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings), attackerIsPlayer: !!attackerCharacter, now, tileX: to.tileX, tileY: to.tileY, dimensionId: normalizeDimensionId(from.dimensionId ?? to.dimensionId ?? OVERWORLD_ID) }); return events; } return events.concat(applyLocalMeleeHit( world, attackerId, targetId, attackerHandle, target.handle, profile, now, to )); } /** Authoritative ranged hit when the defender lives on this worker. */ export function applyRemoteRangedShot (world, payload) { const targetHandle = world.ecs.handleOf(payload.targetId); if (targetHandle == null) { return { events: [], forwards: [] }; } const targetPos = world.ecs.get(targetHandle, Component.position); const snapshot = { tileX: payload.tileX, tileY: payload.tileY, dimensionId: normalizeDimensionId( payload.dimensionId ?? targetPos?.dimensionId ?? OVERWORLD_ID ) }; const hitEvents = applyLocalMeleeHit( world, payload.attackerId, payload.targetId, null, targetHandle, payload.profile, payload.now ?? Date.now(), snapshot, payload.attackerLevels, payload.attackerIsPlayer ); const outcome = hitEvents.find((e) => e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block"); const currentPos = world.ecs.get(targetHandle, Component.position); let endX = snapshot.tileX; let endY = snapshot.tileY; if (outcome?.type === "combat-miss") { const miss = missProjectileTile(snapshot.tileX, snapshot.tileY); endX = miss.tileX; endY = miss.tileY; } else if (currentPos) { endX = currentPos.tileX; endY = currentPos.tileY; } const events = [{ type: "combat-projectile", attackerId: payload.attackerId, targetId: payload.targetId, fromTileX: payload.fromTileX, fromTileY: payload.fromTileY, tileX: endX, tileY: endY, durationMs: RANGED_PROJECTILE_MS, trackTarget: outcome?.type !== "combat-miss", sprite: payload.sprite ?? "fx:projectile:arrow", shaftTint: payload.shaftTint ?? null, tipTint: payload.tipTint ?? null, coatTint: payload.coatTint ?? null, dimensionId: normalizeDimensionId( payload.dimensionId ?? currentPos?.dimensionId ?? OVERWORLD_ID ) }, ...hitEvents]; const forwards = []; const hitEvent = hitEvents.find((event) => event.type === "combat-hit"); if (hitEvent && payload.attackerIsPlayer) { forwards.push({ type: "forward-combat-xp", entityId: payload.attackerId, profile: payload.profile, damage: hitEvent.damage }); } return { events, forwards }; } /** Authoritative hit resolution when the defender lives on this worker. */ export function applyRemoteMeleeSwing (world, payload) { const targetHandle = world.ecs.handleOf(payload.targetId); if (targetHandle == null) { return { events: [], forwards: [] }; } const to = world.ecs.get(targetHandle, Component.position); if (!to) { return { events: [], forwards: [] }; } const events = applyLocalMeleeHit( world, payload.attackerId, payload.targetId, null, targetHandle, payload.profile, payload.now ?? Date.now(), to, payload.attackerLevels, payload.attackerIsPlayer ); const forwards = []; const hitEvent = events.find((event) => event.type === "combat-hit"); if (hitEvent && payload.attackerIsPlayer) { forwards.push({ type: "forward-combat-xp", entityId: payload.attackerId, profile: payload.profile, damage: hitEvent.damage }); } return { events, forwards }; } function applyLocalMeleeHit ( world, attackerId, targetId, attackerHandle, targetHandle, profile, now, to, attackerLevelsOverride = null, attackerIsPlayerOverride = null ) { const events = []; if (targetHandle == null) { return events; } const attackerIsPlayer = attackerIsPlayerOverride != null ? !!attackerIsPlayerOverride : (attackerHandle != null ? !!world.ecs.get(attackerHandle, Component.character) : null); // Retaliate on the first resolved swing (hit or miss), not on Attack-click engage. // Passive spawners take hits but do not fight back. if ( attackerIsPlayer === true && !entityIsPassive(world.ecs, targetHandle) && ensureMobCombat(world.ecs, targetId) ) { engageTarget(world.ecs, targetId, attackerId, now); if (profile?.mode === "ranged") { markSeekCover(world.ecs, targetId); } } if (attackerIsPlayer === false) { const targetCharacter = world.ecs.get(targetHandle, Component.character); if (targetCharacter) { maybePlayerRetaliate(world, targetId, attackerId, now); } } const defenderSkills = world.ecs.get(targetHandle, Component.skills); const defenderEquipment = world.ecs.get(targetHandle, Component.equipment); const attackerLevels = attackerLevelsOverride ?? (attackerHandle != null ? attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings) : null); if (!attackerLevels) { return events; } const agilityLevel = defenderSkillLevel( defenderSkills, SkillId.agility, defenderEquipment, world.settings ); const defenceLevel = defenderSkillLevel( defenderSkills, SkillId.defence, defenderEquipment, world.settings ); const attackType = resolveAttackDamageType(world.ecs, attackerHandle, profile); const targetCreature = world.ecs.get(targetHandle, Component.creature); const mobAffinities = targetCreature ? mobDamageAffinities(mobDefinition(targetCreature.mobTypeId)) : {}; const targetAffinities = mergeAffinities(mobAffinities, jewelryDamageAffinities(defenderEquipment)); const attackerEquipment = attackerHandle != null ? world.ecs.get(attackerHandle, Component.equipment) : null; let hitRng = Math.random; hitRng = attackerToHitRng(attackerEquipment, hitRng); hitRng = enemyToHitRngAgainst(defenderEquipment, hitRng); const resolved = resolvePhysicalAttack({ hitSkillLevel: effectiveHitSkillInDarkness( attackerLevels.hitLevel, tileLightAt( world, to.tileX, to.tileY, now, normalizeDimensionId(to.dimensionId ?? OVERWORLD_ID) ) ), agilitySkillLevel: agilityLevel, damageSkillLevel: attackerLevels.damageLevel, defenceSkillLevel: defenceLevel, attackType, targetAffinities, rng: hitRng }); if (resolved.outcome === "miss") { events.push({ type: "combat-miss", attackerId, targetId, tileX: to.tileX, tileY: to.tileY, dimensionId: normalizeDimensionId(to.dimensionId ?? OVERWORLD_ID) }); const dodgeXp = awardCombatAvoidanceXp( world.ecs, targetHandle, SkillId.agility, resolved.damageRoll ); if (dodgeXp) { events.push({ type: "skills-updated", entityId: targetId, characterId: dodgeXp.characterId, skills: dodgeXp.skills, combatLevel: dodgeXp.combatLevel, stored: dodgeXp.stored, levelUps: dodgeXp.levelUps ?? [] }); } return events; } if (resolved.outcome === "block") { events.push({ type: "combat-block", attackerId, targetId, tileX: to.tileX, tileY: to.tileY, dimensionId: normalizeDimensionId(to.dimensionId ?? OVERWORLD_ID) }); const blockXp = awardCombatAvoidanceXp( world.ecs, targetHandle, SkillId.defence, resolved.damageRoll ); if (blockXp) { events.push({ type: "skills-updated", entityId: targetId, characterId: blockXp.characterId, skills: blockXp.skills, combatLevel: blockXp.combatLevel, stored: blockXp.stored, levelUps: blockXp.levelUps ?? [] }); } return events; } const damage = resolved.damage; const targetCharacter = world.ecs.get(targetHandle, Component.character); if (targetCharacter) { syncPlayerHealth(world.ecs, targetHandle); } const health = world.ecs.get(targetHandle, Component.health); if (health) { health.current = Math.max(0, (health.current | 0) - damage); markHealthDamaged(health, now); } events.push({ type: "combat-hit", attackerId, targetId, damage, tileX: to.tileX, tileY: to.tileY, health: health?.current ?? 0, maxHealth: health?.max ?? 0, dimensionId: normalizeDimensionId(to.dimensionId ?? OVERWORLD_ID) }); const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage); if (healthXp) { events.push({ type: "skills-updated", entityId: targetId, characterId: healthXp.characterId, skills: healthXp.skills, combatLevel: healthXp.combatLevel, stored: healthXp.stored, levelUps: healthXp.levelUps ?? [] }); if (health) { const hitEvent = events[events.length - 2]; if (hitEvent?.type === "combat-hit") { hitEvent.health = health.current; hitEvent.maxHealth = health.max; } } } events.push(...maybeReflectDamage(world, attackerId, targetId, targetHandle, damage, now)); if (attackerHandle != null) { markFleeOnHit(world, targetId, attackerId); } if (attackerHandle != null) { const attackerCharacter = world.ecs.get(attackerHandle, Component.character); if (attackerCharacter) { const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile, damage); if (xpAward) { events.push({ type: "skills-updated", entityId: attackerId, characterId: attackerCharacter.characterId, skills: xpAward.skills, combatLevel: xpAward.combatLevel, stored: xpAward.stored, levelUps: xpAward.levelUps ?? [] }); } } } if (health && health.current <= 0) { clearEngage(world.ecs, attackerId); clearEngage(world.ecs, targetId); clearAttackersTargeting(world.ecs, targetId); if (targetCharacter && !world.ecs.has(targetHandle, Component.dead)) { const path = world.ecs.get(targetHandle, Component.path); if (path) { path.tiles = []; } const follow = world.ecs.get(targetHandle, Component.follow); if (follow) { follow.targetEntityId = null; follow.trail = []; } world.ecs.add(targetHandle, Component.dead, {}); silenceDeadPlayer(world.ecs, targetHandle); const identity = world.ecs.get(targetHandle, Component.networkIdentity); events.push({ type: "player-died", entityId: targetId, attackerId, characterId: targetCharacter.characterId, sessionId: identity?.sessionId ?? null, tileX: to.tileX, tileY: to.tileY, health: 0, maxHealth: health.max }); } const creature = world.ecs.get(targetHandle, Component.creature); if (creature && !world.ecs.get(targetHandle, Component.character)) { events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now)); } } return events; } /** * Drops, despawn, and `mob-killed` for bounty / town-guard reaction. * Shared by melee and spell kill paths. */ export function finalizeMobKill (world, attackerId, targetId, targetHandle, tileX, tileY, now) { const events = []; const handle = targetHandle ?? world.ecs.handleOf(targetId); if (handle == null) { return events; } const creature = world.ecs.get(handle, Component.creature); const origin = world.ecs.get(handle, Component.spawnOrigin); const appearance = world.ecs.get(handle, Component.appearance); const summon = world.ecs.get(handle, Component.summon); const position = world.ecs.get(handle, Component.position); const dimensionId = normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID); if (summon?.kind === "jadeite-fairy") { const respawnAt = now + JADEITE_FAIRY_RESPAWN_MS; const characterId = summon.ownerCharacterId | 0; if (!world.jadeiteFairyTimers) { world.jadeiteFairyTimers = new Map(); } if (characterId) { world.jadeiteFairyTimers.set(characterId, respawnAt); } const ownerHandle = summon.ownerEntityId != null ? world.ecs.handleOf(summon.ownerEntityId) : null; const character = ownerHandle != null ? world.ecs.get(ownerHandle, Component.character) : null; if (character) { character.jadeiteFairyRespawnAt = respawnAt; } } events.push(...spawnMobDrops(world, handle, tileX, tileY, now, attackerId)); events.push({ type: "mob-killed", entityId: targetId, attackerId, mobTypeId: creature?.mobTypeId ?? null, level: creature?.level ?? origin?.level ?? 1, bounty: Math.max(0, origin?.bounty | 0 || 0), spawnerId: origin?.spawnerId ?? null, originTileX: origin?.originTileX ?? tileX, originTileY: origin?.originTileY ?? tileY, wanderRangeTiles: origin?.wanderRangeTiles ?? 0, townGuard: !!origin?.townGuard, displayName: appearance?.firstName ?? null, tileX, tileY, dimensionId }); if (origin?.spawnerId) { scheduleSpawnerRespawn( world, origin.spawnerId, origin.respawnDelaySeconds ?? 25, now ); } const view = world.destroyEntity?.(targetId) ?? null; if (view) { events.push({ type: "entity-despawn", entityId: targetId, tileX: view.tileX, tileY: view.tileY, dimensionId: view.dimensionId, cause: "death" }); } return events; } /** Apply HP loss and shared death/loot side-effects (used by spell impacts). */ export function applyDamageAndKill (world, attackerId, targetId, damage, now = Date.now(), options = {}) { const events = []; const targetHandle = world.ecs.handleOf(targetId); if (targetHandle == null) { return events; } const to = world.ecs.get(targetHandle, Component.position); if (!to) { return events; } const health = world.ecs.get(targetHandle, Component.health); if (health) { health.current = Math.max(0, (health.current | 0) - damage); markHealthDamaged(health, now); } events.push({ type: "combat-hit", attackerId, targetId, damage, tileX: to.tileX, tileY: to.tileY, health: health?.current ?? 0, maxHealth: health?.max ?? 0, dimensionId: normalizeDimensionId(to.dimensionId ?? OVERWORLD_ID) }); const attackerHandle = world.ecs.handleOf(attackerId); if ( attackerHandle != null && !entityIsPassive(world.ecs, targetHandle) && ensureMobCombat(world.ecs, targetId) ) { const attackerIsPlayer = !!world.ecs.get(attackerHandle, Component.character); const targetCombat = world.ecs.get(targetHandle, Component.combat); if (targetCombat && targetCombat.targetEntityId == null) { engageTarget(world.ecs, targetId, attackerId, now); } if (attackerIsPlayer) { markSeekCover(world.ecs, targetId); } } if (attackerHandle != null) { markFleeOnHit(world, targetId, attackerId); } if (attackerHandle != null && world.ecs.get(targetHandle, Component.character)) { const attackerCreature = world.ecs.get(attackerHandle, Component.creature); if (attackerCreature) { maybePlayerRetaliate(world, targetId, attackerId, now); } } const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage); if (healthXp) { events.push({ type: "skills-updated", entityId: targetId, characterId: healthXp.characterId, skills: healthXp.skills, combatLevel: healthXp.combatLevel, stored: healthXp.stored, levelUps: healthXp.levelUps ?? [] }); } events.push(...maybeReflectDamage(world, attackerId, targetId, targetHandle, damage, now, options)); if (health && health.current <= 0) { clearEngage(world.ecs, attackerId); clearEngage(world.ecs, targetId); clearAttackersTargeting(world.ecs, targetId); const targetCharacter = world.ecs.get(targetHandle, Component.character); if (targetCharacter && !world.ecs.has(targetHandle, Component.dead)) { const path = world.ecs.get(targetHandle, Component.path); if (path) { path.tiles = []; } world.ecs.add(targetHandle, Component.dead, {}); silenceDeadPlayer(world.ecs, targetHandle); const identity = world.ecs.get(targetHandle, Component.networkIdentity); events.push({ type: "player-died", entityId: targetId, attackerId, characterId: targetCharacter.characterId, sessionId: identity?.sessionId ?? null, tileX: to.tileX, tileY: to.tileY, health: 0, maxHealth: health.max }); } const creature = world.ecs.get(targetHandle, Component.creature); if (creature && !targetCharacter) { events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now)); } } return events; } function maybeReflectDamage (world, attackerId, targetId, targetHandle, damage, now, options = {}) { if (options.noReflect || !(damage > 0) || attackerId == null || attackerId === targetId) { return []; } const equipment = world.ecs.get(targetHandle, Component.equipment); const fraction = damageReflectFraction(equipment); if (!(fraction > 0)) { return []; } const attackerHandle = world.ecs.handleOf(attackerId); if (attackerHandle == null) { return []; } const reflectDamage = Math.max(1, Math.floor(damage * fraction)); return applyDamageAndKill(world, targetId, attackerId, reflectDamage, now, { noReflect: true }); }