@rpgm-tools/neo-angband-core 0.24.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +1 -1
  2. package/dist/agent/entity-views.d.ts +62 -0
  3. package/dist/agent/entity-views.d.ts.map +1 -0
  4. package/dist/agent/entity-views.js +195 -0
  5. package/dist/agent/entity-views.js.map +1 -0
  6. package/dist/agent/index.d.ts +5 -1
  7. package/dist/agent/index.d.ts.map +1 -1
  8. package/dist/agent/index.js +2 -0
  9. package/dist/agent/index.js.map +1 -1
  10. package/dist/agent/loadout.d.ts +97 -0
  11. package/dist/agent/loadout.d.ts.map +1 -0
  12. package/dist/agent/loadout.js +312 -0
  13. package/dist/agent/loadout.js.map +1 -0
  14. package/dist/agent/perceive.d.ts.map +1 -1
  15. package/dist/agent/perceive.js +16 -162
  16. package/dist/agent/perceive.js.map +1 -1
  17. package/dist/agent/types.d.ts +167 -2
  18. package/dist/agent/types.d.ts.map +1 -1
  19. package/dist/agent/types.js +10 -1
  20. package/dist/agent/types.js.map +1 -1
  21. package/dist/game/context.d.ts +15 -0
  22. package/dist/game/context.d.ts.map +1 -1
  23. package/dist/game/context.js.map +1 -1
  24. package/dist/index.d.ts +1 -0
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +1 -0
  27. package/dist/index.js.map +1 -1
  28. package/dist/mod/registry-host.d.ts +97 -0
  29. package/dist/mod/registry-host.d.ts.map +1 -1
  30. package/dist/mod/registry-host.js +7 -0
  31. package/dist/mod/registry-host.js.map +1 -1
  32. package/dist/mod/save-blocks.d.ts +1 -1
  33. package/dist/player/calcs.d.ts +9 -0
  34. package/dist/player/calcs.d.ts.map +1 -1
  35. package/dist/player/calcs.js +13 -1
  36. package/dist/player/calcs.js.map +1 -1
  37. package/dist/player/loadout.d.ts +178 -0
  38. package/dist/player/loadout.d.ts.map +1 -0
  39. package/dist/player/loadout.js +172 -0
  40. package/dist/player/loadout.js.map +1 -0
  41. package/dist/player/spell.d.ts +21 -1
  42. package/dist/player/spell.d.ts.map +1 -1
  43. package/dist/player/spell.js +53 -14
  44. package/dist/player/spell.js.map +1 -1
  45. package/dist/session/game.d.ts +39 -0
  46. package/dist/session/game.d.ts.map +1 -1
  47. package/dist/session/game.js +201 -31
  48. package/dist/session/game.js.map +1 -1
  49. package/dist/version.d.ts +1 -1
  50. package/dist/version.js +1 -1
  51. package/package.json +1 -1
  52. package/src/agent/entity-views.ts +227 -0
  53. package/src/agent/index.ts +9 -0
  54. package/src/agent/loadout.ts +400 -0
  55. package/src/agent/perceive.ts +22 -168
  56. package/src/agent/types.ts +166 -2
  57. package/src/game/context.ts +18 -0
  58. package/src/index.ts +1 -0
  59. package/src/mod/registry-host.ts +108 -0
  60. package/src/player/calcs.ts +22 -1
  61. package/src/player/loadout.ts +331 -0
  62. package/src/player/spell.ts +67 -16
  63. package/src/session/game.ts +287 -35
  64. package/src/version.ts +1 -1
