BlueGit

timfa questward

Implement ranged combat with darkness to-hit and aggro penalties.

Bow tier boosts Archery hit rolls, arrow tier boosts Dexterity damage, shots consume offhand ammo, and target-tile lighting affects hit chance and mob detection range.

timfa Tim Falken · pushed by timfa

Authored 2026-08-26 · 2 months ago

Hash
ac50f31d8db3755d132fa969fbdaa7116c1c4743
Parent
8454745b
9 files changed +633 −2
server/src/combat/service.js +384 −2
@@ -9,16 +9,31 @@ import {
9 9 mobAggroRangeTiles
10 10 } from "../../../shared/definitions/mobCombat.js";
11 11 import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
12 import {
13 effectiveHitSkillInDarkness,
14 aggroDistanceMultiplier
15 } from "../../../shared/combat/darkness.js";
16 import {
17 bakedTileLight01,
18 entityLightAtTile,
19 tileCombatLight01,
20 tileIndexLocal
21 } from "../../../shared/lighting/combatLight.js";
12 22 import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
13 23 import {
14 24 effectiveSkillLevel,
15 25 equipmentBonusesFromSlots
16 26 } from "../../../shared/equipment/stats.js";
27 import { tierStatBonus } from "../../../shared/definitions/materialTiers.js";
28 import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
17 29 import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
18 30 import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
19 31 import { chunkBoundsAround, findPath } from "../navigation/astar.js";
20 32 import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
21 33 import { rayReaches } from "../../../shared/lighting/raycast.js";
34 import { tileToChunk } from "../world/coordinates.js";
35 import { stackQuantity } from "../../../shared/items/inventory.js";
36 import { addGroundItem, publicGroundItem } from "../items/bags.js";
22 37
23 38 export function chebyshev (ax, ay, bx, by)
24 39 {
@@ -82,6 +97,24 @@ function playerCombatLevels (ecs, handle, profile)
82 97 const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
83 98 bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0);
84 99 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
100
101 if (profile.mode === "ranged")
102 {
103 const weapon = equipment?.slots?.weapon;
104 const offhand = equipment?.slots?.offhand;
105 const bowDef = weapon ? itemDefinition(weapon.itemId) : null;
106 const arrowDef = offhand ? itemDefinition(offhand.itemId) : null;
107 const bowTier = bowDef?.equipment?.tier;
108 const arrowTier = arrowDef?.equipment?.tier;
109 return {
110 hitLevel: skillLevel(skills, SkillId.archery) + (bowTier ? tierStatBonus(bowTier) : 0),
111 damageLevel: effectiveSkillLevel(skills, SkillId.dexterity, bonuses)
112 + (arrowTier ? tierStatBonus(arrowTier) : 0),
113 agilityLevel: effectiveSkillLevel(skills, SkillId.dexterity, bonuses),
114 defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses)
115 };
116 }
117
85 118 return {
86 119 hitLevel: skillLevel(skills, profile.hitSkillId),
87 120 damageLevel: effectiveSkillLevel(skills, profile.damageSkillId, bonuses),
@@ -132,6 +165,90 @@ export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)
132 165 return rayReaches(fromX, fromY, toX, toY, (x, y) => world.isEnterable(x, y));
133 166 }
134 167
168 /** Target-tile lighting 0–1 (baked + entity lights + time of day). */
169 export function tileLightAt (world, tileX, tileY, now = Date.now())
170 {
171 const data = world.chunkData?.(tileToChunk(tileX), tileToChunk(tileY));
172 const index = tileIndexLocal(tileX, tileY);
173 const baked = bakedTileLight01(data?.light, index);
174 const entity = entityLightAtTile(world.ecs, Component, tileX, tileY, now);
175 const worldTime = world.worldTime?.(now);
176 return tileCombatLight01({
177 bakedLight01: baked,
178 entityLight01: entity,
179 worldHour: worldTime?.hour ?? 12,
180 nightDarkness: world.settings?.nightDarkness ?? 0.72
181 });
182 }
183
184 function arrowStackInOffhand (equipment)
185 {
186 const stack = equipment?.slots?.offhand;
187 if (!stack)
188 { return null; }
189 const def = itemDefinition(stack.itemId);
190 if (def?.equipment?.kind !== EquipmentKind.arrowAmmo)
191 { return null; }
192 return stack;
193 }
194
195 function consumeArrow (ecs, handle)
196 {
197 const equipment = ecs.get(handle, Component.equipment);
198 const stack = arrowStackInOffhand(equipment);
199 if (!stack || stackQuantity(stack.quantity) <= 0)
200 { return false; }
201 if (stackQuantity(stack.quantity) <= 1)
202 { equipment.slots.offhand = null; }
203 else
204 { stack.quantity = stackQuantity(stack.quantity) - 1; }
205 return true;
206 }
207
208 function spawnMobDrops (world, targetHandle, tileX, tileY, now)
209 {
210 const creature = world.ecs.get(targetHandle, Component.creature);
211 if (!creature)
212 { return []; }
213 const def = mobDefinition(creature.mobTypeId);
214 const events = [];
215 for (const drop of def?.drops ?? [])
216 {
217 if (Math.random() > (drop.chance ?? 1))
218 { continue; }
219 const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
220 const item = {
221 groundItemId,
222 tileX,
223 tileY,
224 stack: { itemId: drop.itemId, quantity: drop.quantity ?? 1 },
225 droppedAt: now,
226 expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000),
227 source: "mob-drop"
228 };
229 addGroundItem(world, item);
230 events.push({
231 type: "ground-item-appear",
232 ...publicGroundItem(item),
233 stack: item.stack,
234 droppedAt: item.droppedAt,
235 source: item.source,
236 expiresAt: item.expiresAt
237 });
238 }
239 return events;
240 }
241
242 function missProjectileTile (targetTileX, targetTileY, rng = Math.random)
243 {
244 const angle = rng() * Math.PI * 2;
245 const dist = rng();
246 return {
247 tileX: Math.round(targetTileX + Math.cos(angle) * dist),
248 tileY: Math.round(targetTileY + Math.sin(angle) * dist)
249 };
250 }
251
135 252 /**
136 253 * Aggressive mobs auto-engage the nearest player character within aggro range
137 254 * when they have line of sight. Does nothing while already engaged.
@@ -172,6 +289,14 @@ export function stepAggression (world, now = Date.now())
172 289 );
173 290 if (dist < 1 || dist > range)
174 291 { continue; }
292 let effectiveDist = dist;
293 if (dist > 1)
294 {
295 const light = tileLightAt(world, player.position.tileX, player.position.tileY);
296 effectiveDist = dist * aggroDistanceMultiplier(light);
297 }
298 if (effectiveDist > range)
299 { continue; }
175 300 if (!hasCombatLineOfSight(
176 301 world,
177 302 entity.position.tileX,
@@ -264,10 +389,48 @@ export function stepCombat (world, now = Date.now())
264 389 }
265 390
266 391 const profile = attackProfileOf(world.ecs, entity.handle);
392 const targetPos = target.pos;
393
394 if (profile.mode === "ranged")
395 {
396 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
397 const maxRange = profile.rangeTiles | 0 || 8;
398 const equipment = world.ecs.get(entity.handle, Component.equipment);
399 const hasArrows = arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0;
400 const inRange = dist >= 1 && dist <= maxRange
401 && hasCombatLineOfSight(
402 world,
403 entity.position.tileX,
404 entity.position.tileY,
405 targetPos.tileX,
406 targetPos.tileY
407 );
408 if (!inRange || !hasArrows)
409 {
410 if (inRange && !hasArrows && now >= (combat.nextSwingAt || 0)
411 && world.ecs.get(entity.handle, Component.character))
412 {
413 combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200);
414 events.push({
415 type: "combat-no-arrows",
416 attackerId: entity.entityId,
417 sessionId: world.ecs.get(entity.handle, Component.networkIdentity)?.sessionId ?? null
418 });
419 }
420 queueRangedApproach(world, entity.entityId, entity.handle, entity.position, targetPos, maxRange);
421 continue;
422 }
423 clearCombatApproachPath(world.ecs, entity.handle);
424 if (now < (combat.nextSwingAt || 0))
425 { continue; }
426 combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200);
427 events.push(...resolveRangedShot(world, entity.entityId, targetId, profile, now, targetPos));
428 continue;
429 }
430
267 431 if (profile.mode !== "melee")
268 432 { continue; }
269 433
270 const targetPos = target.pos;
271 434 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
272 435 const canSwing = dist === 1
273 436 && world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY);
@@ -361,6 +524,153 @@ function queueMeleeApproach (world, entityId, handle, position, targetPos)
361 524 { movement.walkCarry = 0; }
362 525 }
363 526
527 function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange)
528 {
529 if (world.frozen?.has?.(entityId))
530 { return; }
531 let path = world.ecs.get(handle, Component.path);
532 if (!path)
533 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
534
535 const dist = chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY);
536 if (dist >= 1 && dist <= maxRange && hasCombatLineOfSight(
537 world, position.tileX, position.tileY, targetPos.tileX, targetPos.tileY
538 ))
539 {
540 path.tiles = [];
541 return;
542 }
543
544 let bestGoal = null;
545 let bestDist = Infinity;
546 for (let dy = -maxRange; dy <= maxRange; dy++)
547 {
548 for (let dx = -maxRange; dx <= maxRange; dx++)
549 {
550 const x = targetPos.tileX + dx;
551 const y = targetPos.tileY + dy;
552 const toTarget = chebyshev(x, y, targetPos.tileX, targetPos.tileY);
553 if (toTarget < 1 || toTarget > maxRange)
554 { continue; }
555 if (!world.walkableFor(entityId, x, y))
556 { continue; }
557 if (!hasCombatLineOfSight(world, x, y, targetPos.tileX, targetPos.tileY))
558 { continue; }
559 const d = chebyshev(position.tileX, position.tileY, x, y);
560 if (d < bestDist)
561 {
562 bestDist = d;
563 bestGoal = { x, y };
564 }
565 }
566 }
567 if (!bestGoal)
568 {
569 path.tiles = [];
570 return;
571 }
572 if (bestGoal.x === position.tileX && bestGoal.y === position.tileY)
573 {
574 path.tiles = [];
575 return;
576 }
577 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
578 const preferVertical = !!world.ecs.get(handle, Component.character);
579 const tiles = findPath(
580 position.tileX,
581 position.tileY,
582 bestGoal.x,
583 bestGoal.y,
584 (x, y) => world.walkableFor(entityId, x, y),
585 bounds.minX,
586 bounds.minY,
587 bounds.maxX,
588 bounds.maxY,
589 { preferVertical }
590 );
591 path.tiles = tiles.length ? tiles : [];
592 const movement = world.ecs.get(handle, Component.movement);
593 if (movement)
594 { movement.walkCarry = 0; }
595 }
596
597 export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos)
598 {
599 const events = [];
600 const attackerHandle = world.ecs.handleOf(attackerId);
601 if (attackerHandle == null)
602 { return events; }
603 const from = world.ecs.get(attackerHandle, Component.position);
604 if (!from || !targetPos)
605 { return events; }
606 if (!consumeArrow(world.ecs, attackerHandle))
607 { return events; }
608
609 const snapshot = { tileX: targetPos.tileX, tileY: targetPos.tileY };
610 const target = resolveCombatTarget(world, targetId);
611 if (!target)
612 { return events; }
613
614 if (!target.local)
615 {
616 events.push({
617 type: "remote-ranged-resolve",
618 attackerId,
619 targetId,
620 profile,
621 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile),
622 attackerIsPlayer: !!world.ecs.get(attackerHandle, Component.character),
623 now,
624 tileX: snapshot.tileX,
625 tileY: snapshot.tileY,
626 fromTileX: from.tileX,
627 fromTileY: from.tileY
628 });
629 return events;
630 }
631
632 const hitEvents = applyLocalMeleeHit(
633 world,
634 attackerId,
635 targetId,
636 attackerHandle,
637 target.handle,
638 profile,
639 now,
640 snapshot
641 );
642 const outcome = hitEvents.find((e) =>
643 e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block");
644 let endX = snapshot.tileX;
645 let endY = snapshot.tileY;
646 if (outcome?.type === "combat-miss")
647 {
648 const miss = missProjectileTile(snapshot.tileX, snapshot.tileY);
649 endX = miss.tileX;
650 endY = miss.tileY;
651 }
652 else
653 {
654 const currentPos = world.ecs.get(target.handle, Component.position);
655 if (currentPos)
656 {
657 endX = currentPos.tileX;
658 endY = currentPos.tileY;
659 }
660 }
661 events.push({
662 type: "combat-projectile",
663 attackerId,
664 targetId,
665 fromTileX: from.tileX,
666 fromTileY: from.tileY,
667 tileX: endX,
668 tileY: endY,
669 durationMs: 400
670 });
671 return events.concat(hitEvents);
672 }
673
364 674 function meleePathStale (world, entityId, position, targetPos, path, goal)
365 675 {
366 676 const dest = path.tiles[path.tiles.length - 1];
@@ -462,6 +772,74 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
462 772 ));
463 773 }
464 774
775 /** Authoritative ranged hit when the defender lives on this worker. */
776 export function applyRemoteRangedShot (world, payload)
777 {
778 const targetHandle = world.ecs.handleOf(payload.targetId);
779 if (targetHandle == null)
780 { return { events: [], forwards: [] }; }
781 const snapshot = {
782 tileX: payload.tileX,
783 tileY: payload.tileY
784 };
785
786 const hitEvents = applyLocalMeleeHit(
787 world,
788 payload.attackerId,
789 payload.targetId,
790 null,
791 targetHandle,
792 payload.profile,
793 payload.now ?? Date.now(),
794 snapshot,
795 payload.attackerLevels,
796 payload.attackerIsPlayer
797 );
798
799 const outcome = hitEvents.find((e) =>
800 e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block");
801 let endX = snapshot.tileX;
802 let endY = snapshot.tileY;
803 if (outcome?.type === "combat-miss")
804 {
805 const miss = missProjectileTile(snapshot.tileX, snapshot.tileY);
806 endX = miss.tileX;
807 endY = miss.tileY;
808 }
809 else
810 {
811 const currentPos = world.ecs.get(targetHandle, Component.position);
812 if (currentPos)
813 {
814 endX = currentPos.tileX;
815 endY = currentPos.tileY;
816 }
817 }
818
819 const events = [{
820 type: "combat-projectile",
821 attackerId: payload.attackerId,
822 targetId: payload.targetId,
823 fromTileX: payload.fromTileX,
824 fromTileY: payload.fromTileY,
825 tileX: endX,
826 tileY: endY,
827 durationMs: 400
828 }, ...hitEvents];
829
830 const forwards = [];
831 const hitEvent = hitEvents.find((event) => event.type === "combat-hit");
832 if (hitEvent && payload.attackerIsPlayer)
833 {
834 forwards.push({
835 type: "forward-combat-xp",
836 entityId: payload.attackerId,
837 profile: payload.profile
838 });
839 }
840 return { events, forwards };
841 }
842
465 843 /** Authoritative hit resolution when the defender lives on this worker. */
466 844 export function applyRemoteMeleeSwing (world, payload)
467 845 {
@@ -558,7 +936,10 @@ function applyLocalMeleeHit (
558 936 );
559 937
560 938 const resolved = resolvePhysicalAttack({
561 hitSkillLevel: attackerLevels.hitLevel,
939 hitSkillLevel: effectiveHitSkillInDarkness(
940 attackerLevels.hitLevel,
941 tileLightAt(world, to.tileX, to.tileY)
942 ),
562 943 agilitySkillLevel: agilityLevel,
563 944 damageSkillLevel: attackerLevels.damageLevel,
564 945 defenceSkillLevel: defenceLevel,
@@ -688,6 +1069,7 @@ function applyLocalMeleeHit (
688 1069 const creature = world.ecs.get(targetHandle, Component.creature);
689 1070 if (creature && !world.ecs.get(targetHandle, Component.character))
690 1071 {
1072 events.push(...spawnMobDrops(world, targetHandle, to.tileX, to.tileY, now));
691 1073 const view = world.destroyEntity?.(targetId) ?? null;
692 1074 if (view)
693 1075 {
@@ -9,16 +9,31 @@ import {
9 mobAggroRangeTiles
9 mobAggroRangeTiles
10} from "../../../shared/definitions/mobCombat.js";
10} from "../../../shared/definitions/mobCombat.js";
11import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
11import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
12import {
13 effectiveHitSkillInDarkness,
14 aggroDistanceMultiplier
15} from "../../../shared/combat/darkness.js";
16import {
17 bakedTileLight01,
18 entityLightAtTile,
19 tileCombatLight01,
20 tileIndexLocal
21} from "../../../shared/lighting/combatLight.js";
12import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
22import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
13import {
23import {
14 effectiveSkillLevel,
24 effectiveSkillLevel,
15 equipmentBonusesFromSlots
25 equipmentBonusesFromSlots
16} from "../../../shared/equipment/stats.js";
26} from "../../../shared/equipment/stats.js";
27import { tierStatBonus } from "../../../shared/definitions/materialTiers.js";
28import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
17import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
29import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
18import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
30import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
19import { chunkBoundsAround, findPath } from "../navigation/astar.js";
31import { chunkBoundsAround, findPath } from "../navigation/astar.js";
20import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
32import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
21import { rayReaches } from "../../../shared/lighting/raycast.js";
33import { rayReaches } from "../../../shared/lighting/raycast.js";
34import { tileToChunk } from "../world/coordinates.js";
35import { stackQuantity } from "../../../shared/items/inventory.js";
36import { addGroundItem, publicGroundItem } from "../items/bags.js";
22
37
23export function chebyshev (ax, ay, bx, by)
38export function chebyshev (ax, ay, bx, by)
24{
39{
@@ -82,6 +97,24 @@ function playerCombatLevels (ecs, handle, profile)
82 const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
97 const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
83 bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0);
98 bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0);
84 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
99 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
100
101 if (profile.mode === "ranged")
102 {
103 const weapon = equipment?.slots?.weapon;
104 const offhand = equipment?.slots?.offhand;
105 const bowDef = weapon ? itemDefinition(weapon.itemId) : null;
106 const arrowDef = offhand ? itemDefinition(offhand.itemId) : null;
107 const bowTier = bowDef?.equipment?.tier;
108 const arrowTier = arrowDef?.equipment?.tier;
109 return {
110 hitLevel: skillLevel(skills, SkillId.archery) + (bowTier ? tierStatBonus(bowTier) : 0),
111 damageLevel: effectiveSkillLevel(skills, SkillId.dexterity, bonuses)
112 + (arrowTier ? tierStatBonus(arrowTier) : 0),
113 agilityLevel: effectiveSkillLevel(skills, SkillId.dexterity, bonuses),
114 defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses)
115 };
116 }
117
85 return {
118 return {
86 hitLevel: skillLevel(skills, profile.hitSkillId),
119 hitLevel: skillLevel(skills, profile.hitSkillId),
87 damageLevel: effectiveSkillLevel(skills, profile.damageSkillId, bonuses),
120 damageLevel: effectiveSkillLevel(skills, profile.damageSkillId, bonuses),
@@ -132,6 +165,90 @@ export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)
132 return rayReaches(fromX, fromY, toX, toY, (x, y) => world.isEnterable(x, y));
165 return rayReaches(fromX, fromY, toX, toY, (x, y) => world.isEnterable(x, y));
133}
166}
134
167
168/** Target-tile lighting 0–1 (baked + entity lights + time of day). */
169export function tileLightAt (world, tileX, tileY, now = Date.now())
170{
171 const data = world.chunkData?.(tileToChunk(tileX), tileToChunk(tileY));
172 const index = tileIndexLocal(tileX, tileY);
173 const baked = bakedTileLight01(data?.light, index);
174 const entity = entityLightAtTile(world.ecs, Component, tileX, tileY, now);
175 const worldTime = world.worldTime?.(now);
176 return tileCombatLight01({
177 bakedLight01: baked,
178 entityLight01: entity,
179 worldHour: worldTime?.hour ?? 12,
180 nightDarkness: world.settings?.nightDarkness ?? 0.72
181 });
182}
183
184function arrowStackInOffhand (equipment)
185{
186 const stack = equipment?.slots?.offhand;
187 if (!stack)
188 { return null; }
189 const def = itemDefinition(stack.itemId);
190 if (def?.equipment?.kind !== EquipmentKind.arrowAmmo)
191 { return null; }
192 return stack;
193}
194
195function consumeArrow (ecs, handle)
196{
197 const equipment = ecs.get(handle, Component.equipment);
198 const stack = arrowStackInOffhand(equipment);
199 if (!stack || stackQuantity(stack.quantity) <= 0)
200 { return false; }
201 if (stackQuantity(stack.quantity) <= 1)
202 { equipment.slots.offhand = null; }
203 else
204 { stack.quantity = stackQuantity(stack.quantity) - 1; }
205 return true;
206}
207
208function spawnMobDrops (world, targetHandle, tileX, tileY, now)
209{
210 const creature = world.ecs.get(targetHandle, Component.creature);
211 if (!creature)
212 { return []; }
213 const def = mobDefinition(creature.mobTypeId);
214 const events = [];
215 for (const drop of def?.drops ?? [])
216 {
217 if (Math.random() > (drop.chance ?? 1))
218 { continue; }
219 const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
220 const item = {
221 groundItemId,
222 tileX,
223 tileY,
224 stack: { itemId: drop.itemId, quantity: drop.quantity ?? 1 },
225 droppedAt: now,
226 expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000),
227 source: "mob-drop"
228 };
229 addGroundItem(world, item);
230 events.push({
231 type: "ground-item-appear",
232 ...publicGroundItem(item),
233 stack: item.stack,
234 droppedAt: item.droppedAt,
235 source: item.source,
236 expiresAt: item.expiresAt
237 });
238 }
239 return events;
240}
241
242function missProjectileTile (targetTileX, targetTileY, rng = Math.random)
243{
244 const angle = rng() * Math.PI * 2;
245 const dist = rng();
246 return {
247 tileX: Math.round(targetTileX + Math.cos(angle) * dist),
248 tileY: Math.round(targetTileY + Math.sin(angle) * dist)
249 };
250}
251
135/**
252/**
136 * Aggressive mobs auto-engage the nearest player character within aggro range
253 * Aggressive mobs auto-engage the nearest player character within aggro range
137 * when they have line of sight. Does nothing while already engaged.
254 * when they have line of sight. Does nothing while already engaged.
@@ -172,6 +289,14 @@ export function stepAggression (world, now = Date.now())
172 );
289 );
173 if (dist < 1 || dist > range)
290 if (dist < 1 || dist > range)
174 { continue; }
291 { continue; }
292 let effectiveDist = dist;
293 if (dist > 1)
294 {
295 const light = tileLightAt(world, player.position.tileX, player.position.tileY);
296 effectiveDist = dist * aggroDistanceMultiplier(light);
297 }
298 if (effectiveDist > range)
299 { continue; }
175 if (!hasCombatLineOfSight(
300 if (!hasCombatLineOfSight(
176 world,
301 world,
177 entity.position.tileX,
302 entity.position.tileX,
@@ -264,10 +389,48 @@ export function stepCombat (world, now = Date.now())
264 }
389 }
265
390
266 const profile = attackProfileOf(world.ecs, entity.handle);
391 const profile = attackProfileOf(world.ecs, entity.handle);
392 const targetPos = target.pos;
393
394 if (profile.mode === "ranged")
395 {
396 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
397 const maxRange = profile.rangeTiles | 0 || 8;
398 const equipment = world.ecs.get(entity.handle, Component.equipment);
399 const hasArrows = arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0;
400 const inRange = dist >= 1 && dist <= maxRange
401 && hasCombatLineOfSight(
402 world,
403 entity.position.tileX,
404 entity.position.tileY,
405 targetPos.tileX,
406 targetPos.tileY
407 );
408 if (!inRange || !hasArrows)
409 {
410 if (inRange && !hasArrows && now >= (combat.nextSwingAt || 0)
411 && world.ecs.get(entity.handle, Component.character))
412 {
413 combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200);
414 events.push({
415 type: "combat-no-arrows",
416 attackerId: entity.entityId,
417 sessionId: world.ecs.get(entity.handle, Component.networkIdentity)?.sessionId ?? null
418 });
419 }
420 queueRangedApproach(world, entity.entityId, entity.handle, entity.position, targetPos, maxRange);
421 continue;
422 }
423 clearCombatApproachPath(world.ecs, entity.handle);
424 if (now < (combat.nextSwingAt || 0))
425 { continue; }
426 combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200);
427 events.push(...resolveRangedShot(world, entity.entityId, targetId, profile, now, targetPos));
428 continue;
429 }
430
267 if (profile.mode !== "melee")
431 if (profile.mode !== "melee")
268 { continue; }
432 { continue; }
269
433
270 const targetPos = target.pos;
271 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
434 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
272 const canSwing = dist === 1
435 const canSwing = dist === 1
273 && world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY);
436 && world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY);
@@ -361,6 +524,153 @@ function queueMeleeApproach (world, entityId, handle, position, targetPos)
361 { movement.walkCarry = 0; }
524 { movement.walkCarry = 0; }
362}
525}
363
526
527function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange)
528{
529 if (world.frozen?.has?.(entityId))
530 { return; }
531 let path = world.ecs.get(handle, Component.path);
532 if (!path)
533 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
534
535 const dist = chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY);
536 if (dist >= 1 && dist <= maxRange && hasCombatLineOfSight(
537 world, position.tileX, position.tileY, targetPos.tileX, targetPos.tileY
538 ))
539 {
540 path.tiles = [];
541 return;
542 }
543
544 let bestGoal = null;
545 let bestDist = Infinity;
546 for (let dy = -maxRange; dy <= maxRange; dy++)
547 {
548 for (let dx = -maxRange; dx <= maxRange; dx++)
549 {
550 const x = targetPos.tileX + dx;
551 const y = targetPos.tileY + dy;
552 const toTarget = chebyshev(x, y, targetPos.tileX, targetPos.tileY);
553 if (toTarget < 1 || toTarget > maxRange)
554 { continue; }
555 if (!world.walkableFor(entityId, x, y))
556 { continue; }
557 if (!hasCombatLineOfSight(world, x, y, targetPos.tileX, targetPos.tileY))
558 { continue; }
559 const d = chebyshev(position.tileX, position.tileY, x, y);
560 if (d < bestDist)
561 {
562 bestDist = d;
563 bestGoal = { x, y };
564 }
565 }
566 }
567 if (!bestGoal)
568 {
569 path.tiles = [];
570 return;
571 }
572 if (bestGoal.x === position.tileX && bestGoal.y === position.tileY)
573 {
574 path.tiles = [];
575 return;
576 }
577 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
578 const preferVertical = !!world.ecs.get(handle, Component.character);
579 const tiles = findPath(
580 position.tileX,
581 position.tileY,
582 bestGoal.x,
583 bestGoal.y,
584 (x, y) => world.walkableFor(entityId, x, y),
585 bounds.minX,
586 bounds.minY,
587 bounds.maxX,
588 bounds.maxY,
589 { preferVertical }
590 );
591 path.tiles = tiles.length ? tiles : [];
592 const movement = world.ecs.get(handle, Component.movement);
593 if (movement)
594 { movement.walkCarry = 0; }
595}
596
597export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos)
598{
599 const events = [];
600 const attackerHandle = world.ecs.handleOf(attackerId);
601 if (attackerHandle == null)
602 { return events; }
603 const from = world.ecs.get(attackerHandle, Component.position);
604 if (!from || !targetPos)
605 { return events; }
606 if (!consumeArrow(world.ecs, attackerHandle))
607 { return events; }
608
609 const snapshot = { tileX: targetPos.tileX, tileY: targetPos.tileY };
610 const target = resolveCombatTarget(world, targetId);
611 if (!target)
612 { return events; }
613
614 if (!target.local)
615 {
616 events.push({
617 type: "remote-ranged-resolve",
618 attackerId,
619 targetId,
620 profile,
621 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile),
622 attackerIsPlayer: !!world.ecs.get(attackerHandle, Component.character),
623 now,
624 tileX: snapshot.tileX,
625 tileY: snapshot.tileY,
626 fromTileX: from.tileX,
627 fromTileY: from.tileY
628 });
629 return events;
630 }
631
632 const hitEvents = applyLocalMeleeHit(
633 world,
634 attackerId,
635 targetId,
636 attackerHandle,
637 target.handle,
638 profile,
639 now,
640 snapshot
641 );
642 const outcome = hitEvents.find((e) =>
643 e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block");
644 let endX = snapshot.tileX;
645 let endY = snapshot.tileY;
646 if (outcome?.type === "combat-miss")
647 {
648 const miss = missProjectileTile(snapshot.tileX, snapshot.tileY);
649 endX = miss.tileX;
650 endY = miss.tileY;
651 }
652 else
653 {
654 const currentPos = world.ecs.get(target.handle, Component.position);
655 if (currentPos)
656 {
657 endX = currentPos.tileX;
658 endY = currentPos.tileY;
659 }
660 }
661 events.push({
662 type: "combat-projectile",
663 attackerId,
664 targetId,
665 fromTileX: from.tileX,
666 fromTileY: from.tileY,
667 tileX: endX,
668 tileY: endY,
669 durationMs: 400
670 });
671 return events.concat(hitEvents);
672}
673
364function meleePathStale (world, entityId, position, targetPos, path, goal)
674function meleePathStale (world, entityId, position, targetPos, path, goal)
365{
675{
366 const dest = path.tiles[path.tiles.length - 1];
676 const dest = path.tiles[path.tiles.length - 1];
@@ -462,6 +772,74 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
462 ));
772 ));
463}
773}
464
774
775/** Authoritative ranged hit when the defender lives on this worker. */
776export function applyRemoteRangedShot (world, payload)
777{
778 const targetHandle = world.ecs.handleOf(payload.targetId);
779 if (targetHandle == null)
780 { return { events: [], forwards: [] }; }
781 const snapshot = {
782 tileX: payload.tileX,
783 tileY: payload.tileY
784 };
785
786 const hitEvents = applyLocalMeleeHit(
787 world,
788 payload.attackerId,
789 payload.targetId,
790 null,
791 targetHandle,
792 payload.profile,
793 payload.now ?? Date.now(),
794 snapshot,
795 payload.attackerLevels,
796 payload.attackerIsPlayer
797 );
798
799 const outcome = hitEvents.find((e) =>
800 e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block");
801 let endX = snapshot.tileX;
802 let endY = snapshot.tileY;
803 if (outcome?.type === "combat-miss")
804 {
805 const miss = missProjectileTile(snapshot.tileX, snapshot.tileY);
806 endX = miss.tileX;
807 endY = miss.tileY;
808 }
809 else
810 {
811 const currentPos = world.ecs.get(targetHandle, Component.position);
812 if (currentPos)
813 {
814 endX = currentPos.tileX;
815 endY = currentPos.tileY;
816 }
817 }
818
819 const events = [{
820 type: "combat-projectile",
821 attackerId: payload.attackerId,
822 targetId: payload.targetId,
823 fromTileX: payload.fromTileX,
824 fromTileY: payload.fromTileY,
825 tileX: endX,
826 tileY: endY,
827 durationMs: 400
828 }, ...hitEvents];
829
830 const forwards = [];
831 const hitEvent = hitEvents.find((event) => event.type === "combat-hit");
832 if (hitEvent && payload.attackerIsPlayer)
833 {
834 forwards.push({
835 type: "forward-combat-xp",
836 entityId: payload.attackerId,
837 profile: payload.profile
838 });
839 }
840 return { events, forwards };
841}
842
465/** Authoritative hit resolution when the defender lives on this worker. */
843/** Authoritative hit resolution when the defender lives on this worker. */
466export function applyRemoteMeleeSwing (world, payload)
844export function applyRemoteMeleeSwing (world, payload)
467{
845{
@@ -558,7 +936,10 @@ function applyLocalMeleeHit (
558 );
936 );
559
937
560 const resolved = resolvePhysicalAttack({
938 const resolved = resolvePhysicalAttack({
561 hitSkillLevel: attackerLevels.hitLevel,
939 hitSkillLevel: effectiveHitSkillInDarkness(
940 attackerLevels.hitLevel,
941 tileLightAt(world, to.tileX, to.tileY)
942 ),
562 agilitySkillLevel: agilityLevel,
943 agilitySkillLevel: agilityLevel,
563 damageSkillLevel: attackerLevels.damageLevel,
944 damageSkillLevel: attackerLevels.damageLevel,
564 defenceSkillLevel: defenceLevel,
945 defenceSkillLevel: defenceLevel,
@@ -688,6 +1069,7 @@ function applyLocalMeleeHit (
688 const creature = world.ecs.get(targetHandle, Component.creature);
1069 const creature = world.ecs.get(targetHandle, Component.creature);
689 if (creature && !world.ecs.get(targetHandle, Component.character))
1070 if (creature && !world.ecs.get(targetHandle, Component.character))
690 {
1071 {
1072 events.push(...spawnMobDrops(world, targetHandle, to.tileX, to.tileY, now));
691 const view = world.destroyEntity?.(targetId) ?? null;
1073 const view = world.destroyEntity?.(targetId) ?? null;
692 if (view)
1074 if (view)
693 {
1075 {
server/src/simulation/protocol.js +1 −0
@@ -30,6 +30,7 @@ export const WorkerMessage = Object.freeze({
30 30 inspectStamina: "inspectStamina",
31 31 remoteCombatEngage: "remoteCombatEngage",
32 32 applyRemoteMelee: "applyRemoteMelee",
33 applyRemoteRanged: "applyRemoteRanged",
33 34 applyCombatHitXp: "applyCombatHitXp",
34 35 spawnCorpseDrops: "spawnCorpseDrops",
35 36 applyRespawn: "applyRespawn",
@@ -30,6 +30,7 @@ export const WorkerMessage = Object.freeze({
30 inspectStamina: "inspectStamina",
30 inspectStamina: "inspectStamina",
31 remoteCombatEngage: "remoteCombatEngage",
31 remoteCombatEngage: "remoteCombatEngage",
32 applyRemoteMelee: "applyRemoteMelee",
32 applyRemoteMelee: "applyRemoteMelee",
33 applyRemoteRanged: "applyRemoteRanged",
33 applyCombatHitXp: "applyCombatHitXp",
34 applyCombatHitXp: "applyCombatHitXp",
34 spawnCorpseDrops: "spawnCorpseDrops",
35 spawnCorpseDrops: "spawnCorpseDrops",
35 applyRespawn: "applyRespawn",
36 applyRespawn: "applyRespawn",
server/src/simulation/simulation.js +63 −0
@@ -198,6 +198,7 @@ export class Simulation
198 198 {
199 199 const transfers = [];
200 200 const remoteMelee = [];
201 const remoteRanged = [];
201 202 for (const worker of this.workers)
202 203 {
203 204 const result = worker.call({ type: WorkerMessage.stepSystems, now, dt });
@@ -208,6 +209,11 @@ export class Simulation
208 209 remoteMelee.push(event);
209 210 continue;
210 211 }
212 if (event.type === "remote-ranged-resolve")
213 {
214 remoteRanged.push(event);
215 continue;
216 }
211 217 if (event.type === "entity-move")
212 218 { this.#applyMoveToDirectory(event); }
213 219 if (event.type === "entity-despawn")
@@ -241,6 +247,8 @@ export class Simulation
241 247 }
242 248 for (const payload of remoteMelee)
243 249 { events.push(...this.#applyRemoteMelee(payload)); }
250 for (const payload of remoteRanged)
251 { events.push(...this.#applyRemoteRanged(payload)); }
244 252 if (transfers.length)
245 253 {
246 254 events.push(...this.#applyTransfers(transfers));
@@ -1067,6 +1075,61 @@ export class Simulation
1067 1075 return events;
1068 1076 }
1069 1077
1078 #applyRemoteRanged (payload)
1079 {
1080 const targetRecord = this.directory.get(payload.targetId);
1081 if (!targetRecord)
1082 { return []; }
1083 const result = this.workers[targetRecord.workerId].call({
1084 ...payload,
1085 type: WorkerMessage.applyRemoteRanged
1086 });
1087 const events = [];
1088 for (const event of result?.events ?? [])
1089 {
1090 if (event.type === "entity-despawn")
1091 { this.#forget(event.entityId); }
1092 if (event.type === "skills-updated")
1093 {
1094 this.#applySkillsUpdated(event);
1095 events.push(...this.#skillLevelUpEvents(event));
1096 continue;
1097 }
1098 if (event.type === "player-died")
1099 {
1100 events.push(...this.#applyPlayerDeath(event));
1101 continue;
1102 }
1103 this.#persistGroundEvent(event);
1104 if (event.type !== "skills-updated")
1105 { events.push(event); }
1106 }
1107 for (const forward of result?.forwards ?? [])
1108 {
1109 if (forward.type !== "forward-combat-xp")
1110 { continue; }
1111 const attackerRecord = this.directory.get(forward.entityId);
1112 if (!attackerRecord)
1113 { continue; }
1114 const xpResult = this.workers[attackerRecord.workerId].call({
1115 type: WorkerMessage.applyCombatHitXp,
1116 entityId: forward.entityId,
1117 profile: forward.profile
1118 });
1119 for (const xpEvent of xpResult?.events ?? [])
1120 {
1121 if (xpEvent.type === "skills-updated")
1122 {
1123 this.#applySkillsUpdated(xpEvent);
1124 events.push(...this.#skillLevelUpEvents(xpEvent));
1125 continue;
1126 }
1127 events.push(xpEvent);
1128 }
1129 }
1130 return events;
1131 }
1132
1070 1133 #applyPlayerDeath (event)
1071 1134 {
1072 1135 const record = this.directory.get(event.entityId);
@@ -198,6 +198,7 @@ export class Simulation
198 {
198 {
199 const transfers = [];
199 const transfers = [];
200 const remoteMelee = [];
200 const remoteMelee = [];
201 const remoteRanged = [];
201 for (const worker of this.workers)
202 for (const worker of this.workers)
202 {
203 {
203 const result = worker.call({ type: WorkerMessage.stepSystems, now, dt });
204 const result = worker.call({ type: WorkerMessage.stepSystems, now, dt });
@@ -208,6 +209,11 @@ export class Simulation
208 remoteMelee.push(event);
209 remoteMelee.push(event);
209 continue;
210 continue;
210 }
211 }
212 if (event.type === "remote-ranged-resolve")
213 {
214 remoteRanged.push(event);
215 continue;
216 }
211 if (event.type === "entity-move")
217 if (event.type === "entity-move")
212 { this.#applyMoveToDirectory(event); }
218 { this.#applyMoveToDirectory(event); }
213 if (event.type === "entity-despawn")
219 if (event.type === "entity-despawn")
@@ -241,6 +247,8 @@ export class Simulation
241 }
247 }
242 for (const payload of remoteMelee)
248 for (const payload of remoteMelee)
243 { events.push(...this.#applyRemoteMelee(payload)); }
249 { events.push(...this.#applyRemoteMelee(payload)); }
250 for (const payload of remoteRanged)
251 { events.push(...this.#applyRemoteRanged(payload)); }
244 if (transfers.length)
252 if (transfers.length)
245 {
253 {
246 events.push(...this.#applyTransfers(transfers));
254 events.push(...this.#applyTransfers(transfers));
@@ -1067,6 +1075,61 @@ export class Simulation
1067 return events;
1075 return events;
1068 }
1076 }
1069
1077
1078 #applyRemoteRanged (payload)
1079 {
1080 const targetRecord = this.directory.get(payload.targetId);
1081 if (!targetRecord)
1082 { return []; }
1083 const result = this.workers[targetRecord.workerId].call({
1084 ...payload,
1085 type: WorkerMessage.applyRemoteRanged
1086 });
1087 const events = [];
1088 for (const event of result?.events ?? [])
1089 {
1090 if (event.type === "entity-despawn")
1091 { this.#forget(event.entityId); }
1092 if (event.type === "skills-updated")
1093 {
1094 this.#applySkillsUpdated(event);
1095 events.push(...this.#skillLevelUpEvents(event));
1096 continue;
1097 }
1098 if (event.type === "player-died")
1099 {
1100 events.push(...this.#applyPlayerDeath(event));
1101 continue;
1102 }
1103 this.#persistGroundEvent(event);
1104 if (event.type !== "skills-updated")
1105 { events.push(event); }
1106 }
1107 for (const forward of result?.forwards ?? [])
1108 {
1109 if (forward.type !== "forward-combat-xp")
1110 { continue; }
1111 const attackerRecord = this.directory.get(forward.entityId);
1112 if (!attackerRecord)
1113 { continue; }
1114 const xpResult = this.workers[attackerRecord.workerId].call({
1115 type: WorkerMessage.applyCombatHitXp,
1116 entityId: forward.entityId,
1117 profile: forward.profile
1118 });
1119 for (const xpEvent of xpResult?.events ?? [])
1120 {
1121 if (xpEvent.type === "skills-updated")
1122 {
1123 this.#applySkillsUpdated(xpEvent);
1124 events.push(...this.#skillLevelUpEvents(xpEvent));
1125 continue;
1126 }
1127 events.push(xpEvent);
1128 }
1129 }
1130 return events;
1131 }
1132
1070 #applyPlayerDeath (event)
1133 #applyPlayerDeath (event)
1071 {
1134 {
1072 const record = this.directory.get(event.entityId);
1135 const record = this.directory.get(event.entityId);
server/src/simulation/workerWorld.js +8 −0
@@ -43,6 +43,7 @@ import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
43 43 import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
44 44 import {
45 45 applyRemoteMeleeSwing,
46 applyRemoteRangedShot,
46 47 clearEngage,
47 48 engageTarget,
48 49 ensureMobCombat,
@@ -154,6 +155,8 @@ export class WorkerWorld
154 155 return this.#remoteCombatEngage(message);
155 156 case WorkerMessage.applyRemoteMelee:
156 157 return this.#applyRemoteMelee(message);
158 case WorkerMessage.applyRemoteRanged:
159 return this.#applyRemoteRanged(message);
157 160 case WorkerMessage.applyCombatHitXp:
158 161 return this.#applyCombatHitXp(message);
159 162 case WorkerMessage.spawnCorpseDrops:
@@ -719,6 +722,11 @@ export class WorkerWorld
719 722 return applyRemoteMeleeSwing(this, payload);
720 723 }
721 724
725 #applyRemoteRanged (payload)
726 {
727 return applyRemoteRangedShot(this, payload);
728 }
729
722 730 #applyCombatHitXp ({ entityId, profile })
723 731 {
724 732 const handle = this.ecs.handleOf(entityId);
@@ -43,6 +43,7 @@ import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
43import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
43import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
44import {
44import {
45 applyRemoteMeleeSwing,
45 applyRemoteMeleeSwing,
46 applyRemoteRangedShot,
46 clearEngage,
47 clearEngage,
47 engageTarget,
48 engageTarget,
48 ensureMobCombat,
49 ensureMobCombat,
@@ -154,6 +155,8 @@ export class WorkerWorld
154 return this.#remoteCombatEngage(message);
155 return this.#remoteCombatEngage(message);
155 case WorkerMessage.applyRemoteMelee:
156 case WorkerMessage.applyRemoteMelee:
156 return this.#applyRemoteMelee(message);
157 return this.#applyRemoteMelee(message);
158 case WorkerMessage.applyRemoteRanged:
159 return this.#applyRemoteRanged(message);
157 case WorkerMessage.applyCombatHitXp:
160 case WorkerMessage.applyCombatHitXp:
158 return this.#applyCombatHitXp(message);
161 return this.#applyCombatHitXp(message);
159 case WorkerMessage.spawnCorpseDrops:
162 case WorkerMessage.spawnCorpseDrops:
@@ -719,6 +722,11 @@ export class WorkerWorld
719 return applyRemoteMeleeSwing(this, payload);
722 return applyRemoteMeleeSwing(this, payload);
720 }
723 }
721
724
725 #applyRemoteRanged (payload)
726 {
727 return applyRemoteRangedShot(this, payload);
728 }
729
722 #applyCombatHitXp ({ entityId, profile })
730 #applyCombatHitXp ({ entityId, profile })
723 {
731 {
724 const handle = this.ecs.handleOf(entityId);
732 const handle = this.ecs.handleOf(entityId);
server/tests/darkness.test.js added +28 −0
@@ -0,0 +1,28 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import {
4 toHitDarknessPenalty,
5 effectiveHitSkillInDarkness,
6 aggroDistanceMultiplier
7 } from "../../shared/combat/darkness.js";
8
9 test("toHitDarknessPenalty scales quadratically with darkness", () =>
10 {
11 assert.equal(toHitDarknessPenalty(1), 0);
12 assert.equal(toHitDarknessPenalty(0.5), 0.125);
13 assert.equal(toHitDarknessPenalty(0), 0.5);
14 });
15
16 test("effectiveHitSkillInDarkness applies penalty to hit skill", () =>
17 {
18 assert.equal(effectiveHitSkillInDarkness(100, 1), 100);
19 assert.equal(effectiveHitSkillInDarkness(100, 0.5), 87);
20 assert.equal(effectiveHitSkillInDarkness(100, 0), 50);
21 });
22
23 test("aggroDistanceMultiplier lengthens effective distance in dark", () =>
24 {
25 assert.equal(aggroDistanceMultiplier(1), 1);
26 assert.equal(aggroDistanceMultiplier(0.5), 1.5);
27 assert.equal(aggroDistanceMultiplier(0), 2);
28 });
@@ -0,0 +1,28 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import {
4 toHitDarknessPenalty,
5 effectiveHitSkillInDarkness,
6 aggroDistanceMultiplier
7} from "../../shared/combat/darkness.js";
8
9test("toHitDarknessPenalty scales quadratically with darkness", () =>
10{
11 assert.equal(toHitDarknessPenalty(1), 0);
12 assert.equal(toHitDarknessPenalty(0.5), 0.125);
13 assert.equal(toHitDarknessPenalty(0), 0.5);
14});
15
16test("effectiveHitSkillInDarkness applies penalty to hit skill", () =>
17{
18 assert.equal(effectiveHitSkillInDarkness(100, 1), 100);
19 assert.equal(effectiveHitSkillInDarkness(100, 0.5), 87);
20 assert.equal(effectiveHitSkillInDarkness(100, 0), 50);
21});
22
23test("aggroDistanceMultiplier lengthens effective distance in dark", () =>
24{
25 assert.equal(aggroDistanceMultiplier(1), 1);
26 assert.equal(aggroDistanceMultiplier(0.5), 1.5);
27 assert.equal(aggroDistanceMultiplier(0), 2);
28});
server/tests/ranged.test.js added +39 −0
@@ -0,0 +1,39 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { itemDefinition, ItemId } from "../../shared/definitions/items.js";
4 import { RangedItemId } from "../../shared/definitions/rangedItems.js";
5 import { recipesForStation } from "../../shared/crafting/stationRecipes.js";
6 import { CraftingStationId } from "../../shared/definitions/craftingStations.js";
7 import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";
8 import { AttackType } from "../../shared/definitions/attackTypes.js";
9 import { mobDefinition, MobId } from "../../shared/definitions/mobs.js";
10
11 test("ranged items: bow is ranged weapon, arrows stack in offhand", () =>
12 {
13 const bow = itemDefinition(RangedItemId.pineBow);
14 assert.equal(bow?.equipment?.attack?.mode, "ranged");
15 assert.equal(bow?.equipment?.kind, EquipmentKind.bow);
16
17 const arrow = itemDefinition(RangedItemId.bronzeArrow);
18 assert.equal(arrow?.equipment?.kind, EquipmentKind.arrowAmmo);
19 assert.equal(arrow?.equipment?.slot, "offhand");
20 assert.equal(arrow?.maxStackSize, 999);
21 assert.equal(arrow?.equipment?.hideEquipSprite, true);
22 });
23
24 test("ranged recipes load on crafting stations", () =>
25 {
26 const bench = recipesForStation(CraftingStationId.craftingBench);
27 const woodworking = recipesForStation(CraftingStationId.woodworkingBench);
28 const anvil = recipesForStation(CraftingStationId.anvil);
29 assert.ok(bench.some((r) => r.recipeId?.includes("arrow")));
30 assert.ok(woodworking.some((r) => r.recipeId?.includes("arrow-shaft")));
31 assert.ok(anvil.some((r) => r.recipeId?.includes("arrow-tip")));
32 assert.ok(woodworking.some((r) => r.recipeId?.includes("unstrung-bow")));
33 });
34
35 test("chicken drops feathers", () =>
36 {
37 const chicken = mobDefinition(MobId.chicken);
38 assert.ok(chicken?.drops?.some((drop) => drop.itemId === RangedItemId.feather));
39 });
@@ -0,0 +1,39 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { itemDefinition, ItemId } from "../../shared/definitions/items.js";
4import { RangedItemId } from "../../shared/definitions/rangedItems.js";
5import { recipesForStation } from "../../shared/crafting/stationRecipes.js";
6import { CraftingStationId } from "../../shared/definitions/craftingStations.js";
7import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";
8import { AttackType } from "../../shared/definitions/attackTypes.js";
9import { mobDefinition, MobId } from "../../shared/definitions/mobs.js";
10
11test("ranged items: bow is ranged weapon, arrows stack in offhand", () =>
12{
13 const bow = itemDefinition(RangedItemId.pineBow);
14 assert.equal(bow?.equipment?.attack?.mode, "ranged");
15 assert.equal(bow?.equipment?.kind, EquipmentKind.bow);
16
17 const arrow = itemDefinition(RangedItemId.bronzeArrow);
18 assert.equal(arrow?.equipment?.kind, EquipmentKind.arrowAmmo);
19 assert.equal(arrow?.equipment?.slot, "offhand");
20 assert.equal(arrow?.maxStackSize, 999);
21 assert.equal(arrow?.equipment?.hideEquipSprite, true);
22});
23
24test("ranged recipes load on crafting stations", () =>
25{
26 const bench = recipesForStation(CraftingStationId.craftingBench);
27 const woodworking = recipesForStation(CraftingStationId.woodworkingBench);
28 const anvil = recipesForStation(CraftingStationId.anvil);
29 assert.ok(bench.some((r) => r.recipeId?.includes("arrow")));
30 assert.ok(woodworking.some((r) => r.recipeId?.includes("arrow-shaft")));
31 assert.ok(anvil.some((r) => r.recipeId?.includes("arrow-tip")));
32 assert.ok(woodworking.some((r) => r.recipeId?.includes("unstrung-bow")));
33});
34
35test("chicken drops feathers", () =>
36{
37 const chicken = mobDefinition(MobId.chicken);
38 assert.ok(chicken?.drops?.some((drop) => drop.itemId === RangedItemId.feather));
39});
shared/combat/darkness.js added +28 −0
@@ -0,0 +1,28 @@
1 /**
2 * Combat modifiers from target tile lighting (0 = dark, 1 = fully lit).
3 * Penalty scales quadratically: 0% lit → 50% to-hit penalty, 50% lit → 12.5%.
4 */
5
6 /** Fraction subtracted from effective hit skill (0–0.5). */
7 export function toHitDarknessPenalty (light01)
8 {
9 const lit = Math.min(1, Math.max(0, Number(light01) || 0));
10 return 0.5 * (1 - lit) ** 2;
11 }
12
13 /** Effective hit skill after darkness penalty on the target tile. */
14 export function effectiveHitSkillInDarkness (hitSkillLevel, light01)
15 {
16 const penalty = toHitDarknessPenalty(light01);
17 return Math.max(1, Math.floor((hitSkillLevel | 0) * (1 - penalty)));
18 }
19
20 /**
21 * Multiplier applied to Chebyshev aggro distance (1 = normal, 2 = target in full dark).
22 * Linear: 0 lit → 2×, 0.5 lit → 1.5×, 1 lit → 1×.
23 */
24 export function aggroDistanceMultiplier (light01)
25 {
26 const lit = Math.min(1, Math.max(0, Number(light01) || 0));
27 return 2 - lit;
28 }
@@ -0,0 +1,28 @@
1/**
2 * Combat modifiers from target tile lighting (0 = dark, 1 = fully lit).
3 * Penalty scales quadratically: 0% lit → 50% to-hit penalty, 50% lit → 12.5%.
4 */
5
6/** Fraction subtracted from effective hit skill (0–0.5). */
7export function toHitDarknessPenalty (light01)
8{
9 const lit = Math.min(1, Math.max(0, Number(light01) || 0));
10 return 0.5 * (1 - lit) ** 2;
11}
12
13/** Effective hit skill after darkness penalty on the target tile. */
14export function effectiveHitSkillInDarkness (hitSkillLevel, light01)
15{
16 const penalty = toHitDarknessPenalty(light01);
17 return Math.max(1, Math.floor((hitSkillLevel | 0) * (1 - penalty)));
18}
19
20/**
21 * Multiplier applied to Chebyshev aggro distance (1 = normal, 2 = target in full dark).
22 * Linear: 0 lit → 2×, 0.5 lit → 1.5×, 1 lit → 1×.
23 */
24export function aggroDistanceMultiplier (light01)
25{
26 const lit = Math.min(1, Math.max(0, Number(light01) || 0));
27 return 2 - lit;
28}
shared/lighting/combatLight.js added +80 −0
@@ -0,0 +1,80 @@
1 import { CHUNK_SIZE } from "../protocol/constants.js";
2 import { lightIntensity, falloffAtDistance } from "./raycast.js";
3 import { equippedLightRadiusTiles } from "../definitions/items.js";
4 import { statusExtraLightRadius } from "../statusEffects/rules.js";
5
6 /** Night ambient darkness 0–1 (matches client `nightFactor`). */
7 export function nightFactor (hour, nightDarkness = 0.72)
8 {
9 const peak = Math.min(1, Math.max(0, nightDarkness));
10 if (hour >= 8 && hour <= 16)
11 { return 0; }
12 if (hour >= 22 || hour <= 5)
13 { return peak; }
14 if (hour < 8)
15 { return lerp(peak, 0, (hour - 5) / 3); }
16 return lerp(0, peak, (hour - 16) / 6);
17 }
18
19 function lerp (a, b, t)
20 {
21 return a + (b - a) * Math.min(1, Math.max(0, t));
22 }
23
24 function chebyshev (ax, ay, bx, by)
25 {
26 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
27 }
28
29 /** Baked static light 0–1 at a tile (0 when unlit / unbaked). */
30 export function bakedTileLight01 (lightArray, index)
31 {
32 if (!lightArray || index < 0 || index >= lightArray.length)
33 { return 0; }
34 return lightIntensity(lightArray[index] ?? 0);
35 }
36
37 /** Combined target-tile lighting 0–1 for combat (static + entity lights + time of day). */
38 export function tileCombatLight01 ({
39 bakedLight01 = 0,
40 entityLight01 = 0,
41 worldHour = 12,
42 nightDarkness = 0.72
43 } = {})
44 {
45 const localLit = Math.min(1, Math.max(bakedLight01, entityLight01));
46 const ambientDark = nightFactor(worldHour, nightDarkness);
47 return 1 - ambientDark * (1 - localLit);
48 }
49
50 /** Best dynamic entity light reaching a tile (0–1). */
51 export function entityLightAtTile (ecs, Component, tileX, tileY, now = Date.now())
52 {
53 let best = 0;
54 for (const entity of ecs.query(Component.position))
55 {
56 const radius = entityLightRadiusTiles(ecs, entity.handle, Component, now);
57 if (radius <= 0)
58 { continue; }
59 const dist = chebyshev(entity.position.tileX, entity.position.tileY, tileX, tileY);
60 if (dist > radius)
61 { continue; }
62 best = Math.max(best, falloffAtDistance(dist, radius));
63 }
64 return best;
65 }
66
67 function entityLightRadiusTiles (ecs, handle, Component, now)
68 {
69 const equipment = ecs.get(handle, Component.equipment);
70 const gear = equippedLightRadiusTiles(equipment);
71 const status = statusExtraLightRadius(ecs.get(handle, Component.statusEffects), now);
72 return Math.max(gear, status);
73 }
74
75 export function tileIndexLocal (tileX, tileY, chunkSize = CHUNK_SIZE)
76 {
77 const localX = ((tileX % chunkSize) + chunkSize) % chunkSize;
78 const localY = ((tileY % chunkSize) + chunkSize) % chunkSize;
79 return localY * chunkSize + localX;
80 }
@@ -0,0 +1,80 @@
1import { CHUNK_SIZE } from "../protocol/constants.js";
2import { lightIntensity, falloffAtDistance } from "./raycast.js";
3import { equippedLightRadiusTiles } from "../definitions/items.js";
4import { statusExtraLightRadius } from "../statusEffects/rules.js";
5
6/** Night ambient darkness 0–1 (matches client `nightFactor`). */
7export function nightFactor (hour, nightDarkness = 0.72)
8{
9 const peak = Math.min(1, Math.max(0, nightDarkness));
10 if (hour >= 8 && hour <= 16)
11 { return 0; }
12 if (hour >= 22 || hour <= 5)
13 { return peak; }
14 if (hour < 8)
15 { return lerp(peak, 0, (hour - 5) / 3); }
16 return lerp(0, peak, (hour - 16) / 6);
17}
18
19function lerp (a, b, t)
20{
21 return a + (b - a) * Math.min(1, Math.max(0, t));
22}
23
24function chebyshev (ax, ay, bx, by)
25{
26 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
27}
28
29/** Baked static light 0–1 at a tile (0 when unlit / unbaked). */
30export function bakedTileLight01 (lightArray, index)
31{
32 if (!lightArray || index < 0 || index >= lightArray.length)
33 { return 0; }
34 return lightIntensity(lightArray[index] ?? 0);
35}
36
37/** Combined target-tile lighting 0–1 for combat (static + entity lights + time of day). */
38export function tileCombatLight01 ({
39 bakedLight01 = 0,
40 entityLight01 = 0,
41 worldHour = 12,
42 nightDarkness = 0.72
43} = {})
44{
45 const localLit = Math.min(1, Math.max(bakedLight01, entityLight01));
46 const ambientDark = nightFactor(worldHour, nightDarkness);
47 return 1 - ambientDark * (1 - localLit);
48}
49
50/** Best dynamic entity light reaching a tile (0–1). */
51export function entityLightAtTile (ecs, Component, tileX, tileY, now = Date.now())
52{
53 let best = 0;
54 for (const entity of ecs.query(Component.position))
55 {
56 const radius = entityLightRadiusTiles(ecs, entity.handle, Component, now);
57 if (radius <= 0)
58 { continue; }
59 const dist = chebyshev(entity.position.tileX, entity.position.tileY, tileX, tileY);
60 if (dist > radius)
61 { continue; }
62 best = Math.max(best, falloffAtDistance(dist, radius));
63 }
64 return best;
65}
66
67function entityLightRadiusTiles (ecs, handle, Component, now)
68{
69 const equipment = ecs.get(handle, Component.equipment);
70 const gear = equippedLightRadiusTiles(equipment);
71 const status = statusExtraLightRadius(ecs.get(handle, Component.statusEffects), now);
72 return Math.max(gear, status);
73}
74
75export function tileIndexLocal (tileX, tileY, chunkSize = CHUNK_SIZE)
76{
77 const localX = ((tileX % chunkSize) + chunkSize) % chunkSize;
78 const localY = ((tileY % chunkSize) + chunkSize) % chunkSize;
79 return localY * chunkSize + localX;
80}
shared/protocol/constants.js +2 −0
@@ -145,6 +145,8 @@ export const MessageType = Object.freeze({
145 145 combatHit: "COMBAT_HIT",
146 146 combatMiss: "COMBAT_MISS",
147 147 combatBlock: "COMBAT_BLOCK",
148 combatProjectile: "COMBAT_PROJECTILE",
149 combatNoArrows: "COMBAT_NO_ARROWS",
148 150 entityHealth: "ENTITY_HEALTH",
149 151 playerDied: "PLAYER_DIED",
150 152 respawn: "RESPAWN",
@@ -145,6 +145,8 @@ export const MessageType = Object.freeze({
145 combatHit: "COMBAT_HIT",
145 combatHit: "COMBAT_HIT",
146 combatMiss: "COMBAT_MISS",
146 combatMiss: "COMBAT_MISS",
147 combatBlock: "COMBAT_BLOCK",
147 combatBlock: "COMBAT_BLOCK",
148 combatProjectile: "COMBAT_PROJECTILE",
149 combatNoArrows: "COMBAT_NO_ARROWS",
148 entityHealth: "ENTITY_HEALTH",
150 entityHealth: "ENTITY_HEALTH",
149 playerDied: "PLAYER_DIED",
151 playerDied: "PLAYER_DIED",
150 respawn: "RESPAWN",
152 respawn: "RESPAWN",