BlueGit

timfa questward

Add riskiest non-overworld follow-up tests for spawners and PvP logout.

Cover same local spawnerId across overworld+cave for item and mob spawners,
PvP combat-logout offline death (loot/altar/letter), and multi-worker region
ownership. Prefer death-dimension altars for church offline letters.

timfa Tim Falken · pushed by timfa

Authored 2026-09-15 · 2 months ago

Hash
cfe3f8771b33ff9d939766842c7c8e21ce7a0a9e
Parent
64b985b7
4 files changed +488 −12
server/src/combat/combatLogout.js +22 −10
@@ -14,6 +14,7 @@ import
14 14 formatCombatLogoutCowardiceBody
15 15 } from "../../../shared/courier/systemLetters.js";
16 16 import { defaultPlayerSkills } from "../../../shared/skills/state.js";
17 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
17 18
18 19 /**
19 20 * Apply PvP combat-logout cowardice (skull + bank letter), honouring the
@@ -72,38 +73,49 @@ export function dispatchCombatLogoutBankLetter (simulation, characterId)
72 73 });
73 74 }
74 75
75 export function dispatchChurchOfflineResurrectionLetter (simulation, characterId, tileX, tileY)
76 export function dispatchChurchOfflineResurrectionLetter (simulation, characterId, tileX, tileY, dimensionId = OVERWORLD_ID)
76 77 {
77 78 if (!simulation.courier)
78 79 { return; }
79 const altar = nearestAltarTile(simulation, tileX, tileY);
80 const altar = nearestAltarTile(simulation, tileX, tileY, dimensionId);
80 81 simulation.courier.enqueueSystemLetter({
81 82 characterId,
82 83 originTileX: altar?.tileX ?? (tileX | 0),
83 84 originTileY: altar?.tileY ?? (tileY | 0),
84 originDimensionId: altar?.dimensionId,
85 originDimensionId: altar?.dimensionId ?? normalizeDimensionId(dimensionId),
85 86 authorDisplayName: CHURCH_LETTER_AUTHOR,
86 87 body: formatChurchOfflineResurrectionBody()
87 88 });
88 89 }
89 90
90 function nearestAltarTile (simulation, tileX, tileY)
91 /** Prefer same-dimension altars (matches respawn), then nearest overall. */
92 function nearestAltarTile (simulation, tileX, tileY, dimensionId = null)
91 93 {
92 94 const altars = simulation.altarTiles ?? [];
93 95 if (!altars.length)
94 96 { return null; }
95 let best = null;
96 let bestDist = Infinity;
97 const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : null;
98 let bestSame = null;
99 let bestSameDist = Infinity;
100 let bestAny = null;
101 let bestAnyDist = Infinity;
97 102 for (const altar of altars)
98 103 {
99 104 const dist = Math.hypot((altar.tileX | 0) - (tileX | 0), (altar.tileY | 0) - (tileY | 0));
100 if (dist < bestDist)
105 if (dist < bestAnyDist)
101 106 {
102 best = altar;
103 bestDist = dist;
107 bestAnyDist = dist;
108 bestAny = altar;
109 }
110 if (dim != null
111 && normalizeDimensionId(altar.dimensionId ?? OVERWORLD_ID) === dim
112 && dist < bestSameDist)
113 {
114 bestSameDist = dist;
115 bestSame = altar;
104 116 }
105 117 }
106 return best;
118 return bestSame ?? bestAny;
107 119 }
108 120
109 121 export function coinsDroppedFromDeathEvents (events)
@@ -14,6 +14,7 @@ import
14 formatCombatLogoutCowardiceBody
14 formatCombatLogoutCowardiceBody
15 } from "../../../shared/courier/systemLetters.js";
15 } from "../../../shared/courier/systemLetters.js";
16import { defaultPlayerSkills } from "../../../shared/skills/state.js";
16import { defaultPlayerSkills } from "../../../shared/skills/state.js";
17import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
17
18
18/**
19/**
19 * Apply PvP combat-logout cowardice (skull + bank letter), honouring the
20 * Apply PvP combat-logout cowardice (skull + bank letter), honouring the
@@ -72,38 +73,49 @@ export function dispatchCombatLogoutBankLetter (simulation, characterId)
72 });
73 });
73}
74}
74
75
75export function dispatchChurchOfflineResurrectionLetter (simulation, characterId, tileX, tileY)
76export function dispatchChurchOfflineResurrectionLetter (simulation, characterId, tileX, tileY, dimensionId = OVERWORLD_ID)
76{
77{
77 if (!simulation.courier)
78 if (!simulation.courier)
78 { return; }
79 { return; }
79 const altar = nearestAltarTile(simulation, tileX, tileY);
80 const altar = nearestAltarTile(simulation, tileX, tileY, dimensionId);
80 simulation.courier.enqueueSystemLetter({
81 simulation.courier.enqueueSystemLetter({
81 characterId,
82 characterId,
82 originTileX: altar?.tileX ?? (tileX | 0),
83 originTileX: altar?.tileX ?? (tileX | 0),
83 originTileY: altar?.tileY ?? (tileY | 0),
84 originTileY: altar?.tileY ?? (tileY | 0),
84 originDimensionId: altar?.dimensionId,
85 originDimensionId: altar?.dimensionId ?? normalizeDimensionId(dimensionId),
85 authorDisplayName: CHURCH_LETTER_AUTHOR,
86 authorDisplayName: CHURCH_LETTER_AUTHOR,
86 body: formatChurchOfflineResurrectionBody()
87 body: formatChurchOfflineResurrectionBody()
87 });
88 });
88}
89}
89
90
90function nearestAltarTile (simulation, tileX, tileY)
91/** Prefer same-dimension altars (matches respawn), then nearest overall. */
92function nearestAltarTile (simulation, tileX, tileY, dimensionId = null)
91{
93{
92 const altars = simulation.altarTiles ?? [];
94 const altars = simulation.altarTiles ?? [];
93 if (!altars.length)
95 if (!altars.length)
94 { return null; }
96 { return null; }
95 let best = null;
97 const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : null;
96 let bestDist = Infinity;
98 let bestSame = null;
99 let bestSameDist = Infinity;
100 let bestAny = null;
101 let bestAnyDist = Infinity;
97 for (const altar of altars)
102 for (const altar of altars)
98 {
103 {
99 const dist = Math.hypot((altar.tileX | 0) - (tileX | 0), (altar.tileY | 0) - (tileY | 0));
104 const dist = Math.hypot((altar.tileX | 0) - (tileX | 0), (altar.tileY | 0) - (tileY | 0));
100 if (dist < bestDist)
105 if (dist < bestAnyDist)
101 {
106 {
102 best = altar;
107 bestAnyDist = dist;
103 bestDist = dist;
108 bestAny = altar;
109 }
110 if (dim != null
111 && normalizeDimensionId(altar.dimensionId ?? OVERWORLD_ID) === dim
112 && dist < bestSameDist)
113 {
114 bestSameDist = dist;
115 bestSame = altar;
104 }
116 }
105 }
117 }
106 return best;
118 return bestSame ?? bestAny;
107}
119}
108
120
109export function coinsDroppedFromDeathEvents (events)
121export function coinsDroppedFromDeathEvents (events)
server/src/simulation/simulation.js +6 −1
@@ -2404,11 +2404,16 @@ export class Simulation
2404 2404 now: this.now
2405 2405 });
2406 2406 }
2407 const deathRecord = this.directory.get(event.entityId);
2408 const deathDimensionId = normalizeDimensionId(
2409 deathRecord?.dimensionId ?? event.dimensionId ?? OVERWORLD_ID
2410 );
2407 2411 dispatchChurchOfflineResurrectionLetter(
2408 2412 this,
2409 2413 characterId,
2410 2414 event.tileX | 0,
2411 event.tileY | 0
2415 event.tileY | 0,
2416 deathDimensionId
2412 2417 );
2413 2418 try
2414 2419 { events.push(...this.#respawnCharacter(event.sessionId ?? null, characterId)); }
@@ -2404,11 +2404,16 @@ export class Simulation
2404 now: this.now
2404 now: this.now
2405 });
2405 });
2406 }
2406 }
2407 const deathRecord = this.directory.get(event.entityId);
2408 const deathDimensionId = normalizeDimensionId(
2409 deathRecord?.dimensionId ?? event.dimensionId ?? OVERWORLD_ID
2410 );
2407 dispatchChurchOfflineResurrectionLetter(
2411 dispatchChurchOfflineResurrectionLetter(
2408 this,
2412 this,
2409 characterId,
2413 characterId,
2410 event.tileX | 0,
2414 event.tileX | 0,
2411 event.tileY | 0
2415 event.tileY | 0,
2416 deathDimensionId
2412 );
2417 );
2413 try
2418 try
2414 { events.push(...this.#respawnCharacter(event.sessionId ?? null, characterId)); }
2419 { events.push(...this.#respawnCharacter(event.sessionId ?? null, characterId)); }
server/tests/dimension-interactions.test.js +303 −1
@@ -20,8 +20,15 @@ import { Component } from "../src/ecs/components.js";
20 20 import { WorkerMessage } from "../src/simulation/protocol.js";
21 21 import { eventInterestKeys } from "../src/gateway/eventInterest.js";
22 22 import { chunkKey, tileToChunk } from "../src/world/coordinates.js";
23 import { makeCharacter, openChunkStrip, writeOpenChunk } from "./helpers/simulationHarness.js";
23 import { makeCharacter, openChunkStrip, writeOpenChunk, ensureDimension, makeDimensionSimulation, pinEastSplit } from "./helpers/simulationHarness.js";
24 24 import { normalizeQuestDef } from "../../shared/quests/normalize.js";
25 import { normalizeSpawnerConfig } from "../../shared/definitions/mobs.js";
26 import { regionKey } from "../src/world/coordinates.js";
27 import
28 {
29 CHURCH_LETTER_AUTHOR,
30 formatChurchOfflineResurrectionBody
31 } from "../../shared/courier/systemLetters.js";
25 32
26 33 const CAVE_ID = "test-cave";
27 34
@@ -385,3 +392,298 @@ test("combat logout quiet despawn carries cave dimensionId", () =>
385 392 finally
386 393 { harness.close(); }
387 394 });
395
396
397 const SHARED_MOB_SPAWNER_ID = "shared-mob-local";
398
399 function placeMobSpawner (worldDb, localX, localY, dimensionId, spawnerId, extras = {})
400 {
401 ensureDimension(worldDb, dimensionId);
402 const rev = worldDb.getActiveRevisionId();
403 const data = createEmptyChunkData();
404 data.open = true;
405 data.spawners = [{
406 localX,
407 localY,
408 config: normalizeSpawnerConfig({
409 spawnerId,
410 mobTypeId: MobId.rat,
411 maxAlive: 1,
412 spawnRangeTiles: 0,
413 maxWanderRangeTiles: 0,
414 respawnDelaySeconds: 60,
415 ...extras
416 })
417 }];
418 worldDb.saveChunkVersion(0, 0, rev, true, encodeChunkBlob(data), dimensionId);
419 }
420
421 test("authored overworld + cave mob spawners with same local spawnerId stay independent", () =>
422 {
423 const harness = makeDimensionSimulation(CAVE_ID, { workerCount: 1 });
424 try
425 {
426 placeMobSpawner(harness.worldDb, 9, 8, OVERWORLD_ID, SHARED_MOB_SPAWNER_ID, {
427 drops: [{ itemId: ItemId.apple, chance: 1, quantityMin: 1, quantityMax: 1 }]
428 });
429 placeMobSpawner(harness.worldDb, 9, 8, CAVE_ID, SHARED_MOB_SPAWNER_ID, {
430 drops: [{ itemId: ItemId.stick, chance: 1, quantityMin: 1, quantityMax: 1 }]
431 });
432 harness.simulation.reloadWorld();
433
434 const overChar = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, lastName: "MobOver" });
435 const overId = harness.simulation.spawnCharacter(1, overChar);
436 const caveChar = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, lastName: "MobCave" });
437 harness.stateDb.saveCharacterPosition(caveChar.character_id, 8, 8, "walk", CAVE_ID);
438 const caveId = harness.simulation.spawnCharacter(2, caveChar);
439 assert.equal(harness.simulation.positionOf(overId).dimensionId, OVERWORLD_ID);
440 assert.equal(harness.simulation.positionOf(caveId).dimensionId, CAVE_ID);
441
442 for (let i = 0; i < 40; i++)
443 {
444 harness.advance(50);
445 harness.simulation.step();
446 }
447
448 const worker = workerOf(harness.simulation, caveId);
449 const rats = [];
450 for (const entity of worker.world.ecs.query(Component.creature, Component.position, Component.spawnOrigin))
451 {
452 if (entity.creature.mobTypeId !== MobId.rat)
453 { continue; }
454 rats.push({
455 entityId: entity.entityId,
456 dimensionId: entity.position.dimensionId,
457 spawnerId: entity.spawnOrigin.spawnerId
458 });
459 }
460 const caveRats = rats.filter((r) => r.dimensionId === CAVE_ID);
461 const overRats = rats.filter((r) => r.dimensionId === OVERWORLD_ID);
462 assert.equal(caveRats.length, 1, JSON.stringify(rats));
463 assert.equal(overRats.length, 1, JSON.stringify(rats));
464 assert.equal(caveRats[0].spawnerId, `${CAVE_ID}:${SHARED_MOB_SPAWNER_ID}`);
465 assert.equal(overRats[0].spawnerId, `${OVERWORLD_ID}:${SHARED_MOB_SPAWNER_ID}`);
466
467 worker.world.ecs.get(worker.world.ecs.handleOf(caveRats[0].entityId), Component.health).current = 1;
468 const killEvents = applyDamageAndKill(
469 worker.world,
470 caveId,
471 caveRats[0].entityId,
472 1,
473 harness.now()
474 );
475 assert.ok(killEvents.some((e) => e.type === "entity-despawn" && e.entityId === caveRats[0].entityId));
476 const stillOver = [];
477 for (const entity of worker.world.ecs.query(Component.creature, Component.position, Component.spawnOrigin))
478 {
479 if (entity.creature.mobTypeId !== MobId.rat)
480 { continue; }
481 if (entity.position.dimensionId === OVERWORLD_ID)
482 { stillOver.push(entity.spawnOrigin.spawnerId); }
483 }
484 assert.deepEqual(stillOver, [`${OVERWORLD_ID}:${SHARED_MOB_SPAWNER_ID}`]);
485 }
486 finally
487 { harness.close(); }
488 });
489
490 test("region ownership keys are independent per dimension", () =>
491 {
492 assert.notEqual(regionKey(0, 0, OVERWORLD_ID), regionKey(0, 0, CAVE_ID));
493 const harness = makeDimensionSimulation(CAVE_ID, {
494 workerCount: 2,
495 pinRegion: pinEastSplit
496 });
497 try
498 {
499 const overChar = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, lastName: "OwnOver" });
500 const overId = harness.simulation.spawnCharacter(1, overChar);
501 const caveChar = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, lastName: "OwnCave" });
502 harness.stateDb.saveCharacterPosition(caveChar.character_id, 8, 8, "walk", CAVE_ID);
503 const caveId = harness.simulation.spawnCharacter(2, caveChar);
504 harness.simulation.step();
505 assert.equal(harness.simulation.positionOf(overId).dimensionId, OVERWORLD_ID);
506 assert.equal(harness.simulation.positionOf(caveId).dimensionId, CAVE_ID);
507 assert.equal(
508 harness.simulation.chunkIsSimulating(8, 8, OVERWORLD_ID),
509 true
510 );
511 assert.equal(
512 harness.simulation.chunkIsSimulating(8, 8, CAVE_ID),
513 true
514 );
515 const owners = harness.simulation.regionOwner;
516 assert.ok(owners.has(regionKey(0, 0, OVERWORLD_ID)), "overworld region owned");
517 assert.ok(owners.has(regionKey(0, 0, CAVE_ID)), "cave region owned");
518 }
519 finally
520 { harness.close(); }
521 });
522
523 test("PvP combat-logout offline death in cave keeps loot and altar/letter dimension-aware", () =>
524 {
525 const harness = makeCaveHarness();
526 try
527 {
528 // Overworld altar + bank; death happens in cave (no cave altar).
529 const overChunk = createEmptyChunkData();
530 overChunk.open = true;
531 overChunk.blocks[8 * 16 + 4] = { typeId: BlockType.bank, state: 0 };
532 harness.worldDb.saveChunkVersion(
533 0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(overChunk), OVERWORLD_ID
534 );
535 const altarChunk = createEmptyChunkData();
536 altarChunk.open = true;
537 altarChunk.blocks[8 * 16 + 4] = { typeId: BlockType.churchAltar, state: 0 }; // tile 20,8 in chunk 1,0
538 // chunk 1,0 local (4,8) => tileX=20, tileY=8
539 harness.worldDb.saveChunkVersion(
540 1, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(altarChunk), OVERWORLD_ID
541 );
542 // Also place a closer cave altar so letter/respawn preference is tested against XY proximity.
543 const caveAltar = createEmptyChunkData();
544 caveAltar.open = true;
545 caveAltar.blocks[8 * 16 + 10] = { typeId: BlockType.churchAltar, state: 0 }; // tile 10,8
546 harness.worldDb.saveChunkVersion(
547 0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(caveAltar), CAVE_ID
548 );
549 harness.simulation.reloadWorld();
550
551 const victim = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Vic", lastName: "CaveVic" });
552 harness.stateDb.saveCharacterPosition(victim.character_id, 8, 8, "walk", CAVE_ID);
553 harness.stateDb.saveBag(victim.character_id, {
554 inventory: emptySlots(),
555 equipment: emptyEquipment(),
556 vault: [],
557 vaultReserved: []
558 });
559 const attacker = makeCharacter(harness.stateDb, { tileX: 9, tileY: 8, firstName: "Atk", lastName: "CaveAtk" });
560 harness.stateDb.saveCharacterPosition(attacker.character_id, 9, 8, "walk", CAVE_ID);
561 const victimId = harness.simulation.spawnCharacter(1, victim);
562 const attackerId = harness.simulation.spawnCharacter(2, attacker);
563 assert.equal(harness.simulation.positionOf(victimId).dimensionId, CAVE_ID);
564 assert.equal(harness.simulation.positionOf(attackerId).dimensionId, CAVE_ID);
565
566 harness.simulation.enqueue(1, {
567 type: "attack",
568 characterId: victim.character_id,
569 targetEntityId: attackerId
570 });
571 harness.simulation.step();
572 assert.equal(harness.simulation.beginCombatLogout(victim.character_id), true);
573 assert.equal(
574 harness.simulation.combatLogouts.get(victim.character_id).pendingCowardice,
575 true
576 );
577
578 const worker = workerOf(harness.simulation, victimId);
579 worker.world.ecs.get(worker.world.ecs.handleOf(victimId), Component.health).current = 1;
580 const deathEvents = applyDamageAndKill(worker.world, attackerId, victimId, 999, harness.now());
581 const died = deathEvents.find((event) => event.type === "player-died");
582 assert.ok(died, JSON.stringify(deathEvents.map((e) => e.type)));
583 const applied = harness.simulation.applyPlayerDiedEvent(died);
584
585 const loot = applied.filter((event) =>
586 event.type === "ground-item-appear"
587 && (event.stack?.itemId === ItemId.bones || event.stack?.itemId === ItemId.skull)
588 );
589 assert.ok(loot.length >= 2, JSON.stringify(applied.filter((e) => e.type === "ground-item-appear")));
590 for (const drop of loot)
591 { assert.equal(drop.dimensionId, CAVE_ID); }
592 const onGround = [...worker.world.groundItems.values()].filter(
593 (item) => item.dimensionId === CAVE_ID
594 && (item.stack?.itemId === ItemId.bones || item.stack?.itemId === ItemId.skull)
595 );
596 assert.ok(onGround.length >= 2);
597 assert.equal(
598 [...worker.world.groundItems.values()].filter(
599 (item) => item.dimensionId === OVERWORLD_ID
600 && (item.stack?.itemId === ItemId.bones || item.stack?.itemId === ItemId.skull)
601 ).length,
602 0
603 );
604
605 const despawn = applied.find((event) =>
606 event.type === "entity-despawn" && event.entityId === victimId && event.cause === "death"
607 );
608 assert.ok(despawn);
609 assert.equal(despawn.dimensionId, CAVE_ID);
610
611 const letters = harness.stateDb.listHeldCourierDeliveries(victim.character_id)
612 .map((hold) => hold.cargo?.stack)
613 .filter((stack) => stack?.itemId === ItemId.letter);
614 assert.ok(letters.some((stack) =>
615 stack.instance?.authorDisplayName === CHURCH_LETTER_AUTHOR
616 && stack.instance?.body === formatChurchOfflineResurrectionBody()
617 ));
618 // Church letter should originate from the cave altar (same dim), not the farther overworld one.
619 const churchHold = harness.stateDb.listHeldCourierDeliveries(victim.character_id)
620 .find((hold) => hold.cargo?.stack?.instance?.authorDisplayName === CHURCH_LETTER_AUTHOR);
621 assert.ok(churchHold);
622 assert.equal(churchHold.originDimensionId, CAVE_ID);
623
624 assert.equal(harness.simulation.isCharacterInWorld(victim.character_id), false);
625 assert.equal(harness.stateDb.getCharacter(victim.character_id).is_dead, 0);
626 const row = harness.stateDb.getCharacter(victim.character_id);
627 // Respawn prefers death-dimension altar at (10,8).
628 assert.equal(row.dimension_id, CAVE_ID);
629 assert.equal(
630 Math.max(Math.abs(row.tile_x - 10), Math.abs(row.tile_y - 8)),
631 1
632 );
633 }
634 finally
635 { harness.close(); }
636 });
637
638 test("PvP combat-logout quiet despawn in cave still carries cave dimensionId", () =>
639 {
640 const harness = makeCaveHarness();
641 try
642 {
643 const victim = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Quiet", lastName: "Vic" });
644 harness.stateDb.saveCharacterPosition(victim.character_id, 8, 8, "walk", CAVE_ID);
645 const attacker = makeCharacter(harness.stateDb, { tileX: 9, tileY: 8, firstName: "Quiet", lastName: "Atk" });
646 harness.stateDb.saveCharacterPosition(attacker.character_id, 9, 8, "walk", CAVE_ID);
647 const victimId = harness.simulation.spawnCharacter(1, victim);
648 const attackerId = harness.simulation.spawnCharacter(2, attacker);
649 harness.simulation.enqueue(1, {
650 type: "attack",
651 characterId: victim.character_id,
652 targetEntityId: attackerId
653 });
654 harness.simulation.step();
655 assert.equal(harness.simulation.beginCombatLogout(victim.character_id), true);
656 harness.simulation.drainReplication();
657
658 const record = harness.simulation.entityRecord(victimId);
659 harness.simulation.workers[record.workerId].call({
660 type: WorkerMessage.clearCombat,
661 entityId: victimId,
662 targetEntityId: victimId
663 });
664 const track = harness.simulation.combatTracking.get(victim.character_id);
665 track.lastCombatActivityAt = harness.now() - COMBAT_LOGOUT_MS - 1;
666 track.wasInCombat = false;
667 harness.simulation.combatLogouts.get(victim.character_id).startedAt = harness.now() - COMBAT_LOGOUT_MS - 1;
668
669 const replication = [];
670 for (let i = 0; i < 60; i++)
671 {
672 harness.advance(50);
673 const stepped = harness.simulation.step();
674 replication.push(...(stepped.replication ?? []));
675 replication.push(...harness.simulation.drainReplication());
676 }
677 assert.equal(harness.simulation.isCharacterInWorld(victim.character_id), false);
678 const despawn = replication.find((event) =>
679 event.type === "entity-despawn" && event.entityId === victimId
680 );
681 assert.ok(despawn);
682 assert.equal(despawn.dimensionId, CAVE_ID);
683 const keys = eventInterestKeys(despawn, () => null);
684 assert.equal(keys.dimensionId, CAVE_ID);
685 assert.equal(keys.toKey, chunkKey(tileToChunk(8), tileToChunk(8), CAVE_ID));
686 }
687 finally
688 { harness.close(); }
689 });
@@ -20,8 +20,15 @@ import { Component } from "../src/ecs/components.js";
20import { WorkerMessage } from "../src/simulation/protocol.js";
20import { WorkerMessage } from "../src/simulation/protocol.js";
21import { eventInterestKeys } from "../src/gateway/eventInterest.js";
21import { eventInterestKeys } from "../src/gateway/eventInterest.js";
22import { chunkKey, tileToChunk } from "../src/world/coordinates.js";
22import { chunkKey, tileToChunk } from "../src/world/coordinates.js";
23import { makeCharacter, openChunkStrip, writeOpenChunk } from "./helpers/simulationHarness.js";
23import { makeCharacter, openChunkStrip, writeOpenChunk, ensureDimension, makeDimensionSimulation, pinEastSplit } from "./helpers/simulationHarness.js";
24import { normalizeQuestDef } from "../../shared/quests/normalize.js";
24import { normalizeQuestDef } from "../../shared/quests/normalize.js";
25import { normalizeSpawnerConfig } from "../../shared/definitions/mobs.js";
26import { regionKey } from "../src/world/coordinates.js";
27import
28 {
29 CHURCH_LETTER_AUTHOR,
30 formatChurchOfflineResurrectionBody
31 } from "../../shared/courier/systemLetters.js";
25
32
26const CAVE_ID = "test-cave";
33const CAVE_ID = "test-cave";
27
34
@@ -385,3 +392,298 @@ test("combat logout quiet despawn carries cave dimensionId", () =>
385 finally
392 finally
386 { harness.close(); }
393 { harness.close(); }
387});
394});
395
396
397const SHARED_MOB_SPAWNER_ID = "shared-mob-local";
398
399function placeMobSpawner (worldDb, localX, localY, dimensionId, spawnerId, extras = {})
400{
401 ensureDimension(worldDb, dimensionId);
402 const rev = worldDb.getActiveRevisionId();
403 const data = createEmptyChunkData();
404 data.open = true;
405 data.spawners = [{
406 localX,
407 localY,
408 config: normalizeSpawnerConfig({
409 spawnerId,
410 mobTypeId: MobId.rat,
411 maxAlive: 1,
412 spawnRangeTiles: 0,
413 maxWanderRangeTiles: 0,
414 respawnDelaySeconds: 60,
415 ...extras
416 })
417 }];
418 worldDb.saveChunkVersion(0, 0, rev, true, encodeChunkBlob(data), dimensionId);
419}
420
421test("authored overworld + cave mob spawners with same local spawnerId stay independent", () =>
422{
423 const harness = makeDimensionSimulation(CAVE_ID, { workerCount: 1 });
424 try
425 {
426 placeMobSpawner(harness.worldDb, 9, 8, OVERWORLD_ID, SHARED_MOB_SPAWNER_ID, {
427 drops: [{ itemId: ItemId.apple, chance: 1, quantityMin: 1, quantityMax: 1 }]
428 });
429 placeMobSpawner(harness.worldDb, 9, 8, CAVE_ID, SHARED_MOB_SPAWNER_ID, {
430 drops: [{ itemId: ItemId.stick, chance: 1, quantityMin: 1, quantityMax: 1 }]
431 });
432 harness.simulation.reloadWorld();
433
434 const overChar = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, lastName: "MobOver" });
435 const overId = harness.simulation.spawnCharacter(1, overChar);
436 const caveChar = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, lastName: "MobCave" });
437 harness.stateDb.saveCharacterPosition(caveChar.character_id, 8, 8, "walk", CAVE_ID);
438 const caveId = harness.simulation.spawnCharacter(2, caveChar);
439 assert.equal(harness.simulation.positionOf(overId).dimensionId, OVERWORLD_ID);
440 assert.equal(harness.simulation.positionOf(caveId).dimensionId, CAVE_ID);
441
442 for (let i = 0; i < 40; i++)
443 {
444 harness.advance(50);
445 harness.simulation.step();
446 }
447
448 const worker = workerOf(harness.simulation, caveId);
449 const rats = [];
450 for (const entity of worker.world.ecs.query(Component.creature, Component.position, Component.spawnOrigin))
451 {
452 if (entity.creature.mobTypeId !== MobId.rat)
453 { continue; }
454 rats.push({
455 entityId: entity.entityId,
456 dimensionId: entity.position.dimensionId,
457 spawnerId: entity.spawnOrigin.spawnerId
458 });
459 }
460 const caveRats = rats.filter((r) => r.dimensionId === CAVE_ID);
461 const overRats = rats.filter((r) => r.dimensionId === OVERWORLD_ID);
462 assert.equal(caveRats.length, 1, JSON.stringify(rats));
463 assert.equal(overRats.length, 1, JSON.stringify(rats));
464 assert.equal(caveRats[0].spawnerId, `${CAVE_ID}:${SHARED_MOB_SPAWNER_ID}`);
465 assert.equal(overRats[0].spawnerId, `${OVERWORLD_ID}:${SHARED_MOB_SPAWNER_ID}`);
466
467 worker.world.ecs.get(worker.world.ecs.handleOf(caveRats[0].entityId), Component.health).current = 1;
468 const killEvents = applyDamageAndKill(
469 worker.world,
470 caveId,
471 caveRats[0].entityId,
472 1,
473 harness.now()
474 );
475 assert.ok(killEvents.some((e) => e.type === "entity-despawn" && e.entityId === caveRats[0].entityId));
476 const stillOver = [];
477 for (const entity of worker.world.ecs.query(Component.creature, Component.position, Component.spawnOrigin))
478 {
479 if (entity.creature.mobTypeId !== MobId.rat)
480 { continue; }
481 if (entity.position.dimensionId === OVERWORLD_ID)
482 { stillOver.push(entity.spawnOrigin.spawnerId); }
483 }
484 assert.deepEqual(stillOver, [`${OVERWORLD_ID}:${SHARED_MOB_SPAWNER_ID}`]);
485 }
486 finally
487 { harness.close(); }
488});
489
490test("region ownership keys are independent per dimension", () =>
491{
492 assert.notEqual(regionKey(0, 0, OVERWORLD_ID), regionKey(0, 0, CAVE_ID));
493 const harness = makeDimensionSimulation(CAVE_ID, {
494 workerCount: 2,
495 pinRegion: pinEastSplit
496 });
497 try
498 {
499 const overChar = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, lastName: "OwnOver" });
500 const overId = harness.simulation.spawnCharacter(1, overChar);
501 const caveChar = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, lastName: "OwnCave" });
502 harness.stateDb.saveCharacterPosition(caveChar.character_id, 8, 8, "walk", CAVE_ID);
503 const caveId = harness.simulation.spawnCharacter(2, caveChar);
504 harness.simulation.step();
505 assert.equal(harness.simulation.positionOf(overId).dimensionId, OVERWORLD_ID);
506 assert.equal(harness.simulation.positionOf(caveId).dimensionId, CAVE_ID);
507 assert.equal(
508 harness.simulation.chunkIsSimulating(8, 8, OVERWORLD_ID),
509 true
510 );
511 assert.equal(
512 harness.simulation.chunkIsSimulating(8, 8, CAVE_ID),
513 true
514 );
515 const owners = harness.simulation.regionOwner;
516 assert.ok(owners.has(regionKey(0, 0, OVERWORLD_ID)), "overworld region owned");
517 assert.ok(owners.has(regionKey(0, 0, CAVE_ID)), "cave region owned");
518 }
519 finally
520 { harness.close(); }
521});
522
523test("PvP combat-logout offline death in cave keeps loot and altar/letter dimension-aware", () =>
524{
525 const harness = makeCaveHarness();
526 try
527 {
528 // Overworld altar + bank; death happens in cave (no cave altar).
529 const overChunk = createEmptyChunkData();
530 overChunk.open = true;
531 overChunk.blocks[8 * 16 + 4] = { typeId: BlockType.bank, state: 0 };
532 harness.worldDb.saveChunkVersion(
533 0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(overChunk), OVERWORLD_ID
534 );
535 const altarChunk = createEmptyChunkData();
536 altarChunk.open = true;
537 altarChunk.blocks[8 * 16 + 4] = { typeId: BlockType.churchAltar, state: 0 }; // tile 20,8 in chunk 1,0
538 // chunk 1,0 local (4,8) => tileX=20, tileY=8
539 harness.worldDb.saveChunkVersion(
540 1, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(altarChunk), OVERWORLD_ID
541 );
542 // Also place a closer cave altar so letter/respawn preference is tested against XY proximity.
543 const caveAltar = createEmptyChunkData();
544 caveAltar.open = true;
545 caveAltar.blocks[8 * 16 + 10] = { typeId: BlockType.churchAltar, state: 0 }; // tile 10,8
546 harness.worldDb.saveChunkVersion(
547 0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(caveAltar), CAVE_ID
548 );
549 harness.simulation.reloadWorld();
550
551 const victim = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Vic", lastName: "CaveVic" });
552 harness.stateDb.saveCharacterPosition(victim.character_id, 8, 8, "walk", CAVE_ID);
553 harness.stateDb.saveBag(victim.character_id, {
554 inventory: emptySlots(),
555 equipment: emptyEquipment(),
556 vault: [],
557 vaultReserved: []
558 });
559 const attacker = makeCharacter(harness.stateDb, { tileX: 9, tileY: 8, firstName: "Atk", lastName: "CaveAtk" });
560 harness.stateDb.saveCharacterPosition(attacker.character_id, 9, 8, "walk", CAVE_ID);
561 const victimId = harness.simulation.spawnCharacter(1, victim);
562 const attackerId = harness.simulation.spawnCharacter(2, attacker);
563 assert.equal(harness.simulation.positionOf(victimId).dimensionId, CAVE_ID);
564 assert.equal(harness.simulation.positionOf(attackerId).dimensionId, CAVE_ID);
565
566 harness.simulation.enqueue(1, {
567 type: "attack",
568 characterId: victim.character_id,
569 targetEntityId: attackerId
570 });
571 harness.simulation.step();
572 assert.equal(harness.simulation.beginCombatLogout(victim.character_id), true);
573 assert.equal(
574 harness.simulation.combatLogouts.get(victim.character_id).pendingCowardice,
575 true
576 );
577
578 const worker = workerOf(harness.simulation, victimId);
579 worker.world.ecs.get(worker.world.ecs.handleOf(victimId), Component.health).current = 1;
580 const deathEvents = applyDamageAndKill(worker.world, attackerId, victimId, 999, harness.now());
581 const died = deathEvents.find((event) => event.type === "player-died");
582 assert.ok(died, JSON.stringify(deathEvents.map((e) => e.type)));
583 const applied = harness.simulation.applyPlayerDiedEvent(died);
584
585 const loot = applied.filter((event) =>
586 event.type === "ground-item-appear"
587 && (event.stack?.itemId === ItemId.bones || event.stack?.itemId === ItemId.skull)
588 );
589 assert.ok(loot.length >= 2, JSON.stringify(applied.filter((e) => e.type === "ground-item-appear")));
590 for (const drop of loot)
591 { assert.equal(drop.dimensionId, CAVE_ID); }
592 const onGround = [...worker.world.groundItems.values()].filter(
593 (item) => item.dimensionId === CAVE_ID
594 && (item.stack?.itemId === ItemId.bones || item.stack?.itemId === ItemId.skull)
595 );
596 assert.ok(onGround.length >= 2);
597 assert.equal(
598 [...worker.world.groundItems.values()].filter(
599 (item) => item.dimensionId === OVERWORLD_ID
600 && (item.stack?.itemId === ItemId.bones || item.stack?.itemId === ItemId.skull)
601 ).length,
602 0
603 );
604
605 const despawn = applied.find((event) =>
606 event.type === "entity-despawn" && event.entityId === victimId && event.cause === "death"
607 );
608 assert.ok(despawn);
609 assert.equal(despawn.dimensionId, CAVE_ID);
610
611 const letters = harness.stateDb.listHeldCourierDeliveries(victim.character_id)
612 .map((hold) => hold.cargo?.stack)
613 .filter((stack) => stack?.itemId === ItemId.letter);
614 assert.ok(letters.some((stack) =>
615 stack.instance?.authorDisplayName === CHURCH_LETTER_AUTHOR
616 && stack.instance?.body === formatChurchOfflineResurrectionBody()
617 ));
618 // Church letter should originate from the cave altar (same dim), not the farther overworld one.
619 const churchHold = harness.stateDb.listHeldCourierDeliveries(victim.character_id)
620 .find((hold) => hold.cargo?.stack?.instance?.authorDisplayName === CHURCH_LETTER_AUTHOR);
621 assert.ok(churchHold);
622 assert.equal(churchHold.originDimensionId, CAVE_ID);
623
624 assert.equal(harness.simulation.isCharacterInWorld(victim.character_id), false);
625 assert.equal(harness.stateDb.getCharacter(victim.character_id).is_dead, 0);
626 const row = harness.stateDb.getCharacter(victim.character_id);
627 // Respawn prefers death-dimension altar at (10,8).
628 assert.equal(row.dimension_id, CAVE_ID);
629 assert.equal(
630 Math.max(Math.abs(row.tile_x - 10), Math.abs(row.tile_y - 8)),
631 1
632 );
633 }
634 finally
635 { harness.close(); }
636});
637
638test("PvP combat-logout quiet despawn in cave still carries cave dimensionId", () =>
639{
640 const harness = makeCaveHarness();
641 try
642 {
643 const victim = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Quiet", lastName: "Vic" });
644 harness.stateDb.saveCharacterPosition(victim.character_id, 8, 8, "walk", CAVE_ID);
645 const attacker = makeCharacter(harness.stateDb, { tileX: 9, tileY: 8, firstName: "Quiet", lastName: "Atk" });
646 harness.stateDb.saveCharacterPosition(attacker.character_id, 9, 8, "walk", CAVE_ID);
647 const victimId = harness.simulation.spawnCharacter(1, victim);
648 const attackerId = harness.simulation.spawnCharacter(2, attacker);
649 harness.simulation.enqueue(1, {
650 type: "attack",
651 characterId: victim.character_id,
652 targetEntityId: attackerId
653 });
654 harness.simulation.step();
655 assert.equal(harness.simulation.beginCombatLogout(victim.character_id), true);
656 harness.simulation.drainReplication();
657
658 const record = harness.simulation.entityRecord(victimId);
659 harness.simulation.workers[record.workerId].call({
660 type: WorkerMessage.clearCombat,
661 entityId: victimId,
662 targetEntityId: victimId
663 });
664 const track = harness.simulation.combatTracking.get(victim.character_id);
665 track.lastCombatActivityAt = harness.now() - COMBAT_LOGOUT_MS - 1;
666 track.wasInCombat = false;
667 harness.simulation.combatLogouts.get(victim.character_id).startedAt = harness.now() - COMBAT_LOGOUT_MS - 1;
668
669 const replication = [];
670 for (let i = 0; i < 60; i++)
671 {
672 harness.advance(50);
673 const stepped = harness.simulation.step();
674 replication.push(...(stepped.replication ?? []));
675 replication.push(...harness.simulation.drainReplication());
676 }
677 assert.equal(harness.simulation.isCharacterInWorld(victim.character_id), false);
678 const despawn = replication.find((event) =>
679 event.type === "entity-despawn" && event.entityId === victimId
680 );
681 assert.ok(despawn);
682 assert.equal(despawn.dimensionId, CAVE_ID);
683 const keys = eventInterestKeys(despawn, () => null);
684 assert.equal(keys.dimensionId, CAVE_ID);
685 assert.equal(keys.toKey, chunkKey(tileToChunk(8), tileToChunk(8), CAVE_ID));
686 }
687 finally
688 { harness.close(); }
689});
server/tests/item-spawners-dimension.test.js +157 −0
@@ -316,3 +316,160 @@ test("container respawn stays in custom dimension after open", () =>
316 316 finally
317 317 { harness.close(); }
318 318 });
319
320 const SHARED_LOCAL_ID = "shared-local-spawner";
321
322 function placeItemSpawnerWithId (harness, localX, localY, config, dimensionId, spawnerId)
323 {
324 ensureDimension(harness.worldDb, dimensionId);
325 const data = createEmptyChunkData();
326 data.open = true;
327 data.spawners = [{
328 localX,
329 localY,
330 config: normalizeItemSpawnerConfig({
331 spawnerId,
332 ...config
333 })
334 }];
335 harness.worldDb.saveChunkVersion(
336 0,
337 0,
338 harness.worldDb.getActiveRevisionId(),
339 true,
340 encodeChunkBlob(data),
341 dimensionId
342 );
343 harness.simulation.reloadWorld();
344 }
345
346 test("authored overworld + cave item spawners with same local spawnerId stay independent", () =>
347 {
348 const harness = makeDimensionSimulation(CAVE_ID, { workerCount: 1 });
349 try
350 {
351 placeItemSpawnerWithId(harness, 9, 8, {
352 appearance: ItemSpawnerAppearance.chest,
353 material: "oak",
354 items: [{ itemId: ItemId.apple, quantity: 1 }],
355 respawnDelaySeconds: 60,
356 spawnRangeTiles: 0
357 }, OVERWORLD_ID, SHARED_LOCAL_ID);
358 placeItemSpawnerWithId(harness, 9, 8, {
359 appearance: ItemSpawnerAppearance.chest,
360 material: "oak",
361 items: [{ itemId: ItemId.stick, quantity: 1 }],
362 respawnDelaySeconds: 60,
363 spawnRangeTiles: 0
364 }, CAVE_ID, SHARED_LOCAL_ID);
365
366 const overworld = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, lastName: "Over" });
367 harness.stateDb.saveBag(overworld.character_id, {
368 inventory: emptySlots(),
369 equipment: emptyEquipment(),
370 vault: [],
371 vaultReserved: []
372 });
373 const overworldId = harness.simulation.spawnCharacter(1, overworld);
374 assert.equal(harness.simulation.positionOf(overworldId).dimensionId, OVERWORLD_ID);
375
376 const caveChar = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, lastName: "CaveLoot" });
377 harness.stateDb.saveCharacterPosition(caveChar.character_id, 8, 8, "walk", CAVE_ID);
378 harness.stateDb.saveBag(caveChar.character_id, {
379 inventory: emptySlots(),
380 equipment: emptyEquipment(),
381 vault: [],
382 vaultReserved: []
383 });
384 const playerId = harness.simulation.spawnCharacter(2, caveChar);
385 assert.equal(harness.simulation.positionOf(playerId).dimensionId, CAVE_ID);
386 advanceMs(harness, 200);
387
388 const caveWorker = workerOf(harness.simulation, playerId);
389 const overWorker = workerOf(harness.simulation, overworldId);
390 const caveContainer = itemContainerAtTile(caveWorker.world, 9, 8, CAVE_ID);
391 const overContainer = itemContainerAtTile(overWorker.world, 9, 8, OVERWORLD_ID);
392 assert.ok(caveContainer, "expected cave chest");
393 assert.ok(overContainer, "expected overworld chest");
394 assert.equal(caveContainer.dimensionId, CAVE_ID);
395 assert.equal(overContainer.dimensionId, OVERWORLD_ID);
396 assert.notEqual(caveContainer.containerId, overContainer.containerId);
397 assert.equal(caveContainer.spawnerId, `${CAVE_ID}:${SHARED_LOCAL_ID}`);
398 assert.equal(overContainer.spawnerId, `${OVERWORLD_ID}:${SHARED_LOCAL_ID}`);
399
400 const active = [...ensureItemSpawnerState(caveWorker.world).active.values()];
401 const caveActive = active.filter((e) => e.dimensionId === CAVE_ID && e.spawnerId.endsWith(`:${SHARED_LOCAL_ID}`));
402 const overActive = active.filter((e) => e.dimensionId === OVERWORLD_ID && e.spawnerId.endsWith(`:${SHARED_LOCAL_ID}`));
403 assert.equal(caveActive.length, 1);
404 assert.equal(overActive.length, 1);
405
406 harness.simulation.enqueue(2, {
407 type: "open-item-container",
408 characterId: caveChar.character_id,
409 containerId: caveContainer.containerId
410 });
411 harness.simulation.step();
412 advanceMs(harness, ITEM_SPAWNER_OPEN_DURATION_MS + 200);
413
414 assert.equal(itemContainerAtTile(caveWorker.world, 9, 8, CAVE_ID), null, "cave chest consumed");
415 assert.ok(
416 itemContainerAtTile(overWorker.world, 9, 8, OVERWORLD_ID),
417 "overworld chest must remain after cave open"
418 );
419 const inventory = caveWorker.world.ecs.get(
420 caveWorker.world.ecs.handleOf(playerId),
421 Component.inventory
422 );
423 const sticks = (inventory?.slots ?? [])
424 .filter((s) => s?.itemId === ItemId.stick)
425 .reduce((n, s) => n + (s.quantity | 0), 0);
426 assert.equal(sticks, 1, "cave chest grants cave loot only");
427 }
428 finally
429 { harness.close(); }
430 });
431
432 test("authored overworld + cave ground item spawners with same local spawnerId stay independent", () =>
433 {
434 const harness = makeDimensionSimulation(CAVE_ID, { workerCount: 1 });
435 try
436 {
437 placeItemSpawnerWithId(harness, 9, 8, {
438 appearance: ItemSpawnerAppearance.item,
439 items: [{ itemId: ItemId.apple, quantity: 1 }],
440 respawnDelaySeconds: 60,
441 spawnRangeTiles: 0
442 }, OVERWORLD_ID, SHARED_LOCAL_ID);
443 placeItemSpawnerWithId(harness, 9, 8, {
444 appearance: ItemSpawnerAppearance.item,
445 items: [{ itemId: ItemId.stick, quantity: 1 }],
446 respawnDelaySeconds: 60,
447 spawnRangeTiles: 0
448 }, CAVE_ID, SHARED_LOCAL_ID);
449
450 const overworld = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, lastName: "PileOver" });
451 const overworldId = harness.simulation.spawnCharacter(1, overworld);
452 const caveChar = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, lastName: "PileCave" });
453 harness.stateDb.saveCharacterPosition(caveChar.character_id, 8, 8, "walk", CAVE_ID);
454 const playerId = harness.simulation.spawnCharacter(2, caveChar);
455 assert.equal(harness.simulation.positionOf(playerId).dimensionId, CAVE_ID);
456 advanceMs(harness, 200);
457
458 const worker = workerOf(harness.simulation, playerId);
459 const caveGround = [...worker.world.groundItems.values()].filter(
460 (item) => item.itemSpawnerId === `${CAVE_ID}:${SHARED_LOCAL_ID}`
461 );
462 const overGround = [...worker.world.groundItems.values()].filter(
463 (item) => item.itemSpawnerId === `${OVERWORLD_ID}:${SHARED_LOCAL_ID}`
464 );
465 assert.equal(caveGround.length, 1);
466 assert.equal(overGround.length, 1);
467 assert.equal(caveGround[0].dimensionId, CAVE_ID);
468 assert.equal(overGround[0].dimensionId, OVERWORLD_ID);
469 assert.equal(caveGround[0].stack.itemId, ItemId.stick);
470 assert.equal(overGround[0].stack.itemId, ItemId.apple);
471 void overworldId;
472 }
473 finally
474 { harness.close(); }
475 });
@@ -316,3 +316,160 @@ test("container respawn stays in custom dimension after open", () =>
316 finally
316 finally
317 { harness.close(); }
317 { harness.close(); }
318});
318});
319
320const SHARED_LOCAL_ID = "shared-local-spawner";
321
322function placeItemSpawnerWithId (harness, localX, localY, config, dimensionId, spawnerId)
323{
324 ensureDimension(harness.worldDb, dimensionId);
325 const data = createEmptyChunkData();
326 data.open = true;
327 data.spawners = [{
328 localX,
329 localY,
330 config: normalizeItemSpawnerConfig({
331 spawnerId,
332 ...config
333 })
334 }];
335 harness.worldDb.saveChunkVersion(
336 0,
337 0,
338 harness.worldDb.getActiveRevisionId(),
339 true,
340 encodeChunkBlob(data),
341 dimensionId
342 );
343 harness.simulation.reloadWorld();
344}
345
346test("authored overworld + cave item spawners with same local spawnerId stay independent", () =>
347{
348 const harness = makeDimensionSimulation(CAVE_ID, { workerCount: 1 });
349 try
350 {
351 placeItemSpawnerWithId(harness, 9, 8, {
352 appearance: ItemSpawnerAppearance.chest,
353 material: "oak",
354 items: [{ itemId: ItemId.apple, quantity: 1 }],
355 respawnDelaySeconds: 60,
356 spawnRangeTiles: 0
357 }, OVERWORLD_ID, SHARED_LOCAL_ID);
358 placeItemSpawnerWithId(harness, 9, 8, {
359 appearance: ItemSpawnerAppearance.chest,
360 material: "oak",
361 items: [{ itemId: ItemId.stick, quantity: 1 }],
362 respawnDelaySeconds: 60,
363 spawnRangeTiles: 0
364 }, CAVE_ID, SHARED_LOCAL_ID);
365
366 const overworld = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, lastName: "Over" });
367 harness.stateDb.saveBag(overworld.character_id, {
368 inventory: emptySlots(),
369 equipment: emptyEquipment(),
370 vault: [],
371 vaultReserved: []
372 });
373 const overworldId = harness.simulation.spawnCharacter(1, overworld);
374 assert.equal(harness.simulation.positionOf(overworldId).dimensionId, OVERWORLD_ID);
375
376 const caveChar = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, lastName: "CaveLoot" });
377 harness.stateDb.saveCharacterPosition(caveChar.character_id, 8, 8, "walk", CAVE_ID);
378 harness.stateDb.saveBag(caveChar.character_id, {
379 inventory: emptySlots(),
380 equipment: emptyEquipment(),
381 vault: [],
382 vaultReserved: []
383 });
384 const playerId = harness.simulation.spawnCharacter(2, caveChar);
385 assert.equal(harness.simulation.positionOf(playerId).dimensionId, CAVE_ID);
386 advanceMs(harness, 200);
387
388 const caveWorker = workerOf(harness.simulation, playerId);
389 const overWorker = workerOf(harness.simulation, overworldId);
390 const caveContainer = itemContainerAtTile(caveWorker.world, 9, 8, CAVE_ID);
391 const overContainer = itemContainerAtTile(overWorker.world, 9, 8, OVERWORLD_ID);
392 assert.ok(caveContainer, "expected cave chest");
393 assert.ok(overContainer, "expected overworld chest");
394 assert.equal(caveContainer.dimensionId, CAVE_ID);
395 assert.equal(overContainer.dimensionId, OVERWORLD_ID);
396 assert.notEqual(caveContainer.containerId, overContainer.containerId);
397 assert.equal(caveContainer.spawnerId, `${CAVE_ID}:${SHARED_LOCAL_ID}`);
398 assert.equal(overContainer.spawnerId, `${OVERWORLD_ID}:${SHARED_LOCAL_ID}`);
399
400 const active = [...ensureItemSpawnerState(caveWorker.world).active.values()];
401 const caveActive = active.filter((e) => e.dimensionId === CAVE_ID && e.spawnerId.endsWith(`:${SHARED_LOCAL_ID}`));
402 const overActive = active.filter((e) => e.dimensionId === OVERWORLD_ID && e.spawnerId.endsWith(`:${SHARED_LOCAL_ID}`));
403 assert.equal(caveActive.length, 1);
404 assert.equal(overActive.length, 1);
405
406 harness.simulation.enqueue(2, {
407 type: "open-item-container",
408 characterId: caveChar.character_id,
409 containerId: caveContainer.containerId
410 });
411 harness.simulation.step();
412 advanceMs(harness, ITEM_SPAWNER_OPEN_DURATION_MS + 200);
413
414 assert.equal(itemContainerAtTile(caveWorker.world, 9, 8, CAVE_ID), null, "cave chest consumed");
415 assert.ok(
416 itemContainerAtTile(overWorker.world, 9, 8, OVERWORLD_ID),
417 "overworld chest must remain after cave open"
418 );
419 const inventory = caveWorker.world.ecs.get(
420 caveWorker.world.ecs.handleOf(playerId),
421 Component.inventory
422 );
423 const sticks = (inventory?.slots ?? [])
424 .filter((s) => s?.itemId === ItemId.stick)
425 .reduce((n, s) => n + (s.quantity | 0), 0);
426 assert.equal(sticks, 1, "cave chest grants cave loot only");
427 }
428 finally
429 { harness.close(); }
430});
431
432test("authored overworld + cave ground item spawners with same local spawnerId stay independent", () =>
433{
434 const harness = makeDimensionSimulation(CAVE_ID, { workerCount: 1 });
435 try
436 {
437 placeItemSpawnerWithId(harness, 9, 8, {
438 appearance: ItemSpawnerAppearance.item,
439 items: [{ itemId: ItemId.apple, quantity: 1 }],
440 respawnDelaySeconds: 60,
441 spawnRangeTiles: 0
442 }, OVERWORLD_ID, SHARED_LOCAL_ID);
443 placeItemSpawnerWithId(harness, 9, 8, {
444 appearance: ItemSpawnerAppearance.item,
445 items: [{ itemId: ItemId.stick, quantity: 1 }],
446 respawnDelaySeconds: 60,
447 spawnRangeTiles: 0
448 }, CAVE_ID, SHARED_LOCAL_ID);
449
450 const overworld = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, lastName: "PileOver" });
451 const overworldId = harness.simulation.spawnCharacter(1, overworld);
452 const caveChar = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, lastName: "PileCave" });
453 harness.stateDb.saveCharacterPosition(caveChar.character_id, 8, 8, "walk", CAVE_ID);
454 const playerId = harness.simulation.spawnCharacter(2, caveChar);
455 assert.equal(harness.simulation.positionOf(playerId).dimensionId, CAVE_ID);
456 advanceMs(harness, 200);
457
458 const worker = workerOf(harness.simulation, playerId);
459 const caveGround = [...worker.world.groundItems.values()].filter(
460 (item) => item.itemSpawnerId === `${CAVE_ID}:${SHARED_LOCAL_ID}`
461 );
462 const overGround = [...worker.world.groundItems.values()].filter(
463 (item) => item.itemSpawnerId === `${OVERWORLD_ID}:${SHARED_LOCAL_ID}`
464 );
465 assert.equal(caveGround.length, 1);
466 assert.equal(overGround.length, 1);
467 assert.equal(caveGround[0].dimensionId, CAVE_ID);
468 assert.equal(overGround[0].dimensionId, OVERWORLD_ID);
469 assert.equal(caveGround[0].stack.itemId, ItemId.stick);
470 assert.equal(overGround[0].stack.itemId, ItemId.apple);
471 void overworldId;
472 }
473 finally
474 { harness.close(); }
475});