@@ -0,0 +1,227 @@
1
+ /**
2
+ * The two plain-data view builders the perceive facade and the loadout
3
+ * simulation SHARE: one object as an `ItemView`, and the player as a
4
+ * `PlayerView`.
5
+ *
6
+ * They live in their own module rather than in perceive.ts for one reason.
7
+ * `agent/loadout.ts` describes a loadout the player is not wearing, and it has
8
+ * to describe it in the same shape and through the same builders as the live
9
+ * view - an `ItemView` carrying `value` in one and not the other would change
10
+ * what an agent decides about the same object depending on which view handed it
11
+ * over. Having both importers reach the same function is what makes that
12
+ * structural instead of a convention, and it keeps the import graph one-way
13
+ * (perceive and loadout both depend on this; neither depends on the other).
14
+ */
15
+
16
+ import { ELEMENT_ENTRIES, OBJECT_FLAG_ENTRIES, TMD } from "../generated/index.js";
17
+ import type { FlagSet } from "../bitflag.js";
18
+ import type { GameState } from "../game/context.js";
19
+ import type { GameObject } from "../obj/object.js";
20
+ import { OBJ_MOD_NAMES } from "../obj/bind.js";
21
+ import { objectValue } from "../obj/value.js";
22
+ import type { PlayerState } from "../player/calcs.js";
23
+ import type { PlayerCombatState } from "../combat/melee.js";
24
+ import type { AgentViewDeps, ItemView, PlayerView } from "./types.js";
25
+
26
+ /** OF_* codes for the set flags in an object-flag FlagSet (OF is 1-indexed). */
27
+ export function ofCodes(flags: FlagSet): string[] {
28
+ const out: string[] = [];
29
+ for (const f of flags) {
30
+ const entry = OBJECT_FLAG_ENTRIES[f - 1];
31
+ if (entry) out.push(entry.name);
32
+ }
33
+ return out;
34
+ }
35
+
36
+ /**
37
+ * One object as an ItemView. `handle` is 0 for anything not in the gear.
38
+ *
39
+ * `count` overrides obj->number for both the reported stack size and the value
40
+ * quantity. It exists for the hypothetical loadouts in agent/loadout.ts, where
41
+ * "three of the five potions I am carrying" and "one of the twelve on that
42
+ * shelf" are real cases and the object itself must not be touched to express
43
+ * them. Absent, the object's own number is used, which is every live read.
44
+ */
45
+ export function itemView(
46
+ handle: number,
47
+ obj: GameObject,
48
+ state: GameState,
49
+ deps: AgentViewDeps,
50
+ count?: number,
51
+ ): ItemView {
52
+ const number = count ?? obj.number;
53
+ const modifiers: Array<{ code: string; value: number }> = [];
54
+ for (let i = 0; i < obj.modifiers.length; i++) {
55
+ const value = obj.modifiers[i] ?? 0;
56
+ if (value === 0) continue;
57
+ const code = OBJ_MOD_NAMES[i];
58
+ if (code) modifiers.push({ code, value });
59
+ }
60
+
61
+ const brands: string[] = [];
62
+ if (obj.brands) {
63
+ for (let i = 0; i < obj.brands.length; i++) {
64
+ if (!obj.brands[i]) continue;
65
+ const code = state.brands[i]?.code;
66
+ if (code) brands.push(code);
67
+ }
68
+ }
69
+
70
+ const slays: string[] = [];
71
+ if (obj.slays) {
72
+ for (let i = 0; i < obj.slays.length; i++) {
73
+ if (!obj.slays[i]) continue;
74
+ const code = state.slays[i]?.code;
75
+ if (code) slays.push(code);
76
+ }
77
+ }
78
+
79
+ const resists: Array<{ element: string; level: number }> = [];
80
+ for (let i = 0; i < obj.elInfo.length; i++) {
81
+ const level = obj.elInfo[i]?.resLevel ?? 0;
82
+ if (level === 0) continue;
83
+ const name = ELEMENT_ENTRIES[i]?.name;
84
+ if (name) resists.push({ element: name, level });
85
+ }
86
+
87
+ const curses: string[] = [];
88
+ if (obj.curses) {
89
+ for (let i = 0; i < obj.curses.length; i++) {
90
+ const power = obj.curses[i]?.power ?? 0;
91
+ if (power <= 0) continue;
92
+ /* Curse names resolve from the always-present RuneEnv curse table (real
93
+ * in production, inert [null] in the worldless harness), then the
94
+ * optional registry dep, then the numeric index as a last resort. */
95
+ curses.push(
96
+ state.runeEnv.curses[i]?.name ??
97
+ deps.reg?.curses[i]?.name ??
98
+ String(i),
99
+ );
100
+ }
101
+ }
102
+
103
+ const view: ItemView = {
104
+ handle,
105
+ label: obj.kind.name,
106
+ tval: obj.tval,
107
+ sval: obj.sval,
108
+ pval: obj.pval,
109
+ number,
110
+ weight: obj.weight,
111
+ ac: obj.ac,
112
+ toA: obj.toA,
113
+ toH: obj.toH,
114
+ toD: obj.toD,
115
+ dd: obj.dd,
116
+ ds: obj.ds,
117
+ ego: obj.ego !== null,
118
+ artifact: obj.artifact !== null,
119
+ flags: ofCodes(obj.flags),
120
+ modifiers,
121
+ brands,
122
+ slays,
123
+ resists,
124
+ curses,
125
+ egoName: obj.ego?.name ?? null,
126
+ artifactName: obj.artifact?.name ?? null,
127
+ activation: obj.activation !== null,
128
+ timeout: obj.timeout,
129
+ inscription: obj.note ?? null,
130
+ };
131
+ if (deps.resolver) {
132
+ const kindId = deps.resolver.kindIdOrNull(obj.kind.kidx);
133
+ if (kindId !== null) view.kindId = kindId;
134
+ }
135
+ if (deps.reg) {
136
+ const aware = deps.aware ?? ((): boolean => true);
137
+ view.value = objectValue(deps.reg, obj, number, aware(obj.kind));
138
+ }
139
+ return view;
140
+ }
141
+
142
+ /**
143
+ * The derived facts playerViewFor reads off the live actor, supplied explicitly
144
+ * so a HYPOTHETICAL loadout can be described in exactly the same shape (see
145
+ * agent/loadout.ts). Absent, the live values are used, which is the ordinary
146
+ * perceive path.
147
+ *
148
+ * Only the fields a loadout can move are here. Level, experience, gold, grid,
149
+ * timed status and the rest are properties of the character rather than of what
150
+ * it is wearing, so a simulated view reports the live ones.
151
+ */
152
+ export interface PlayerViewDerived {
153
+ playerState: PlayerState;
154
+ combat: PlayerCombatState;
155
+ speed: number;
156
+ light: number;
157
+ maxHp: number;
158
+ maxSp: number;
159
+ }
160
+
161
+ /**
162
+ * Build a PlayerView from the live game, or - with `over` - from a derive for a
163
+ * loadout the player is not wearing.
164
+ *
165
+ * NOTE on `skills`: this is p->skills, the birth-time level-based skill array
166
+ * (calcSkills), NOT state->skills. It is not a function of the worn loadout, so
167
+ * a simulated view carries the live one, exactly as the live view does. The full
168
+ * derived skills, equipment contributions included, are on
169
+ * DerivedStatsView.skills (player/loadout.ts).
170
+ */
171
+ export function playerViewFor(
172
+ state: GameState,
173
+ deps: AgentViewDeps,
174
+ over?: PlayerViewDerived,
175
+ ): PlayerView {
176
+ const p = state.actor.player;
177
+ const combat = over ? over.combat : state.actor.combat;
178
+ const playerState = over ? over.playerState : state.playerState;
179
+ const view: PlayerView = {
180
+ race: p.race.name,
181
+ cls: p.cls.name,
182
+ level: p.lev,
183
+ maxLevel: p.maxLev,
184
+ exp: p.exp,
185
+ maxExp: p.maxExp,
186
+ gold: p.au,
187
+ depth: state.chunk.depth,
188
+ maxDepth: p.maxDepth,
189
+ hp: p.chp,
190
+ maxHp: over ? over.maxHp : p.mhp,
191
+ sp: p.csp,
192
+ maxSp: over ? over.maxSp : p.msp,
193
+ speed: over ? over.speed : state.actor.speed,
194
+ /* Displayed AC is state->ac + state->to_a. */
195
+ ac: combat.ac + combat.toA,
196
+ toHit: combat.toH,
197
+ toDam: combat.toD,
198
+ stats: [...p.statCur],
199
+ light: over ? over.light : state.actor.light,
200
+ grid: { x: state.actor.grid.x, y: state.actor.grid.y },
201
+ status: {
202
+ blind: p.timed[TMD.BLIND] ?? 0,
203
+ confused: p.timed[TMD.CONFUSED] ?? 0,
204
+ afraid: p.timed[TMD.AFRAID] ?? 0,
205
+ poisoned: p.timed[TMD.POISONED] ?? 0,
206
+ cut: p.timed[TMD.CUT] ?? 0,
207
+ stun: p.timed[TMD.STUN] ?? 0,
208
+ paralyzed: p.timed[TMD.PARALYZED] ?? 0,
209
+ food: p.timed[TMD.FOOD] ?? 0,
210
+ },
211
+ dead: state.isDead,
212
+ winner: p.totalWinner,
213
+ skills: [...p.skills],
214
+ shape: p.shape?.name ?? null,
215
+ objectFlags: playerState ? ofCodes(playerState.flags) : [],
216
+ seeInfra: playerState?.seeInfra ?? p.race.infravision,
217
+ blows: combat.numBlows,
218
+ shots: combat.numShots,
219
+ };
220
+ if (deps.resolver) {
221
+ const raceId = deps.resolver.playerRaceIdOrNull(p.race.ridx);
222
+ if (raceId !== null) view.playerRaceId = raceId;
223
+ const classId = deps.resolver.playerClassIdOrNull(p.cls.cidx);
224
+ if (classId !== null) view.playerClassId = classId;
225
+ }
226
+ return view;
227
+ }
@@ -21,6 +21,11 @@ export type {
21
21
  CellView,
22
22
  ControllerOptions,
23
23
  ItemView,
24
+ LoadoutChange,
25
+ LoadoutItemRef,
26
+ LoadoutPlacement,
27
+ LoadoutSimulation,
28
+ LoadoutView,
24
29
  MonsterView,
25
30
  PlayerStatusView,
26
31
  PlayerView,
@@ -31,6 +36,10 @@ export type {
31
36
  TargetView,
32
37
  } from "./types.js";
33
38
  export { createAgentView } from "./perceive.js";
39
+ export { itemView, playerViewFor } from "./entity-views.js";
40
+ export type { PlayerViewDerived } from "./entity-views.js";
41
+ export { simulateLoadout } from "./loadout.js";
42
+ export type { LoadoutDerive, LoadoutSimOptions } from "./loadout.js";
34
43
  export { createAgentActions } from "./act.js";
35
44
  export { AgentCapabilityError, installController } from "./controller.js";
36
45
  export { subscribeEvents } from "./events.js";
@@ -0,0 +1,400 @@
1
+ /**
2
+ * What the character would BE, wearing something else.
3
+ *
4
+ * ------------------------------------------------------------------
5
+ * WHY THIS EXISTS
6
+ * ------------------------------------------------------------------
7
+ *
8
+ * `calc_bonuses` (player/calcs.ts) answers "what is this character, in this
9
+ * gear". Two consumers need the same answer for gear the character is not in:
10
+ *
11
+ * 1. An autoplayer deciding whether to wear, buy or sell a thing. Upstream's
12
+ * borg does exactly this by WIELDING the candidate, recomputing, and
13
+ * reverting (borg-power.c / borg_notice).
14
+ * 2. A player asking what an item would do for them, which wants the whole
15
+ * difference and not a score - which resist went, what happened to mana,
16
+ * whether the weapon is now too heavy to swing properly.
17
+ *
18
+ * The trap either one falls into alone is summing the item's own bonuses. That
19
+ * is a second implementation of calc_bonuses, it cannot see the interactions
20
+ * (the STR ring that changes the blow count, the cuirass that costs a caster
21
+ * mana, the weight that costs speed), and it drifts from the real derive with
22
+ * nothing to notice. So this module runs the REAL derive, `update: false`, over
23
+ * a hypothetical equipment array, and nothing in the live game is written.
24
+ *
25
+ * ------------------------------------------------------------------
26
+ * WHERE THE DERIVE COMES FROM, AND WHY IT IS NOT BUILT HERE
27
+ * ------------------------------------------------------------------
28
+ *
29
+ * `state.derivedFor` is installed by the session (session/game.ts wireGame),
30
+ * which is the only place that holds the whole calc_bonuses options bag: the
31
+ * bound timed-effect table and the curse registry travel with it. A derive
32
+ * assembled here would have to guess at both, and a hypothetical loadout
33
+ * measured with a thinner bag than the live one is worse than no answer - it
34
+ * looks like an answer. So an absent `derivedFor` produces null.
35
+ *
36
+ * ------------------------------------------------------------------
37
+ * WHAT IS AND IS NOT MODELLED
38
+ * ------------------------------------------------------------------
39
+ *
40
+ * Modelled: the worn set, per body slot, through the engine's own wield_slot; the
41
+ * carried weight, because the STR encumbrance penalty reads it and buying heavy
42
+ * armour is exactly where that bites; max hitpoints (a CON change moves them) and
43
+ * max mana with the armour encumbrance (a caster's real cost of plate).
44
+ *
45
+ * NOT modelled: anything that happens as a CONSEQUENCE of the change rather than
46
+ * being the change - the gold a purchase costs, an inscription, learning a rune
47
+ * by wearing the thing. Those are outcomes of the action, not of the loadout, and
48
+ * a comparison that folded them in would be answering a different question.
49
+ */
50
+
51
+ import { calcHitpoints } from "../player/calcs.js";
52
+ import type { PlayerState } from "../player/calcs.js";
53
+ import { maxManaFrom, wornArmorWeight } from "../player/spell.js";
54
+ import { derivedStatsView, diffDerivedStats } from "../player/loadout.js";
55
+ import { STAT } from "../generated/index.js";
56
+ import { toCombatState, weightLimit } from "../player/calcs.js";
57
+ import { gearGet, wieldSlot } from "../game/gear.js";
58
+ import { objectWeightOne } from "../obj/object.js";
59
+ import type { GameObject } from "../obj/object.js";
60
+ import type { GameState } from "../game/context.js";
61
+ import { itemView, playerViewFor } from "./entity-views.js";
62
+ import type {
63
+ AgentViewDeps,
64
+ ItemView,
65
+ LoadoutChange,
66
+ LoadoutItemRef,
67
+ LoadoutPlacement,
68
+ LoadoutSimulation,
69
+ LoadoutView,
70
+ } from "./types.js";
71
+
72
+ /** calc_bonuses for a loadout, as GameState.derivedFor supplies it. */
73
+ export type LoadoutDerive = (
74
+ equipment: readonly (GameObject | null)[],
75
+ totalWeight?: number,
76
+ ) => PlayerState;
77
+
78
+ /** What simulateLoadout may be told rather than reading off the state. */
79
+ export interface LoadoutSimOptions {
80
+ /**
81
+ * The same AgentViewDeps the live view was built with, so the ItemViews in the
82
+ * result carry the same `value` / `kindId` fields the live ones do. Omitted
83
+ * fields degrade exactly as they do in perceive.
84
+ */
85
+ viewDeps?: AgentViewDeps;
86
+ /**
87
+ * The derive to use. Defaults to `state.derivedFor`, which the session
88
+ * installs; supply it directly only in a test that has no session.
89
+ */
90
+ derive?: LoadoutDerive;
91
+ }
92
+
93
+ /**
94
+ * One entry of the hypothetical carried set: the object, how many of it, and the
95
+ * gear handle it came from (0 for something being acquired, which has none).
96
+ */
97
+ interface Carried {
98
+ readonly handle: number;
99
+ readonly obj: GameObject;
100
+ number: number;
101
+ }
102
+
103
+ /** The working loadout the change is applied to. */
104
+ interface Working {
105
+ /** By body slot; null for an empty slot. */
106
+ readonly equip: (Carried | null)[];
107
+ /** The pack, in pack order. */
108
+ readonly pack: Carried[];
109
+ /** Total carried weight in tenth pounds (upstream p->upkeep->total_weight). */
110
+ weight: number;
111
+ /** References that named nothing (see LoadoutSimulation.unresolved). */
112
+ readonly unresolved: LoadoutItemRef[];
113
+ /** The view deps every ItemView built from this loadout is built with. */
114
+ readonly deps: AgentViewDeps;
115
+ }
116
+
117
+ /** The live loadout as a Working, before any change is applied. */
118
+ function liveLoadout(state: GameState, deps: AgentViewDeps): Working {
119
+ const p = state.actor.player;
120
+ const equip = p.equipment.map((handle): Carried | null => {
121
+ if (!handle) return null;
122
+ const obj = gearGet(state.gear, handle);
123
+ return obj ? { handle, obj, number: obj.number } : null;
124
+ });
125
+ const pack: Carried[] = [];
126
+ for (const handle of state.gear.pack) {
127
+ const obj = gearGet(state.gear, handle);
128
+ if (obj) pack.push({ handle, obj, number: obj.number });
129
+ }
130
+ return {
131
+ equip,
132
+ pack,
133
+ weight: p.upkeep.totalWeight,
134
+ unresolved: [],
135
+ deps,
136
+ };
137
+ }
138
+
139
+ /** The object a reference names, or null (recorded as unresolved by the caller). */
140
+ function resolveRef(state: GameState, ref: LoadoutItemRef): GameObject | null {
141
+ switch (ref.from) {
142
+ case "gear":
143
+ return gearGet(state.gear, ref.handle);
144
+ case "store": {
145
+ const store = (state.stores ?? [])[ref.store];
146
+ return store?.stock[ref.index] ?? null;
147
+ }
148
+ case "object":
149
+ return ref.object;
150
+ }
151
+ }
152
+
153
+ /** object_weight_one for a stack of `n` (obj-gear.c's total_weight term). */
154
+ function stackWeight(state: GameState, obj: GameObject, n: number): number {
155
+ return n * objectWeightOne(obj, state.gear.curses);
156
+ }
157
+
158
+ /** Take `n` of `handle` out of the working loadout entirely (a sale, a drop). */
159
+ function release(
160
+ state: GameState,
161
+ w: Working,
162
+ handle: number,
163
+ n: number | undefined,
164
+ ): void {
165
+ if (!handle) return;
166
+ const slot = w.equip.findIndex((c) => c?.handle === handle);
167
+ if (slot >= 0) {
168
+ const worn = w.equip[slot];
169
+ if (!worn) return;
170
+ const take = Math.min(n ?? worn.number, worn.number);
171
+ w.weight -= stackWeight(state, worn.obj, take);
172
+ if (take >= worn.number) w.equip[slot] = null;
173
+ else worn.number -= take;
174
+ return;
175
+ }
176
+ const at = w.pack.findIndex((c) => c.handle === handle);
177
+ if (at < 0) {
178
+ w.unresolved.push({ from: "gear", handle });
179
+ return;
180
+ }
181
+ const held = w.pack[at]!;
182
+ const take = Math.min(n ?? held.number, held.number);
183
+ w.weight -= stackWeight(state, held.obj, take);
184
+ if (take >= held.number) w.pack.splice(at, 1);
185
+ else held.number -= take;
186
+ }
187
+
188
+ /** Take a slot's contents off and put them in the pack (weight unchanged). */
189
+ function removeSlot(w: Working, slot: number): void {
190
+ const worn = w.equip[slot];
191
+ if (!worn) return;
192
+ w.equip[slot] = null;
193
+ w.pack.push(worn);
194
+ }
195
+
196
+ /**
197
+ * Wield one reference. Resolves the slot through the engine's own wield_slot
198
+ * over the HYPOTHETICAL occupancy, so the second ring of a pair goes to the
199
+ * second ring slot exactly as it would in play.
200
+ */
201
+ function wield(
202
+ state: GameState,
203
+ w: Working,
204
+ ref: LoadoutItemRef,
205
+ ): { slot: number; worn: Carried; displaced: Carried | null } | null {
206
+ const obj = resolveRef(state, ref);
207
+ if (!obj) {
208
+ w.unresolved.push(ref);
209
+ return null;
210
+ }
211
+ const body = state.actor.player.body;
212
+ /* wield_slot reads occupancy off a handle array; a slot holding an object
213
+ with no handle (a ware being bought) still has to read as full, so the
214
+ synthetic 1 stands in for "occupied by something". */
215
+ const occupancy = w.equip.map((c) => (c ? c.handle || 1 : 0));
216
+ const slot = wieldSlot(body, obj.tval, occupancy);
217
+ if (slot < 0 || slot >= body.count) {
218
+ w.unresolved.push(ref);
219
+ return null;
220
+ }
221
+
222
+ /* An item already in the pack MOVES; anything else is being acquired, and
223
+ its weight joins the carried total. */
224
+ const fromPack = w.pack.findIndex(
225
+ (c) => ref.from === "gear" && c.handle === ref.handle,
226
+ );
227
+ let worn: Carried;
228
+ if (fromPack >= 0) {
229
+ const held = w.pack[fromPack]!;
230
+ if (held.number > 1) {
231
+ /* Wielding one of a stack leaves the rest in the pack. */
232
+ held.number -= 1;
233
+ worn = { handle: held.handle, obj, number: 1 };
234
+ } else {
235
+ w.pack.splice(fromPack, 1);
236
+ worn = held;
237
+ worn.number = 1;
238
+ }
239
+ } else if (ref.from === "gear" && w.equip.some((c) => c?.handle === ref.handle)) {
240
+ /* Already worn: moving it to the slot wield_slot picks, weight unchanged. */
241
+ const at = w.equip.findIndex((c) => c?.handle === ref.handle);
242
+ worn = w.equip[at]!;
243
+ w.equip[at] = null;
244
+ } else {
245
+ worn = { handle: 0, obj, number: 1 };
246
+ w.weight += stackWeight(state, obj, 1);
247
+ }
248
+
249
+ const displaced = w.equip[slot] ?? null;
250
+ if (displaced) w.pack.push(displaced);
251
+ w.equip[slot] = worn;
252
+ return { slot, worn, displaced };
253
+ }
254
+
255
+ /** Put `n` of a reference into the pack without wearing it (a purchase). */
256
+ function carry(
257
+ state: GameState,
258
+ w: Working,
259
+ ref: LoadoutItemRef,
260
+ n: number | undefined,
261
+ ): void {
262
+ const obj = resolveRef(state, ref);
263
+ if (!obj) {
264
+ w.unresolved.push(ref);
265
+ return;
266
+ }
267
+ const count = Math.max(1, n ?? obj.number);
268
+ const handle = ref.from === "gear" ? ref.handle : 0;
269
+ const existing = handle ? w.pack.find((c) => c.handle === handle) : undefined;
270
+ if (existing) existing.number += count;
271
+ else w.pack.push({ handle, obj, number: count });
272
+ w.weight += stackWeight(state, obj, count);
273
+ }
274
+
275
+ /** Apply the whole change, in the documented order. */
276
+ function applyChange(
277
+ state: GameState,
278
+ w: Working,
279
+ change: LoadoutChange,
280
+ ): LoadoutPlacement[] {
281
+ for (const entry of change.release ?? []) {
282
+ release(state, w, entry.handle, entry.number);
283
+ }
284
+ for (const slot of change.remove ?? []) {
285
+ if (slot >= 0 && slot < w.equip.length) removeSlot(w, slot);
286
+ }
287
+ const placed: Array<{ slot: number; worn: Carried; displaced: Carried | null }> = [];
288
+ for (const ref of change.wield ?? []) {
289
+ const done = wield(state, w, ref);
290
+ if (done) placed.push(done);
291
+ }
292
+ for (const entry of change.carry ?? []) {
293
+ carry(state, w, entry.item, entry.number);
294
+ }
295
+ /* Placements are built last so `displaced` is described from the objects, not
296
+ from a Carried whose count a later step may have changed. */
297
+ return placed.map(({ slot, worn, displaced }) => ({
298
+ slot,
299
+ worn: viewOf(state, w, worn),
300
+ displaced: displaced ? viewOf(state, w, displaced) : null,
301
+ }));
302
+ }
303
+
304
+ /** One Carried as an ItemView, with its hypothetical stack count. */
305
+ function viewOf(state: GameState, w: Working, c: Carried): ItemView {
306
+ return itemView(c.handle, c.obj, state, w.deps, c.number);
307
+ }
308
+
309
+ /** Derive and describe one working loadout. */
310
+ function describe(
311
+ state: GameState,
312
+ w: Working,
313
+ derive: LoadoutDerive,
314
+ ): LoadoutView {
315
+ const p = state.actor.player;
316
+ const equipObjects = w.equip.map((c) => c?.obj ?? null);
317
+ const derived = derive(equipObjects, w.weight);
318
+ const armorWeight = wornArmorWeight(p, equipObjects);
319
+ const maxHp = calcHitpoints(
320
+ p.playerHp[p.lev - 1] ?? p.hitdie,
321
+ p.lev,
322
+ derived.statInd[STAT.CON] ?? 0,
323
+ );
324
+ const maxSp = maxManaFrom(p, derived.statInd, armorWeight);
325
+ /* calc_mana owns cumber_armor (player-calcs.c:1524-1529); the same predicate
326
+ the session records after its own calc_mana call. */
327
+ const cumberArmor =
328
+ p.cls.magic.totalSpells > 0 &&
329
+ Math.trunc((armorWeight - p.cls.magic.spellWeight) / 10) > 0;
330
+ const stats = derivedStatsView(derived, {
331
+ maxHp,
332
+ maxSp,
333
+ cumberArmor,
334
+ totalWeight: w.weight,
335
+ weightLimit: weightLimit(derived),
336
+ });
337
+ return {
338
+ player: playerViewFor(state, w.deps, {
339
+ playerState: derived,
340
+ combat: toCombatState(derived),
341
+ speed: derived.speed,
342
+ light: derived.curLight,
343
+ maxHp,
344
+ maxSp,
345
+ }),
346
+ equipment: w.equip.map((c) => (c ? viewOf(state, w, c) : null)),
347
+ inventory: w.pack.map((c) => viewOf(state, w, c)),
348
+ stats,
349
+ };
350
+ }
351
+
352
+ /**
353
+ * Derive the character both as it stands and with `change` applied, and diff the
354
+ * two. Returns null when the state has no `derivedFor` installed (a worldless
355
+ * harness), because an approximate answer here is indistinguishable from a real
356
+ * one at every call site.
357
+ *
358
+ * PURE: nothing on the GameState, the player, the gear or any object is written.
359
+ * The derive runs with `update: false`, which is what keeps calc_bonuses' own
360
+ * faithful side effects (zeroing TMD_FASTCAST on a stun grade) out of it.
361
+ *
362
+ * COMPARE AN `after` AGAINST THIS `before`, NEVER AGAINST THE LIVE CHARACTER'S
363
+ * OWN NUMBERS. Both sides here come out of the same `update: false` derive, and
364
+ * upstream's calc_bonuses does not answer identically in both modes: its
365
+ * town-daylight shortcut in calc_light is gated on `update`
366
+ * (player-calcs.c:1607), so in a daytime town a shadow derive reports the light
367
+ * radius of the equipment and the live derive reports zero. That is upstream's
368
+ * asymmetry and the port keeps it.
369
+ *
370
+ * MEASURED, 2026-08-21, which is why this paragraph exists: an autoplayer scored
371
+ * a candidate loadout through this function and compared the result against the
372
+ * score it had computed from the LIVE view. In a daytime town the two derives
373
+ * differed by 14000 points of the Borg's own power metric, so every wearable item
374
+ * looked like an upgrade and it spent 3964 of 4000 decisions swapping one wooden
375
+ * torch for an identical one. `delta` - or the difference between an `after` and
376
+ * this `before` - is the quantity a decision wants; an absolute `after` is not.
377
+ */
378
+ export function simulateLoadout(
379
+ state: GameState,
380
+ change: LoadoutChange,
381
+ opts: LoadoutSimOptions = {},
382
+ ): LoadoutSimulation | null {
383
+ const derive = opts.derive ?? state.derivedFor;
384
+ if (!derive) return null;
385
+ const deps = opts.viewDeps ?? {};
386
+
387
+ const before = describe(state, liveLoadout(state, deps), derive);
388
+
389
+ const afterWork = liveLoadout(state, deps);
390
+ const placements = applyChange(state, afterWork, change);
391
+ const after = describe(state, afterWork, derive);
392
+
393
+ return {
394
+ before,
395
+ after,
396
+ delta: diffDerivedStats(before.stats, after.stats),
397
+ placements,
398
+ unresolved: afterWork.unresolved,
399
+ };
400
+ }