BlueGit

timfa questward

Files

questward / server / src / quests / runtime.js

runtime.js

runtime.js 21.5 KiB Download Raw
1import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
2import { countItemInSlots, insertStack, takeMatchingFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
3import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
4import { itemDefinition } from "../../../shared/definitions/items.js";
5import { applySkillXp } from "../../../shared/skills/state.js";
6import { skillLevel } from "../../../shared/definitions/skills.js";
7import { formatDialogueRewardMessage } from "../../../shared/quests/dialogueRewards.js";
8import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
9import { floorDiv } from "../world/coordinates.js";
10import { WorkerMessage } from "../simulation/protocol.js";
11
12/**
13 * Quest progress + dialogue sessions (main simulation thread).
14 */
15export class QuestRuntime
16{
17 constructor ({ stateDb, content, simulation })
18 {
19 this.stateDb = stateDb;
20 this.content = content;
21 this.simulation = simulation;
22 /** @type {Map<number, { entityId: number, dialogueId: string, stepId: string }>} */
23 this.sessions = new Map();
24 }
25
26 reloadContent ()
27 {
28 this.content.reload();
29 }
30
31 closeAllSessions ()
32 {
33 for (const characterId of [...this.sessions.keys()])
34 { this.closeDialogue(characterId, "revision"); }
35 }
36
37 questSnapshot (characterId)
38 {
39 const states = this.stateDb.listQuestStates(characterId)
40 .filter((row) => row.state !== "not-started");
41 const quests = [];
42 for (const row of states)
43 {
44 const def = this.content.quest(row.questId);
45 if (!def)
46 {
47 quests.push({
48 questId: row.questId,
49 title: "Quest unavailable",
50 orphaned: true,
51 state: row.state,
52 description: "",
53 step: null,
54 journal: this.stateDb.listQuestJournal(characterId, row.questId).map(journalPublic)
55 });
56 continue;
57 }
58 const stepIndex = typeof row.state === "number" ? row.state : null;
59 const stepDef = stepIndex != null ? def.steps[stepIndex - 1] : null;
60 const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];
61 quests.push({
62 questId: def.questId,
63 title: def.title,
64 orphaned: false,
65 state: row.state,
66 description: def.description,
67 step: stepDef
68 ? {
69 stepId: stepDef.stepId,
70 title: stepDef.title,
71 description: stepDef.description,
72 objectives: stepDef.objectives.map((obj) => ({
73 objectiveId: obj.objectiveId,
74 text: obj.text,
75 done: completedObjectiveIds.includes(obj.objectiveId)
76 }))
77 }
78 : null,
79 journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)
80 });
81 }
82 quests.sort((a, b) =>
83 {
84 const aDone = a.state === "completed" ? 1 : 0;
85 const bDone = b.state === "completed" ? 1 : 0;
86 if (aDone !== bDone)
87 { return aDone - bDone; }
88 return String(a.title).localeCompare(String(b.title));
89 });
90 return { quests };
91 }
92
93 playerViewFor (characterId)
94 {
95 const entityId = this.simulation.characterEntities.get(characterId | 0);
96 const record = entityId != null ? this.simulation.directory.get(entityId) : null;
97 const skills = this.stateDb.getSkills(characterId) ?? {};
98 let hp = 1;
99 let maxHp = 1;
100 let stamina = 1;
101 let maxStamina = 1;
102 if (entityId != null && record)
103 {
104 const staminaComp = this.simulation.staminaOf(entityId);
105 if (staminaComp)
106 {
107 stamina = Number(staminaComp.current) || 0;
108 maxStamina = Math.max(1, Number(staminaComp.max) || 1);
109 }
110 const worker = this.simulation.workers[record.workerId];
111 const view = worker?.call?.({
112 type: WorkerMessage.inspect,
113 entityId
114 });
115 if (view && view.health != null)
116 {
117 hp = Number(view.health) || 0;
118 maxHp = Math.max(1, Number(view.maxHealth) || 1);
119 }
120 }
121 return {
122 tileX: record?.tileX | 0,
123 tileY: record?.tileY | 0,
124 dimensionId: record?.dimensionId ?? "overworld",
125 skills,
126 hp,
127 maxHp,
128 stamina,
129 maxStamina
130 };
131 }
132
133 buildConditionContext (characterId, playerView, activeQuestId = null)
134 {
135 const bag = this.#loadBag(characterId);
136 const inventory = bag?.inventory ?? [];
137 const tileX = playerView?.tileX | 0;
138 const tileY = playerView?.tileY | 0;
139 const dimensionId = playerView?.dimensionId ?? "overworld";
140 const chunkX = floorDiv(tileX, CHUNK_SIZE);
141 const chunkY = floorDiv(tileY, CHUNK_SIZE);
142 const questRow = activeQuestId ? this.stateDb.getQuestState(characterId, activeQuestId) : null;
143 return {
144 tileX,
145 tileY,
146 chunkX,
147 chunkY,
148 dimensionId,
149 hp: playerView?.hp ?? 0,
150 maxHp: playerView?.maxHp ?? 1,
151 stamina: playerView?.stamina ?? 0,
152 maxStamina: playerView?.maxStamina ?? 1,
153 countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
154 questState: (questId) => this.stateDb.getQuestState(characterId, questId).state,
155 dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId),
156 dialogueTriggerLatched: (dialogueId, trigger) =>
157 this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger),
158 skillLevel: (skillId) => skillLevel(playerView?.skills ?? {}, skillId),
159 hasVisitedDimension: (dimId) => this.stateDb.hasVisitedDimension(characterId, dimId),
160 killCount: (condition) =>
161 {
162 if (!questRow)
163 { return 0; }
164 return questRow.progress?.counters?.[killKey(condition)] | 0;
165 },
166 interactBlockDone: (condition) =>
167 {
168 if (!questRow)
169 { return false; }
170 return !!questRow.progress?.interacts?.[interactKey(condition)];
171 }
172 };
173 }
174
175 tryOpenDialogue (characterId, entityId, dialogueId)
176 {
177 const tree = this.content.dialogue(dialogueId);
178 if (!tree)
179 { return { ok: false, error: "Nothing to say." }; }
180 this.closeDialogue(characterId, "replace");
181 const playerView = this.playerViewFor(characterId);
182 return this.#enterStep(characterId, entityId, tree, tree.entryStepId, playerView);
183 }
184
185 chooseDialogue (characterId, triggerId)
186 {
187 const session = this.sessions.get(characterId | 0);
188 if (!session)
189 { return { ok: false, error: "No dialogue open." }; }
190 if (session.phase === "lines")
191 { return { ok: false, error: "Finish reading first." }; }
192 if (session.phase === "rewards")
193 { return { ok: false, error: "Finish reading first." }; }
194 const tree = this.content.dialogue(session.dialogueId);
195 if (!tree)
196 {
197 this.closeDialogue(characterId, "missing");
198 return { ok: false, error: "Dialogue missing." };
199 }
200 const step = tree.steps.find((s) => s.stepId === session.stepId);
201 if (!step || step.exit?.kind !== "triggers")
202 { return { ok: false, error: "Cannot choose now." }; }
203 const trigger = step.exit.triggers.find((t) => t.trigger === String(triggerId));
204 if (!trigger)
205 { return { ok: false, error: "Unknown choice." }; }
206 const playerView = this.playerViewFor(characterId);
207 const ctx = this.buildConditionContext(characterId, playerView);
208 if (!evaluateConditionSet(trigger.when, ctx))
209 { return { ok: false, error: "That choice is unavailable." }; }
210 this.stateDb.latchDialogueTrigger(characterId, tree.dialogueId, trigger.trigger);
211 const events = [];
212 this.#applyEffects(characterId, trigger.effects, playerView, events);
213 this.#reevaluateQuests(characterId, playerView, events);
214 if (!trigger.nextStepId)
215 {
216 const npcEntityId = session.entityId;
217 this.sessions.delete(characterId | 0);
218 events.push({ type: "dialogueClose", reason: "end", npcEntityId });
219 return { ok: true, events };
220 }
221 return this.#enterStep(characterId, session.entityId, tree, trigger.nextStepId, playerView, events);
222 }
223
224 closeDialogue (characterId, reason = "close")
225 {
226 const id = characterId | 0;
227 const session = this.sessions.get(id);
228 if (!session)
229 { return { events: [] }; }
230 this.sessions.delete(id);
231 return {
232 events: [{
233 type: "dialogueClose",
234 reason,
235 npcEntityId: session.entityId
236 }]
237 };
238 }
239
240 interruptDialogueForEntity (entityId)
241 {
242 const events = [];
243 for (const [characterId, session] of [...this.sessions])
244 {
245 if (session.entityId === (entityId | 0))
246 {
247 const closed = this.closeDialogue(characterId, "attacked");
248 events.push(...closed.events.map((e) => ({ ...e, characterId })));
249 }
250 }
251 return events;
252 }
253
254 #enterStep (characterId, entityId, tree, stepId, playerView, priorEvents = [])
255 {
256 const step = tree.steps.find((s) => s.stepId === stepId);
257 if (!step)
258 {
259 this.sessions.delete(characterId | 0);
260 priorEvents.push({ type: "dialogueClose", reason: "missing-step" });
261 return { ok: false, error: "Broken dialogue.", events: priorEvents };
262 }
263 this.stateDb.markDialogueHeard(characterId, tree.dialogueId, step.stepId);
264 const events = [...priorEvents];
265 const linePayloads = [];
266 for (const line of step.lines)
267 {
268 this.#applyEffects(characterId, line.effects, playerView, events);
269 linePayloads.push({ speaker: line.speaker, text: line.text });
270 }
271 // Stay open while the client pages lines; resolve exit only on dialogueAdvance.
272 this.sessions.set(characterId | 0, {
273 entityId: entityId | 0,
274 dialogueId: tree.dialogueId,
275 stepId: step.stepId,
276 phase: "lines",
277 pendingExit: step.exit ?? { kind: "end" }
278 });
279 events.push({
280 type: "dialogueStep",
281 dialogueId: tree.dialogueId,
282 stepId: step.stepId,
283 label: step.label,
284 npcEntityId: entityId | 0,
285 lines: linePayloads
286 });
287 this.#reevaluateQuests(characterId, playerView, events);
288 return { ok: true, events };
289 }
290
291 /** Client finished reading all lines (or reward notices) of the current step. */
292 advanceDialogue (characterId)
293 {
294 const session = this.sessions.get(characterId | 0);
295 if (!session || (session.phase !== "lines" && session.phase !== "rewards"))
296 { return { ok: false, error: "No dialogue lines to advance." }; }
297 const tree = this.content.dialogue(session.dialogueId);
298 if (!tree)
299 {
300 this.sessions.delete(characterId | 0);
301 return { ok: true, events: [{ type: "dialogueClose", reason: "missing" }] };
302 }
303 const playerView = this.playerViewFor(characterId);
304 const events = [];
305
306 if (session.phase === "lines")
307 {
308 const step = tree.steps.find((s) => s.stepId === session.stepId);
309 const rewardMessages = this.#grantStepItemRewards(
310 characterId,
311 step,
312 events
313 );
314 this.#reevaluateQuests(characterId, playerView, events);
315 if (rewardMessages.length > 0)
316 {
317 session.phase = "rewards";
318 events.push({
319 type: "dialogueItemRewards",
320 dialogueId: session.dialogueId,
321 stepId: session.stepId,
322 npcEntityId: session.entityId,
323 messages: rewardMessages
324 });
325 return { ok: true, events };
326 }
327 }
328
329 return this.#resolveDialogueExit(characterId, session, tree, playerView, events);
330 }
331
332 #resolveDialogueExit (characterId, session, tree, playerView, events)
333 {
334 const exit = session.pendingExit ?? { kind: "end" };
335
336 if (exit.kind === "branches")
337 {
338 const ctx = this.buildConditionContext(characterId, playerView);
339 let matched = null;
340 for (const branch of exit.branches ?? [])
341 {
342 if (evaluateConditionSet(branch.when, ctx))
343 {
344 matched = branch;
345 break;
346 }
347 }
348 if (!matched || !matched.nextStepId)
349 {
350 this.#applyEffects(characterId, matched?.effects, playerView, events);
351 const npcEntityId = session.entityId;
352 this.sessions.delete(characterId | 0);
353 events.push({ type: "dialogueClose", reason: "branch-end", npcEntityId });
354 return { ok: true, events };
355 }
356 this.#applyEffects(characterId, matched.effects, playerView, events);
357 return this.#enterStep(characterId, session.entityId, tree, matched.nextStepId, playerView, events);
358 }
359
360 if (exit.kind === "triggers")
361 {
362 const ctx = this.buildConditionContext(characterId, playerView);
363 const triggers = (exit.triggers ?? [])
364 .filter((t) => evaluateConditionSet(t.when, ctx))
365 .map((t) => ({ trigger: t.trigger, text: t.text }));
366 if (triggers.length === 0)
367 {
368 const npcEntityId = session.entityId;
369 this.sessions.delete(characterId | 0);
370 events.push({ type: "dialogueClose", reason: "no-triggers", npcEntityId });
371 return { ok: true, events };
372 }
373 session.phase = "choices";
374 session.pendingExit = null;
375 events.push({
376 type: "dialogueChoices",
377 dialogueId: session.dialogueId,
378 stepId: session.stepId,
379 npcEntityId: session.entityId,
380 triggers
381 });
382 return { ok: true, events };
383 }
384
385 const npcEntityId = session.entityId;
386 this.sessions.delete(characterId | 0);
387 events.push({ type: "dialogueClose", reason: "end", npcEntityId });
388 return { ok: true, events };
389 }
390
391 /**
392 * Grant step.itemRewards into bag (overflow → bank/vault). Returns player-facing notices.
393 */
394 #grantStepItemRewards (characterId, step, events)
395 {
396 const rewards = step?.itemRewards ?? [];
397 if (!rewards.length)
398 { return []; }
399 const bagParts = [];
400 const bankParts = [];
401 for (const reward of rewards)
402 {
403 const bag = this.#loadBag(characterId);
404 if (!bag)
405 { continue; }
406 const itemId = reward.itemId | 0;
407 const def = itemDefinition(itemId);
408 const quantity = Math.max(1, Number(reward.quantity) || 1);
409 const displayName = def?.displayName ?? `Item ${itemId}`;
410 const stack = attachOrigins({
411 itemId,
412 quantity,
413 origins: [{ origin: godsOrigin(), quantity }]
414 });
415 const result = insertStack(bag.inventory, stack, def);
416 bag.inventory = result.slots;
417 const intoBag = quantity - Math.max(0, result.remainder | 0);
418 let intoBank = 0;
419 if (result.remainder > 0)
420 {
421 const vaultResult = insertStackGrowable(
422 bag.vault,
423 attachOrigins({
424 itemId,
425 quantity: result.remainder,
426 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
427 }),
428 def
429 );
430 bag.vault = vaultResult.slots;
431 intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
432 }
433 this.#persistBag(characterId, bag);
434 events.push({ type: "inventoryDirty" });
435 if (intoBag > 0)
436 { bagParts.push({ displayName, quantity: intoBag }); }
437 if (intoBank > 0)
438 { bankParts.push({ displayName, quantity: intoBank }); }
439 }
440 const messages = [];
441 const bagMsg = formatDialogueRewardMessage(bagParts, "bag");
442 const bankMsg = formatDialogueRewardMessage(bankParts, "bank");
443 if (bagMsg)
444 { messages.push(bagMsg); }
445 if (bankMsg)
446 { messages.push(bankMsg); }
447 return messages;
448 }
449
450 #loadBag (characterId)
451 {
452 const onlineId = this.simulation.characterEntities.get(characterId | 0);
453 const bag = onlineId
454 ? this.simulation.bagOf(onlineId)
455 : this.stateDb.getBag(characterId);
456 return bag;
457 }
458
459 #persistBag (characterId, bag)
460 {
461 this.stateDb.saveBag(characterId, bag);
462 const onlineId = this.simulation.characterEntities.get(characterId | 0);
463 if (onlineId)
464 {
465 this.simulation.applyBag?.(onlineId, bag);
466 this.simulation.pushInventory?.(characterId, bag);
467 }
468 }
469
470 #applyEffects (characterId, effects, playerView, events)
471 {
472 if (!Array.isArray(effects) || effects.length === 0)
473 { return; }
474 for (const effect of effects)
475 {
476 if (effect.kind === EffectKind.giveItem)
477 {
478 const bag = this.#loadBag(characterId);
479 if (!bag)
480 { continue; }
481 const def = itemDefinition(effect.itemId | 0);
482 const quantity = Math.max(1, Number(effect.quantity) || 1);
483 const stack = attachOrigins({
484 itemId: effect.itemId | 0,
485 quantity,
486 origins: [{ origin: godsOrigin(), quantity }]
487 });
488 const result = insertStack(bag.inventory, stack, def);
489 bag.inventory = result.slots;
490 if (result.remainder > 0)
491 {
492 const vaultResult = insertStackGrowable(
493 bag.vault,
494 attachOrigins({
495 itemId: effect.itemId | 0,
496 quantity: result.remainder,
497 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
498 }),
499 def
500 );
501 bag.vault = vaultResult.slots;
502 }
503 this.#persistBag(characterId, bag);
504 events.push({ type: "inventoryDirty" });
505 }
506 else if (effect.kind === EffectKind.takeItem)
507 {
508 const bag = this.#loadBag(characterId);
509 if (!bag)
510 { continue; }
511 const taken = takeMatchingFromSlots(bag.inventory, {
512 itemId: effect.itemId | 0,
513 quantity: Math.max(1, Number(effect.quantity) || 1),
514 compact: false
515 });
516 if (taken.ok)
517 {
518 bag.inventory = taken.slots;
519 this.#persistBag(characterId, bag);
520 events.push({ type: "inventoryDirty" });
521 }
522 }
523 else if (effect.kind === EffectKind.giveXp)
524 {
525 const skills = this.stateDb.getSkills(characterId);
526 if (skills)
527 {
528 applySkillXp(skills, effect.skillId, Math.max(0, Number(effect.amount) || 0));
529 this.stateDb.saveSkills(characterId, skills);
530 if (playerView)
531 { playerView.skills = skills; }
532 events.push({ type: "skillsDirty" });
533 }
534 }
535 else if (effect.kind === EffectKind.startQuest)
536 { this.startQuest(characterId, effect.questId, playerView, events); }
537 }
538 }
539
540 startQuest (characterId, questId, playerView, events = [])
541 {
542 const def = this.content.quest(questId);
543 if (!def)
544 { return; }
545 const current = this.stateDb.getQuestState(characterId, questId);
546 if (current.state !== "not-started")
547 { return; }
548 this.stateDb.saveQuestState(characterId, questId, 1, {
549 completedObjectiveIds: [],
550 counters: {},
551 interacts: {}
552 }, Date.now(), null);
553 this.#applyEffects(characterId, def.steps[0]?.onEnter, playerView, events);
554 events.push({ type: "questsDirty" });
555 this.#reevaluateQuests(characterId, playerView, events);
556 }
557
558 #reevaluateQuests (characterId, playerView, events)
559 {
560 const states = this.stateDb.listQuestStates(characterId)
561 .filter((row) => typeof row.state === "number");
562 for (const row of states)
563 {
564 const def = this.content.quest(row.questId);
565 if (!def)
566 { continue; }
567 const stepDef = def.steps[row.state - 1];
568 if (!stepDef)
569 { continue; }
570 const ctx = this.buildConditionContext(characterId, playerView, row.questId);
571 const completed = new Set(row.progress?.completedObjectiveIds ?? []);
572 let changed = false;
573 for (const obj of stepDef.objectives)
574 {
575 if (completed.has(obj.objectiveId))
576 { continue; }
577 if (evaluateConditionSet(obj.when, ctx))
578 {
579 completed.add(obj.objectiveId);
580 changed = true;
581 }
582 }
583 if (!changed)
584 { continue; }
585 const progress = {
586 ...row.progress,
587 completedObjectiveIds: [...completed]
588 };
589 const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
590 if (!allDone)
591 {
592 this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
593 events.push({ type: "questsDirty" });
594 continue;
595 }
596 this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
597 const journal = this.stateDb.appendQuestJournal(
598 characterId,
599 row.questId,
600 stepDef.stepId,
601 stepDef.completionJournalText
602 );
603 const nextIndex = row.state + 1;
604 if (nextIndex > def.steps.length)
605 {
606 this.#applyEffects(characterId, def.rewards, playerView, events);
607 this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now());
608 }
609 else
610 {
611 const nextStep = def.steps[nextIndex - 1];
612 this.stateDb.saveQuestState(characterId, row.questId, nextIndex, {
613 completedObjectiveIds: [],
614 counters: {},
615 interacts: {}
616 }, row.startedAt, null);
617 this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
618 }
619 events.push({
620 type: "questStepComplete",
621 questId: row.questId,
622 title: def.title,
623 journalText: journal?.text ?? null
624 });
625 events.push({ type: "questsDirty" });
626 }
627 }
628
629 noteKill (characterId, { mobTypeId, spawnerId })
630 {
631 const events = [];
632 const playerView = this.playerViewFor(characterId);
633 const states = this.stateDb.listQuestStates(characterId)
634 .filter((row) => typeof row.state === "number");
635 for (const row of states)
636 {
637 const def = this.content.quest(row.questId);
638 const stepDef = def?.steps[row.state - 1];
639 if (!stepDef)
640 { continue; }
641 let changed = false;
642 const counters = { ...(row.progress?.counters ?? {}) };
643 for (const obj of stepDef.objectives)
644 {
645 for (const clause of obj.when?.all ?? [])
646 {
647 const c = clause.condition;
648 if (c?.kind !== "killCount")
649 { continue; }
650 const matchMob = c.mobTypeId != null && String(c.mobTypeId) === String(mobTypeId);
651 const matchSpawner = c.spawnerId != null && String(c.spawnerId) === String(spawnerId);
652 if (!matchMob && !matchSpawner)
653 { continue; }
654 const key = killKey(c);
655 counters[key] = (counters[key] | 0) + 1;
656 changed = true;
657 }
658 }
659 if (!changed)
660 { continue; }
661 this.stateDb.saveQuestState(characterId, row.questId, row.state, {
662 ...row.progress,
663 counters
664 }, row.startedAt, row.completedAt);
665 }
666 this.#reevaluateQuests(characterId, playerView, events);
667 return events;
668 }
669}
670
671function journalPublic (row)
672{
673 return {
674 entryId: row.entry_id ?? row.entryId,
675 questId: row.quest_id ?? row.questId,
676 stepId: row.step_id ?? row.stepId,
677 text: row.text,
678 writtenAt: row.written_at ?? row.writtenAt
679 };
680}
681
682function killKey (condition)
683{
684 if (condition.spawnerId)
685 { return `spawner:${condition.spawnerId}`; }
686 return `mob:${condition.mobTypeId}`;
687}
688
689function interactKey (condition)
690{
691 if (condition.tileX != null)
692 { return `tile:${condition.tileX},${condition.tileY}`; }
693 return `block:${condition.blockTypeId}`;
694}