BlueGit

timfa questward

Return far mobs home chunk-by-chunk and cross-aggro guards.

Spawner mobs outside wander range path toward the origin one pathfinding window at a time (else local wander). Aggressive creatures and town guards now engage each other.

timfa Tim Falken · pushed by timfa

Authored 2026-08-31 · 2 months ago

Hash
d66e49b9f29569cf5960ecda4d11b40af2a5f2e4
Parent
60d4e770
3 files changed +350 −55
server/src/combat/service.js +121 −43
@@ -1,7 +1,7 @@
1 1 import { Component } from "../ecs/components.js";
2 2 import { itemDefinition } from "../../../shared/definitions/items.js";
3 3 import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
4 import { mobDefinition } from "../../../shared/definitions/mobs.js";
4 import { mobDefinition, isTownGuardMob } from "../../../shared/definitions/mobs.js";
5 5 import
6 6 {
7 7 mobCanFightType,
@@ -521,8 +521,9 @@ function missProjectileTile (targetTileX, targetTileY, rng = Math.random)
521 521 }
522 522
523 523 /**
524 * Aggressive mobs auto-engage the nearest player character within aggro range
525 * when they have line of sight. Does nothing while already engaged.
524 * Aggressive mobs auto-engage the nearest player or town guard within aggro range
525 * when they have line of sight. Town guards auto-engage aggressive creatures.
526 * Does nothing while already engaged.
526 527 */
527 528 export function stepAggression (world, now = Date.now())
528 529 {
@@ -534,10 +535,11 @@ export function stepAggression (world, now = Date.now())
534 535 if (world.ecs.get(entity.handle, Component.summon))
535 536 { continue; }
536 537 const origin = world.ecs.get(entity.handle, Component.spawnOrigin);
538 const townGuard = !!origin?.townGuard || isTownGuardMob(entity.creature.mobTypeId);
537 539 const aggressive = origin
538 540 ? !!origin.aggressive
539 541 : mobIsAggressive(def);
540 if (!aggressive || !mobCanFight(def))
542 if ((!aggressive && !townGuard) || !mobCanFight(def))
541 543 { continue; }
542 544 if (world.ecs.has(entity.handle, Component.dead))
543 545 { continue; }
@@ -549,45 +551,9 @@ export function stepAggression (world, now = Date.now())
549 551 { continue; }
550 552
551 553 const range = mobAggroRangeTiles(def);
552 let bestId = null;
553 let bestDist = Infinity;
554 for (const player of world.ecs.query(Component.character, Component.position))
555 {
556 if (world.ecs.has(player.handle, Component.dead))
557 { continue; }
558 const playerHealth = world.ecs.get(player.handle, Component.health);
559 if (playerHealth && playerHealth.current <= 0)
560 { continue; }
561 const dist = chebyshev(
562 entity.position.tileX,
563 entity.position.tileY,
564 player.position.tileX,
565 player.position.tileY
566 );
567 if (dist < 1 || dist > range)
568 { continue; }
569 let effectiveDist = dist;
570 if (dist > 1)
571 {
572 const light = tileLightAt(world, player.position.tileX, player.position.tileY);
573 effectiveDist = dist * aggroDistanceMultiplier(light);
574 }
575 if (effectiveDist > range)
576 { continue; }
577 if (!hasCombatLineOfSight(
578 world,
579 entity.position.tileX,
580 entity.position.tileY,
581 player.position.tileX,
582 player.position.tileY
583 ))
584 { continue; }
585 if (dist < bestDist)
586 {
587 bestDist = dist;
588 bestId = player.entityId;
589 }
590 }
554 const bestId = townGuard
555 ? pickAggressionTargetAggressiveMob(world, entity, range)
556 : pickAggressionTargetPlayerOrGuard(world, entity, range);
591 557 if (bestId == null)
592 558 { continue; }
593 559 if (!ensureMobCombat(world.ecs, entity.entityId))
@@ -596,6 +562,118 @@ export function stepAggression (world, now = Date.now())
596 562 }
597 563 }
598 564
565 function creatureIsAggressiveHostile (world, handle, creature)
566 {
567 if (!creature || world.ecs.get(handle, Component.character))
568 { return false; }
569 if (world.ecs.get(handle, Component.summon))
570 { return false; }
571 const origin = world.ecs.get(handle, Component.spawnOrigin);
572 if (origin?.townGuard || isTownGuardMob(creature.mobTypeId))
573 { return false; }
574 if (origin)
575 { return !!origin.aggressive; }
576 return mobIsAggressive(mobDefinition(creature.mobTypeId));
577 }
578
579 function entityIsTownGuard (world, handle, creature)
580 {
581 if (!creature || world.ecs.get(handle, Component.character))
582 { return false; }
583 const origin = world.ecs.get(handle, Component.spawnOrigin);
584 return !!origin?.townGuard || isTownGuardMob(creature.mobTypeId);
585 }
586
587 /** Nearest living player or town guard in range with LOS. */
588 function pickAggressionTargetPlayerOrGuard (world, entity, range)
589 {
590 let bestId = null;
591 let bestDist = Infinity;
592 for (const player of world.ecs.query(Component.character, Component.position))
593 {
594 const dist = considerAggressionCandidate(world, entity, player.handle, player.entityId, player.position, range);
595 if (dist != null && dist < bestDist)
596 {
597 bestDist = dist;
598 bestId = player.entityId;
599 }
600 }
601 for (const other of world.ecs.query(Component.creature, Component.position))
602 {
603 if (other.entityId === entity.entityId)
604 { continue; }
605 if (!entityIsTownGuard(world, other.handle, other.creature))
606 { continue; }
607 const dist = considerAggressionCandidate(world, entity, other.handle, other.entityId, other.position, range);
608 if (dist != null && dist < bestDist)
609 {
610 bestDist = dist;
611 bestId = other.entityId;
612 }
613 }
614 return bestId;
615 }
616
617 /** Nearest aggressive hostile creature in range with LOS (for town guards). */
618 function pickAggressionTargetAggressiveMob (world, entity, range)
619 {
620 let bestId = null;
621 let bestDist = Infinity;
622 for (const other of world.ecs.query(Component.creature, Component.position))
623 {
624 if (other.entityId === entity.entityId)
625 { continue; }
626 if (!creatureIsAggressiveHostile(world, other.handle, other.creature))
627 { continue; }
628 if (!mobCanFight(mobDefinition(other.creature.mobTypeId)))
629 { continue; }
630 const dist = considerAggressionCandidate(world, entity, other.handle, other.entityId, other.position, range);
631 if (dist != null && dist < bestDist)
632 {
633 bestDist = dist;
634 bestId = other.entityId;
635 }
636 }
637 return bestId;
638 }
639
640 /**
641 * @returns {number|null} Chebyshev distance if a valid aggro candidate, else null.
642 */
643 function considerAggressionCandidate (world, attacker, targetHandle, targetEntityId, targetPos, range)
644 {
645 if (world.ecs.has(targetHandle, Component.dead))
646 { return null; }
647 const health = world.ecs.get(targetHandle, Component.health);
648 if (health && health.current <= 0)
649 { return null; }
650 const dist = chebyshev(
651 attacker.position.tileX,
652 attacker.position.tileY,
653 targetPos.tileX,
654 targetPos.tileY
655 );
656 if (dist < 1 || dist > range)
657 { return null; }
658 let effectiveDist = dist;
659 if (dist > 1)
660 {
661 const light = tileLightAt(world, targetPos.tileX, targetPos.tileY);
662 effectiveDist = dist * aggroDistanceMultiplier(light);
663 }
664 if (effectiveDist > range)
665 { return null; }
666 if (!hasCombatLineOfSight(
667 world,
668 attacker.position.tileX,
669 attacker.position.tileY,
670 targetPos.tileX,
671 targetPos.tileY
672 ))
673 { return null; }
674 return dist;
675 }
676
599 677 /** Local entity handle or a nearby ghost snapshot for cross-worker combat. */
600 678 export function resolveCombatTarget (world, targetId)
601 679 {
@@ -1,7 +1,7 @@
1import { Component } from "../ecs/components.js";
1import { Component } from "../ecs/components.js";
2import { itemDefinition } from "../../../shared/definitions/items.js";
2import { itemDefinition } from "../../../shared/definitions/items.js";
3import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
3import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
4import { mobDefinition } from "../../../shared/definitions/mobs.js";
4import { mobDefinition, isTownGuardMob } from "../../../shared/definitions/mobs.js";
5import
5import
6 {
6 {
7 mobCanFightType,
7 mobCanFightType,
@@ -521,8 +521,9 @@ function missProjectileTile (targetTileX, targetTileY, rng = Math.random)
521}
521}
522
522
523/**
523/**
524 * Aggressive mobs auto-engage the nearest player character within aggro range
524 * Aggressive mobs auto-engage the nearest player or town guard within aggro range
525 * when they have line of sight. Does nothing while already engaged.
525 * when they have line of sight. Town guards auto-engage aggressive creatures.
526 * Does nothing while already engaged.
526 */
527 */
527export function stepAggression (world, now = Date.now())
528export function stepAggression (world, now = Date.now())
528{
529{
@@ -534,10 +535,11 @@ export function stepAggression (world, now = Date.now())
534 if (world.ecs.get(entity.handle, Component.summon))
535 if (world.ecs.get(entity.handle, Component.summon))
535 { continue; }
536 { continue; }
536 const origin = world.ecs.get(entity.handle, Component.spawnOrigin);
537 const origin = world.ecs.get(entity.handle, Component.spawnOrigin);
538 const townGuard = !!origin?.townGuard || isTownGuardMob(entity.creature.mobTypeId);
537 const aggressive = origin
539 const aggressive = origin
538 ? !!origin.aggressive
540 ? !!origin.aggressive
539 : mobIsAggressive(def);
541 : mobIsAggressive(def);
540 if (!aggressive || !mobCanFight(def))
542 if ((!aggressive && !townGuard) || !mobCanFight(def))
541 { continue; }
543 { continue; }
542 if (world.ecs.has(entity.handle, Component.dead))
544 if (world.ecs.has(entity.handle, Component.dead))
543 { continue; }
545 { continue; }
@@ -549,45 +551,9 @@ export function stepAggression (world, now = Date.now())
549 { continue; }
551 { continue; }
550
552
551 const range = mobAggroRangeTiles(def);
553 const range = mobAggroRangeTiles(def);
552 let bestId = null;
554 const bestId = townGuard
553 let bestDist = Infinity;
555 ? pickAggressionTargetAggressiveMob(world, entity, range)
554 for (const player of world.ecs.query(Component.character, Component.position))
556 : pickAggressionTargetPlayerOrGuard(world, entity, range);
555 {
556 if (world.ecs.has(player.handle, Component.dead))
557 { continue; }
558 const playerHealth = world.ecs.get(player.handle, Component.health);
559 if (playerHealth && playerHealth.current <= 0)
560 { continue; }
561 const dist = chebyshev(
562 entity.position.tileX,
563 entity.position.tileY,
564 player.position.tileX,
565 player.position.tileY
566 );
567 if (dist < 1 || dist > range)
568 { continue; }
569 let effectiveDist = dist;
570 if (dist > 1)
571 {
572 const light = tileLightAt(world, player.position.tileX, player.position.tileY);
573 effectiveDist = dist * aggroDistanceMultiplier(light);
574 }
575 if (effectiveDist > range)
576 { continue; }
577 if (!hasCombatLineOfSight(
578 world,
579 entity.position.tileX,
580 entity.position.tileY,
581 player.position.tileX,
582 player.position.tileY
583 ))
584 { continue; }
585 if (dist < bestDist)
586 {
587 bestDist = dist;
588 bestId = player.entityId;
589 }
590 }
591 if (bestId == null)
557 if (bestId == null)
592 { continue; }
558 { continue; }
593 if (!ensureMobCombat(world.ecs, entity.entityId))
559 if (!ensureMobCombat(world.ecs, entity.entityId))
@@ -596,6 +562,118 @@ export function stepAggression (world, now = Date.now())
596 }
562 }
597}
563}
598
564
565function creatureIsAggressiveHostile (world, handle, creature)
566{
567 if (!creature || world.ecs.get(handle, Component.character))
568 { return false; }
569 if (world.ecs.get(handle, Component.summon))
570 { return false; }
571 const origin = world.ecs.get(handle, Component.spawnOrigin);
572 if (origin?.townGuard || isTownGuardMob(creature.mobTypeId))
573 { return false; }
574 if (origin)
575 { return !!origin.aggressive; }
576 return mobIsAggressive(mobDefinition(creature.mobTypeId));
577}
578
579function entityIsTownGuard (world, handle, creature)
580{
581 if (!creature || world.ecs.get(handle, Component.character))
582 { return false; }
583 const origin = world.ecs.get(handle, Component.spawnOrigin);
584 return !!origin?.townGuard || isTownGuardMob(creature.mobTypeId);
585}
586
587/** Nearest living player or town guard in range with LOS. */
588function pickAggressionTargetPlayerOrGuard (world, entity, range)
589{
590 let bestId = null;
591 let bestDist = Infinity;
592 for (const player of world.ecs.query(Component.character, Component.position))
593 {
594 const dist = considerAggressionCandidate(world, entity, player.handle, player.entityId, player.position, range);
595 if (dist != null && dist < bestDist)
596 {
597 bestDist = dist;
598 bestId = player.entityId;
599 }
600 }
601 for (const other of world.ecs.query(Component.creature, Component.position))
602 {
603 if (other.entityId === entity.entityId)
604 { continue; }
605 if (!entityIsTownGuard(world, other.handle, other.creature))
606 { continue; }
607 const dist = considerAggressionCandidate(world, entity, other.handle, other.entityId, other.position, range);
608 if (dist != null && dist < bestDist)
609 {
610 bestDist = dist;
611 bestId = other.entityId;
612 }
613 }
614 return bestId;
615}
616
617/** Nearest aggressive hostile creature in range with LOS (for town guards). */
618function pickAggressionTargetAggressiveMob (world, entity, range)
619{
620 let bestId = null;
621 let bestDist = Infinity;
622 for (const other of world.ecs.query(Component.creature, Component.position))
623 {
624 if (other.entityId === entity.entityId)
625 { continue; }
626 if (!creatureIsAggressiveHostile(world, other.handle, other.creature))
627 { continue; }
628 if (!mobCanFight(mobDefinition(other.creature.mobTypeId)))
629 { continue; }
630 const dist = considerAggressionCandidate(world, entity, other.handle, other.entityId, other.position, range);
631 if (dist != null && dist < bestDist)
632 {
633 bestDist = dist;
634 bestId = other.entityId;
635 }
636 }
637 return bestId;
638}
639
640/**
641 * @returns {number|null} Chebyshev distance if a valid aggro candidate, else null.
642 */
643function considerAggressionCandidate (world, attacker, targetHandle, targetEntityId, targetPos, range)
644{
645 if (world.ecs.has(targetHandle, Component.dead))
646 { return null; }
647 const health = world.ecs.get(targetHandle, Component.health);
648 if (health && health.current <= 0)
649 { return null; }
650 const dist = chebyshev(
651 attacker.position.tileX,
652 attacker.position.tileY,
653 targetPos.tileX,
654 targetPos.tileY
655 );
656 if (dist < 1 || dist > range)
657 { return null; }
658 let effectiveDist = dist;
659 if (dist > 1)
660 {
661 const light = tileLightAt(world, targetPos.tileX, targetPos.tileY);
662 effectiveDist = dist * aggroDistanceMultiplier(light);
663 }
664 if (effectiveDist > range)
665 { return null; }
666 if (!hasCombatLineOfSight(
667 world,
668 attacker.position.tileX,
669 attacker.position.tileY,
670 targetPos.tileX,
671 targetPos.tileY
672 ))
673 { return null; }
674 return dist;
675}
676
599/** Local entity handle or a nearby ghost snapshot for cross-worker combat. */
677/** Local entity handle or a nearby ghost snapshot for cross-worker combat. */
600export function resolveCombatTarget (world, targetId)
678export function resolveCombatTarget (world, targetId)
601{
679{
server/src/simulation/workerWorld.js +117 −3
@@ -1576,13 +1576,28 @@ export class WorkerWorld
1576 1576 { continue; }
1577 1577 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID))
1578 1578 { continue; }
1579 // ~4× longer idle stands than the old 0.4 chance (mobs mostly idle, rarely walk).
1580 if (Math.random() > 0.1)
1581 { continue; }
1582 1579
1583 1580 const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
1584 1581 const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY;
1585 1582 const range = Math.max(0, origin.wanderRangeTiles | 0);
1583 const homeDist = Math.max(
1584 Math.abs(entity.position.tileX - originX),
1585 Math.abs(entity.position.tileY - originY)
1586 );
1587 const tooFar = homeDist > range;
1588
1589 // Outside the leash: always try to step home. Inside: mostly idle.
1590 if (!tooFar && Math.random() > 0.1)
1591 { continue; }
1592
1593 if (tooFar)
1594 {
1595 if (this.#queueReturnTowardSpawn(entity.entityId, entity.handle, entity.position, path, originX, originY))
1596 { continue; }
1597 queueLocalRandomWanderStep(this, entity.entityId, entity.position, path);
1598 continue;
1599 }
1600
1586 1601 const goal = pickWanderGoalInRange(this, entity.entityId, originX, originY, range);
1587 1602 if (!goal)
1588 1603 { continue; }
@@ -1606,6 +1621,46 @@ export class WorkerWorld
1606 1621 }
1607 1622 }
1608 1623
1624 /**
1625 * Path toward the spawner within the current pathfinding window (chunk-step home).
1626 * @returns {boolean} true if a return path was queued
1627 */
1628 #queueReturnTowardSpawn (entityId, handle, position, path, originX, originY)
1629 {
1630 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1631 const goal = pickClearGoalToward(
1632 this,
1633 entityId,
1634 position.tileX,
1635 position.tileY,
1636 originX,
1637 originY,
1638 bounds
1639 );
1640 if (!goal)
1641 { return false; }
1642 if (goal.tileX === position.tileX && goal.tileY === position.tileY)
1643 { return false; }
1644 const tiles = findPath(
1645 position.tileX,
1646 position.tileY,
1647 goal.tileX,
1648 goal.tileY,
1649 (x, y) => this.walkableFor(entityId, x, y),
1650 bounds.minX,
1651 bounds.minY,
1652 bounds.maxX,
1653 bounds.maxY
1654 );
1655 if (!tiles?.length)
1656 { return false; }
1657 path.tiles = tiles;
1658 const movement = this.ecs.get(handle, Component.movement);
1659 if (movement)
1660 { movement.walkCarry = 0; }
1661 return true;
1662 }
1663
1609 1664 /**
1610 1665 * Send an idle Central Exchange clerk to the staff-side tile of a counter.
1611 1666 * message: { stationTileX, stationTileY }
@@ -2177,6 +2232,65 @@ function pickWanderGoalInRange (world, entityId, originX, originY, range)
2177 2232 return null;
2178 2233 }
2179 2234
2235 /**
2236 * Clearest standable tile in pathfinding bounds, pulled toward (destX, destY).
2237 * When the destination is outside the window this becomes a chunk-step toward home.
2238 */
2239 function pickClearGoalToward (world, entityId, fromX, fromY, destX, destY, bounds)
2240 {
2241 const idealX = Math.max(bounds.minX, Math.min(bounds.maxX, destX | 0));
2242 const idealY = Math.max(bounds.minY, Math.min(bounds.maxY, destY | 0));
2243 if (world.isClearStanding(entityId, idealX, idealY))
2244 { return { tileX: idealX, tileY: idealY }; }
2245 for (let radius = 1; radius <= 4; radius++)
2246 {
2247 for (let dy = -radius; dy <= radius; dy++)
2248 {
2249 for (let dx = -radius; dx <= radius; dx++)
2250 {
2251 if (Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
2252 { continue; }
2253 const tileX = idealX + dx;
2254 const tileY = idealY + dy;
2255 if (tileX < bounds.minX || tileX > bounds.maxX || tileY < bounds.minY || tileY > bounds.maxY)
2256 { continue; }
2257 if (tileX === fromX && tileY === fromY)
2258 { continue; }
2259 if (!world.isClearStanding(entityId, tileX, tileY))
2260 { continue; }
2261 return { tileX, tileY };
2262 }
2263 }
2264 }
2265 return null;
2266 }
2267
2268 /** One random adjacent step so a stranded mob does not freeze in place. */
2269 function queueLocalRandomWanderStep (world, entityId, position, path)
2270 {
2271 const dirs = [
2272 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
2273 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
2274 ];
2275 for (let i = dirs.length - 1; i > 0; i--)
2276 {
2277 const j = Math.floor(Math.random() * (i + 1));
2278 const tmp = dirs[i];
2279 dirs[i] = dirs[j];
2280 dirs[j] = tmp;
2281 }
2282 for (const dir of dirs)
2283 {
2284 const nextX = position.tileX + dir.x;
2285 const nextY = position.tileY + dir.y;
2286 if (!world.isClearStanding(entityId, nextX, nextY))
2287 { continue; }
2288 path.tiles = [{ x: nextX, y: nextY }];
2289 return true;
2290 }
2291 return false;
2292 }
2293
2180 2294 function hasDialogueBrowsers (origin)
2181 2295 {
2182 2296 return originIsBusyPinned(origin);
@@ -1576,13 +1576,28 @@ export class WorkerWorld
1576 { continue; }
1576 { continue; }
1577 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID))
1577 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID))
1578 { continue; }
1578 { continue; }
1579 // ~4× longer idle stands than the old 0.4 chance (mobs mostly idle, rarely walk).
1580 if (Math.random() > 0.1)
1581 { continue; }
1582
1579
1583 const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
1580 const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
1584 const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY;
1581 const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY;
1585 const range = Math.max(0, origin.wanderRangeTiles | 0);
1582 const range = Math.max(0, origin.wanderRangeTiles | 0);
1583 const homeDist = Math.max(
1584 Math.abs(entity.position.tileX - originX),
1585 Math.abs(entity.position.tileY - originY)
1586 );
1587 const tooFar = homeDist > range;
1588
1589 // Outside the leash: always try to step home. Inside: mostly idle.
1590 if (!tooFar && Math.random() > 0.1)
1591 { continue; }
1592
1593 if (tooFar)
1594 {
1595 if (this.#queueReturnTowardSpawn(entity.entityId, entity.handle, entity.position, path, originX, originY))
1596 { continue; }
1597 queueLocalRandomWanderStep(this, entity.entityId, entity.position, path);
1598 continue;
1599 }
1600
1586 const goal = pickWanderGoalInRange(this, entity.entityId, originX, originY, range);
1601 const goal = pickWanderGoalInRange(this, entity.entityId, originX, originY, range);
1587 if (!goal)
1602 if (!goal)
1588 { continue; }
1603 { continue; }
@@ -1606,6 +1621,46 @@ export class WorkerWorld
1606 }
1621 }
1607 }
1622 }
1608
1623
1624 /**
1625 * Path toward the spawner within the current pathfinding window (chunk-step home).
1626 * @returns {boolean} true if a return path was queued
1627 */
1628 #queueReturnTowardSpawn (entityId, handle, position, path, originX, originY)
1629 {
1630 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1631 const goal = pickClearGoalToward(
1632 this,
1633 entityId,
1634 position.tileX,
1635 position.tileY,
1636 originX,
1637 originY,
1638 bounds
1639 );
1640 if (!goal)
1641 { return false; }
1642 if (goal.tileX === position.tileX && goal.tileY === position.tileY)
1643 { return false; }
1644 const tiles = findPath(
1645 position.tileX,
1646 position.tileY,
1647 goal.tileX,
1648 goal.tileY,
1649 (x, y) => this.walkableFor(entityId, x, y),
1650 bounds.minX,
1651 bounds.minY,
1652 bounds.maxX,
1653 bounds.maxY
1654 );
1655 if (!tiles?.length)
1656 { return false; }
1657 path.tiles = tiles;
1658 const movement = this.ecs.get(handle, Component.movement);
1659 if (movement)
1660 { movement.walkCarry = 0; }
1661 return true;
1662 }
1663
1609 /**
1664 /**
1610 * Send an idle Central Exchange clerk to the staff-side tile of a counter.
1665 * Send an idle Central Exchange clerk to the staff-side tile of a counter.
1611 * message: { stationTileX, stationTileY }
1666 * message: { stationTileX, stationTileY }
@@ -2177,6 +2232,65 @@ function pickWanderGoalInRange (world, entityId, originX, originY, range)
2177 return null;
2232 return null;
2178}
2233}
2179
2234
2235/**
2236 * Clearest standable tile in pathfinding bounds, pulled toward (destX, destY).
2237 * When the destination is outside the window this becomes a chunk-step toward home.
2238 */
2239function pickClearGoalToward (world, entityId, fromX, fromY, destX, destY, bounds)
2240{
2241 const idealX = Math.max(bounds.minX, Math.min(bounds.maxX, destX | 0));
2242 const idealY = Math.max(bounds.minY, Math.min(bounds.maxY, destY | 0));
2243 if (world.isClearStanding(entityId, idealX, idealY))
2244 { return { tileX: idealX, tileY: idealY }; }
2245 for (let radius = 1; radius <= 4; radius++)
2246 {
2247 for (let dy = -radius; dy <= radius; dy++)
2248 {
2249 for (let dx = -radius; dx <= radius; dx++)
2250 {
2251 if (Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
2252 { continue; }
2253 const tileX = idealX + dx;
2254 const tileY = idealY + dy;
2255 if (tileX < bounds.minX || tileX > bounds.maxX || tileY < bounds.minY || tileY > bounds.maxY)
2256 { continue; }
2257 if (tileX === fromX && tileY === fromY)
2258 { continue; }
2259 if (!world.isClearStanding(entityId, tileX, tileY))
2260 { continue; }
2261 return { tileX, tileY };
2262 }
2263 }
2264 }
2265 return null;
2266}
2267
2268/** One random adjacent step so a stranded mob does not freeze in place. */
2269function queueLocalRandomWanderStep (world, entityId, position, path)
2270{
2271 const dirs = [
2272 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
2273 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
2274 ];
2275 for (let i = dirs.length - 1; i > 0; i--)
2276 {
2277 const j = Math.floor(Math.random() * (i + 1));
2278 const tmp = dirs[i];
2279 dirs[i] = dirs[j];
2280 dirs[j] = tmp;
2281 }
2282 for (const dir of dirs)
2283 {
2284 const nextX = position.tileX + dir.x;
2285 const nextY = position.tileY + dir.y;
2286 if (!world.isClearStanding(entityId, nextX, nextY))
2287 { continue; }
2288 path.tiles = [{ x: nextX, y: nextY }];
2289 return true;
2290 }
2291 return false;
2292}
2293
2180function hasDialogueBrowsers (origin)
2294function hasDialogueBrowsers (origin)
2181{
2295{
2182 return originIsBusyPinned(origin);
2296 return originIsBusyPinned(origin);
server/tests/combat.test.js +112 −9
@@ -551,6 +551,99 @@ test("aggressive rats engage players within aggro range and LOS", () =>
551 551 { harness.close(); }
552 552 });
553 553
554 test("aggressive mobs and town guards aggro each other", () =>
555 {
556 const harness = makeSimulation({ workerCount: 1 });
557 try
558 {
559 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 2 });
560 harness.simulation.spawnCharacter(1, character);
561 const guardId = harness.simulation.spawnEntity(mobComponents({
562 tileX: 10,
563 tileY: 8,
564 mobTypeId: MobId.townGuard,
565 spawnerId: "0:0:guard",
566 originTileX: 10,
567 originTileY: 8,
568 wanderRangeTiles: 4,
569 level: 10
570 }));
571 const ratId = harness.simulation.spawnEntity(mobComponents({
572 tileX: 12,
573 tileY: 8,
574 mobTypeId: MobId.rat,
575 spawnerId: "0:0:rat",
576 originTileX: 12,
577 originTileY: 8,
578 wanderRangeTiles: 4,
579 aggressive: true
580 }));
581
582 harness.simulation.step();
583 const ratCombat = componentsOf(harness.simulation, ratId).combat?.targetEntityId;
584 const guardCombat = componentsOf(harness.simulation, guardId).combat?.targetEntityId;
585 assert.ok(
586 ratCombat === guardId || guardCombat === ratId,
587 `expected mutual aggro; rat→${ratCombat} guard→${guardCombat}`
588 );
589 }
590 finally
591 { harness.close(); }
592 });
593
594 test("spawner mobs far from home path chunk-step toward the origin", () =>
595 {
596 const harness = makeSimulation({ workerCount: 1, maxChunkX: 5 });
597 try
598 {
599 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
600 const playerId = harness.simulation.spawnCharacter(1, character);
601 const deerId = harness.simulation.spawnEntity(mobComponents({
602 tileX: 10,
603 tileY: 8,
604 mobTypeId: MobId.deer,
605 spawnerId: "0:0:deer",
606 originTileX: 8,
607 originTileY: 8,
608 wanderRangeTiles: 2
609 }));
610 const worker = workerOf(harness.simulation, playerId);
611 teleportEntity(worker, deerId, 40, 8);
612 const handle = worker.world.ecs.handleOf(deerId);
613 worker.world.ecs.get(handle, Component.path).tiles = [];
614
615 let movedCloser = false;
616 for (let i = 0; i < 40; i++)
617 {
618 harness.advance(50);
619 harness.simulation.step();
620 const pos = worker.world.ecs.get(handle, Component.position);
621 const path = worker.world.ecs.get(handle, Component.path)?.tiles ?? [];
622 const fromX = pos.tileX;
623 const fromY = pos.tileY;
624 const fromDist = Math.max(Math.abs(fromX - 8), Math.abs(fromY - 8));
625 if (path.length)
626 {
627 const dest = path[path.length - 1];
628 const destDist = Math.max(Math.abs(dest.x - 8), Math.abs(dest.y - 8));
629 if (destDist < fromDist)
630 {
631 movedCloser = true;
632 break;
633 }
634 }
635 if (fromDist < 32)
636 {
637 movedCloser = true;
638 break;
639 }
640 }
641 assert.ok(movedCloser, "expected a return path closer to the spawner");
642 }
643 finally
644 { harness.close(); }
645 });
646
554 647 test("players retaliate when a mob swings at them", () =>
555 648 {
556 649 const harness = makeSimulation({ workerCount: 1 });
@@ -598,28 +691,38 @@ test("aggressive rats do not aggro through walls or beyond range", () =>
598 691 {
599 692 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
600 693 const playerId = harness.simulation.spawnCharacter(1, character);
601 const record = harness.simulation.entityRecord(playerId);
602 const worker = harness.simulation.workers[record.workerId];
603
604 694 const blockedRat = harness.simulation.spawnEntity(mobComponents({
605 695 tileX: 12,
606 696 tileY: 8,
607 697 mobTypeId: MobId.rat,
608 698 spawnerId: null
609 699 }));
610 const data = worker.world.chunkData(0, 0);
611 data.blocks[8 * 16 + 10] = { typeId: BlockType.stoneWall, state: null, config: null };
700 const worker = workerOf(harness.simulation, playerId);
701 const world = worker.world;
702 const data = world.chunkData(0, 0);
703 const wall = { typeId: BlockType.stoneWall, state: null, config: null };
704 for (let y = 6; y <= 10; y++)
705 { data.blocks[y * 16 + 10] = wall; }
706
707 harness.simulation.step();
708 assert.equal(
709 componentsOf(harness.simulation, blockedRat).combat?.targetEntityId ?? null,
710 null,
711 "wall blocks LOS aggro"
712 );
612 713
613 714 const farRat = harness.simulation.spawnEntity(mobComponents({
614 tileX: 14,
715 tileX: 20,
615 716 tileY: 8,
616 717 mobTypeId: MobId.rat,
617 718 spawnerId: null
618 719 }));
619
620 720 harness.simulation.step();
621 assert.equal(componentsOf(harness.simulation, blockedRat).combat?.targetEntityId ?? null, null);
622 assert.equal(componentsOf(harness.simulation, farRat).combat?.targetEntityId ?? null, null);
721 assert.equal(
722 componentsOf(harness.simulation, farRat).combat?.targetEntityId ?? null,
723 null,
724 "out of range does not aggro"
725 );
623 726 }
624 727 finally
625 728 { harness.close(); }
@@ -551,6 +551,99 @@ test("aggressive rats engage players within aggro range and LOS", () =>
551 { harness.close(); }
551 { harness.close(); }
552});
552});
553
553
554test("aggressive mobs and town guards aggro each other", () =>
555{
556 const harness = makeSimulation({ workerCount: 1 });
557 try
558 {
559 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 2 });
560 harness.simulation.spawnCharacter(1, character);
561 const guardId = harness.simulation.spawnEntity(mobComponents({
562 tileX: 10,
563 tileY: 8,
564 mobTypeId: MobId.townGuard,
565 spawnerId: "0:0:guard",
566 originTileX: 10,
567 originTileY: 8,
568 wanderRangeTiles: 4,
569 level: 10
570 }));
571 const ratId = harness.simulation.spawnEntity(mobComponents({
572 tileX: 12,
573 tileY: 8,
574 mobTypeId: MobId.rat,
575 spawnerId: "0:0:rat",
576 originTileX: 12,
577 originTileY: 8,
578 wanderRangeTiles: 4,
579 aggressive: true
580 }));
581
582 harness.simulation.step();
583 const ratCombat = componentsOf(harness.simulation, ratId).combat?.targetEntityId;
584 const guardCombat = componentsOf(harness.simulation, guardId).combat?.targetEntityId;
585 assert.ok(
586 ratCombat === guardId || guardCombat === ratId,
587 `expected mutual aggro; rat→${ratCombat} guard→${guardCombat}`
588 );
589 }
590 finally
591 { harness.close(); }
592});
593
594test("spawner mobs far from home path chunk-step toward the origin", () =>
595{
596 const harness = makeSimulation({ workerCount: 1, maxChunkX: 5 });
597 try
598 {
599 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
600 const playerId = harness.simulation.spawnCharacter(1, character);
601 const deerId = harness.simulation.spawnEntity(mobComponents({
602 tileX: 10,
603 tileY: 8,
604 mobTypeId: MobId.deer,
605 spawnerId: "0:0:deer",
606 originTileX: 8,
607 originTileY: 8,
608 wanderRangeTiles: 2
609 }));
610 const worker = workerOf(harness.simulation, playerId);
611 teleportEntity(worker, deerId, 40, 8);
612 const handle = worker.world.ecs.handleOf(deerId);
613 worker.world.ecs.get(handle, Component.path).tiles = [];
614
615 let movedCloser = false;
616 for (let i = 0; i < 40; i++)
617 {
618 harness.advance(50);
619 harness.simulation.step();
620 const pos = worker.world.ecs.get(handle, Component.position);
621 const path = worker.world.ecs.get(handle, Component.path)?.tiles ?? [];
622 const fromX = pos.tileX;
623 const fromY = pos.tileY;
624 const fromDist = Math.max(Math.abs(fromX - 8), Math.abs(fromY - 8));
625 if (path.length)
626 {
627 const dest = path[path.length - 1];
628 const destDist = Math.max(Math.abs(dest.x - 8), Math.abs(dest.y - 8));
629 if (destDist < fromDist)
630 {
631 movedCloser = true;
632 break;
633 }
634 }
635 if (fromDist < 32)
636 {
637 movedCloser = true;
638 break;
639 }
640 }
641 assert.ok(movedCloser, "expected a return path closer to the spawner");
642 }
643 finally
644 { harness.close(); }
645});
646
554test("players retaliate when a mob swings at them", () =>
647test("players retaliate when a mob swings at them", () =>
555{
648{
556 const harness = makeSimulation({ workerCount: 1 });
649 const harness = makeSimulation({ workerCount: 1 });
@@ -598,28 +691,38 @@ test("aggressive rats do not aggro through walls or beyond range", () =>
598 {
691 {
599 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
692 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
600 const playerId = harness.simulation.spawnCharacter(1, character);
693 const playerId = harness.simulation.spawnCharacter(1, character);
601 const record = harness.simulation.entityRecord(playerId);
602 const worker = harness.simulation.workers[record.workerId];
603
604 const blockedRat = harness.simulation.spawnEntity(mobComponents({
694 const blockedRat = harness.simulation.spawnEntity(mobComponents({
605 tileX: 12,
695 tileX: 12,
606 tileY: 8,
696 tileY: 8,
607 mobTypeId: MobId.rat,
697 mobTypeId: MobId.rat,
608 spawnerId: null
698 spawnerId: null
609 }));
699 }));
610 const data = worker.world.chunkData(0, 0);
700 const worker = workerOf(harness.simulation, playerId);
611 data.blocks[8 * 16 + 10] = { typeId: BlockType.stoneWall, state: null, config: null };
701 const world = worker.world;
702 const data = world.chunkData(0, 0);
703 const wall = { typeId: BlockType.stoneWall, state: null, config: null };
704 for (let y = 6; y <= 10; y++)
705 { data.blocks[y * 16 + 10] = wall; }
706
707 harness.simulation.step();
708 assert.equal(
709 componentsOf(harness.simulation, blockedRat).combat?.targetEntityId ?? null,
710 null,
711 "wall blocks LOS aggro"
712 );
612
713
613 const farRat = harness.simulation.spawnEntity(mobComponents({
714 const farRat = harness.simulation.spawnEntity(mobComponents({
614 tileX: 14,
715 tileX: 20,
615 tileY: 8,
716 tileY: 8,
616 mobTypeId: MobId.rat,
717 mobTypeId: MobId.rat,
617 spawnerId: null
718 spawnerId: null
618 }));
719 }));
619
620 harness.simulation.step();
720 harness.simulation.step();
621 assert.equal(componentsOf(harness.simulation, blockedRat).combat?.targetEntityId ?? null, null);
721 assert.equal(
622 assert.equal(componentsOf(harness.simulation, farRat).combat?.targetEntityId ?? null, null);
722 componentsOf(harness.simulation, farRat).combat?.targetEntityId ?? null,
723 null,
724 "out of range does not aggro"
725 );
623 }
726 }
624 finally
727 finally
625 { harness.close(); }
728 { harness.close(); }