Push quest snapshots after mob kills (incl. other dimensions).
noteKill already counted kills in any dimension, but questsDirty never produced a client snapshot because characterId was omitted.
@@ -1,1006 +1,1006 @@
1
import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
2
import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
3
import {
4
countableObjectiveProgress,
5
objectiveProgressFingerprint
6
} from "../../../shared/quests/objectiveProgress.js";
7
import { countItemInSlots, insertStack, takeMatchingFromSlots, takeMatchingUpToFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
8
import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
9
import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
10
import { applySkillXp, publicSkillsPayload } from "../../../shared/skills/state.js";
11
import { SKILL_DEFINITIONS } from "../../../shared/definitions/skills.js";
12
import { resolveSkillRequirementLevel } from "../../../shared/combat/combatLevel.js";
13
import {
14
formatDialogueRewardMessage,
15
formatDialogueQuestRewardMessage,
16
formatDialogueTakeMessage
17
} from "../../../shared/quests/dialogueRewards.js";
18
import { applyDialogueTextReplacements } from "../../../shared/speech/dialogueText.js";
19
import {
20
formatQuestBankRewardLetterBody,
21
QUESTWARD_GIFT_AUTHOR,
22
QUESTWARD_GIFT_ORG
23
} from "../../../shared/courier/questRewardLetters.js";
24
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
25
import { floorDiv } from "../world/coordinates.js";
26
import { WorkerMessage } from "../simulation/protocol.js";
27
28
/**
29
* Quest progress + dialogue sessions (main simulation thread).
30
*/
31
export class QuestRuntime
32
{
33
constructor ({ stateDb, content, simulation })
34
{
35
this.stateDb = stateDb;
36
this.content = content;
37
this.simulation = simulation;
38
/** @type {Map<number, { entityId: number, dialogueId: string, stepId: string }>} */
39
this.sessions = new Map();
40
}
41
42
reloadContent ()
43
{
44
this.content.reload();
45
}
46
47
closeAllSessions ()
48
{
49
for (const characterId of [...this.sessions.keys()])
50
{ this.closeDialogue(characterId, "revision"); }
51
}
52
53
questSnapshot (characterId)
54
{
55
const states = this.stateDb.listQuestStates(characterId)
56
.filter((row) => row.state !== "not-started");
57
const quests = [];
58
const playerView = this.playerViewFor(characterId);
59
for (const row of states)
60
{
61
const def = this.content.quest(row.questId);
62
if (!def)
63
{
64
quests.push({
65
questId: row.questId,
66
title: "Quest unavailable",
67
orphaned: true,
68
state: row.state,
69
description: "",
70
step: null,
71
journal: this.stateDb.listQuestJournal(characterId, row.questId).map(journalPublic)
72
});
73
continue;
74
}
75
const stepIndex = typeof row.state === "number" ? row.state : null;
76
const stepDef = stepIndex != null ? def.steps[stepIndex - 1] : null;
77
const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];
78
const ctx = stepDef
79
? this.buildConditionContext(characterId, playerView, row.questId)
80
: null;
81
quests.push({
82
questId: def.questId,
83
title: def.title,
84
orphaned: false,
85
state: row.state,
86
description: def.description,
87
step: stepDef
88
? {
89
stepId: stepDef.stepId,
90
title: stepDef.title,
91
description: stepDef.description,
92
objectives: stepDef.objectives.map((obj) =>
93
{
94
const done = completedObjectiveIds.includes(obj.objectiveId);
95
const progress = countableObjectiveProgress(obj.when, ctx);
96
return {
97
objectiveId: obj.objectiveId,
98
text: obj.text,
99
done,
100
current: progress?.current ?? null,
101
required: progress?.required ?? null
102
};
103
})
104
}
105
: null,
106
journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)
107
});
108
}
109
quests.sort((a, b) =>
110
{
111
const aDone = a.state === "completed" ? 1 : 0;
112
const bDone = b.state === "completed" ? 1 : 0;
113
if (aDone !== bDone)
114
{ return aDone - bDone; }
115
return String(a.title).localeCompare(String(b.title));
116
});
117
return { quests };
118
}
119
120
playerViewFor (characterId)
121
{
122
const entityId = this.simulation.characterEntities.get(characterId | 0);
123
const record = entityId != null ? this.simulation.directory.get(entityId) : null;
124
const skills = this.stateDb.getSkills(characterId) ?? {};
125
let hp = 1;
126
let maxHp = 1;
127
let stamina = 1;
128
let maxStamina = 1;
129
if (entityId != null && record)
130
{
131
const staminaComp = this.simulation.staminaOf(entityId);
132
if (staminaComp)
133
{
134
stamina = Number(staminaComp.current) || 0;
135
maxStamina = Math.max(1, Number(staminaComp.max) || 1);
136
}
137
const worker = this.simulation.workers[record.workerId];
138
const view = worker?.call?.({
139
type: WorkerMessage.inspect,
140
entityId
141
});
142
if (view && view.health != null)
143
{
144
hp = Number(view.health) || 0;
145
maxHp = Math.max(1, Number(view.maxHealth) || 1);
146
}
147
}
148
return {
149
tileX: record?.tileX | 0,
150
tileY: record?.tileY | 0,
151
dimensionId: record?.dimensionId ?? "overworld",
152
skills,
153
hp,
154
maxHp,
155
stamina,
156
maxStamina
157
};
158
}
159
160
buildConditionContext (characterId, playerView, activeQuestId = null)
161
{
162
const bag = this.#loadBag(characterId);
163
const inventory = bag?.inventory ?? [];
164
const tileX = playerView?.tileX | 0;
165
const tileY = playerView?.tileY | 0;
166
const dimensionId = playerView?.dimensionId ?? "overworld";
167
const chunkX = floorDiv(tileX, CHUNK_SIZE);
168
const chunkY = floorDiv(tileY, CHUNK_SIZE);
169
const questRow = activeQuestId ? this.stateDb.getQuestState(characterId, activeQuestId) : null;
170
return {
171
tileX,
172
tileY,
173
chunkX,
174
chunkY,
175
dimensionId,
176
hp: playerView?.hp ?? 0,
177
maxHp: playerView?.maxHp ?? 1,
178
stamina: playerView?.stamina ?? 0,
179
maxStamina: playerView?.maxStamina ?? 1,
180
countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
181
questState: (questId) => this.stateDb.getQuestState(characterId, questId).state,
182
dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId),
183
dialogueTriggerLatched: (dialogueId, trigger) =>
184
this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger),
185
skillLevel: (skillId) => resolveSkillRequirementLevel(playerView?.skills ?? {}, skillId),
186
hasVisitedDimension: (dimId) => this.stateDb.hasVisitedDimension(characterId, dimId),
187
killCount: (condition) =>
188
{
189
if (!questRow)
190
{ return 0; }
191
return questRow.progress?.counters?.[killKey(condition)] | 0;
192
},
193
interactBlockDone: (condition) =>
194
{
195
if (!questRow)
196
{ return false; }
197
return !!questRow.progress?.interacts?.[interactKey(condition)];
198
}
199
};
200
}
201
202
tryOpenDialogue (characterId, entityId, dialogueId)
203
{
204
const tree = this.content.dialogue(dialogueId);
205
if (!tree)
206
{ return { ok: false, error: "Nothing to say." }; }
207
this.closeDialogue(characterId, "replace");
208
const playerView = this.playerViewFor(characterId);
209
return this.#enterStep(characterId, entityId, tree, tree.entryStepId, playerView);
210
}
211
212
chooseDialogue (characterId, triggerId)
213
{
214
const session = this.sessions.get(characterId | 0);
215
if (!session)
216
{ return { ok: false, error: "No dialogue open." }; }
217
if (session.phase === "lines")
218
{ return { ok: false, error: "Finish reading first." }; }
219
if (session.phase === "rewards")
220
{ return { ok: false, error: "Finish reading first." }; }
221
const tree = this.content.dialogue(session.dialogueId);
222
if (!tree)
223
{
224
this.closeDialogue(characterId, "missing");
225
return { ok: false, error: "Dialogue missing." };
226
}
227
const step = tree.steps.find((s) => s.stepId === session.stepId);
228
if (!step || step.exit?.kind !== "triggers")
229
{ return { ok: false, error: "Cannot choose now." }; }
230
const trigger = step.exit.triggers.find((t) => t.trigger === String(triggerId));
231
if (!trigger)
232
{ return { ok: false, error: "Unknown choice." }; }
233
const playerView = this.playerViewFor(characterId);
234
const ctx = this.buildConditionContext(characterId, playerView);
235
if (!evaluateConditionSet(trigger.when, ctx))
236
{ return { ok: false, error: "That choice is unavailable." }; }
237
this.stateDb.latchDialogueTrigger(characterId, tree.dialogueId, trigger.trigger);
238
const events = [];
239
this.#applyEffects(characterId, trigger.effects, playerView, events);
240
this.#reevaluateQuests(characterId, playerView, events);
241
if (!trigger.nextStepId)
242
{
243
const npcEntityId = session.entityId;
244
this.sessions.delete(characterId | 0);
245
events.push({ type: "dialogueClose", reason: "end", npcEntityId });
246
return { ok: true, events };
247
}
248
return this.#enterStep(characterId, session.entityId, tree, trigger.nextStepId, playerView, events);
249
}
250
251
closeDialogue (characterId, reason = "close")
252
{
253
const id = characterId | 0;
254
const session = this.sessions.get(id);
255
if (!session)
256
{ return { events: [] }; }
257
this.sessions.delete(id);
258
return {
259
events: [{
260
type: "dialogueClose",
261
reason,
262
npcEntityId: session.entityId
263
}]
264
};
265
}
266
267
interruptDialogueForEntity (entityId)
268
{
269
const events = [];
270
for (const [characterId, session] of [...this.sessions])
271
{
272
if (session.entityId === (entityId | 0))
273
{
274
const closed = this.closeDialogue(characterId, "attacked");
275
events.push(...closed.events.map((e) => ({ ...e, characterId })));
276
}
277
}
278
return events;
279
}
280
281
#enterStep (characterId, entityId, tree, stepId, playerView, priorEvents = [])
282
{
283
const step = tree.steps.find((s) => s.stepId === stepId);
284
if (!step)
285
{
286
this.sessions.delete(characterId | 0);
287
priorEvents.push({ type: "dialogueClose", reason: "missing-step" });
288
return { ok: false, error: "Broken dialogue.", events: priorEvents };
289
}
290
const events = [...priorEvents];
291
const identity = this.#playerDialogueIdentity(characterId);
292
const linePayloads = [];
293
for (const line of step.lines)
294
{
295
this.#applyEffects(characterId, line.effects, playerView, events);
296
linePayloads.push({
297
speaker: line.speaker,
298
text: applyDialogueTextReplacements(line.text, identity)
299
});
300
}
301
// Stay open while the client pages lines; resolve exit only on dialogueAdvance.
302
// dialogueHeard is marked only when the step fully completes (after rewards).
303
this.sessions.set(characterId | 0, {
304
entityId: entityId | 0,
305
dialogueId: tree.dialogueId,
306
stepId: step.stepId,
307
phase: "lines",
308
pendingExit: step.exit ?? { kind: "end" }
309
});
310
events.push({
311
type: "dialogueStep",
312
dialogueId: tree.dialogueId,
313
stepId: step.stepId,
314
label: step.label,
315
npcEntityId: entityId | 0,
316
lines: linePayloads
317
});
318
this.#reevaluateQuests(characterId, playerView, events);
319
return { ok: true, events };
320
}
321
322
/** Client finished reading all lines (or reward notices) of the current step. */
323
advanceDialogue (characterId)
324
{
325
const session = this.sessions.get(characterId | 0);
326
if (!session || (session.phase !== "lines" && session.phase !== "rewards"))
327
{ return { ok: false, error: "No dialogue lines to advance." }; }
328
const tree = this.content.dialogue(session.dialogueId);
329
if (!tree)
330
{
331
this.sessions.delete(characterId | 0);
332
return { ok: true, events: [{ type: "dialogueClose", reason: "missing" }] };
333
}
334
const playerView = this.playerViewFor(characterId);
335
const events = [];
336
337
if (session.phase === "lines")
338
{
339
const step = tree.steps.find((s) => s.stepId === session.stepId);
340
const rewardMessages = [
341
...this.#takeStepItems(characterId, step, events),
342
...this.#grantStepItemRewards(characterId, step, events),
343
...this.#grantStepQuestRewards(characterId, step, playerView, events)
344
];
345
this.#reevaluateQuests(characterId, playerView, events);
346
if (rewardMessages.length > 0)
347
{
348
session.phase = "rewards";
349
events.push({
350
type: "dialogueItemRewards",
351
dialogueId: session.dialogueId,
352
stepId: session.stepId,
353
npcEntityId: session.entityId,
354
messages: rewardMessages
355
});
356
return { ok: true, events };
357
}
358
}
359
360
return this.#resolveDialogueExit(characterId, session, tree, playerView, events);
361
}
362
363
#resolveDialogueExit (characterId, session, tree, playerView, events)
364
{
365
// Step is fully finished: lines read + takes/rewards/quest notices acknowledged.
366
this.stateDb.markDialogueHeard(characterId, tree.dialogueId, session.stepId);
367
this.#reevaluateQuests(characterId, playerView, events);
368
369
const exit = session.pendingExit ?? { kind: "end" };
370
371
if (exit.kind === "branches")
372
{
373
const ctx = this.buildConditionContext(characterId, playerView);
374
let matched = null;
375
for (const branch of exit.branches ?? [])
376
{
377
if (evaluateConditionSet(branch.when, ctx))
378
{
379
matched = branch;
380
break;
381
}
382
}
383
if (!matched || !matched.nextStepId)
384
{
385
this.#applyEffects(characterId, matched?.effects, playerView, events);
386
const npcEntityId = session.entityId;
387
this.sessions.delete(characterId | 0);
388
events.push({ type: "dialogueClose", reason: "branch-end", npcEntityId });
389
return { ok: true, events };
390
}
391
this.#applyEffects(characterId, matched.effects, playerView, events);
392
return this.#enterStep(characterId, session.entityId, tree, matched.nextStepId, playerView, events);
393
}
394
395
if (exit.kind === "triggers")
396
{
397
const ctx = this.buildConditionContext(characterId, playerView);
398
const identity = this.#playerDialogueIdentity(characterId);
399
const triggers = (exit.triggers ?? [])
400
.filter((t) => evaluateConditionSet(t.when, ctx))
401
.map((t) => ({
402
trigger: t.trigger,
403
text: applyDialogueTextReplacements(t.text, identity)
404
}));
405
if (triggers.length === 0)
406
{
407
const npcEntityId = session.entityId;
408
this.sessions.delete(characterId | 0);
409
events.push({ type: "dialogueClose", reason: "no-triggers", npcEntityId });
410
return { ok: true, events };
411
}
412
session.phase = "choices";
413
session.pendingExit = null;
414
events.push({
415
type: "dialogueChoices",
416
dialogueId: session.dialogueId,
417
stepId: session.stepId,
418
npcEntityId: session.entityId,
419
triggers
420
});
421
return { ok: true, events };
422
}
423
424
if (exit.kind === "continue")
425
{
426
if (!exit.nextStepId)
427
{
428
const npcEntityId = session.entityId;
429
this.sessions.delete(characterId | 0);
430
events.push({ type: "dialogueClose", reason: "continue-end", npcEntityId });
431
return { ok: true, events };
432
}
433
return this.#enterStep(characterId, session.entityId, tree, exit.nextStepId, playerView, events);
434
}
435
436
const npcEntityId = session.entityId;
437
this.sessions.delete(characterId | 0);
438
events.push({ type: "dialogueClose", reason: "end", npcEntityId });
439
return { ok: true, events };
440
}
441
442
/**
443
* Soft-take step.itemTakes from the bag (min(have, required)). Returns player-facing notices.
444
*/
445
#takeStepItems (characterId, step, events)
446
{
447
const takes = step?.itemTakes ?? [];
448
if (!takes.length)
449
{ return []; }
450
const parts = [];
451
for (const take of takes)
452
{
453
const bag = this.#loadBag(characterId);
454
if (!bag)
455
{ continue; }
456
const itemId = take.itemId | 0;
457
const want = Math.max(1, Number(take.quantity) || 1);
458
const def = itemDefinition(itemId);
459
const displayName = def?.displayName ?? `Item ${itemId}`;
460
const result = takeMatchingUpToFromSlots(bag.inventory, {
461
itemId,
462
quantity: want,
463
compact: false
464
});
465
if (!result.ok || result.takenQuantity <= 0)
466
{ continue; }
467
bag.inventory = result.slots;
468
this.#persistBag(characterId, bag);
469
events.push({ type: "inventoryDirty" });
470
parts.push({ displayName, quantity: result.takenQuantity });
471
}
472
const message = formatDialogueTakeMessage(parts);
473
return message ? [message] : [];
474
}
475
476
/**
477
* Grant step.itemRewards into bag (overflow → bank/vault). Returns player-facing notices.
478
*/
479
#grantStepItemRewards (characterId, step, events)
480
{
481
const rewards = step?.itemRewards ?? [];
482
if (!rewards.length)
483
{ return []; }
484
const bagParts = [];
485
const bankParts = [];
486
for (const reward of rewards)
487
{
488
const bag = this.#loadBag(characterId);
489
if (!bag)
490
{ continue; }
491
const itemId = reward.itemId | 0;
492
const def = itemDefinition(itemId);
493
const quantity = Math.max(1, Number(reward.quantity) || 1);
494
const displayName = def?.displayName ?? `Item ${itemId}`;
495
const stack = attachOrigins({
496
itemId,
497
quantity,
498
origins: [{ origin: godsOrigin(), quantity }]
499
});
500
const result = insertStack(bag.inventory, stack, def);
501
bag.inventory = result.slots;
502
const intoBag = quantity - Math.max(0, result.remainder | 0);
503
let intoBank = 0;
504
if (result.remainder > 0)
505
{
506
const vaultResult = insertStackGrowable(
507
bag.vault,
508
attachOrigins({
509
itemId,
510
quantity: result.remainder,
511
origins: [{ origin: godsOrigin(), quantity: result.remainder }]
512
}),
513
def
514
);
515
bag.vault = vaultResult.slots;
516
intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
517
}
518
this.#persistBag(characterId, bag);
519
events.push({ type: "inventoryDirty" });
520
if (intoBag > 0)
521
{ bagParts.push({ displayName, quantity: intoBag }); }
522
if (intoBank > 0)
523
{ bankParts.push({ displayName, quantity: intoBank }); }
524
}
525
const messages = [];
526
const bagMsg = formatDialogueRewardMessage(bagParts, "bag");
527
const bankMsg = formatDialogueRewardMessage(bankParts, "bank");
528
if (bagMsg)
529
{ messages.push(bagMsg); }
530
if (bankMsg)
531
{ messages.push(bankMsg); }
532
return messages;
533
}
534
535
/** Start step.questRewards; returns player-facing notices for newly started quests. */
536
#grantStepQuestRewards (characterId, step, playerView, events)
537
{
538
const rewards = step?.questRewards ?? [];
539
if (!rewards.length)
540
{ return []; }
541
const titles = [];
542
for (const questId of rewards)
543
{
544
const current = this.stateDb.getQuestState(characterId, questId);
545
if (current.state !== "not-started")
546
{ continue; }
547
const def = this.content.quest(questId);
548
if (!def)
549
{ continue; }
550
this.startQuest(characterId, questId, playerView, events);
551
titles.push(def.title || def.questId);
552
}
553
const message = formatDialogueQuestRewardMessage(titles);
554
return message ? [message] : [];
555
}
556
557
#loadBag (characterId)
558
{
559
const onlineId = this.simulation.characterEntities.get(characterId | 0);
560
const bag = onlineId
561
? this.simulation.bagOf(onlineId)
562
: this.stateDb.getBag(characterId);
563
return bag;
564
}
565
566
#playerDialogueIdentity (characterId)
567
{
568
const row = this.stateDb.getCharacter(characterId | 0);
569
return {
570
firstName: String(row?.first_name ?? "").trim(),
571
lastName: String(row?.last_name ?? "").trim(),
572
sex: row?.sex === "female" ? "female" : "male"
573
};
574
}
575
576
#persistBag (characterId, bag)
577
{
578
this.stateDb.saveBag(characterId, bag);
579
const onlineId = this.simulation.characterEntities.get(characterId | 0);
580
if (onlineId)
581
{
582
this.simulation.applyBag?.(onlineId, bag);
583
this.simulation.pushInventory?.(characterId, bag);
584
}
585
}
586
587
#applyEffects (characterId, effects, playerView, events)
588
{
589
if (!Array.isArray(effects) || effects.length === 0)
590
{ return; }
591
for (const effect of effects)
592
{
593
if (effect.kind === EffectKind.giveItem)
594
{
595
const bag = this.#loadBag(characterId);
596
if (!bag)
597
{ continue; }
598
const def = itemDefinition(effect.itemId | 0);
599
const quantity = Math.max(1, Number(effect.quantity) || 1);
600
const stack = attachOrigins({
601
itemId: effect.itemId | 0,
602
quantity,
603
origins: [{ origin: godsOrigin(), quantity }]
604
});
605
if (effect.toBank)
606
{
607
const vaultResult = insertStackGrowable(bag.vault ?? [], stack, def);
608
bag.vault = vaultResult.slots;
609
}
610
else
611
{
612
const result = insertStack(bag.inventory, stack, def);
613
bag.inventory = result.slots;
614
if (result.remainder > 0)
615
{
616
const vaultResult = insertStackGrowable(
617
bag.vault ?? [],
618
attachOrigins({
619
itemId: effect.itemId | 0,
620
quantity: result.remainder,
621
origins: [{ origin: godsOrigin(), quantity: result.remainder }]
622
}),
623
def
624
);
625
bag.vault = vaultResult.slots;
626
}
627
}
628
this.#persistBag(characterId, bag);
629
events.push({ type: "inventoryDirty" });
630
}
631
else if (effect.kind === EffectKind.takeItem)
632
{
633
const bag = this.#loadBag(characterId);
634
if (!bag)
635
{ continue; }
636
const taken = takeMatchingFromSlots(bag.inventory, {
637
itemId: effect.itemId | 0,
638
quantity: Math.max(1, Number(effect.quantity) || 1),
639
compact: false
640
});
641
if (taken.ok)
642
{
643
bag.inventory = taken.slots;
644
this.#persistBag(characterId, bag);
645
events.push({ type: "inventoryDirty" });
646
}
647
}
648
else if (effect.kind === EffectKind.giveXp)
649
{
650
const skills = this.stateDb.getSkills(characterId);
651
if (skills)
652
{
653
applySkillXp(skills, effect.skillId, Math.max(0, Number(effect.amount) || 0));
654
this.stateDb.saveSkills(characterId, skills);
655
if (playerView)
656
{ playerView.skills = skills; }
657
events.push({ type: "skillsDirty" });
658
}
659
}
660
else if (effect.kind === EffectKind.startQuest)
661
{ this.startQuest(characterId, effect.questId, playerView, events); }
662
}
663
}
664
665
startQuest (characterId, questId, playerView, events = [])
666
{
667
const def = this.content.quest(questId);
668
if (!def)
669
{ return; }
670
const current = this.stateDb.getQuestState(characterId, questId);
671
if (current.state !== "not-started")
672
{ return; }
673
this.stateDb.saveQuestState(characterId, questId, 1, {
674
completedObjectiveIds: [],
675
counters: {},
676
interacts: {}
677
}, Date.now(), null);
678
this.#applyEffects(characterId, def.steps[0]?.onEnter, playerView, events);
679
events.push({ type: "questsDirty" });
680
this.#reevaluateQuests(characterId, playerView, events);
681
}
682
683
/**
684
* Grant world-settings initial quests when the character has not started or completed them.
685
*/
686
ensureInitialQuests (characterId, playerView = null, events = [])
687
{
688
const list = normalizeInitialQuests(this.simulation?.settings?.initialQuests);
689
for (const questId of list)
690
{ this.startQuest(characterId, questId, playerView, events); }
691
return events;
692
}
693
694
/**
695
* Re-check active quest objectives against live bag/position/etc.
696
* Used when opening the quest log (and wherever progress may have changed offline of dialogue/kills).
697
*/
698
reevaluateQuests (characterId, playerView = null, events = [])
699
{
700
const view = playerView ?? this.playerViewFor(characterId);
701
this.#reevaluateQuests(characterId, view, events);
702
return events;
703
}
704
705
/** Apply initial quests to every character in state (settings save / apply). */
706
grantInitialQuestsToAllCharacters ()
707
{
708
const events = [];
709
for (const characterId of this.stateDb.listAllCharacterIds())
710
{ this.ensureInitialQuests(characterId, null, events); }
711
return events;
712
}
713
714
/**
715
* Final quest rewards: XP + items (bag or bank). Banked items get a Questward letter.
716
* @returns {{ xp: { skillId: string, displayName: string, amount: number }[], bagItems: { displayName: string, quantity: number }[] }}
717
*/
718
#grantQuestCompletionRewards (characterId, def, playerView, events)
719
{
720
const xp = [];
721
const bagItems = [];
722
const bankItems = [];
723
const rewards = def?.rewards ?? [];
724
for (const effect of rewards)
725
{
726
if (effect.kind === EffectKind.giveXp)
727
{
728
const amount = Math.max(0, Number(effect.amount) || 0) | 0;
729
if (amount <= 0)
730
{ continue; }
731
const skillId = String(effect.skillId ?? "").trim();
732
if (!skillId)
733
{ continue; }
734
const onlineId = this.simulation.characterEntities.get(characterId | 0);
735
let skills = onlineId
736
? this.simulation.skillsOf(onlineId)
737
: this.stateDb.getSkills(characterId);
738
if (!skills)
739
{ skills = this.stateDb.getSkills(characterId); }
740
if (!skills)
741
{ continue; }
742
applySkillXp(skills, skillId, amount);
743
this.stateDb.saveSkills(characterId, skills);
744
if (playerView)
745
{ playerView.skills = skills; }
746
if (onlineId)
747
{ this.simulation.applySkills?.(onlineId, skills); }
748
const payload = publicSkillsPayload(skills);
749
this.simulation.pushSkills?.(characterId, payload.skills, payload.combatLevel);
750
xp.push({
751
skillId,
752
displayName: SKILL_DEFINITIONS[skillId]?.displayName ?? skillId,
753
amount
754
});
755
continue;
756
}
757
if (effect.kind !== EffectKind.giveItem)
758
{ continue; }
759
const bag = this.#loadBag(characterId);
760
if (!bag)
761
{ continue; }
762
const itemId = effect.itemId | 0;
763
const defItem = itemDefinition(itemId);
764
const quantity = Math.max(1, Number(effect.quantity) || 1) | 0;
765
const displayName = defItem
766
? itemDisplayName({ itemId, quantity }, defItem)
767
: `Item ${itemId}`;
768
const stack = attachOrigins({
769
itemId,
770
quantity,
771
origins: [{ origin: godsOrigin(), quantity }]
772
});
773
let intoBag = 0;
774
let intoBank = 0;
775
if (effect.toBank)
776
{
777
const vaultResult = insertStackGrowable(bag.vault ?? [], stack, defItem);
778
bag.vault = vaultResult.slots;
779
intoBank = quantity - Math.max(0, vaultResult.remainder | 0);
780
}
781
else
782
{
783
const result = insertStack(bag.inventory, stack, defItem);
784
bag.inventory = result.slots;
785
intoBag = quantity - Math.max(0, result.remainder | 0);
786
if (result.remainder > 0)
787
{
788
const vaultResult = insertStackGrowable(
789
bag.vault ?? [],
790
attachOrigins({
791
itemId,
792
quantity: result.remainder,
793
origins: [{ origin: godsOrigin(), quantity: result.remainder }]
794
}),
795
defItem
796
);
797
bag.vault = vaultResult.slots;
798
intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
799
}
800
}
801
this.#persistBag(characterId, bag);
802
events.push({ type: "inventoryDirty" });
803
if (intoBag > 0)
804
{ bagItems.push({ displayName, quantity: intoBag, itemId }); }
805
if (intoBank > 0)
806
{ bankItems.push({ displayName, quantity: intoBank, itemId }); }
807
}
808
809
if (bankItems.length)
810
{ this.#dispatchQuestBankRewardLetter(characterId, def, bankItems); }
811
812
return { xp, bagItems };
813
}
814
815
#dispatchQuestBankRewardLetter (characterId, def, bankItems)
816
{
817
const courier = this.simulation.courier;
818
if (!courier?.enqueueSystemLetter)
819
{ return; }
820
const row = this.stateDb.getCharacter?.(characterId);
821
const characterDisplayName = row
822
? `${row.first_name ?? ""} ${row.last_name ?? ""}`.trim()
823
: "Adventurer";
824
const originTileX = row?.tile_x | 0;
825
const originTileY = row?.tile_y | 0;
826
const bank = courier.nearestBank?.(originTileX, originTileY);
827
courier.enqueueSystemLetter({
828
characterId: characterId | 0,
829
originTileX: bank?.tileX ?? originTileX,
830
originTileY: bank?.tileY ?? originTileY,
831
authorDisplayName: QUESTWARD_GIFT_AUTHOR,
832
authorOrganization: QUESTWARD_GIFT_ORG,
833
body: formatQuestBankRewardLetterBody({
834
characterDisplayName,
835
questTitle: def?.title ?? def?.questId,
836
items: bankItems
837
})
838
});
839
}
840
841
#reevaluateQuests (characterId, playerView, events)
842
{
843
const states = this.stateDb.listQuestStates(characterId)
844
.filter((row) => typeof row.state === "number");
845
for (const row of states)
846
{
847
const def = this.content.quest(row.questId);
848
if (!def)
849
{ continue; }
850
const stepDef = def.steps[row.state - 1];
851
if (!stepDef)
852
{ continue; }
853
const ctx = this.buildConditionContext(characterId, playerView, row.questId);
854
const completed = new Set(row.progress?.completedObjectiveIds ?? []);
855
const newlyDone = [];
856
let changed = false;
857
for (const obj of stepDef.objectives)
858
{
859
if (completed.has(obj.objectiveId))
860
{ continue; }
861
if (evaluateConditionSet(obj.when, ctx))
862
{
863
completed.add(obj.objectiveId);
864
newlyDone.push(obj);
865
changed = true;
866
}
867
}
868
const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx);
869
const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");
870
if (!changed && !progressChanged)
871
{ continue; }
872
for (const obj of newlyDone)
873
{
874
events.push({
875
type: "questObjectiveComplete",
876
questId: row.questId,
877
objectiveId: obj.objectiveId,
878
text: obj.text || "Objective"
879
});
880
}
881
const progress = {
882
...row.progress,
883
completedObjectiveIds: [...completed],
884
progressFingerprint: fingerprint
885
};
886
const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
887
if (!allDone)
888
{
889
this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
890
events.push({ type: "questsDirty" });
891
continue;
892
}
893
if (!changed)
894
{
895
// Progress-only update while already fully complete (should not happen).
896
this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
897
events.push({ type: "questsDirty" });
898
continue;
899
}
900
this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
901
const journal = this.stateDb.appendQuestJournal(
902
characterId,
903
row.questId,
904
stepDef.stepId,
905
stepDef.completionJournalText
906
);
907
const nextIndex = row.state + 1;
908
if (nextIndex > def.steps.length)
909
{
910
const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events);
911
this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now());
912
events.push({
913
type: "questComplete",
914
questId: row.questId,
915
title: def.title,
916
xp: summary.xp,
917
items: summary.bagItems
918
});
919
}
920
else
921
{
922
const nextStep = def.steps[nextIndex - 1];
923
this.stateDb.saveQuestState(characterId, row.questId, nextIndex, {
924
completedObjectiveIds: [],
925
counters: {},
926
interacts: {},
927
progressFingerprint: ""
928
}, row.startedAt, null);
929
this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
930
events.push({
931
type: "questStepComplete",
932
questId: row.questId,
933
title: def.title,
934
journalText: journal?.text ?? null
935
});
936
}
937
events.push({ type: "questsDirty" });
938
}
939
}
940
941
noteKill (characterId, { mobTypeId, spawnerId })
942
{
943
const events = [];
944
const playerView = this.playerViewFor(characterId);
945
const states = this.stateDb.listQuestStates(characterId)
946
.filter((row) => typeof row.state === "number");
947
for (const row of states)
948
{
949
const def = this.content.quest(row.questId);
950
const stepDef = def?.steps[row.state - 1];
951
if (!stepDef)
952
{ continue; }
953
let changed = false;
954
const counters = { ...(row.progress?.counters ?? {}) };
955
for (const obj of stepDef.objectives)
956
{
957
for (const clause of obj.when?.all ?? [])
958
{
959
const c = clause.condition;
960
if (c?.kind !== "killCount")
961
{ continue; }
962
const matchMob = c.mobTypeId != null && String(c.mobTypeId) === String(mobTypeId);
963
const matchSpawner = c.spawnerId != null && String(c.spawnerId) === String(spawnerId);
964
if (!matchMob && !matchSpawner)
965
{ continue; }
966
const key = killKey(c);
967
counters[key] = (counters[key] | 0) + 1;
968
changed = true;
969
}
970
}
971
if (!changed)
972
{ continue; }
973
this.stateDb.saveQuestState(characterId, row.questId, row.state, {
974
...row.progress,
975
counters
976
}, row.startedAt, row.completedAt);
977
}
978
this.#reevaluateQuests(characterId, playerView, events);
979
return events;
980
}
981
}
982
983
function journalPublic (row)
984
{
985
return {
986
entryId: row.entry_id ?? row.entryId,
987
questId: row.quest_id ?? row.questId,
988
stepId: row.step_id ?? row.stepId,
989
text: row.text,
990
writtenAt: row.written_at ?? row.writtenAt
991
};
992
}
993
994
function killKey (condition)
995
{
996
if (condition.spawnerId)
997
{ return `spawner:${condition.spawnerId}`; }
998
return `mob:${condition.mobTypeId}`;
999
}
1000
1001
function interactKey (condition)
1002
{
1003
if (condition.tileX != null)
1004
{ return `tile:${condition.tileX},${condition.tileY}`; }
1005
return `block:${condition.blockTypeId}`;
1006
}
1
import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
2
import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
3
import {
4
countableObjectiveProgress,
5
objectiveProgressFingerprint
6
} from "../../../shared/quests/objectiveProgress.js";
7
import { countItemInSlots, insertStack, takeMatchingFromSlots, takeMatchingUpToFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
8
import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
9
import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
10
import { applySkillXp, publicSkillsPayload } from "../../../shared/skills/state.js";
11
import { SKILL_DEFINITIONS } from "../../../shared/definitions/skills.js";
12
import { resolveSkillRequirementLevel } from "../../../shared/combat/combatLevel.js";
13
import {
14
formatDialogueRewardMessage,
15
formatDialogueQuestRewardMessage,
16
formatDialogueTakeMessage
17
} from "../../../shared/quests/dialogueRewards.js";
18
import { applyDialogueTextReplacements } from "../../../shared/speech/dialogueText.js";
19
import {
20
formatQuestBankRewardLetterBody,
21
QUESTWARD_GIFT_AUTHOR,
22
QUESTWARD_GIFT_ORG
23
} from "../../../shared/courier/questRewardLetters.js";
24
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
25
import { floorDiv } from "../world/coordinates.js";
26
import { WorkerMessage } from "../simulation/protocol.js";
27
28
/**
29
* Quest progress + dialogue sessions (main simulation thread).
30
*/
31
export class QuestRuntime
32
{
33
constructor ({ stateDb, content, simulation })
34
{
35
this.stateDb = stateDb;
36
this.content = content;
37
this.simulation = simulation;
38
/** @type {Map<number, { entityId: number, dialogueId: string, stepId: string }>} */
39
this.sessions = new Map();
40
}
41
42
reloadContent ()
43
{
44
this.content.reload();
45
}
46
47
closeAllSessions ()
48
{
49
for (const characterId of [...this.sessions.keys()])
50
{ this.closeDialogue(characterId, "revision"); }
51
}
52
53
questSnapshot (characterId)
54
{
55
const states = this.stateDb.listQuestStates(characterId)
56
.filter((row) => row.state !== "not-started");
57
const quests = [];
58
const playerView = this.playerViewFor(characterId);
59
for (const row of states)
60
{
61
const def = this.content.quest(row.questId);
62
if (!def)
63
{
64
quests.push({
65
questId: row.questId,
66
title: "Quest unavailable",
67
orphaned: true,
68
state: row.state,
69
description: "",
70
step: null,
71
journal: this.stateDb.listQuestJournal(characterId, row.questId).map(journalPublic)
72
});
73
continue;
74
}
75
const stepIndex = typeof row.state === "number" ? row.state : null;
76
const stepDef = stepIndex != null ? def.steps[stepIndex - 1] : null;
77
const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];
78
const ctx = stepDef
79
? this.buildConditionContext(characterId, playerView, row.questId)
80
: null;
81
quests.push({
82
questId: def.questId,
83
title: def.title,
84
orphaned: false,
85
state: row.state,
86
description: def.description,
87
step: stepDef
88
? {
89
stepId: stepDef.stepId,
90
title: stepDef.title,
91
description: stepDef.description,
92
objectives: stepDef.objectives.map((obj) =>
93
{
94
const done = completedObjectiveIds.includes(obj.objectiveId);
95
const progress = countableObjectiveProgress(obj.when, ctx);
96
return {
97
objectiveId: obj.objectiveId,
98
text: obj.text,
99
done,
100
current: progress?.current ?? null,
101
required: progress?.required ?? null
102
};
103
})
104
}
105
: null,
106
journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)
107
});
108
}
109
quests.sort((a, b) =>
110
{
111
const aDone = a.state === "completed" ? 1 : 0;
112
const bDone = b.state === "completed" ? 1 : 0;
113
if (aDone !== bDone)
114
{ return aDone - bDone; }
115
return String(a.title).localeCompare(String(b.title));
116
});
117
return { quests };
118
}
119
120
playerViewFor (characterId)
121
{
122
const entityId = this.simulation.characterEntities.get(characterId | 0);
123
const record = entityId != null ? this.simulation.directory.get(entityId) : null;
124
const skills = this.stateDb.getSkills(characterId) ?? {};
125
let hp = 1;
126
let maxHp = 1;
127
let stamina = 1;
128
let maxStamina = 1;
129
if (entityId != null && record)
130
{
131
const staminaComp = this.simulation.staminaOf(entityId);
132
if (staminaComp)
133
{
134
stamina = Number(staminaComp.current) || 0;
135
maxStamina = Math.max(1, Number(staminaComp.max) || 1);
136
}
137
const worker = this.simulation.workers[record.workerId];
138
const view = worker?.call?.({
139
type: WorkerMessage.inspect,
140
entityId
141
});
142
if (view && view.health != null)
143
{
144
hp = Number(view.health) || 0;
145
maxHp = Math.max(1, Number(view.maxHealth) || 1);
146
}
147
}
148
return {
149
tileX: record?.tileX | 0,
150
tileY: record?.tileY | 0,
151
dimensionId: record?.dimensionId ?? "overworld",
152
skills,
153
hp,
154
maxHp,
155
stamina,
156
maxStamina
157
};
158
}
159
160
buildConditionContext (characterId, playerView, activeQuestId = null)
161
{
162
const bag = this.#loadBag(characterId);
163
const inventory = bag?.inventory ?? [];
164
const tileX = playerView?.tileX | 0;
165
const tileY = playerView?.tileY | 0;
166
const dimensionId = playerView?.dimensionId ?? "overworld";
167
const chunkX = floorDiv(tileX, CHUNK_SIZE);
168
const chunkY = floorDiv(tileY, CHUNK_SIZE);
169
const questRow = activeQuestId ? this.stateDb.getQuestState(characterId, activeQuestId) : null;
170
return {
171
tileX,
172
tileY,
173
chunkX,
174
chunkY,
175
dimensionId,
176
hp: playerView?.hp ?? 0,
177
maxHp: playerView?.maxHp ?? 1,
178
stamina: playerView?.stamina ?? 0,
179
maxStamina: playerView?.maxStamina ?? 1,
180
countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
181
questState: (questId) => this.stateDb.getQuestState(characterId, questId).state,
182
dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId),
183
dialogueTriggerLatched: (dialogueId, trigger) =>
184
this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger),
185
skillLevel: (skillId) => resolveSkillRequirementLevel(playerView?.skills ?? {}, skillId),
186
hasVisitedDimension: (dimId) => this.stateDb.hasVisitedDimension(characterId, dimId),
187
killCount: (condition) =>
188
{
189
if (!questRow)
190
{ return 0; }
191
return questRow.progress?.counters?.[killKey(condition)] | 0;
192
},
193
interactBlockDone: (condition) =>
194
{
195
if (!questRow)
196
{ return false; }
197
return !!questRow.progress?.interacts?.[interactKey(condition)];
198
}
199
};
200
}
201
202
tryOpenDialogue (characterId, entityId, dialogueId)
203
{
204
const tree = this.content.dialogue(dialogueId);
205
if (!tree)
206
{ return { ok: false, error: "Nothing to say." }; }
207
this.closeDialogue(characterId, "replace");
208
const playerView = this.playerViewFor(characterId);
209
return this.#enterStep(characterId, entityId, tree, tree.entryStepId, playerView);
210
}
211
212
chooseDialogue (characterId, triggerId)
213
{
214
const session = this.sessions.get(characterId | 0);
215
if (!session)
216
{ return { ok: false, error: "No dialogue open." }; }
217
if (session.phase === "lines")
218
{ return { ok: false, error: "Finish reading first." }; }
219
if (session.phase === "rewards")
220
{ return { ok: false, error: "Finish reading first." }; }
221
const tree = this.content.dialogue(session.dialogueId);
222
if (!tree)
223
{
224
this.closeDialogue(characterId, "missing");
225
return { ok: false, error: "Dialogue missing." };
226
}
227
const step = tree.steps.find((s) => s.stepId === session.stepId);
228
if (!step || step.exit?.kind !== "triggers")
229
{ return { ok: false, error: "Cannot choose now." }; }
230
const trigger = step.exit.triggers.find((t) => t.trigger === String(triggerId));
231
if (!trigger)
232
{ return { ok: false, error: "Unknown choice." }; }
233
const playerView = this.playerViewFor(characterId);
234
const ctx = this.buildConditionContext(characterId, playerView);
235
if (!evaluateConditionSet(trigger.when, ctx))
236
{ return { ok: false, error: "That choice is unavailable." }; }
237
this.stateDb.latchDialogueTrigger(characterId, tree.dialogueId, trigger.trigger);
238
const events = [];
239
this.#applyEffects(characterId, trigger.effects, playerView, events);
240
this.#reevaluateQuests(characterId, playerView, events);
241
if (!trigger.nextStepId)
242
{
243
const npcEntityId = session.entityId;
244
this.sessions.delete(characterId | 0);
245
events.push({ type: "dialogueClose", reason: "end", npcEntityId });
246
return { ok: true, events };
247
}
248
return this.#enterStep(characterId, session.entityId, tree, trigger.nextStepId, playerView, events);
249
}
250
251
closeDialogue (characterId, reason = "close")
252
{
253
const id = characterId | 0;
254
const session = this.sessions.get(id);
255
if (!session)
256
{ return { events: [] }; }
257
this.sessions.delete(id);
258
return {
259
events: [{
260
type: "dialogueClose",
261
reason,
262
npcEntityId: session.entityId
263
}]
264
};
265
}
266
267
interruptDialogueForEntity (entityId)
268
{
269
const events = [];
270
for (const [characterId, session] of [...this.sessions])
271
{
272
if (session.entityId === (entityId | 0))
273
{
274
const closed = this.closeDialogue(characterId, "attacked");
275
events.push(...closed.events.map((e) => ({ ...e, characterId })));
276
}
277
}
278
return events;
279
}
280
281
#enterStep (characterId, entityId, tree, stepId, playerView, priorEvents = [])
282
{
283
const step = tree.steps.find((s) => s.stepId === stepId);
284
if (!step)
285
{
286
this.sessions.delete(characterId | 0);
287
priorEvents.push({ type: "dialogueClose", reason: "missing-step" });
288
return { ok: false, error: "Broken dialogue.", events: priorEvents };
289
}
290
const events = [...priorEvents];
291
const identity = this.#playerDialogueIdentity(characterId);
292
const linePayloads = [];
293
for (const line of step.lines)
294
{
295
this.#applyEffects(characterId, line.effects, playerView, events);
296
linePayloads.push({
297
speaker: line.speaker,
298
text: applyDialogueTextReplacements(line.text, identity)
299
});
300
}
301
// Stay open while the client pages lines; resolve exit only on dialogueAdvance.
302
// dialogueHeard is marked only when the step fully completes (after rewards).
303
this.sessions.set(characterId | 0, {
304
entityId: entityId | 0,
305
dialogueId: tree.dialogueId,
306
stepId: step.stepId,
307
phase: "lines",
308
pendingExit: step.exit ?? { kind: "end" }
309
});
310
events.push({
311
type: "dialogueStep",
312
dialogueId: tree.dialogueId,
313
stepId: step.stepId,
314
label: step.label,
315
npcEntityId: entityId | 0,
316
lines: linePayloads
317
});
318
this.#reevaluateQuests(characterId, playerView, events);
319
return { ok: true, events };
320
}
321
322
/** Client finished reading all lines (or reward notices) of the current step. */
323
advanceDialogue (characterId)
324
{
325
const session = this.sessions.get(characterId | 0);
326
if (!session || (session.phase !== "lines" && session.phase !== "rewards"))
327
{ return { ok: false, error: "No dialogue lines to advance." }; }
328
const tree = this.content.dialogue(session.dialogueId);
329
if (!tree)
330
{
331
this.sessions.delete(characterId | 0);
332
return { ok: true, events: [{ type: "dialogueClose", reason: "missing" }] };
333
}
334
const playerView = this.playerViewFor(characterId);
335
const events = [];
336
337
if (session.phase === "lines")
338
{
339
const step = tree.steps.find((s) => s.stepId === session.stepId);
340
const rewardMessages = [
341
...this.#takeStepItems(characterId, step, events),
342
...this.#grantStepItemRewards(characterId, step, events),
343
...this.#grantStepQuestRewards(characterId, step, playerView, events)
344
];
345
this.#reevaluateQuests(characterId, playerView, events);
346
if (rewardMessages.length > 0)
347
{
348
session.phase = "rewards";
349
events.push({
350
type: "dialogueItemRewards",
351
dialogueId: session.dialogueId,
352
stepId: session.stepId,
353
npcEntityId: session.entityId,
354
messages: rewardMessages
355
});
356
return { ok: true, events };
357
}
358
}
359
360
return this.#resolveDialogueExit(characterId, session, tree, playerView, events);
361
}
362
363
#resolveDialogueExit (characterId, session, tree, playerView, events)
364
{
365
// Step is fully finished: lines read + takes/rewards/quest notices acknowledged.
366
this.stateDb.markDialogueHeard(characterId, tree.dialogueId, session.stepId);
367
this.#reevaluateQuests(characterId, playerView, events);
368
369
const exit = session.pendingExit ?? { kind: "end" };
370
371
if (exit.kind === "branches")
372
{
373
const ctx = this.buildConditionContext(characterId, playerView);
374
let matched = null;
375
for (const branch of exit.branches ?? [])
376
{
377
if (evaluateConditionSet(branch.when, ctx))
378
{
379
matched = branch;
380
break;
381
}
382
}
383
if (!matched || !matched.nextStepId)
384
{
385
this.#applyEffects(characterId, matched?.effects, playerView, events);
386
const npcEntityId = session.entityId;
387
this.sessions.delete(characterId | 0);
388
events.push({ type: "dialogueClose", reason: "branch-end", npcEntityId });
389
return { ok: true, events };
390
}
391
this.#applyEffects(characterId, matched.effects, playerView, events);
392
return this.#enterStep(characterId, session.entityId, tree, matched.nextStepId, playerView, events);
393
}
394
395
if (exit.kind === "triggers")
396
{
397
const ctx = this.buildConditionContext(characterId, playerView);
398
const identity = this.#playerDialogueIdentity(characterId);
399
const triggers = (exit.triggers ?? [])
400
.filter((t) => evaluateConditionSet(t.when, ctx))
401
.map((t) => ({
402
trigger: t.trigger,
403
text: applyDialogueTextReplacements(t.text, identity)
404
}));
405
if (triggers.length === 0)
406
{
407
const npcEntityId = session.entityId;
408
this.sessions.delete(characterId | 0);
409
events.push({ type: "dialogueClose", reason: "no-triggers", npcEntityId });
410
return { ok: true, events };
411
}
412
session.phase = "choices";
413
session.pendingExit = null;
414
events.push({
415
type: "dialogueChoices",
416
dialogueId: session.dialogueId,
417
stepId: session.stepId,
418
npcEntityId: session.entityId,
419
triggers
420
});
421
return { ok: true, events };
422
}
423
424
if (exit.kind === "continue")
425
{
426
if (!exit.nextStepId)
427
{
428
const npcEntityId = session.entityId;
429
this.sessions.delete(characterId | 0);
430
events.push({ type: "dialogueClose", reason: "continue-end", npcEntityId });
431
return { ok: true, events };
432
}
433
return this.#enterStep(characterId, session.entityId, tree, exit.nextStepId, playerView, events);
434
}
435
436
const npcEntityId = session.entityId;
437
this.sessions.delete(characterId | 0);
438
events.push({ type: "dialogueClose", reason: "end", npcEntityId });
439
return { ok: true, events };
440
}
441
442
/**
443
* Soft-take step.itemTakes from the bag (min(have, required)). Returns player-facing notices.
444
*/
445
#takeStepItems (characterId, step, events)
446
{
447
const takes = step?.itemTakes ?? [];
448
if (!takes.length)
449
{ return []; }
450
const parts = [];
451
for (const take of takes)
452
{
453
const bag = this.#loadBag(characterId);
454
if (!bag)
455
{ continue; }
456
const itemId = take.itemId | 0;
457
const want = Math.max(1, Number(take.quantity) || 1);
458
const def = itemDefinition(itemId);
459
const displayName = def?.displayName ?? `Item ${itemId}`;
460
const result = takeMatchingUpToFromSlots(bag.inventory, {
461
itemId,
462
quantity: want,
463
compact: false
464
});
465
if (!result.ok || result.takenQuantity <= 0)
466
{ continue; }
467
bag.inventory = result.slots;
468
this.#persistBag(characterId, bag);
469
events.push({ type: "inventoryDirty" });
470
parts.push({ displayName, quantity: result.takenQuantity });
471
}
472
const message = formatDialogueTakeMessage(parts);
473
return message ? [message] : [];
474
}
475
476
/**
477
* Grant step.itemRewards into bag (overflow → bank/vault). Returns player-facing notices.
478
*/
479
#grantStepItemRewards (characterId, step, events)
480
{
481
const rewards = step?.itemRewards ?? [];
482
if (!rewards.length)
483
{ return []; }
484
const bagParts = [];
485
const bankParts = [];
486
for (const reward of rewards)
487
{
488
const bag = this.#loadBag(characterId);
489
if (!bag)
490
{ continue; }
491
const itemId = reward.itemId | 0;
492
const def = itemDefinition(itemId);
493
const quantity = Math.max(1, Number(reward.quantity) || 1);
494
const displayName = def?.displayName ?? `Item ${itemId}`;
495
const stack = attachOrigins({
496
itemId,
497
quantity,
498
origins: [{ origin: godsOrigin(), quantity }]
499
});
500
const result = insertStack(bag.inventory, stack, def);
501
bag.inventory = result.slots;
502
const intoBag = quantity - Math.max(0, result.remainder | 0);
503
let intoBank = 0;
504
if (result.remainder > 0)
505
{
506
const vaultResult = insertStackGrowable(
507
bag.vault,
508
attachOrigins({
509
itemId,
510
quantity: result.remainder,
511
origins: [{ origin: godsOrigin(), quantity: result.remainder }]
512
}),
513
def
514
);
515
bag.vault = vaultResult.slots;
516
intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
517
}
518
this.#persistBag(characterId, bag);
519
events.push({ type: "inventoryDirty" });
520
if (intoBag > 0)
521
{ bagParts.push({ displayName, quantity: intoBag }); }
522
if (intoBank > 0)
523
{ bankParts.push({ displayName, quantity: intoBank }); }
524
}
525
const messages = [];
526
const bagMsg = formatDialogueRewardMessage(bagParts, "bag");
527
const bankMsg = formatDialogueRewardMessage(bankParts, "bank");
528
if (bagMsg)
529
{ messages.push(bagMsg); }
530
if (bankMsg)
531
{ messages.push(bankMsg); }
532
return messages;
533
}
534
535
/** Start step.questRewards; returns player-facing notices for newly started quests. */
536
#grantStepQuestRewards (characterId, step, playerView, events)
537
{
538
const rewards = step?.questRewards ?? [];
539
if (!rewards.length)
540
{ return []; }
541
const titles = [];
542
for (const questId of rewards)
543
{
544
const current = this.stateDb.getQuestState(characterId, questId);
545
if (current.state !== "not-started")
546
{ continue; }
547
const def = this.content.quest(questId);
548
if (!def)
549
{ continue; }
550
this.startQuest(characterId, questId, playerView, events);
551
titles.push(def.title || def.questId);
552
}
553
const message = formatDialogueQuestRewardMessage(titles);
554
return message ? [message] : [];
555
}
556
557
#loadBag (characterId)
558
{
559
const onlineId = this.simulation.characterEntities.get(characterId | 0);
560
const bag = onlineId
561
? this.simulation.bagOf(onlineId)
562
: this.stateDb.getBag(characterId);
563
return bag;
564
}
565
566
#playerDialogueIdentity (characterId)
567
{
568
const row = this.stateDb.getCharacter(characterId | 0);
569
return {
570
firstName: String(row?.first_name ?? "").trim(),
571
lastName: String(row?.last_name ?? "").trim(),
572
sex: row?.sex === "female" ? "female" : "male"
573
};
574
}
575
576
#persistBag (characterId, bag)
577
{
578
this.stateDb.saveBag(characterId, bag);
579
const onlineId = this.simulation.characterEntities.get(characterId | 0);
580
if (onlineId)
581
{
582
this.simulation.applyBag?.(onlineId, bag);
583
this.simulation.pushInventory?.(characterId, bag);
584
}
585
}
586
587
#applyEffects (characterId, effects, playerView, events)
588
{
589
if (!Array.isArray(effects) || effects.length === 0)
590
{ return; }
591
for (const effect of effects)
592
{
593
if (effect.kind === EffectKind.giveItem)
594
{
595
const bag = this.#loadBag(characterId);
596
if (!bag)
597
{ continue; }
598
const def = itemDefinition(effect.itemId | 0);
599
const quantity = Math.max(1, Number(effect.quantity) || 1);
600
const stack = attachOrigins({
601
itemId: effect.itemId | 0,
602
quantity,
603
origins: [{ origin: godsOrigin(), quantity }]
604
});
605
if (effect.toBank)
606
{
607
const vaultResult = insertStackGrowable(bag.vault ?? [], stack, def);
608
bag.vault = vaultResult.slots;
609
}
610
else
611
{
612
const result = insertStack(bag.inventory, stack, def);
613
bag.inventory = result.slots;
614
if (result.remainder > 0)
615
{
616
const vaultResult = insertStackGrowable(
617
bag.vault ?? [],
618
attachOrigins({
619
itemId: effect.itemId | 0,
620
quantity: result.remainder,
621
origins: [{ origin: godsOrigin(), quantity: result.remainder }]
622
}),
623
def
624
);
625
bag.vault = vaultResult.slots;
626
}
627
}
628
this.#persistBag(characterId, bag);
629
events.push({ type: "inventoryDirty" });
630
}
631
else if (effect.kind === EffectKind.takeItem)
632
{
633
const bag = this.#loadBag(characterId);
634
if (!bag)
635
{ continue; }
636
const taken = takeMatchingFromSlots(bag.inventory, {
637
itemId: effect.itemId | 0,
638
quantity: Math.max(1, Number(effect.quantity) || 1),
639
compact: false
640
});
641
if (taken.ok)
642
{
643
bag.inventory = taken.slots;
644
this.#persistBag(characterId, bag);
645
events.push({ type: "inventoryDirty" });
646
}
647
}
648
else if (effect.kind === EffectKind.giveXp)
649
{
650
const skills = this.stateDb.getSkills(characterId);
651
if (skills)
652
{
653
applySkillXp(skills, effect.skillId, Math.max(0, Number(effect.amount) || 0));
654
this.stateDb.saveSkills(characterId, skills);
655
if (playerView)
656
{ playerView.skills = skills; }
657
events.push({ type: "skillsDirty" });
658
}
659
}
660
else if (effect.kind === EffectKind.startQuest)
661
{ this.startQuest(characterId, effect.questId, playerView, events); }
662
}
663
}
664
665
startQuest (characterId, questId, playerView, events = [])
666
{
667
const def = this.content.quest(questId);
668
if (!def)
669
{ return; }
670
const current = this.stateDb.getQuestState(characterId, questId);
671
if (current.state !== "not-started")
672
{ return; }
673
this.stateDb.saveQuestState(characterId, questId, 1, {
674
completedObjectiveIds: [],
675
counters: {},
676
interacts: {}
677
}, Date.now(), null);
678
this.#applyEffects(characterId, def.steps[0]?.onEnter, playerView, events);
679
events.push({ type: "questsDirty", characterId });
680
this.#reevaluateQuests(characterId, playerView, events);
681
}
682
683
/**
684
* Grant world-settings initial quests when the character has not started or completed them.
685
*/
686
ensureInitialQuests (characterId, playerView = null, events = [])
687
{
688
const list = normalizeInitialQuests(this.simulation?.settings?.initialQuests);
689
for (const questId of list)
690
{ this.startQuest(characterId, questId, playerView, events); }
691
return events;
692
}
693
694
/**
695
* Re-check active quest objectives against live bag/position/etc.
696
* Used when opening the quest log (and wherever progress may have changed offline of dialogue/kills).
697
*/
698
reevaluateQuests (characterId, playerView = null, events = [])
699
{
700
const view = playerView ?? this.playerViewFor(characterId);
701
this.#reevaluateQuests(characterId, view, events);
702
return events;
703
}
704
705
/** Apply initial quests to every character in state (settings save / apply). */
706
grantInitialQuestsToAllCharacters ()
707
{
708
const events = [];
709
for (const characterId of this.stateDb.listAllCharacterIds())
710
{ this.ensureInitialQuests(characterId, null, events); }
711
return events;
712
}
713
714
/**
715
* Final quest rewards: XP + items (bag or bank). Banked items get a Questward letter.
716
* @returns {{ xp: { skillId: string, displayName: string, amount: number }[], bagItems: { displayName: string, quantity: number }[] }}
717
*/
718
#grantQuestCompletionRewards (characterId, def, playerView, events)
719
{
720
const xp = [];
721
const bagItems = [];
722
const bankItems = [];
723
const rewards = def?.rewards ?? [];
724
for (const effect of rewards)
725
{
726
if (effect.kind === EffectKind.giveXp)
727
{
728
const amount = Math.max(0, Number(effect.amount) || 0) | 0;
729
if (amount <= 0)
730
{ continue; }
731
const skillId = String(effect.skillId ?? "").trim();
732
if (!skillId)
733
{ continue; }
734
const onlineId = this.simulation.characterEntities.get(characterId | 0);
735
let skills = onlineId
736
? this.simulation.skillsOf(onlineId)
737
: this.stateDb.getSkills(characterId);
738
if (!skills)
739
{ skills = this.stateDb.getSkills(characterId); }
740
if (!skills)
741
{ continue; }
742
applySkillXp(skills, skillId, amount);
743
this.stateDb.saveSkills(characterId, skills);
744
if (playerView)
745
{ playerView.skills = skills; }
746
if (onlineId)
747
{ this.simulation.applySkills?.(onlineId, skills); }
748
const payload = publicSkillsPayload(skills);
749
this.simulation.pushSkills?.(characterId, payload.skills, payload.combatLevel);
750
xp.push({
751
skillId,
752
displayName: SKILL_DEFINITIONS[skillId]?.displayName ?? skillId,
753
amount
754
});
755
continue;
756
}
757
if (effect.kind !== EffectKind.giveItem)
758
{ continue; }
759
const bag = this.#loadBag(characterId);
760
if (!bag)
761
{ continue; }
762
const itemId = effect.itemId | 0;
763
const defItem = itemDefinition(itemId);
764
const quantity = Math.max(1, Number(effect.quantity) || 1) | 0;
765
const displayName = defItem
766
? itemDisplayName({ itemId, quantity }, defItem)
767
: `Item ${itemId}`;
768
const stack = attachOrigins({
769
itemId,
770
quantity,
771
origins: [{ origin: godsOrigin(), quantity }]
772
});
773
let intoBag = 0;
774
let intoBank = 0;
775
if (effect.toBank)
776
{
777
const vaultResult = insertStackGrowable(bag.vault ?? [], stack, defItem);
778
bag.vault = vaultResult.slots;
779
intoBank = quantity - Math.max(0, vaultResult.remainder | 0);
780
}
781
else
782
{
783
const result = insertStack(bag.inventory, stack, defItem);
784
bag.inventory = result.slots;
785
intoBag = quantity - Math.max(0, result.remainder | 0);
786
if (result.remainder > 0)
787
{
788
const vaultResult = insertStackGrowable(
789
bag.vault ?? [],
790
attachOrigins({
791
itemId,
792
quantity: result.remainder,
793
origins: [{ origin: godsOrigin(), quantity: result.remainder }]
794
}),
795
defItem
796
);
797
bag.vault = vaultResult.slots;
798
intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
799
}
800
}
801
this.#persistBag(characterId, bag);
802
events.push({ type: "inventoryDirty" });
803
if (intoBag > 0)
804
{ bagItems.push({ displayName, quantity: intoBag, itemId }); }
805
if (intoBank > 0)
806
{ bankItems.push({ displayName, quantity: intoBank, itemId }); }
807
}
808
809
if (bankItems.length)
810
{ this.#dispatchQuestBankRewardLetter(characterId, def, bankItems); }
811
812
return { xp, bagItems };
813
}
814
815
#dispatchQuestBankRewardLetter (characterId, def, bankItems)
816
{
817
const courier = this.simulation.courier;
818
if (!courier?.enqueueSystemLetter)
819
{ return; }
820
const row = this.stateDb.getCharacter?.(characterId);
821
const characterDisplayName = row
822
? `${row.first_name ?? ""} ${row.last_name ?? ""}`.trim()
823
: "Adventurer";
824
const originTileX = row?.tile_x | 0;
825
const originTileY = row?.tile_y | 0;
826
const bank = courier.nearestBank?.(originTileX, originTileY);
827
courier.enqueueSystemLetter({
828
characterId: characterId | 0,
829
originTileX: bank?.tileX ?? originTileX,
830
originTileY: bank?.tileY ?? originTileY,
831
authorDisplayName: QUESTWARD_GIFT_AUTHOR,
832
authorOrganization: QUESTWARD_GIFT_ORG,
833
body: formatQuestBankRewardLetterBody({
834
characterDisplayName,
835
questTitle: def?.title ?? def?.questId,
836
items: bankItems
837
})
838
});
839
}
840
841
#reevaluateQuests (characterId, playerView, events)
842
{
843
const states = this.stateDb.listQuestStates(characterId)
844
.filter((row) => typeof row.state === "number");
845
for (const row of states)
846
{
847
const def = this.content.quest(row.questId);
848
if (!def)
849
{ continue; }
850
const stepDef = def.steps[row.state - 1];
851
if (!stepDef)
852
{ continue; }
853
const ctx = this.buildConditionContext(characterId, playerView, row.questId);
854
const completed = new Set(row.progress?.completedObjectiveIds ?? []);
855
const newlyDone = [];
856
let changed = false;
857
for (const obj of stepDef.objectives)
858
{
859
if (completed.has(obj.objectiveId))
860
{ continue; }
861
if (evaluateConditionSet(obj.when, ctx))
862
{
863
completed.add(obj.objectiveId);
864
newlyDone.push(obj);
865
changed = true;
866
}
867
}
868
const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx);
869
const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");
870
if (!changed && !progressChanged)
871
{ continue; }
872
for (const obj of newlyDone)
873
{
874
events.push({
875
type: "questObjectiveComplete",
876
questId: row.questId,
877
objectiveId: obj.objectiveId,
878
text: obj.text || "Objective"
879
});
880
}
881
const progress = {
882
...row.progress,
883
completedObjectiveIds: [...completed],
884
progressFingerprint: fingerprint
885
};
886
const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
887
if (!allDone)
888
{
889
this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
890
events.push({ type: "questsDirty", characterId });
891
continue;
892
}
893
if (!changed)
894
{
895
// Progress-only update while already fully complete (should not happen).
896
this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
897
events.push({ type: "questsDirty", characterId });
898
continue;
899
}
900
this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
901
const journal = this.stateDb.appendQuestJournal(
902
characterId,
903
row.questId,
904
stepDef.stepId,
905
stepDef.completionJournalText
906
);
907
const nextIndex = row.state + 1;
908
if (nextIndex > def.steps.length)
909
{
910
const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events);
911
this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now());
912
events.push({
913
type: "questComplete",
914
questId: row.questId,
915
title: def.title,
916
xp: summary.xp,
917
items: summary.bagItems
918
});
919
}
920
else
921
{
922
const nextStep = def.steps[nextIndex - 1];
923
this.stateDb.saveQuestState(characterId, row.questId, nextIndex, {
924
completedObjectiveIds: [],
925
counters: {},
926
interacts: {},
927
progressFingerprint: ""
928
}, row.startedAt, null);
929
this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
930
events.push({
931
type: "questStepComplete",
932
questId: row.questId,
933
title: def.title,
934
journalText: journal?.text ?? null
935
});
936
}
937
events.push({ type: "questsDirty", characterId });
938
}
939
}
940
941
noteKill (characterId, { mobTypeId, spawnerId })
942
{
943
const events = [];
944
const playerView = this.playerViewFor(characterId);
945
const states = this.stateDb.listQuestStates(characterId)
946
.filter((row) => typeof row.state === "number");
947
for (const row of states)
948
{
949
const def = this.content.quest(row.questId);
950
const stepDef = def?.steps[row.state - 1];
951
if (!stepDef)
952
{ continue; }
953
let changed = false;
954
const counters = { ...(row.progress?.counters ?? {}) };
955
for (const obj of stepDef.objectives)
956
{
957
for (const clause of obj.when?.all ?? [])
958
{
959
const c = clause.condition;
960
if (c?.kind !== "killCount")
961
{ continue; }
962
const matchMob = c.mobTypeId != null && String(c.mobTypeId) === String(mobTypeId);
963
const matchSpawner = c.spawnerId != null && String(c.spawnerId) === String(spawnerId);
964
if (!matchMob && !matchSpawner)
965
{ continue; }
966
const key = killKey(c);
967
counters[key] = (counters[key] | 0) + 1;
968
changed = true;
969
}
970
}
971
if (!changed)
972
{ continue; }
973
this.stateDb.saveQuestState(characterId, row.questId, row.state, {
974
...row.progress,
975
counters
976
}, row.startedAt, row.completedAt);
977
}
978
this.#reevaluateQuests(characterId, playerView, events);
979
return events;
980
}
981
}
982
983
function journalPublic (row)
984
{
985
return {
986
entryId: row.entry_id ?? row.entryId,
987
questId: row.quest_id ?? row.questId,
988
stepId: row.step_id ?? row.stepId,
989
text: row.text,
990
writtenAt: row.written_at ?? row.writtenAt
991
};
992
}
993
994
function killKey (condition)
995
{
996
if (condition.spawnerId)
997
{ return `spawner:${condition.spawnerId}`; }
998
return `mob:${condition.mobTypeId}`;
999
}
1000
1001
function interactKey (condition)
1002
{
1003
if (condition.tileX != null)
1004
{ return `tile:${condition.tileX},${condition.tileY}`; }
1005
return `block:${condition.blockTypeId}`;
1006
}
@@ -1,1006 +1,1006 @@1
import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
1
import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";2
import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
2
import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";3
import {
3
import {4
countableObjectiveProgress,
4
countableObjectiveProgress,5
objectiveProgressFingerprint
5
objectiveProgressFingerprint6
} from "../../../shared/quests/objectiveProgress.js";
6
} from "../../../shared/quests/objectiveProgress.js";7
import { countItemInSlots, insertStack, takeMatchingFromSlots, takeMatchingUpToFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
7
import { countItemInSlots, insertStack, takeMatchingFromSlots, takeMatchingUpToFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";8
import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
8
import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";9
import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
9
import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";10
import { applySkillXp, publicSkillsPayload } from "../../../shared/skills/state.js";
10
import { applySkillXp, publicSkillsPayload } from "../../../shared/skills/state.js";11
import { SKILL_DEFINITIONS } from "../../../shared/definitions/skills.js";
11
import { SKILL_DEFINITIONS } from "../../../shared/definitions/skills.js";12
import { resolveSkillRequirementLevel } from "../../../shared/combat/combatLevel.js";
12
import { resolveSkillRequirementLevel } from "../../../shared/combat/combatLevel.js";13
import {
13
import {14
formatDialogueRewardMessage,
14
formatDialogueRewardMessage,15
formatDialogueQuestRewardMessage,
15
formatDialogueQuestRewardMessage,16
formatDialogueTakeMessage
16
formatDialogueTakeMessage17
} from "../../../shared/quests/dialogueRewards.js";
17
} from "../../../shared/quests/dialogueRewards.js";18
import { applyDialogueTextReplacements } from "../../../shared/speech/dialogueText.js";
18
import { applyDialogueTextReplacements } from "../../../shared/speech/dialogueText.js";19
import {
19
import {20
formatQuestBankRewardLetterBody,
20
formatQuestBankRewardLetterBody,21
QUESTWARD_GIFT_AUTHOR,
21
QUESTWARD_GIFT_AUTHOR,22
QUESTWARD_GIFT_ORG
22
QUESTWARD_GIFT_ORG23
} from "../../../shared/courier/questRewardLetters.js";
23
} from "../../../shared/courier/questRewardLetters.js";24
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
24
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";25
import { floorDiv } from "../world/coordinates.js";
25
import { floorDiv } from "../world/coordinates.js";26
import { WorkerMessage } from "../simulation/protocol.js";
26
import { WorkerMessage } from "../simulation/protocol.js";27
27
28
/**
28
/**29
* Quest progress + dialogue sessions (main simulation thread).
29
* Quest progress + dialogue sessions (main simulation thread).30
*/
30
*/31
export class QuestRuntime
31
export class QuestRuntime32
{
32
{33
constructor ({ stateDb, content, simulation })
33
constructor ({ stateDb, content, simulation })34
{
34
{35
this.stateDb = stateDb;
35
this.stateDb = stateDb;36
this.content = content;
36
this.content = content;37
this.simulation = simulation;
37
this.simulation = simulation;38
/** @type {Map<number, { entityId: number, dialogueId: string, stepId: string }>} */
38
/** @type {Map<number, { entityId: number, dialogueId: string, stepId: string }>} */39
this.sessions = new Map();
39
this.sessions = new Map();40
}
40
}41
41
42
reloadContent ()
42
reloadContent ()43
{
43
{44
this.content.reload();
44
this.content.reload();45
}
45
}46
46
47
closeAllSessions ()
47
closeAllSessions ()48
{
48
{49
for (const characterId of [...this.sessions.keys()])
49
for (const characterId of [...this.sessions.keys()])50
{ this.closeDialogue(characterId, "revision"); }
50
{ this.closeDialogue(characterId, "revision"); }51
}
51
}52
52
53
questSnapshot (characterId)
53
questSnapshot (characterId)54
{
54
{55
const states = this.stateDb.listQuestStates(characterId)
55
const states = this.stateDb.listQuestStates(characterId)56
.filter((row) => row.state !== "not-started");
56
.filter((row) => row.state !== "not-started");57
const quests = [];
57
const quests = [];58
const playerView = this.playerViewFor(characterId);
58
const playerView = this.playerViewFor(characterId);59
for (const row of states)
59
for (const row of states)60
{
60
{61
const def = this.content.quest(row.questId);
61
const def = this.content.quest(row.questId);62
if (!def)
62
if (!def)63
{
63
{64
quests.push({
64
quests.push({65
questId: row.questId,
65
questId: row.questId,66
title: "Quest unavailable",
66
title: "Quest unavailable",67
orphaned: true,
67
orphaned: true,68
state: row.state,
68
state: row.state,69
description: "",
69
description: "",70
step: null,
70
step: null,71
journal: this.stateDb.listQuestJournal(characterId, row.questId).map(journalPublic)
71
journal: this.stateDb.listQuestJournal(characterId, row.questId).map(journalPublic)72
});
72
});73
continue;
73
continue;74
}
74
}75
const stepIndex = typeof row.state === "number" ? row.state : null;
75
const stepIndex = typeof row.state === "number" ? row.state : null;76
const stepDef = stepIndex != null ? def.steps[stepIndex - 1] : null;
76
const stepDef = stepIndex != null ? def.steps[stepIndex - 1] : null;77
const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];
77
const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];78
const ctx = stepDef
78
const ctx = stepDef79
? this.buildConditionContext(characterId, playerView, row.questId)
79
? this.buildConditionContext(characterId, playerView, row.questId)80
: null;
80
: null;81
quests.push({
81
quests.push({82
questId: def.questId,
82
questId: def.questId,83
title: def.title,
83
title: def.title,84
orphaned: false,
84
orphaned: false,85
state: row.state,
85
state: row.state,86
description: def.description,
86
description: def.description,87
step: stepDef
87
step: stepDef88
? {
88
? {89
stepId: stepDef.stepId,
89
stepId: stepDef.stepId,90
title: stepDef.title,
90
title: stepDef.title,91
description: stepDef.description,
91
description: stepDef.description,92
objectives: stepDef.objectives.map((obj) =>
92
objectives: stepDef.objectives.map((obj) =>93
{
93
{94
const done = completedObjectiveIds.includes(obj.objectiveId);
94
const done = completedObjectiveIds.includes(obj.objectiveId);95
const progress = countableObjectiveProgress(obj.when, ctx);
95
const progress = countableObjectiveProgress(obj.when, ctx);96
return {
96
return {97
objectiveId: obj.objectiveId,
97
objectiveId: obj.objectiveId,98
text: obj.text,
98
text: obj.text,99
done,
99
done,100
current: progress?.current ?? null,
100
current: progress?.current ?? null,101
required: progress?.required ?? null
101
required: progress?.required ?? null102
};
102
};103
})
103
})104
}
104
}105
: null,
105
: null,106
journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)
106
journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)107
});
107
});108
}
108
}109
quests.sort((a, b) =>
109
quests.sort((a, b) =>110
{
110
{111
const aDone = a.state === "completed" ? 1 : 0;
111
const aDone = a.state === "completed" ? 1 : 0;112
const bDone = b.state === "completed" ? 1 : 0;
112
const bDone = b.state === "completed" ? 1 : 0;113
if (aDone !== bDone)
113
if (aDone !== bDone)114
{ return aDone - bDone; }
114
{ return aDone - bDone; }115
return String(a.title).localeCompare(String(b.title));
115
return String(a.title).localeCompare(String(b.title));116
});
116
});117
return { quests };
117
return { quests };118
}
118
}119
119
120
playerViewFor (characterId)
120
playerViewFor (characterId)121
{
121
{122
const entityId = this.simulation.characterEntities.get(characterId | 0);
122
const entityId = this.simulation.characterEntities.get(characterId | 0);123
const record = entityId != null ? this.simulation.directory.get(entityId) : null;
123
const record = entityId != null ? this.simulation.directory.get(entityId) : null;124
const skills = this.stateDb.getSkills(characterId) ?? {};
124
const skills = this.stateDb.getSkills(characterId) ?? {};125
let hp = 1;
125
let hp = 1;126
let maxHp = 1;
126
let maxHp = 1;127
let stamina = 1;
127
let stamina = 1;128
let maxStamina = 1;
128
let maxStamina = 1;129
if (entityId != null && record)
129
if (entityId != null && record)130
{
130
{131
const staminaComp = this.simulation.staminaOf(entityId);
131
const staminaComp = this.simulation.staminaOf(entityId);132
if (staminaComp)
132
if (staminaComp)133
{
133
{134
stamina = Number(staminaComp.current) || 0;
134
stamina = Number(staminaComp.current) || 0;135
maxStamina = Math.max(1, Number(staminaComp.max) || 1);
135
maxStamina = Math.max(1, Number(staminaComp.max) || 1);136
}
136
}137
const worker = this.simulation.workers[record.workerId];
137
const worker = this.simulation.workers[record.workerId];138
const view = worker?.call?.({
138
const view = worker?.call?.({139
type: WorkerMessage.inspect,
139
type: WorkerMessage.inspect,140
entityId
140
entityId141
});
141
});142
if (view && view.health != null)
142
if (view && view.health != null)143
{
143
{144
hp = Number(view.health) || 0;
144
hp = Number(view.health) || 0;145
maxHp = Math.max(1, Number(view.maxHealth) || 1);
145
maxHp = Math.max(1, Number(view.maxHealth) || 1);146
}
146
}147
}
147
}148
return {
148
return {149
tileX: record?.tileX | 0,
149
tileX: record?.tileX | 0,150
tileY: record?.tileY | 0,
150
tileY: record?.tileY | 0,151
dimensionId: record?.dimensionId ?? "overworld",
151
dimensionId: record?.dimensionId ?? "overworld",152
skills,
152
skills,153
hp,
153
hp,154
maxHp,
154
maxHp,155
stamina,
155
stamina,156
maxStamina
156
maxStamina157
};
157
};158
}
158
}159
159
160
buildConditionContext (characterId, playerView, activeQuestId = null)
160
buildConditionContext (characterId, playerView, activeQuestId = null)161
{
161
{162
const bag = this.#loadBag(characterId);
162
const bag = this.#loadBag(characterId);163
const inventory = bag?.inventory ?? [];
163
const inventory = bag?.inventory ?? [];164
const tileX = playerView?.tileX | 0;
164
const tileX = playerView?.tileX | 0;165
const tileY = playerView?.tileY | 0;
165
const tileY = playerView?.tileY | 0;166
const dimensionId = playerView?.dimensionId ?? "overworld";
166
const dimensionId = playerView?.dimensionId ?? "overworld";167
const chunkX = floorDiv(tileX, CHUNK_SIZE);
167
const chunkX = floorDiv(tileX, CHUNK_SIZE);168
const chunkY = floorDiv(tileY, CHUNK_SIZE);
168
const chunkY = floorDiv(tileY, CHUNK_SIZE);169
const questRow = activeQuestId ? this.stateDb.getQuestState(characterId, activeQuestId) : null;
169
const questRow = activeQuestId ? this.stateDb.getQuestState(characterId, activeQuestId) : null;170
return {
170
return {171
tileX,
171
tileX,172
tileY,
172
tileY,173
chunkX,
173
chunkX,174
chunkY,
174
chunkY,175
dimensionId,
175
dimensionId,176
hp: playerView?.hp ?? 0,
176
hp: playerView?.hp ?? 0,177
maxHp: playerView?.maxHp ?? 1,
177
maxHp: playerView?.maxHp ?? 1,178
stamina: playerView?.stamina ?? 0,
178
stamina: playerView?.stamina ?? 0,179
maxStamina: playerView?.maxStamina ?? 1,
179
maxStamina: playerView?.maxStamina ?? 1,180
countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
180
countItem: (itemId) => countItemInSlots(inventory, itemId | 0),181
questState: (questId) => this.stateDb.getQuestState(characterId, questId).state,
181
questState: (questId) => this.stateDb.getQuestState(characterId, questId).state,182
dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId),
182
dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId),183
dialogueTriggerLatched: (dialogueId, trigger) =>
183
dialogueTriggerLatched: (dialogueId, trigger) =>184
this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger),
184
this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger),185
skillLevel: (skillId) => resolveSkillRequirementLevel(playerView?.skills ?? {}, skillId),
185
skillLevel: (skillId) => resolveSkillRequirementLevel(playerView?.skills ?? {}, skillId),186
hasVisitedDimension: (dimId) => this.stateDb.hasVisitedDimension(characterId, dimId),
186
hasVisitedDimension: (dimId) => this.stateDb.hasVisitedDimension(characterId, dimId),187
killCount: (condition) =>
187
killCount: (condition) =>188
{
188
{189
if (!questRow)
189
if (!questRow)190
{ return 0; }
190
{ return 0; }191
return questRow.progress?.counters?.[killKey(condition)] | 0;
191
return questRow.progress?.counters?.[killKey(condition)] | 0;192
},
192
},193
interactBlockDone: (condition) =>
193
interactBlockDone: (condition) =>194
{
194
{195
if (!questRow)
195
if (!questRow)196
{ return false; }
196
{ return false; }197
return !!questRow.progress?.interacts?.[interactKey(condition)];
197
return !!questRow.progress?.interacts?.[interactKey(condition)];198
}
198
}199
};
199
};200
}
200
}201
201
202
tryOpenDialogue (characterId, entityId, dialogueId)
202
tryOpenDialogue (characterId, entityId, dialogueId)203
{
203
{204
const tree = this.content.dialogue(dialogueId);
204
const tree = this.content.dialogue(dialogueId);205
if (!tree)
205
if (!tree)206
{ return { ok: false, error: "Nothing to say." }; }
206
{ return { ok: false, error: "Nothing to say." }; }207
this.closeDialogue(characterId, "replace");
207
this.closeDialogue(characterId, "replace");208
const playerView = this.playerViewFor(characterId);
208
const playerView = this.playerViewFor(characterId);209
return this.#enterStep(characterId, entityId, tree, tree.entryStepId, playerView);
209
return this.#enterStep(characterId, entityId, tree, tree.entryStepId, playerView);210
}
210
}211
211
212
chooseDialogue (characterId, triggerId)
212
chooseDialogue (characterId, triggerId)213
{
213
{214
const session = this.sessions.get(characterId | 0);
214
const session = this.sessions.get(characterId | 0);215
if (!session)
215
if (!session)216
{ return { ok: false, error: "No dialogue open." }; }
216
{ return { ok: false, error: "No dialogue open." }; }217
if (session.phase === "lines")
217
if (session.phase === "lines")218
{ return { ok: false, error: "Finish reading first." }; }
218
{ return { ok: false, error: "Finish reading first." }; }219
if (session.phase === "rewards")
219
if (session.phase === "rewards")220
{ return { ok: false, error: "Finish reading first." }; }
220
{ return { ok: false, error: "Finish reading first." }; }221
const tree = this.content.dialogue(session.dialogueId);
221
const tree = this.content.dialogue(session.dialogueId);222
if (!tree)
222
if (!tree)223
{
223
{224
this.closeDialogue(characterId, "missing");
224
this.closeDialogue(characterId, "missing");225
return { ok: false, error: "Dialogue missing." };
225
return { ok: false, error: "Dialogue missing." };226
}
226
}227
const step = tree.steps.find((s) => s.stepId === session.stepId);
227
const step = tree.steps.find((s) => s.stepId === session.stepId);228
if (!step || step.exit?.kind !== "triggers")
228
if (!step || step.exit?.kind !== "triggers")229
{ return { ok: false, error: "Cannot choose now." }; }
229
{ return { ok: false, error: "Cannot choose now." }; }230
const trigger = step.exit.triggers.find((t) => t.trigger === String(triggerId));
230
const trigger = step.exit.triggers.find((t) => t.trigger === String(triggerId));231
if (!trigger)
231
if (!trigger)232
{ return { ok: false, error: "Unknown choice." }; }
232
{ return { ok: false, error: "Unknown choice." }; }233
const playerView = this.playerViewFor(characterId);
233
const playerView = this.playerViewFor(characterId);234
const ctx = this.buildConditionContext(characterId, playerView);
234
const ctx = this.buildConditionContext(characterId, playerView);235
if (!evaluateConditionSet(trigger.when, ctx))
235
if (!evaluateConditionSet(trigger.when, ctx))236
{ return { ok: false, error: "That choice is unavailable." }; }
236
{ return { ok: false, error: "That choice is unavailable." }; }237
this.stateDb.latchDialogueTrigger(characterId, tree.dialogueId, trigger.trigger);
237
this.stateDb.latchDialogueTrigger(characterId, tree.dialogueId, trigger.trigger);238
const events = [];
238
const events = [];239
this.#applyEffects(characterId, trigger.effects, playerView, events);
239
this.#applyEffects(characterId, trigger.effects, playerView, events);240
this.#reevaluateQuests(characterId, playerView, events);
240
this.#reevaluateQuests(characterId, playerView, events);241
if (!trigger.nextStepId)
241
if (!trigger.nextStepId)242
{
242
{243
const npcEntityId = session.entityId;
243
const npcEntityId = session.entityId;244
this.sessions.delete(characterId | 0);
244
this.sessions.delete(characterId | 0);245
events.push({ type: "dialogueClose", reason: "end", npcEntityId });
245
events.push({ type: "dialogueClose", reason: "end", npcEntityId });246
return { ok: true, events };
246
return { ok: true, events };247
}
247
}248
return this.#enterStep(characterId, session.entityId, tree, trigger.nextStepId, playerView, events);
248
return this.#enterStep(characterId, session.entityId, tree, trigger.nextStepId, playerView, events);249
}
249
}250
250
251
closeDialogue (characterId, reason = "close")
251
closeDialogue (characterId, reason = "close")252
{
252
{253
const id = characterId | 0;
253
const id = characterId | 0;254
const session = this.sessions.get(id);
254
const session = this.sessions.get(id);255
if (!session)
255
if (!session)256
{ return { events: [] }; }
256
{ return { events: [] }; }257
this.sessions.delete(id);
257
this.sessions.delete(id);258
return {
258
return {259
events: [{
259
events: [{260
type: "dialogueClose",
260
type: "dialogueClose",261
reason,
261
reason,262
npcEntityId: session.entityId
262
npcEntityId: session.entityId263
}]
263
}]264
};
264
};265
}
265
}266
266
267
interruptDialogueForEntity (entityId)
267
interruptDialogueForEntity (entityId)268
{
268
{269
const events = [];
269
const events = [];270
for (const [characterId, session] of [...this.sessions])
270
for (const [characterId, session] of [...this.sessions])271
{
271
{272
if (session.entityId === (entityId | 0))
272
if (session.entityId === (entityId | 0))273
{
273
{274
const closed = this.closeDialogue(characterId, "attacked");
274
const closed = this.closeDialogue(characterId, "attacked");275
events.push(...closed.events.map((e) => ({ ...e, characterId })));
275
events.push(...closed.events.map((e) => ({ ...e, characterId })));276
}
276
}277
}
277
}278
return events;
278
return events;279
}
279
}280
280
281
#enterStep (characterId, entityId, tree, stepId, playerView, priorEvents = [])
281
#enterStep (characterId, entityId, tree, stepId, playerView, priorEvents = [])282
{
282
{283
const step = tree.steps.find((s) => s.stepId === stepId);
283
const step = tree.steps.find((s) => s.stepId === stepId);284
if (!step)
284
if (!step)285
{
285
{286
this.sessions.delete(characterId | 0);
286
this.sessions.delete(characterId | 0);287
priorEvents.push({ type: "dialogueClose", reason: "missing-step" });
287
priorEvents.push({ type: "dialogueClose", reason: "missing-step" });288
return { ok: false, error: "Broken dialogue.", events: priorEvents };
288
return { ok: false, error: "Broken dialogue.", events: priorEvents };289
}
289
}290
const events = [...priorEvents];
290
const events = [...priorEvents];291
const identity = this.#playerDialogueIdentity(characterId);
291
const identity = this.#playerDialogueIdentity(characterId);292
const linePayloads = [];
292
const linePayloads = [];293
for (const line of step.lines)
293
for (const line of step.lines)294
{
294
{295
this.#applyEffects(characterId, line.effects, playerView, events);
295
this.#applyEffects(characterId, line.effects, playerView, events);296
linePayloads.push({
296
linePayloads.push({297
speaker: line.speaker,
297
speaker: line.speaker,298
text: applyDialogueTextReplacements(line.text, identity)
298
text: applyDialogueTextReplacements(line.text, identity)299
});
299
});300
}
300
}301
// Stay open while the client pages lines; resolve exit only on dialogueAdvance.
301
// Stay open while the client pages lines; resolve exit only on dialogueAdvance.302
// dialogueHeard is marked only when the step fully completes (after rewards).
302
// dialogueHeard is marked only when the step fully completes (after rewards).303
this.sessions.set(characterId | 0, {
303
this.sessions.set(characterId | 0, {304
entityId: entityId | 0,
304
entityId: entityId | 0,305
dialogueId: tree.dialogueId,
305
dialogueId: tree.dialogueId,306
stepId: step.stepId,
306
stepId: step.stepId,307
phase: "lines",
307
phase: "lines",308
pendingExit: step.exit ?? { kind: "end" }
308
pendingExit: step.exit ?? { kind: "end" }309
});
309
});310
events.push({
310
events.push({311
type: "dialogueStep",
311
type: "dialogueStep",312
dialogueId: tree.dialogueId,
312
dialogueId: tree.dialogueId,313
stepId: step.stepId,
313
stepId: step.stepId,314
label: step.label,
314
label: step.label,315
npcEntityId: entityId | 0,
315
npcEntityId: entityId | 0,316
lines: linePayloads
316
lines: linePayloads317
});
317
});318
this.#reevaluateQuests(characterId, playerView, events);
318
this.#reevaluateQuests(characterId, playerView, events);319
return { ok: true, events };
319
return { ok: true, events };320
}
320
}321
321
322
/** Client finished reading all lines (or reward notices) of the current step. */
322
/** Client finished reading all lines (or reward notices) of the current step. */323
advanceDialogue (characterId)
323
advanceDialogue (characterId)324
{
324
{325
const session = this.sessions.get(characterId | 0);
325
const session = this.sessions.get(characterId | 0);326
if (!session || (session.phase !== "lines" && session.phase !== "rewards"))
326
if (!session || (session.phase !== "lines" && session.phase !== "rewards"))327
{ return { ok: false, error: "No dialogue lines to advance." }; }
327
{ return { ok: false, error: "No dialogue lines to advance." }; }328
const tree = this.content.dialogue(session.dialogueId);
328
const tree = this.content.dialogue(session.dialogueId);329
if (!tree)
329
if (!tree)330
{
330
{331
this.sessions.delete(characterId | 0);
331
this.sessions.delete(characterId | 0);332
return { ok: true, events: [{ type: "dialogueClose", reason: "missing" }] };
332
return { ok: true, events: [{ type: "dialogueClose", reason: "missing" }] };333
}
333
}334
const playerView = this.playerViewFor(characterId);
334
const playerView = this.playerViewFor(characterId);335
const events = [];
335
const events = [];336
336
337
if (session.phase === "lines")
337
if (session.phase === "lines")338
{
338
{339
const step = tree.steps.find((s) => s.stepId === session.stepId);
339
const step = tree.steps.find((s) => s.stepId === session.stepId);340
const rewardMessages = [
340
const rewardMessages = [341
...this.#takeStepItems(characterId, step, events),
341
...this.#takeStepItems(characterId, step, events),342
...this.#grantStepItemRewards(characterId, step, events),
342
...this.#grantStepItemRewards(characterId, step, events),343
...this.#grantStepQuestRewards(characterId, step, playerView, events)
343
...this.#grantStepQuestRewards(characterId, step, playerView, events)344
];
344
];345
this.#reevaluateQuests(characterId, playerView, events);
345
this.#reevaluateQuests(characterId, playerView, events);346
if (rewardMessages.length > 0)
346
if (rewardMessages.length > 0)347
{
347
{348
session.phase = "rewards";
348
session.phase = "rewards";349
events.push({
349
events.push({350
type: "dialogueItemRewards",
350
type: "dialogueItemRewards",351
dialogueId: session.dialogueId,
351
dialogueId: session.dialogueId,352
stepId: session.stepId,
352
stepId: session.stepId,353
npcEntityId: session.entityId,
353
npcEntityId: session.entityId,354
messages: rewardMessages
354
messages: rewardMessages355
});
355
});356
return { ok: true, events };
356
return { ok: true, events };357
}
357
}358
}
358
}359
359
360
return this.#resolveDialogueExit(characterId, session, tree, playerView, events);
360
return this.#resolveDialogueExit(characterId, session, tree, playerView, events);361
}
361
}362
362
363
#resolveDialogueExit (characterId, session, tree, playerView, events)
363
#resolveDialogueExit (characterId, session, tree, playerView, events)364
{
364
{365
// Step is fully finished: lines read + takes/rewards/quest notices acknowledged.
365
// Step is fully finished: lines read + takes/rewards/quest notices acknowledged.366
this.stateDb.markDialogueHeard(characterId, tree.dialogueId, session.stepId);
366
this.stateDb.markDialogueHeard(characterId, tree.dialogueId, session.stepId);367
this.#reevaluateQuests(characterId, playerView, events);
367
this.#reevaluateQuests(characterId, playerView, events);368
368
369
const exit = session.pendingExit ?? { kind: "end" };
369
const exit = session.pendingExit ?? { kind: "end" };370
370
371
if (exit.kind === "branches")
371
if (exit.kind === "branches")372
{
372
{373
const ctx = this.buildConditionContext(characterId, playerView);
373
const ctx = this.buildConditionContext(characterId, playerView);374
let matched = null;
374
let matched = null;375
for (const branch of exit.branches ?? [])
375
for (const branch of exit.branches ?? [])376
{
376
{377
if (evaluateConditionSet(branch.when, ctx))
377
if (evaluateConditionSet(branch.when, ctx))378
{
378
{379
matched = branch;
379
matched = branch;380
break;
380
break;381
}
381
}382
}
382
}383
if (!matched || !matched.nextStepId)
383
if (!matched || !matched.nextStepId)384
{
384
{385
this.#applyEffects(characterId, matched?.effects, playerView, events);
385
this.#applyEffects(characterId, matched?.effects, playerView, events);386
const npcEntityId = session.entityId;
386
const npcEntityId = session.entityId;387
this.sessions.delete(characterId | 0);
387
this.sessions.delete(characterId | 0);388
events.push({ type: "dialogueClose", reason: "branch-end", npcEntityId });
388
events.push({ type: "dialogueClose", reason: "branch-end", npcEntityId });389
return { ok: true, events };
389
return { ok: true, events };390
}
390
}391
this.#applyEffects(characterId, matched.effects, playerView, events);
391
this.#applyEffects(characterId, matched.effects, playerView, events);392
return this.#enterStep(characterId, session.entityId, tree, matched.nextStepId, playerView, events);
392
return this.#enterStep(characterId, session.entityId, tree, matched.nextStepId, playerView, events);393
}
393
}394
394
395
if (exit.kind === "triggers")
395
if (exit.kind === "triggers")396
{
396
{397
const ctx = this.buildConditionContext(characterId, playerView);
397
const ctx = this.buildConditionContext(characterId, playerView);398
const identity = this.#playerDialogueIdentity(characterId);
398
const identity = this.#playerDialogueIdentity(characterId);399
const triggers = (exit.triggers ?? [])
399
const triggers = (exit.triggers ?? [])400
.filter((t) => evaluateConditionSet(t.when, ctx))
400
.filter((t) => evaluateConditionSet(t.when, ctx))401
.map((t) => ({
401
.map((t) => ({402
trigger: t.trigger,
402
trigger: t.trigger,403
text: applyDialogueTextReplacements(t.text, identity)
403
text: applyDialogueTextReplacements(t.text, identity)404
}));
404
}));405
if (triggers.length === 0)
405
if (triggers.length === 0)406
{
406
{407
const npcEntityId = session.entityId;
407
const npcEntityId = session.entityId;408
this.sessions.delete(characterId | 0);
408
this.sessions.delete(characterId | 0);409
events.push({ type: "dialogueClose", reason: "no-triggers", npcEntityId });
409
events.push({ type: "dialogueClose", reason: "no-triggers", npcEntityId });410
return { ok: true, events };
410
return { ok: true, events };411
}
411
}412
session.phase = "choices";
412
session.phase = "choices";413
session.pendingExit = null;
413
session.pendingExit = null;414
events.push({
414
events.push({415
type: "dialogueChoices",
415
type: "dialogueChoices",416
dialogueId: session.dialogueId,
416
dialogueId: session.dialogueId,417
stepId: session.stepId,
417
stepId: session.stepId,418
npcEntityId: session.entityId,
418
npcEntityId: session.entityId,419
triggers
419
triggers420
});
420
});421
return { ok: true, events };
421
return { ok: true, events };422
}
422
}423
423
424
if (exit.kind === "continue")
424
if (exit.kind === "continue")425
{
425
{426
if (!exit.nextStepId)
426
if (!exit.nextStepId)427
{
427
{428
const npcEntityId = session.entityId;
428
const npcEntityId = session.entityId;429
this.sessions.delete(characterId | 0);
429
this.sessions.delete(characterId | 0);430
events.push({ type: "dialogueClose", reason: "continue-end", npcEntityId });
430
events.push({ type: "dialogueClose", reason: "continue-end", npcEntityId });431
return { ok: true, events };
431
return { ok: true, events };432
}
432
}433
return this.#enterStep(characterId, session.entityId, tree, exit.nextStepId, playerView, events);
433
return this.#enterStep(characterId, session.entityId, tree, exit.nextStepId, playerView, events);434
}
434
}435
435
436
const npcEntityId = session.entityId;
436
const npcEntityId = session.entityId;437
this.sessions.delete(characterId | 0);
437
this.sessions.delete(characterId | 0);438
events.push({ type: "dialogueClose", reason: "end", npcEntityId });
438
events.push({ type: "dialogueClose", reason: "end", npcEntityId });439
return { ok: true, events };
439
return { ok: true, events };440
}
440
}441
441
442
/**
442
/**443
* Soft-take step.itemTakes from the bag (min(have, required)). Returns player-facing notices.
443
* Soft-take step.itemTakes from the bag (min(have, required)). Returns player-facing notices.444
*/
444
*/445
#takeStepItems (characterId, step, events)
445
#takeStepItems (characterId, step, events)446
{
446
{447
const takes = step?.itemTakes ?? [];
447
const takes = step?.itemTakes ?? [];448
if (!takes.length)
448
if (!takes.length)449
{ return []; }
449
{ return []; }450
const parts = [];
450
const parts = [];451
for (const take of takes)
451
for (const take of takes)452
{
452
{453
const bag = this.#loadBag(characterId);
453
const bag = this.#loadBag(characterId);454
if (!bag)
454
if (!bag)455
{ continue; }
455
{ continue; }456
const itemId = take.itemId | 0;
456
const itemId = take.itemId | 0;457
const want = Math.max(1, Number(take.quantity) || 1);
457
const want = Math.max(1, Number(take.quantity) || 1);458
const def = itemDefinition(itemId);
458
const def = itemDefinition(itemId);459
const displayName = def?.displayName ?? `Item ${itemId}`;
459
const displayName = def?.displayName ?? `Item ${itemId}`;460
const result = takeMatchingUpToFromSlots(bag.inventory, {
460
const result = takeMatchingUpToFromSlots(bag.inventory, {461
itemId,
461
itemId,462
quantity: want,
462
quantity: want,463
compact: false
463
compact: false464
});
464
});465
if (!result.ok || result.takenQuantity <= 0)
465
if (!result.ok || result.takenQuantity <= 0)466
{ continue; }
466
{ continue; }467
bag.inventory = result.slots;
467
bag.inventory = result.slots;468
this.#persistBag(characterId, bag);
468
this.#persistBag(characterId, bag);469
events.push({ type: "inventoryDirty" });
469
events.push({ type: "inventoryDirty" });470
parts.push({ displayName, quantity: result.takenQuantity });
470
parts.push({ displayName, quantity: result.takenQuantity });471
}
471
}472
const message = formatDialogueTakeMessage(parts);
472
const message = formatDialogueTakeMessage(parts);473
return message ? [message] : [];
473
return message ? [message] : [];474
}
474
}475
475
476
/**
476
/**477
* Grant step.itemRewards into bag (overflow → bank/vault). Returns player-facing notices.
477
* Grant step.itemRewards into bag (overflow → bank/vault). Returns player-facing notices.478
*/
478
*/479
#grantStepItemRewards (characterId, step, events)
479
#grantStepItemRewards (characterId, step, events)480
{
480
{481
const rewards = step?.itemRewards ?? [];
481
const rewards = step?.itemRewards ?? [];482
if (!rewards.length)
482
if (!rewards.length)483
{ return []; }
483
{ return []; }484
const bagParts = [];
484
const bagParts = [];485
const bankParts = [];
485
const bankParts = [];486
for (const reward of rewards)
486
for (const reward of rewards)487
{
487
{488
const bag = this.#loadBag(characterId);
488
const bag = this.#loadBag(characterId);489
if (!bag)
489
if (!bag)490
{ continue; }
490
{ continue; }491
const itemId = reward.itemId | 0;
491
const itemId = reward.itemId | 0;492
const def = itemDefinition(itemId);
492
const def = itemDefinition(itemId);493
const quantity = Math.max(1, Number(reward.quantity) || 1);
493
const quantity = Math.max(1, Number(reward.quantity) || 1);494
const displayName = def?.displayName ?? `Item ${itemId}`;
494
const displayName = def?.displayName ?? `Item ${itemId}`;495
const stack = attachOrigins({
495
const stack = attachOrigins({496
itemId,
496
itemId,497
quantity,
497
quantity,498
origins: [{ origin: godsOrigin(), quantity }]
498
origins: [{ origin: godsOrigin(), quantity }]499
});
499
});500
const result = insertStack(bag.inventory, stack, def);
500
const result = insertStack(bag.inventory, stack, def);501
bag.inventory = result.slots;
501
bag.inventory = result.slots;502
const intoBag = quantity - Math.max(0, result.remainder | 0);
502
const intoBag = quantity - Math.max(0, result.remainder | 0);503
let intoBank = 0;
503
let intoBank = 0;504
if (result.remainder > 0)
504
if (result.remainder > 0)505
{
505
{506
const vaultResult = insertStackGrowable(
506
const vaultResult = insertStackGrowable(507
bag.vault,
507
bag.vault,508
attachOrigins({
508
attachOrigins({509
itemId,
509
itemId,510
quantity: result.remainder,
510
quantity: result.remainder,511
origins: [{ origin: godsOrigin(), quantity: result.remainder }]
511
origins: [{ origin: godsOrigin(), quantity: result.remainder }]512
}),
512
}),513
def
513
def514
);
514
);515
bag.vault = vaultResult.slots;
515
bag.vault = vaultResult.slots;516
intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
516
intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);517
}
517
}518
this.#persistBag(characterId, bag);
518
this.#persistBag(characterId, bag);519
events.push({ type: "inventoryDirty" });
519
events.push({ type: "inventoryDirty" });520
if (intoBag > 0)
520
if (intoBag > 0)521
{ bagParts.push({ displayName, quantity: intoBag }); }
521
{ bagParts.push({ displayName, quantity: intoBag }); }522
if (intoBank > 0)
522
if (intoBank > 0)523
{ bankParts.push({ displayName, quantity: intoBank }); }
523
{ bankParts.push({ displayName, quantity: intoBank }); }524
}
524
}525
const messages = [];
525
const messages = [];526
const bagMsg = formatDialogueRewardMessage(bagParts, "bag");
526
const bagMsg = formatDialogueRewardMessage(bagParts, "bag");527
const bankMsg = formatDialogueRewardMessage(bankParts, "bank");
527
const bankMsg = formatDialogueRewardMessage(bankParts, "bank");528
if (bagMsg)
528
if (bagMsg)529
{ messages.push(bagMsg); }
529
{ messages.push(bagMsg); }530
if (bankMsg)
530
if (bankMsg)531
{ messages.push(bankMsg); }
531
{ messages.push(bankMsg); }532
return messages;
532
return messages;533
}
533
}534
534
535
/** Start step.questRewards; returns player-facing notices for newly started quests. */
535
/** Start step.questRewards; returns player-facing notices for newly started quests. */536
#grantStepQuestRewards (characterId, step, playerView, events)
536
#grantStepQuestRewards (characterId, step, playerView, events)537
{
537
{538
const rewards = step?.questRewards ?? [];
538
const rewards = step?.questRewards ?? [];539
if (!rewards.length)
539
if (!rewards.length)540
{ return []; }
540
{ return []; }541
const titles = [];
541
const titles = [];542
for (const questId of rewards)
542
for (const questId of rewards)543
{
543
{544
const current = this.stateDb.getQuestState(characterId, questId);
544
const current = this.stateDb.getQuestState(characterId, questId);545
if (current.state !== "not-started")
545
if (current.state !== "not-started")546
{ continue; }
546
{ continue; }547
const def = this.content.quest(questId);
547
const def = this.content.quest(questId);548
if (!def)
548
if (!def)549
{ continue; }
549
{ continue; }550
this.startQuest(characterId, questId, playerView, events);
550
this.startQuest(characterId, questId, playerView, events);551
titles.push(def.title || def.questId);
551
titles.push(def.title || def.questId);552
}
552
}553
const message = formatDialogueQuestRewardMessage(titles);
553
const message = formatDialogueQuestRewardMessage(titles);554
return message ? [message] : [];
554
return message ? [message] : [];555
}
555
}556
556
557
#loadBag (characterId)
557
#loadBag (characterId)558
{
558
{559
const onlineId = this.simulation.characterEntities.get(characterId | 0);
559
const onlineId = this.simulation.characterEntities.get(characterId | 0);560
const bag = onlineId
560
const bag = onlineId561
? this.simulation.bagOf(onlineId)
561
? this.simulation.bagOf(onlineId)562
: this.stateDb.getBag(characterId);
562
: this.stateDb.getBag(characterId);563
return bag;
563
return bag;564
}
564
}565
565
566
#playerDialogueIdentity (characterId)
566
#playerDialogueIdentity (characterId)567
{
567
{568
const row = this.stateDb.getCharacter(characterId | 0);
568
const row = this.stateDb.getCharacter(characterId | 0);569
return {
569
return {570
firstName: String(row?.first_name ?? "").trim(),
570
firstName: String(row?.first_name ?? "").trim(),571
lastName: String(row?.last_name ?? "").trim(),
571
lastName: String(row?.last_name ?? "").trim(),572
sex: row?.sex === "female" ? "female" : "male"
572
sex: row?.sex === "female" ? "female" : "male"573
};
573
};574
}
574
}575
575
576
#persistBag (characterId, bag)
576
#persistBag (characterId, bag)577
{
577
{578
this.stateDb.saveBag(characterId, bag);
578
this.stateDb.saveBag(characterId, bag);579
const onlineId = this.simulation.characterEntities.get(characterId | 0);
579
const onlineId = this.simulation.characterEntities.get(characterId | 0);580
if (onlineId)
580
if (onlineId)581
{
581
{582
this.simulation.applyBag?.(onlineId, bag);
582
this.simulation.applyBag?.(onlineId, bag);583
this.simulation.pushInventory?.(characterId, bag);
583
this.simulation.pushInventory?.(characterId, bag);584
}
584
}585
}
585
}586
586
587
#applyEffects (characterId, effects, playerView, events)
587
#applyEffects (characterId, effects, playerView, events)588
{
588
{589
if (!Array.isArray(effects) || effects.length === 0)
589
if (!Array.isArray(effects) || effects.length === 0)590
{ return; }
590
{ return; }591
for (const effect of effects)
591
for (const effect of effects)592
{
592
{593
if (effect.kind === EffectKind.giveItem)
593
if (effect.kind === EffectKind.giveItem)594
{
594
{595
const bag = this.#loadBag(characterId);
595
const bag = this.#loadBag(characterId);596
if (!bag)
596
if (!bag)597
{ continue; }
597
{ continue; }598
const def = itemDefinition(effect.itemId | 0);
598
const def = itemDefinition(effect.itemId | 0);599
const quantity = Math.max(1, Number(effect.quantity) || 1);
599
const quantity = Math.max(1, Number(effect.quantity) || 1);600
const stack = attachOrigins({
600
const stack = attachOrigins({601
itemId: effect.itemId | 0,
601
itemId: effect.itemId | 0,602
quantity,
602
quantity,603
origins: [{ origin: godsOrigin(), quantity }]
603
origins: [{ origin: godsOrigin(), quantity }]604
});
604
});605
if (effect.toBank)
605
if (effect.toBank)606
{
606
{607
const vaultResult = insertStackGrowable(bag.vault ?? [], stack, def);
607
const vaultResult = insertStackGrowable(bag.vault ?? [], stack, def);608
bag.vault = vaultResult.slots;
608
bag.vault = vaultResult.slots;609
}
609
}610
else
610
else611
{
611
{612
const result = insertStack(bag.inventory, stack, def);
612
const result = insertStack(bag.inventory, stack, def);613
bag.inventory = result.slots;
613
bag.inventory = result.slots;614
if (result.remainder > 0)
614
if (result.remainder > 0)615
{
615
{616
const vaultResult = insertStackGrowable(
616
const vaultResult = insertStackGrowable(617
bag.vault ?? [],
617
bag.vault ?? [],618
attachOrigins({
618
attachOrigins({619
itemId: effect.itemId | 0,
619
itemId: effect.itemId | 0,620
quantity: result.remainder,
620
quantity: result.remainder,621
origins: [{ origin: godsOrigin(), quantity: result.remainder }]
621
origins: [{ origin: godsOrigin(), quantity: result.remainder }]622
}),
622
}),623
def
623
def624
);
624
);625
bag.vault = vaultResult.slots;
625
bag.vault = vaultResult.slots;626
}
626
}627
}
627
}628
this.#persistBag(characterId, bag);
628
this.#persistBag(characterId, bag);629
events.push({ type: "inventoryDirty" });
629
events.push({ type: "inventoryDirty" });630
}
630
}631
else if (effect.kind === EffectKind.takeItem)
631
else if (effect.kind === EffectKind.takeItem)632
{
632
{633
const bag = this.#loadBag(characterId);
633
const bag = this.#loadBag(characterId);634
if (!bag)
634
if (!bag)635
{ continue; }
635
{ continue; }636
const taken = takeMatchingFromSlots(bag.inventory, {
636
const taken = takeMatchingFromSlots(bag.inventory, {637
itemId: effect.itemId | 0,
637
itemId: effect.itemId | 0,638
quantity: Math.max(1, Number(effect.quantity) || 1),
638
quantity: Math.max(1, Number(effect.quantity) || 1),639
compact: false
639
compact: false640
});
640
});641
if (taken.ok)
641
if (taken.ok)642
{
642
{643
bag.inventory = taken.slots;
643
bag.inventory = taken.slots;644
this.#persistBag(characterId, bag);
644
this.#persistBag(characterId, bag);645
events.push({ type: "inventoryDirty" });
645
events.push({ type: "inventoryDirty" });646
}
646
}647
}
647
}648
else if (effect.kind === EffectKind.giveXp)
648
else if (effect.kind === EffectKind.giveXp)649
{
649
{650
const skills = this.stateDb.getSkills(characterId);
650
const skills = this.stateDb.getSkills(characterId);651
if (skills)
651
if (skills)652
{
652
{653
applySkillXp(skills, effect.skillId, Math.max(0, Number(effect.amount) || 0));
653
applySkillXp(skills, effect.skillId, Math.max(0, Number(effect.amount) || 0));654
this.stateDb.saveSkills(characterId, skills);
654
this.stateDb.saveSkills(characterId, skills);655
if (playerView)
655
if (playerView)656
{ playerView.skills = skills; }
656
{ playerView.skills = skills; }657
events.push({ type: "skillsDirty" });
657
events.push({ type: "skillsDirty" });658
}
658
}659
}
659
}660
else if (effect.kind === EffectKind.startQuest)
660
else if (effect.kind === EffectKind.startQuest)661
{ this.startQuest(characterId, effect.questId, playerView, events); }
661
{ this.startQuest(characterId, effect.questId, playerView, events); }662
}
662
}663
}
663
}664
664
665
startQuest (characterId, questId, playerView, events = [])
665
startQuest (characterId, questId, playerView, events = [])666
{
666
{667
const def = this.content.quest(questId);
667
const def = this.content.quest(questId);668
if (!def)
668
if (!def)669
{ return; }
669
{ return; }670
const current = this.stateDb.getQuestState(characterId, questId);
670
const current = this.stateDb.getQuestState(characterId, questId);671
if (current.state !== "not-started")
671
if (current.state !== "not-started")672
{ return; }
672
{ return; }673
this.stateDb.saveQuestState(characterId, questId, 1, {
673
this.stateDb.saveQuestState(characterId, questId, 1, {674
completedObjectiveIds: [],
674
completedObjectiveIds: [],675
counters: {},
675
counters: {},676
interacts: {}
676
interacts: {}677
}, Date.now(), null);
677
}, Date.now(), null);678
this.#applyEffects(characterId, def.steps[0]?.onEnter, playerView, events);
678
this.#applyEffects(characterId, def.steps[0]?.onEnter, playerView, events);679
events.push({ type: "questsDirty" });
679
events.push({ type: "questsDirty", characterId });680
this.#reevaluateQuests(characterId, playerView, events);
680
this.#reevaluateQuests(characterId, playerView, events);681
}
681
}682
682
683
/**
683
/**684
* Grant world-settings initial quests when the character has not started or completed them.
684
* Grant world-settings initial quests when the character has not started or completed them.685
*/
685
*/686
ensureInitialQuests (characterId, playerView = null, events = [])
686
ensureInitialQuests (characterId, playerView = null, events = [])687
{
687
{688
const list = normalizeInitialQuests(this.simulation?.settings?.initialQuests);
688
const list = normalizeInitialQuests(this.simulation?.settings?.initialQuests);689
for (const questId of list)
689
for (const questId of list)690
{ this.startQuest(characterId, questId, playerView, events); }
690
{ this.startQuest(characterId, questId, playerView, events); }691
return events;
691
return events;692
}
692
}693
693
694
/**
694
/**695
* Re-check active quest objectives against live bag/position/etc.
695
* Re-check active quest objectives against live bag/position/etc.696
* Used when opening the quest log (and wherever progress may have changed offline of dialogue/kills).
696
* Used when opening the quest log (and wherever progress may have changed offline of dialogue/kills).697
*/
697
*/698
reevaluateQuests (characterId, playerView = null, events = [])
698
reevaluateQuests (characterId, playerView = null, events = [])699
{
699
{700
const view = playerView ?? this.playerViewFor(characterId);
700
const view = playerView ?? this.playerViewFor(characterId);701
this.#reevaluateQuests(characterId, view, events);
701
this.#reevaluateQuests(characterId, view, events);702
return events;
702
return events;703
}
703
}704
704
705
/** Apply initial quests to every character in state (settings save / apply). */
705
/** Apply initial quests to every character in state (settings save / apply). */706
grantInitialQuestsToAllCharacters ()
706
grantInitialQuestsToAllCharacters ()707
{
707
{708
const events = [];
708
const events = [];709
for (const characterId of this.stateDb.listAllCharacterIds())
709
for (const characterId of this.stateDb.listAllCharacterIds())710
{ this.ensureInitialQuests(characterId, null, events); }
710
{ this.ensureInitialQuests(characterId, null, events); }711
return events;
711
return events;712
}
712
}713
713
714
/**
714
/**715
* Final quest rewards: XP + items (bag or bank). Banked items get a Questward letter.
715
* Final quest rewards: XP + items (bag or bank). Banked items get a Questward letter.716
* @returns {{ xp: { skillId: string, displayName: string, amount: number }[], bagItems: { displayName: string, quantity: number }[] }}
716
* @returns {{ xp: { skillId: string, displayName: string, amount: number }[], bagItems: { displayName: string, quantity: number }[] }}717
*/
717
*/718
#grantQuestCompletionRewards (characterId, def, playerView, events)
718
#grantQuestCompletionRewards (characterId, def, playerView, events)719
{
719
{720
const xp = [];
720
const xp = [];721
const bagItems = [];
721
const bagItems = [];722
const bankItems = [];
722
const bankItems = [];723
const rewards = def?.rewards ?? [];
723
const rewards = def?.rewards ?? [];724
for (const effect of rewards)
724
for (const effect of rewards)725
{
725
{726
if (effect.kind === EffectKind.giveXp)
726
if (effect.kind === EffectKind.giveXp)727
{
727
{728
const amount = Math.max(0, Number(effect.amount) || 0) | 0;
728
const amount = Math.max(0, Number(effect.amount) || 0) | 0;729
if (amount <= 0)
729
if (amount <= 0)730
{ continue; }
730
{ continue; }731
const skillId = String(effect.skillId ?? "").trim();
731
const skillId = String(effect.skillId ?? "").trim();732
if (!skillId)
732
if (!skillId)733
{ continue; }
733
{ continue; }734
const onlineId = this.simulation.characterEntities.get(characterId | 0);
734
const onlineId = this.simulation.characterEntities.get(characterId | 0);735
let skills = onlineId
735
let skills = onlineId736
? this.simulation.skillsOf(onlineId)
736
? this.simulation.skillsOf(onlineId)737
: this.stateDb.getSkills(characterId);
737
: this.stateDb.getSkills(characterId);738
if (!skills)
738
if (!skills)739
{ skills = this.stateDb.getSkills(characterId); }
739
{ skills = this.stateDb.getSkills(characterId); }740
if (!skills)
740
if (!skills)741
{ continue; }
741
{ continue; }742
applySkillXp(skills, skillId, amount);
742
applySkillXp(skills, skillId, amount);743
this.stateDb.saveSkills(characterId, skills);
743
this.stateDb.saveSkills(characterId, skills);744
if (playerView)
744
if (playerView)745
{ playerView.skills = skills; }
745
{ playerView.skills = skills; }746
if (onlineId)
746
if (onlineId)747
{ this.simulation.applySkills?.(onlineId, skills); }
747
{ this.simulation.applySkills?.(onlineId, skills); }748
const payload = publicSkillsPayload(skills);
748
const payload = publicSkillsPayload(skills);749
this.simulation.pushSkills?.(characterId, payload.skills, payload.combatLevel);
749
this.simulation.pushSkills?.(characterId, payload.skills, payload.combatLevel);750
xp.push({
750
xp.push({751
skillId,
751
skillId,752
displayName: SKILL_DEFINITIONS[skillId]?.displayName ?? skillId,
752
displayName: SKILL_DEFINITIONS[skillId]?.displayName ?? skillId,753
amount
753
amount754
});
754
});755
continue;
755
continue;756
}
756
}757
if (effect.kind !== EffectKind.giveItem)
757
if (effect.kind !== EffectKind.giveItem)758
{ continue; }
758
{ continue; }759
const bag = this.#loadBag(characterId);
759
const bag = this.#loadBag(characterId);760
if (!bag)
760
if (!bag)761
{ continue; }
761
{ continue; }762
const itemId = effect.itemId | 0;
762
const itemId = effect.itemId | 0;763
const defItem = itemDefinition(itemId);
763
const defItem = itemDefinition(itemId);764
const quantity = Math.max(1, Number(effect.quantity) || 1) | 0;
764
const quantity = Math.max(1, Number(effect.quantity) || 1) | 0;765
const displayName = defItem
765
const displayName = defItem766
? itemDisplayName({ itemId, quantity }, defItem)
766
? itemDisplayName({ itemId, quantity }, defItem)767
: `Item ${itemId}`;
767
: `Item ${itemId}`;768
const stack = attachOrigins({
768
const stack = attachOrigins({769
itemId,
769
itemId,770
quantity,
770
quantity,771
origins: [{ origin: godsOrigin(), quantity }]
771
origins: [{ origin: godsOrigin(), quantity }]772
});
772
});773
let intoBag = 0;
773
let intoBag = 0;774
let intoBank = 0;
774
let intoBank = 0;775
if (effect.toBank)
775
if (effect.toBank)776
{
776
{777
const vaultResult = insertStackGrowable(bag.vault ?? [], stack, defItem);
777
const vaultResult = insertStackGrowable(bag.vault ?? [], stack, defItem);778
bag.vault = vaultResult.slots;
778
bag.vault = vaultResult.slots;779
intoBank = quantity - Math.max(0, vaultResult.remainder | 0);
779
intoBank = quantity - Math.max(0, vaultResult.remainder | 0);780
}
780
}781
else
781
else782
{
782
{783
const result = insertStack(bag.inventory, stack, defItem);
783
const result = insertStack(bag.inventory, stack, defItem);784
bag.inventory = result.slots;
784
bag.inventory = result.slots;785
intoBag = quantity - Math.max(0, result.remainder | 0);
785
intoBag = quantity - Math.max(0, result.remainder | 0);786
if (result.remainder > 0)
786
if (result.remainder > 0)787
{
787
{788
const vaultResult = insertStackGrowable(
788
const vaultResult = insertStackGrowable(789
bag.vault ?? [],
789
bag.vault ?? [],790
attachOrigins({
790
attachOrigins({791
itemId,
791
itemId,792
quantity: result.remainder,
792
quantity: result.remainder,793
origins: [{ origin: godsOrigin(), quantity: result.remainder }]
793
origins: [{ origin: godsOrigin(), quantity: result.remainder }]794
}),
794
}),795
defItem
795
defItem796
);
796
);797
bag.vault = vaultResult.slots;
797
bag.vault = vaultResult.slots;798
intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
798
intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);799
}
799
}800
}
800
}801
this.#persistBag(characterId, bag);
801
this.#persistBag(characterId, bag);802
events.push({ type: "inventoryDirty" });
802
events.push({ type: "inventoryDirty" });803
if (intoBag > 0)
803
if (intoBag > 0)804
{ bagItems.push({ displayName, quantity: intoBag, itemId }); }
804
{ bagItems.push({ displayName, quantity: intoBag, itemId }); }805
if (intoBank > 0)
805
if (intoBank > 0)806
{ bankItems.push({ displayName, quantity: intoBank, itemId }); }
806
{ bankItems.push({ displayName, quantity: intoBank, itemId }); }807
}
807
}808
808
809
if (bankItems.length)
809
if (bankItems.length)810
{ this.#dispatchQuestBankRewardLetter(characterId, def, bankItems); }
810
{ this.#dispatchQuestBankRewardLetter(characterId, def, bankItems); }811
811
812
return { xp, bagItems };
812
return { xp, bagItems };813
}
813
}814
814
815
#dispatchQuestBankRewardLetter (characterId, def, bankItems)
815
#dispatchQuestBankRewardLetter (characterId, def, bankItems)816
{
816
{817
const courier = this.simulation.courier;
817
const courier = this.simulation.courier;818
if (!courier?.enqueueSystemLetter)
818
if (!courier?.enqueueSystemLetter)819
{ return; }
819
{ return; }820
const row = this.stateDb.getCharacter?.(characterId);
820
const row = this.stateDb.getCharacter?.(characterId);821
const characterDisplayName = row
821
const characterDisplayName = row822
? `${row.first_name ?? ""} ${row.last_name ?? ""}`.trim()
822
? `${row.first_name ?? ""} ${row.last_name ?? ""}`.trim()823
: "Adventurer";
823
: "Adventurer";824
const originTileX = row?.tile_x | 0;
824
const originTileX = row?.tile_x | 0;825
const originTileY = row?.tile_y | 0;
825
const originTileY = row?.tile_y | 0;826
const bank = courier.nearestBank?.(originTileX, originTileY);
826
const bank = courier.nearestBank?.(originTileX, originTileY);827
courier.enqueueSystemLetter({
827
courier.enqueueSystemLetter({828
characterId: characterId | 0,
828
characterId: characterId | 0,829
originTileX: bank?.tileX ?? originTileX,
829
originTileX: bank?.tileX ?? originTileX,830
originTileY: bank?.tileY ?? originTileY,
830
originTileY: bank?.tileY ?? originTileY,831
authorDisplayName: QUESTWARD_GIFT_AUTHOR,
831
authorDisplayName: QUESTWARD_GIFT_AUTHOR,832
authorOrganization: QUESTWARD_GIFT_ORG,
832
authorOrganization: QUESTWARD_GIFT_ORG,833
body: formatQuestBankRewardLetterBody({
833
body: formatQuestBankRewardLetterBody({834
characterDisplayName,
834
characterDisplayName,835
questTitle: def?.title ?? def?.questId,
835
questTitle: def?.title ?? def?.questId,836
items: bankItems
836
items: bankItems837
})
837
})838
});
838
});839
}
839
}840
840
841
#reevaluateQuests (characterId, playerView, events)
841
#reevaluateQuests (characterId, playerView, events)842
{
842
{843
const states = this.stateDb.listQuestStates(characterId)
843
const states = this.stateDb.listQuestStates(characterId)844
.filter((row) => typeof row.state === "number");
844
.filter((row) => typeof row.state === "number");845
for (const row of states)
845
for (const row of states)846
{
846
{847
const def = this.content.quest(row.questId);
847
const def = this.content.quest(row.questId);848
if (!def)
848
if (!def)849
{ continue; }
849
{ continue; }850
const stepDef = def.steps[row.state - 1];
850
const stepDef = def.steps[row.state - 1];851
if (!stepDef)
851
if (!stepDef)852
{ continue; }
852
{ continue; }853
const ctx = this.buildConditionContext(characterId, playerView, row.questId);
853
const ctx = this.buildConditionContext(characterId, playerView, row.questId);854
const completed = new Set(row.progress?.completedObjectiveIds ?? []);
854
const completed = new Set(row.progress?.completedObjectiveIds ?? []);855
const newlyDone = [];
855
const newlyDone = [];856
let changed = false;
856
let changed = false;857
for (const obj of stepDef.objectives)
857
for (const obj of stepDef.objectives)858
{
858
{859
if (completed.has(obj.objectiveId))
859
if (completed.has(obj.objectiveId))860
{ continue; }
860
{ continue; }861
if (evaluateConditionSet(obj.when, ctx))
861
if (evaluateConditionSet(obj.when, ctx))862
{
862
{863
completed.add(obj.objectiveId);
863
completed.add(obj.objectiveId);864
newlyDone.push(obj);
864
newlyDone.push(obj);865
changed = true;
865
changed = true;866
}
866
}867
}
867
}868
const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx);
868
const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx);869
const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");
869
const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");870
if (!changed && !progressChanged)
870
if (!changed && !progressChanged)871
{ continue; }
871
{ continue; }872
for (const obj of newlyDone)
872
for (const obj of newlyDone)873
{
873
{874
events.push({
874
events.push({875
type: "questObjectiveComplete",
875
type: "questObjectiveComplete",876
questId: row.questId,
876
questId: row.questId,877
objectiveId: obj.objectiveId,
877
objectiveId: obj.objectiveId,878
text: obj.text || "Objective"
878
text: obj.text || "Objective"879
});
879
});880
}
880
}881
const progress = {
881
const progress = {882
...row.progress,
882
...row.progress,883
completedObjectiveIds: [...completed],
883
completedObjectiveIds: [...completed],884
progressFingerprint: fingerprint
884
progressFingerprint: fingerprint885
};
885
};886
const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
886
const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));887
if (!allDone)
887
if (!allDone)888
{
888
{889
this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
889
this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);890
events.push({ type: "questsDirty" });
890
events.push({ type: "questsDirty", characterId });891
continue;
891
continue;892
}
892
}893
if (!changed)
893
if (!changed)894
{
894
{895
// Progress-only update while already fully complete (should not happen).
895
// Progress-only update while already fully complete (should not happen).896
this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
896
this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);897
events.push({ type: "questsDirty" });
897
events.push({ type: "questsDirty", characterId });898
continue;
898
continue;899
}
899
}900
this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
900
this.#applyEffects(characterId, stepDef.onComplete, playerView, events);901
const journal = this.stateDb.appendQuestJournal(
901
const journal = this.stateDb.appendQuestJournal(902
characterId,
902
characterId,903
row.questId,
903
row.questId,904
stepDef.stepId,
904
stepDef.stepId,905
stepDef.completionJournalText
905
stepDef.completionJournalText906
);
906
);907
const nextIndex = row.state + 1;
907
const nextIndex = row.state + 1;908
if (nextIndex > def.steps.length)
908
if (nextIndex > def.steps.length)909
{
909
{910
const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events);
910
const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events);911
this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now());
911
this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now());912
events.push({
912
events.push({913
type: "questComplete",
913
type: "questComplete",914
questId: row.questId,
914
questId: row.questId,915
title: def.title,
915
title: def.title,916
xp: summary.xp,
916
xp: summary.xp,917
items: summary.bagItems
917
items: summary.bagItems918
});
918
});919
}
919
}920
else
920
else921
{
921
{922
const nextStep = def.steps[nextIndex - 1];
922
const nextStep = def.steps[nextIndex - 1];923
this.stateDb.saveQuestState(characterId, row.questId, nextIndex, {
923
this.stateDb.saveQuestState(characterId, row.questId, nextIndex, {924
completedObjectiveIds: [],
924
completedObjectiveIds: [],925
counters: {},
925
counters: {},926
interacts: {},
926
interacts: {},927
progressFingerprint: ""
927
progressFingerprint: ""928
}, row.startedAt, null);
928
}, row.startedAt, null);929
this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
929
this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);930
events.push({
930
events.push({931
type: "questStepComplete",
931
type: "questStepComplete",932
questId: row.questId,
932
questId: row.questId,933
title: def.title,
933
title: def.title,934
journalText: journal?.text ?? null
934
journalText: journal?.text ?? null935
});
935
});936
}
936
}937
events.push({ type: "questsDirty" });
937
events.push({ type: "questsDirty", characterId });938
}
938
}939
}
939
}940
940
941
noteKill (characterId, { mobTypeId, spawnerId })
941
noteKill (characterId, { mobTypeId, spawnerId })942
{
942
{943
const events = [];
943
const events = [];944
const playerView = this.playerViewFor(characterId);
944
const playerView = this.playerViewFor(characterId);945
const states = this.stateDb.listQuestStates(characterId)
945
const states = this.stateDb.listQuestStates(characterId)946
.filter((row) => typeof row.state === "number");
946
.filter((row) => typeof row.state === "number");947
for (const row of states)
947
for (const row of states)948
{
948
{949
const def = this.content.quest(row.questId);
949
const def = this.content.quest(row.questId);950
const stepDef = def?.steps[row.state - 1];
950
const stepDef = def?.steps[row.state - 1];951
if (!stepDef)
951
if (!stepDef)952
{ continue; }
952
{ continue; }953
let changed = false;
953
let changed = false;954
const counters = { ...(row.progress?.counters ?? {}) };
954
const counters = { ...(row.progress?.counters ?? {}) };955
for (const obj of stepDef.objectives)
955
for (const obj of stepDef.objectives)956
{
956
{957
for (const clause of obj.when?.all ?? [])
957
for (const clause of obj.when?.all ?? [])958
{
958
{959
const c = clause.condition;
959
const c = clause.condition;960
if (c?.kind !== "killCount")
960
if (c?.kind !== "killCount")961
{ continue; }
961
{ continue; }962
const matchMob = c.mobTypeId != null && String(c.mobTypeId) === String(mobTypeId);
962
const matchMob = c.mobTypeId != null && String(c.mobTypeId) === String(mobTypeId);963
const matchSpawner = c.spawnerId != null && String(c.spawnerId) === String(spawnerId);
963
const matchSpawner = c.spawnerId != null && String(c.spawnerId) === String(spawnerId);964
if (!matchMob && !matchSpawner)
964
if (!matchMob && !matchSpawner)965
{ continue; }
965
{ continue; }966
const key = killKey(c);
966
const key = killKey(c);967
counters[key] = (counters[key] | 0) + 1;
967
counters[key] = (counters[key] | 0) + 1;968
changed = true;
968
changed = true;969
}
969
}970
}
970
}971
if (!changed)
971
if (!changed)972
{ continue; }
972
{ continue; }973
this.stateDb.saveQuestState(characterId, row.questId, row.state, {
973
this.stateDb.saveQuestState(characterId, row.questId, row.state, {974
...row.progress,
974
...row.progress,975
counters
975
counters976
}, row.startedAt, row.completedAt);
976
}, row.startedAt, row.completedAt);977
}
977
}978
this.#reevaluateQuests(characterId, playerView, events);
978
this.#reevaluateQuests(characterId, playerView, events);979
return events;
979
return events;980
}
980
}981
}
981
}982
982
983
function journalPublic (row)
983
function journalPublic (row)984
{
984
{985
return {
985
return {986
entryId: row.entry_id ?? row.entryId,
986
entryId: row.entry_id ?? row.entryId,987
questId: row.quest_id ?? row.questId,
987
questId: row.quest_id ?? row.questId,988
stepId: row.step_id ?? row.stepId,
988
stepId: row.step_id ?? row.stepId,989
text: row.text,
989
text: row.text,990
writtenAt: row.written_at ?? row.writtenAt
990
writtenAt: row.written_at ?? row.writtenAt991
};
991
};992
}
992
}993
993
994
function killKey (condition)
994
function killKey (condition)995
{
995
{996
if (condition.spawnerId)
996
if (condition.spawnerId)997
{ return `spawner:${condition.spawnerId}`; }
997
{ return `spawner:${condition.spawnerId}`; }998
return `mob:${condition.mobTypeId}`;
998
return `mob:${condition.mobTypeId}`;999
}
999
}1000
1000
1001
function interactKey (condition)
1001
function interactKey (condition)1002
{
1002
{1003
if (condition.tileX != null)
1003
if (condition.tileX != null)1004
{ return `tile:${condition.tileX},${condition.tileY}`; }
1004
{ return `tile:${condition.tileX},${condition.tileY}`; }1005
return `block:${condition.blockTypeId}`;
1005
return `block:${condition.blockTypeId}`;1006
}
1006
}@@ -2022,6 +2022,7 @@ export class Simulation
2022
2022
{
2023
2023
const out = [];
2024
2024
let needSnapshot = false;
2025
const snapshotCharacterIds = new Set();
2025
2026
const syncAccessIds = new Set();
2026
2027
for (const event of events ?? [])
2027
2028
{
@@ -2102,7 +2103,11 @@ export class Simulation
2102
2103
});
2103
2104
}
2104
2105
else if (event.type === "questsDirty")
2105
{ needSnapshot = true; }
2106
{
2107
needSnapshot = true;
2108
if (cid != null)
2109
{ snapshotCharacterIds.add(cid | 0); }
2110
}
2106
2111
else if (event.type === "inventoryDirty" && cid != null)
2107
2112
{
2108
2113
const onlineId = this.characterEntities.get(cid | 0);
@@ -2129,16 +2134,21 @@ export class Simulation
2129
2134
needSnapshot = true;
2130
2135
}
2131
2136
}
2132
if (needSnapshot && characterId != null)
2137
if (needSnapshot)
2133
2138
{
2134
const snap = this.quests.questSnapshot(characterId);
2135
out.push({
2136
type: "quests-snapshot",
2137
sessionId: sessionId ?? this.#sessionIdForCharacter(characterId),
2138
characterId,
2139
...snap
2140
});
2141
syncAccessIds.add(characterId | 0);
2139
if (characterId != null)
2140
{ snapshotCharacterIds.add(characterId | 0); }
2141
for (const snapCharacterId of snapshotCharacterIds)
2142
{
2143
const snap = this.quests.questSnapshot(snapCharacterId);
2144
out.push({
2145
type: "quests-snapshot",
2146
sessionId: sessionId ?? this.#sessionIdForCharacter(snapCharacterId),
2147
characterId: snapCharacterId,
2148
...snap
2149
});
2150
syncAccessIds.add(snapCharacterId | 0);
2151
}
2142
2152
}
2143
2153
for (const id of syncAccessIds)
2144
2154
{ this.syncCharacterConditionAccess(id); }
@@ -2162,10 +2172,11 @@ export class Simulation
2162
2172
: null;
2163
2173
if (killerCharacterId && this.quests)
2164
2174
{
2175
// Pass characterId so questsDirty produces a quests-snapshot for the killer.
2165
2176
out.push(...this.#mapQuestPrivateEvents(this.quests.noteKill(killerCharacterId, {
2166
2177
mobTypeId: event.mobTypeId,
2167
2178
spawnerId: event.spawnerId
2168
})));
2179
}), null, killerCharacterId));
2169
2180
}
2170
2181
out.push(...this.#mapQuestPrivateEvents(
2171
2182
this.quests?.interruptDialogueForEntity(event.entityId) ?? []
@@ -2022,6 +2022,7 @@ export class Simulation2022
{2022
{2023
const out = [];2023
const out = [];2024
let needSnapshot = false;2024
let needSnapshot = false;2025
const snapshotCharacterIds = new Set();2025
const syncAccessIds = new Set();2026
const syncAccessIds = new Set();2026
for (const event of events ?? [])2027
for (const event of events ?? [])2027
{2028
{@@ -2102,7 +2103,11 @@ export class Simulation2102
});2103
});2103
}2104
}2104
else if (event.type === "questsDirty")2105
else if (event.type === "questsDirty")2105
{ needSnapshot = true; }2106
{2107
needSnapshot = true;2108
if (cid != null)2109
{ snapshotCharacterIds.add(cid | 0); }2110
}2106
else if (event.type === "inventoryDirty" && cid != null)2111
else if (event.type === "inventoryDirty" && cid != null)2107
{2112
{2108
const onlineId = this.characterEntities.get(cid | 0);2113
const onlineId = this.characterEntities.get(cid | 0);@@ -2129,16 +2134,21 @@ export class Simulation2129
needSnapshot = true;2134
needSnapshot = true;2130
}2135
}2131
}2136
}2132
if (needSnapshot && characterId != null)2137
if (needSnapshot)2133
{2138
{2134
const snap = this.quests.questSnapshot(characterId);2139
if (characterId != null)2135
out.push({2140
{ snapshotCharacterIds.add(characterId | 0); }2136
type: "quests-snapshot",2141
for (const snapCharacterId of snapshotCharacterIds)2137
sessionId: sessionId ?? this.#sessionIdForCharacter(characterId),2142
{2138
characterId,2143
const snap = this.quests.questSnapshot(snapCharacterId);2139
...snap2144
out.push({2140
});2145
type: "quests-snapshot",2141
syncAccessIds.add(characterId | 0);2146
sessionId: sessionId ?? this.#sessionIdForCharacter(snapCharacterId),2147
characterId: snapCharacterId,2148
...snap2149
});2150
syncAccessIds.add(snapCharacterId | 0);2151
}2142
}2152
}2143
for (const id of syncAccessIds)2153
for (const id of syncAccessIds)2144
{ this.syncCharacterConditionAccess(id); }2154
{ this.syncCharacterConditionAccess(id); }@@ -2162,10 +2172,11 @@ export class Simulation2162
: null;2172
: null;2163
if (killerCharacterId && this.quests)2173
if (killerCharacterId && this.quests)2164
{2174
{2175
// Pass characterId so questsDirty produces a quests-snapshot for the killer.2165
out.push(...this.#mapQuestPrivateEvents(this.quests.noteKill(killerCharacterId, {2176
out.push(...this.#mapQuestPrivateEvents(this.quests.noteKill(killerCharacterId, {2166
mobTypeId: event.mobTypeId,2177
mobTypeId: event.mobTypeId,2167
spawnerId: event.spawnerId2178
spawnerId: event.spawnerId2168
})));2179
}), null, killerCharacterId));2169
}2180
}2170
out.push(...this.#mapQuestPrivateEvents(2181
out.push(...this.#mapQuestPrivateEvents(2171
this.quests?.interruptDialogueForEntity(event.entityId) ?? []2182
this.quests?.interruptDialogueForEntity(event.entityId) ?? []@@ -17,6 +17,7 @@ import { Component } from "../src/ecs/components.js";
17
17
import { eventInterestKeys } from "../src/gateway/eventInterest.js";
18
18
import { chunkKey, tileToChunk } from "../src/world/coordinates.js";
19
19
import { makeCharacter, openChunkStrip, writeOpenChunk } from "./helpers/simulationHarness.js";
20
import { normalizeQuestDef } from "../../shared/quests/normalize.js";
20
21
21
22
const CAVE_ID = "test-cave";
22
23
@@ -183,3 +184,61 @@ test("mob kill entity-despawn carries cave dimensionId for interest", () =>
183
184
finally
184
185
{ harness.close(); }
185
186
});
187
188
test("cave rat kill advances killCount quest progress", () =>
189
{
190
const harness = makeCaveHarness();
191
try
192
{
193
const quest = normalizeQuestDef({
194
questId: "kill-rats-cave",
195
title: "Kill Rats",
196
steps: [{
197
stepId: "step-1",
198
title: "Hunt",
199
objectives: [{
200
objectiveId: "obj-1",
201
text: "Kill 5 rats",
202
when: { all: [{ condition: { kind: "killCount", mobTypeId: "rat", count: 5 } }] }
203
}],
204
completionJournalText: "Done."
205
}]
206
});
207
const pending = harness.worldDb.ensurePendingRevision(1);
208
harness.worldDb.saveQuestDef(pending, quest);
209
harness.worldDb.promotePendingRevision();
210
harness.simulation.questContent.reload();
211
212
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
213
harness.stateDb.saveCharacterPosition(character.character_id, 8, 8, "walk", CAVE_ID);
214
const playerId = harness.simulation.spawnCharacter(1, character);
215
harness.simulation.quests.startQuest(character.character_id, "kill-rats-cave", null, []);
216
217
const ratId = harness.simulation.spawnEntity(mobComponents({
218
tileX: 8,
219
tileY: 9,
220
mobTypeId: MobId.rat,
221
spawnerId: null,
222
dimensionId: CAVE_ID
223
}));
224
const worker = workerOf(harness.simulation, ratId);
225
worker.world.ecs.get(worker.world.ecs.handleOf(ratId), Component.health).current = 1;
226
const killEvents = applyDamageAndKill(worker.world, playerId, ratId, 1, harness.now());
227
const mobKilled = killEvents.find((event) => event.type === "mob-killed");
228
assert.ok(mobKilled);
229
const noteEvents = harness.simulation.quests.noteKill(character.character_id, {
230
mobTypeId: mobKilled.mobTypeId,
231
spawnerId: mobKilled.spawnerId
232
});
233
assert.ok(noteEvents.some((event) => event.type === "questsDirty"));
234
assert.equal(
235
harness.stateDb.getQuestState(character.character_id, "kill-rats-cave").progress?.counters?.["mob:rat"],
236
1
237
);
238
const snap = harness.simulation.quests.questSnapshot(character.character_id);
239
assert.equal(snap.quests[0].step.objectives[0].current, 1);
240
assert.equal(snap.quests[0].step.objectives[0].required, 5);
241
}
242
finally
243
{ harness.close(); }
244
});
@@ -17,6 +17,7 @@ import { Component } from "../src/ecs/components.js";17
import { eventInterestKeys } from "../src/gateway/eventInterest.js";17
import { eventInterestKeys } from "../src/gateway/eventInterest.js";18
import { chunkKey, tileToChunk } from "../src/world/coordinates.js";18
import { chunkKey, tileToChunk } from "../src/world/coordinates.js";19
import { makeCharacter, openChunkStrip, writeOpenChunk } from "./helpers/simulationHarness.js";19
import { makeCharacter, openChunkStrip, writeOpenChunk } from "./helpers/simulationHarness.js";20
import { normalizeQuestDef } from "../../shared/quests/normalize.js";20
21
21
const CAVE_ID = "test-cave";22
const CAVE_ID = "test-cave";22
23
@@ -183,3 +184,61 @@ test("mob kill entity-despawn carries cave dimensionId for interest", () =>183
finally184
finally184
{ harness.close(); }185
{ harness.close(); }185
});186
});187
188
test("cave rat kill advances killCount quest progress", () =>189
{190
const harness = makeCaveHarness();191
try192
{193
const quest = normalizeQuestDef({194
questId: "kill-rats-cave",195
title: "Kill Rats",196
steps: [{197
stepId: "step-1",198
title: "Hunt",199
objectives: [{200
objectiveId: "obj-1",201
text: "Kill 5 rats",202
when: { all: [{ condition: { kind: "killCount", mobTypeId: "rat", count: 5 } }] }203
}],204
completionJournalText: "Done."205
}]206
});207
const pending = harness.worldDb.ensurePendingRevision(1);208
harness.worldDb.saveQuestDef(pending, quest);209
harness.worldDb.promotePendingRevision();210
harness.simulation.questContent.reload();211
212
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });213
harness.stateDb.saveCharacterPosition(character.character_id, 8, 8, "walk", CAVE_ID);214
const playerId = harness.simulation.spawnCharacter(1, character);215
harness.simulation.quests.startQuest(character.character_id, "kill-rats-cave", null, []);216
217
const ratId = harness.simulation.spawnEntity(mobComponents({218
tileX: 8,219
tileY: 9,220
mobTypeId: MobId.rat,221
spawnerId: null,222
dimensionId: CAVE_ID223
}));224
const worker = workerOf(harness.simulation, ratId);225
worker.world.ecs.get(worker.world.ecs.handleOf(ratId), Component.health).current = 1;226
const killEvents = applyDamageAndKill(worker.world, playerId, ratId, 1, harness.now());227
const mobKilled = killEvents.find((event) => event.type === "mob-killed");228
assert.ok(mobKilled);229
const noteEvents = harness.simulation.quests.noteKill(character.character_id, {230
mobTypeId: mobKilled.mobTypeId,231
spawnerId: mobKilled.spawnerId232
});233
assert.ok(noteEvents.some((event) => event.type === "questsDirty"));234
assert.equal(235
harness.stateDb.getQuestState(character.character_id, "kill-rats-cave").progress?.counters?.["mob:rat"],236
1237
);238
const snap = harness.simulation.quests.questSnapshot(character.character_id);239
assert.equal(snap.quests[0].step.objectives[0].current, 1);240
assert.equal(snap.quests[0].step.objectives[0].required, 5);241
}242
finally243
{ harness.close(); }244
});