jewelerty, skulls
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#5a6a80"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">JW</text></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#5a6a80"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">JW</text></svg>@@ -943,7 +943,7 @@ export function initTileConfigModal ({
943
943
field("Level", numberInput("level", config.level ?? 1, 1, 99)),
944
944
field("Bounty", numberInput("bounty", config.bounty ?? 0, 0, 1_000_000)),
945
945
field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),
946
field("Respawn delay (seconds)", numberInput("respawnDelaySeconds", config.respawnDelaySeconds ?? 0, 0, 86_400)),
946
field("Respawn delay (seconds)", numberInput("respawnDelaySeconds", config.respawnDelaySeconds ?? 25, 0, 86_400)),
947
947
field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)),
948
948
field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)),
949
949
field("Spawner id", textInput("spawnerId", config.spawnerId, true))
@@ -1110,7 +1110,7 @@ export function initTileConfigModal ({
1110
1110
onSave?.(context, normalizeSpawnerConfig({
1111
1111
mobTypeId: String(data.get("mobTypeId") || "deer"),
1112
1112
maxAlive: Number(data.get("maxAlive") || 3),
1113
respawnDelaySeconds: Number(data.get("respawnDelaySeconds") || 0),
1113
respawnDelaySeconds: Number(data.get("respawnDelaySeconds") ?? 25),
1114
1114
spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4),
1115
1115
maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4),
1116
1116
level: Number(data.get("level") || 1),
@@ -943,7 +943,7 @@ export function initTileConfigModal ({943
field("Level", numberInput("level", config.level ?? 1, 1, 99)),943
field("Level", numberInput("level", config.level ?? 1, 1, 99)),944
field("Bounty", numberInput("bounty", config.bounty ?? 0, 0, 1_000_000)),944
field("Bounty", numberInput("bounty", config.bounty ?? 0, 0, 1_000_000)),945
field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),945
field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),946
field("Respawn delay (seconds)", numberInput("respawnDelaySeconds", config.respawnDelaySeconds ?? 0, 0, 86_400)),946
field("Respawn delay (seconds)", numberInput("respawnDelaySeconds", config.respawnDelaySeconds ?? 25, 0, 86_400)),947
field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)),947
field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)),948
field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)),948
field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)),949
field("Spawner id", textInput("spawnerId", config.spawnerId, true))949
field("Spawner id", textInput("spawnerId", config.spawnerId, true))@@ -1110,7 +1110,7 @@ export function initTileConfigModal ({1110
onSave?.(context, normalizeSpawnerConfig({1110
onSave?.(context, normalizeSpawnerConfig({1111
mobTypeId: String(data.get("mobTypeId") || "deer"),1111
mobTypeId: String(data.get("mobTypeId") || "deer"),1112
maxAlive: Number(data.get("maxAlive") || 3),1112
maxAlive: Number(data.get("maxAlive") || 3),1113
respawnDelaySeconds: Number(data.get("respawnDelaySeconds") || 0),1113
respawnDelaySeconds: Number(data.get("respawnDelaySeconds") ?? 25),1114
spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4),1114
spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4),1115
maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4),1115
maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4),1116
level: Number(data.get("level") || 1),1116
level: Number(data.get("level") || 1),@@ -827,6 +827,8 @@ function handleLeftClick (mouseX, mouseY)
827
827
{ requestFish(tile.tileX, tile.tileY); }
828
828
else if (isAnvilTile(view, tile.tileX, tile.tileY))
829
829
{ requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }
830
else if (isJeweleringStationTile(view, tile.tileX, tile.tileY))
831
{ requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY); }
830
832
else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
831
833
{ requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }
832
834
else if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
@@ -1029,6 +1031,14 @@ function handleRightClick (event, mouseX, mouseY)
1029
1031
});
1030
1032
}
1031
1033
1034
if (isJeweleringStationTile(view, tile.tileX, tile.tileY))
1035
{
1036
items.push({
1037
label: "Jewel",
1038
onSelect: () => requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY)
1039
});
1040
}
1041
1032
1042
if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
1033
1043
{
1034
1044
items.push({
@@ -1252,8 +1262,13 @@ function startPlay (payload)
1252
1262
payload.characterId,
1253
1263
payload.layers,
1254
1264
payload.health,
1255
payload.maxHealth
1265
payload.maxHealth,
1266
payload.skullValue
1256
1267
);
1268
social?.setLocalIdentity?.({
1269
accountId: payload.accountId,
1270
characterId: payload.characterId
1271
});
1257
1272
graphicsSettingsUi?.apply();
1258
1273
}
1259
1274
@@ -1325,7 +1340,11 @@ async function main ()
1325
1340
});
1326
1341
social = initSocial({
1327
1342
socket: { send (payload) { socket.send(payload); } },
1328
MessageType
1343
MessageType,
1344
resolveSpriteUrl (name)
1345
{
1346
return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1347
}
1329
1348
});
1330
1349
contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick });
1331
1350
inventory = initInventory({
@@ -1543,6 +1562,9 @@ async function main ()
1543
1562
case MessageType.entityAppearance:
1544
1563
view?.setAppearance(message);
1545
1564
break;
1565
case MessageType.entitySkull:
1566
view?.updateEntitySkull(message.entityId, message.skullValue);
1567
break;
1546
1568
case MessageType.groundItemAppear:
1547
1569
view?.upsertGroundItem(message);
1548
1570
break;
@@ -2047,6 +2069,11 @@ function isAnvilTile (view, tileX, tileY)
2047
2069
return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
2048
2070
}
2049
2071
2072
function isJeweleringStationTile (view, tileX, tileY)
2073
{
2074
return blockTypeAt(view, tileX, tileY) === BlockType.jeweleringStation;
2075
}
2076
2050
2077
function isGroundWoodLog (ground)
2051
2078
{
2052
2079
const def = itemDefinition(ground?.itemId ?? ground?.stack?.itemId);
@@ -2143,7 +2170,11 @@ function updateSpellTargetHighlight ()
2143
2170
function hideWorldTooltip ()
2144
2171
{
2145
2172
if (worldTooltip)
2146
{ worldTooltip.hidden = true; }
2173
{
2174
worldTooltip.hidden = true;
2175
worldTooltip.classList.remove("friend-name");
2176
worldTooltip.style.color = "";
2177
}
2147
2178
}
2148
2179
2149
2180
/** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */
@@ -2169,6 +2200,9 @@ function updateWorldTooltip ()
2169
2200
const label = entityLabel(entity);
2170
2201
worldTooltip.hidden = false;
2171
2202
worldTooltip.textContent = label;
2203
const friend = entity.characterId && social?.isFriendCharacter?.(entity.characterId, entity.accountId);
2204
worldTooltip.classList.toggle("friend-name", !!friend);
2205
worldTooltip.style.color = friend ? "#e8c84a" : "";
2172
2206
worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
2173
2207
worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
2174
2208
return;
@@ -827,6 +827,8 @@ function handleLeftClick (mouseX, mouseY)827
{ requestFish(tile.tileX, tile.tileY); }827
{ requestFish(tile.tileX, tile.tileY); }828
else if (isAnvilTile(view, tile.tileX, tile.tileY))828
else if (isAnvilTile(view, tile.tileX, tile.tileY))829
{ requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }829
{ requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }830
else if (isJeweleringStationTile(view, tile.tileX, tile.tileY))831
{ requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY); }830
else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))832
else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))831
{ requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }833
{ requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }832
else if (isCraftingBenchTile(view, tile.tileX, tile.tileY))834
else if (isCraftingBenchTile(view, tile.tileX, tile.tileY))@@ -1029,6 +1031,14 @@ function handleRightClick (event, mouseX, mouseY)1029
});1031
});1030
}1032
}1031
1033
1034
if (isJeweleringStationTile(view, tile.tileX, tile.tileY))1035
{1036
items.push({1037
label: "Jewel",1038
onSelect: () => requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY)1039
});1040
}1041
1032
if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))1042
if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))1033
{1043
{1034
items.push({1044
items.push({@@ -1252,8 +1262,13 @@ function startPlay (payload)1252
payload.characterId,1262
payload.characterId,1253
payload.layers,1263
payload.layers,1254
payload.health,1264
payload.health,1255
payload.maxHealth1265
payload.maxHealth,1266
payload.skullValue1256
);1267
);1268
social?.setLocalIdentity?.({1269
accountId: payload.accountId,1270
characterId: payload.characterId1271
});1257
graphicsSettingsUi?.apply();1272
graphicsSettingsUi?.apply();1258
}1273
}1259
1274
@@ -1325,7 +1340,11 @@ async function main ()1325
});1340
});1326
social = initSocial({1341
social = initSocial({1327
socket: { send (payload) { socket.send(payload); } },1342
socket: { send (payload) { socket.send(payload); } },1328
MessageType1343
MessageType,1344
resolveSpriteUrl (name)1345
{1346
return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;1347
}1329
});1348
});1330
contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick });1349
contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick });1331
inventory = initInventory({1350
inventory = initInventory({@@ -1543,6 +1562,9 @@ async function main ()1543
case MessageType.entityAppearance:1562
case MessageType.entityAppearance:1544
view?.setAppearance(message);1563
view?.setAppearance(message);1545
break;1564
break;1565
case MessageType.entitySkull:1566
view?.updateEntitySkull(message.entityId, message.skullValue);1567
break;1546
case MessageType.groundItemAppear:1568
case MessageType.groundItemAppear:1547
view?.upsertGroundItem(message);1569
view?.upsertGroundItem(message);1548
break;1570
break;@@ -2047,6 +2069,11 @@ function isAnvilTile (view, tileX, tileY)2047
return blockTypeAt(view, tileX, tileY) === BlockType.anvil;2069
return blockTypeAt(view, tileX, tileY) === BlockType.anvil;2048
}2070
}2049
2071
2072
function isJeweleringStationTile (view, tileX, tileY)2073
{2074
return blockTypeAt(view, tileX, tileY) === BlockType.jeweleringStation;2075
}2076
2050
function isGroundWoodLog (ground)2077
function isGroundWoodLog (ground)2051
{2078
{2052
const def = itemDefinition(ground?.itemId ?? ground?.stack?.itemId);2079
const def = itemDefinition(ground?.itemId ?? ground?.stack?.itemId);@@ -2143,7 +2170,11 @@ function updateSpellTargetHighlight ()2143
function hideWorldTooltip ()2170
function hideWorldTooltip ()2144
{2171
{2145
if (worldTooltip)2172
if (worldTooltip)2146
{ worldTooltip.hidden = true; }2173
{2174
worldTooltip.hidden = true;2175
worldTooltip.classList.remove("friend-name");2176
worldTooltip.style.color = "";2177
}2147
}2178
}2148
2179
2149
/** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */2180
/** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */@@ -2169,6 +2200,9 @@ function updateWorldTooltip ()2169
const label = entityLabel(entity);2200
const label = entityLabel(entity);2170
worldTooltip.hidden = false;2201
worldTooltip.hidden = false;2171
worldTooltip.textContent = label;2202
worldTooltip.textContent = label;2203
const friend = entity.characterId && social?.isFriendCharacter?.(entity.characterId, entity.accountId);2204
worldTooltip.classList.toggle("friend-name", !!friend);2205
worldTooltip.style.color = friend ? "#e8c84a" : "";2172
worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;2206
worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;2173
worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;2207
worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;2174
return;2208
return;@@ -1,4 +1,6 @@
1
export function initSocial ({ socket, MessageType })
1
const FRIEND_NAME_COLOR = "#e8c84a";
2
3
export function initSocial ({ socket, MessageType, resolveSpriteUrl = null })
2
4
{
3
5
const nametag = document.getElementById("nametag");
4
6
const inspect = document.getElementById("inspect-modal");
@@ -14,6 +16,10 @@ export function initSocial ({ socket, MessageType })
14
16
let social = { friends: [], incoming: [], outgoing: [] };
15
17
let inspected = null;
16
18
let open = false;
19
/** @type {number|null} expanded friend account in the panel */
20
let expandedAccountId = null;
21
let localAccountId = null;
22
let localCharacterId = null;
17
23
18
24
document.getElementById("inspect-close").addEventListener("click", () => hideInspect());
19
25
inspectBackdrop.addEventListener("click", () => hideInspect());
@@ -36,46 +42,91 @@ export function initSocial ({ socket, MessageType })
36
42
}
37
43
}
38
44
45
function friendAccountOfCharacter (characterId)
46
{
47
const id = characterId | 0;
48
for (const account of social.friends ?? [])
49
{
50
if ((account.characters ?? []).some((entry) => entry.characterId === id))
51
{ return account; }
52
}
53
return null;
54
}
55
56
function isFriendCharacter (characterId, accountId = null)
57
{
58
const id = characterId | 0;
59
if (!id)
60
{ return false; }
61
if (localAccountId && accountId && (accountId | 0) === (localAccountId | 0) && id !== (localCharacterId | 0))
62
{ return true; }
63
return !!friendAccountOfCharacter(id);
64
}
65
39
66
function relation (characterId)
40
67
{
41
if (social.friends.some((entry) => entry.characterId === characterId))
68
if (isFriendCharacter(characterId))
42
69
{ return "friends"; }
43
if (social.incoming.some((entry) => entry.characterId === characterId))
70
const account = accountHoldingCharacter(characterId, social.incoming);
71
if (account)
44
72
{ return "incoming"; }
45
if (social.outgoing.some((entry) => entry.characterId === characterId))
73
if (accountHoldingCharacter(characterId, social.outgoing))
46
74
{ return "outgoing"; }
47
75
return "none";
48
76
}
49
77
78
function accountHoldingCharacter (characterId, accounts)
79
{
80
const id = characterId | 0;
81
return (accounts ?? []).find((account) =>
82
(account.characters ?? []).some((entry) => entry.characterId === id)) ?? null;
83
}
84
50
85
function renderInspect ()
51
86
{
52
87
if (!inspected)
53
88
{ return; }
54
89
inspectName.textContent = `${inspected.firstName} ${inspected.lastName}`;
90
inspectName.style.color = isFriendCharacter(inspected.characterId, inspected.accountId) ? FRIEND_NAME_COLOR : "";
55
91
inspectAction.replaceChildren();
56
92
const status = relation(inspected.characterId);
93
const friendAccount = friendAccountOfCharacter(inspected.characterId);
57
94
if (status === "friends")
58
95
{
59
96
inspectAction.append(actionButton("Remove friend", () =>
60
97
{
61
socket.send({ type: MessageType.friendRemove, characterId: inspected.characterId });
98
socket.send({
99
type: MessageType.friendRemove,
100
accountId: friendAccount?.accountId,
101
characterId: inspected.characterId
102
});
62
103
}));
63
104
}
64
105
else if (status === "incoming")
65
106
{
107
const incoming = accountHoldingCharacter(inspected.characterId, social.incoming);
66
108
inspectAction.append(
67
109
actionButton("Accept friend request", () =>
68
110
{
69
socket.send({ type: MessageType.friendAccept, characterId: inspected.characterId });
111
socket.send({
112
type: MessageType.friendAccept,
113
accountId: incoming?.accountId,
114
characterId: inspected.characterId
115
});
70
116
}),
71
117
actionButton("Decline", () =>
72
118
{
73
socket.send({ type: MessageType.friendDecline, characterId: inspected.characterId });
119
socket.send({
120
type: MessageType.friendDecline,
121
accountId: incoming?.accountId,
122
characterId: inspected.characterId
123
});
74
124
})
75
125
);
76
126
}
77
127
else if (status === "outgoing")
78
128
{
129
const outgoing = accountHoldingCharacter(inspected.characterId, social.outgoing);
79
130
const pending = document.createElement("p");
80
131
pending.className = "hint";
81
132
pending.textContent = "Friend request sent.";
@@ -83,7 +134,11 @@ export function initSocial ({ socket, MessageType })
83
134
pending,
84
135
actionButton("Cancel request", () =>
85
136
{
86
socket.send({ type: MessageType.friendDecline, characterId: inspected.characterId });
137
socket.send({
138
type: MessageType.friendDecline,
139
accountId: outgoing?.accountId,
140
characterId: inspected.characterId
141
});
87
142
})
88
143
);
89
144
}
@@ -98,39 +153,109 @@ export function initSocial ({ socket, MessageType })
98
153
99
154
function renderLists ()
100
155
{
101
fillList(friendsList, social.friends, "No friends yet.", (entry) =>
156
fillList(friendsList, social.friends, "No friends yet.", (account) => accountRow(account, {
157
expanded: expandedAccountId === account.accountId,
158
onToggle ()
159
{
160
expandedAccountId = expandedAccountId === account.accountId ? null : account.accountId;
161
renderLists();
162
},
163
onRemove ()
164
{
165
socket.send({ type: MessageType.friendRemove, accountId: account.accountId });
166
}
167
}));
168
fillList(incomingList, social.incoming, "No incoming requests.", (account) => accountRequestRow(account, {
169
onAccept ()
170
{
171
socket.send({ type: MessageType.friendAccept, accountId: account.accountId });
172
},
173
onDecline ()
174
{
175
socket.send({ type: MessageType.friendDecline, accountId: account.accountId });
176
}
177
}));
178
fillList(outgoingList, social.outgoing, "No outgoing requests.", (account) => accountRequestRow(account, {
179
onDecline ()
180
{
181
socket.send({ type: MessageType.friendDecline, accountId: account.accountId });
182
},
183
declineLabel: "Cancel"
184
}));
185
}
186
187
function accountRow (account, { expanded, onToggle, onRemove })
188
{
189
const wrap = document.createElement("div");
190
wrap.className = "friend-account";
191
const header = document.createElement("div");
192
header.className = "social-row friend-account-header";
193
const nameBtn = document.createElement("button");
194
nameBtn.type = "button";
195
nameBtn.className = "friend-account-name";
196
nameBtn.textContent = account.username || `Account ${account.accountId}`;
197
nameBtn.addEventListener("click", onToggle);
198
header.append(nameBtn, actionButton("Remove", onRemove));
199
wrap.append(header);
200
if (expanded)
102
201
{
103
const row = namedRow(entry);
104
row.append(actionButton("Remove", () =>
202
const list = document.createElement("div");
203
list.className = "friend-character-list";
204
for (const character of account.characters ?? [])
205
{ list.append(characterPreviewRow(character)); }
206
if (!(account.characters ?? []).length)
105
207
{
106
socket.send({ type: MessageType.friendRemove, characterId: entry.characterId });
107
}));
108
return row;
109
});
110
fillList(incomingList, social.incoming, "No incoming requests.", (entry) =>
208
const empty = document.createElement("p");
209
empty.className = "hint";
210
empty.textContent = "No characters.";
211
list.append(empty);
212
}
213
wrap.append(list);
214
}
215
return wrap;
216
}
217
218
function accountRequestRow (account, { onAccept = null, onDecline, declineLabel = "Decline" })
219
{
220
const row = document.createElement("div");
221
row.className = "social-row";
222
const name = document.createElement("span");
223
name.textContent = account.username || `Account ${account.accountId}`;
224
row.append(name);
225
if (onAccept)
226
{ row.append(actionButton("Accept", onAccept)); }
227
row.append(actionButton(declineLabel, onDecline));
228
return row;
229
}
230
231
function characterPreviewRow (entry)
232
{
233
const row = document.createElement("div");
234
row.className = "friend-character-row";
235
row.append(characterPreview(entry.layers), (() =>
111
236
{
112
const row = namedRow(entry);
113
row.append(
114
actionButton("Accept", () =>
115
{
116
socket.send({ type: MessageType.friendAccept, characterId: entry.characterId });
117
}),
118
actionButton("Decline", () =>
119
{
120
socket.send({ type: MessageType.friendDecline, characterId: entry.characterId });
121
})
122
);
123
return row;
124
});
125
fillList(outgoingList, social.outgoing, "No outgoing requests.", (entry) =>
237
const name = document.createElement("span");
238
name.textContent = `${entry.firstName} ${entry.lastName}`.trim();
239
return name;
240
})());
241
return row;
242
}
243
244
function characterPreview (layers)
245
{
246
const wrap = document.createElement("div");
247
wrap.className = "char-preview friend-char-preview";
248
for (const layer of layers ?? [])
126
249
{
127
const row = namedRow(entry);
128
row.append(actionButton("Cancel", () =>
129
{
130
socket.send({ type: MessageType.friendDecline, characterId: entry.characterId });
131
}));
132
return row;
133
});
250
const url = resolveSpriteUrl?.(layer.sprite);
251
if (!url)
252
{ continue; }
253
const img = document.createElement("img");
254
img.src = url;
255
img.alt = "";
256
wrap.append(img);
257
}
258
return wrap;
134
259
}
135
260
136
261
return {
@@ -158,13 +283,31 @@ export function initSocial ({ socket, MessageType })
158
283
incoming: message.incoming ?? [],
159
284
outgoing: message.outgoing ?? []
160
285
};
286
if (
287
expandedAccountId != null
288
&& !(social.friends ?? []).some((account) => account.accountId === expandedAccountId)
289
)
290
{ expandedAccountId = null; }
161
291
renderLists();
162
292
if (open)
163
293
{ renderInspect(); }
164
294
},
295
/** Flat character list for pigeon send targets. */
165
296
getFriends ()
166
297
{
167
return social.friends ?? [];
298
const out = [];
299
for (const account of social.friends ?? [])
300
{
301
for (const character of account.characters ?? [])
302
{ out.push(character); }
303
}
304
return out;
305
},
306
isFriendCharacter,
307
setLocalIdentity ({ accountId = null, characterId = null } = {})
308
{
309
localAccountId = accountId | 0 || null;
310
localCharacterId = characterId | 0 || null;
168
311
},
169
312
inspect (entity)
170
313
{
@@ -172,6 +315,7 @@ export function initSocial ({ socket, MessageType })
172
315
{ return; }
173
316
inspected = {
174
317
characterId: entity.characterId,
318
accountId: entity.accountId ?? null,
175
319
firstName: entity.firstName ?? "",
176
320
lastName: entity.lastName ?? ""
177
321
};
@@ -240,6 +384,9 @@ export function initSocial ({ socket, MessageType })
240
384
}
241
385
nametag.hidden = false;
242
386
nametag.textContent = entity.firstName;
387
const friend = entity.characterId && isFriendCharacter(entity.characterId, entity.accountId);
388
nametag.classList.toggle("friend-name", !!friend);
389
nametag.style.color = friend ? FRIEND_NAME_COLOR : "";
243
390
nametag.style.left = `${rect.left + anchor.x}px`;
244
391
nametag.style.top = `${rect.top + anchor.y - 6}px`;
245
392
canvas.style.cursor = "pointer";
@@ -252,16 +399,6 @@ export function initSocial ({ socket, MessageType })
252
399
};
253
400
}
254
401
255
function namedRow (entry)
256
{
257
const row = document.createElement("div");
258
row.className = "social-row";
259
const name = document.createElement("span");
260
name.textContent = `${entry.firstName} ${entry.lastName}`;
261
row.append(name);
262
return row;
263
}
264
265
402
function fillList (root, entries, emptyText, renderRow)
266
403
{
267
404
root.replaceChildren();
@@ -1,4 +1,6 @@1
export function initSocial ({ socket, MessageType })1
const FRIEND_NAME_COLOR = "#e8c84a";2
3
export function initSocial ({ socket, MessageType, resolveSpriteUrl = null })2
{4
{3
const nametag = document.getElementById("nametag");5
const nametag = document.getElementById("nametag");4
const inspect = document.getElementById("inspect-modal");6
const inspect = document.getElementById("inspect-modal");@@ -14,6 +16,10 @@ export function initSocial ({ socket, MessageType })14
let social = { friends: [], incoming: [], outgoing: [] };16
let social = { friends: [], incoming: [], outgoing: [] };15
let inspected = null;17
let inspected = null;16
let open = false;18
let open = false;19
/** @type {number|null} expanded friend account in the panel */20
let expandedAccountId = null;21
let localAccountId = null;22
let localCharacterId = null;17
23
18
document.getElementById("inspect-close").addEventListener("click", () => hideInspect());24
document.getElementById("inspect-close").addEventListener("click", () => hideInspect());19
inspectBackdrop.addEventListener("click", () => hideInspect());25
inspectBackdrop.addEventListener("click", () => hideInspect());@@ -36,46 +42,91 @@ export function initSocial ({ socket, MessageType })36
}42
}37
}43
}38
44
45
function friendAccountOfCharacter (characterId)46
{47
const id = characterId | 0;48
for (const account of social.friends ?? [])49
{50
if ((account.characters ?? []).some((entry) => entry.characterId === id))51
{ return account; }52
}53
return null;54
}55
56
function isFriendCharacter (characterId, accountId = null)57
{58
const id = characterId | 0;59
if (!id)60
{ return false; }61
if (localAccountId && accountId && (accountId | 0) === (localAccountId | 0) && id !== (localCharacterId | 0))62
{ return true; }63
return !!friendAccountOfCharacter(id);64
}65
39
function relation (characterId)66
function relation (characterId)40
{67
{41
if (social.friends.some((entry) => entry.characterId === characterId))68
if (isFriendCharacter(characterId))42
{ return "friends"; }69
{ return "friends"; }43
if (social.incoming.some((entry) => entry.characterId === characterId))70
const account = accountHoldingCharacter(characterId, social.incoming);71
if (account)44
{ return "incoming"; }72
{ return "incoming"; }45
if (social.outgoing.some((entry) => entry.characterId === characterId))73
if (accountHoldingCharacter(characterId, social.outgoing))46
{ return "outgoing"; }74
{ return "outgoing"; }47
return "none";75
return "none";48
}76
}49
77
78
function accountHoldingCharacter (characterId, accounts)79
{80
const id = characterId | 0;81
return (accounts ?? []).find((account) =>82
(account.characters ?? []).some((entry) => entry.characterId === id)) ?? null;83
}84
50
function renderInspect ()85
function renderInspect ()51
{86
{52
if (!inspected)87
if (!inspected)53
{ return; }88
{ return; }54
inspectName.textContent = `${inspected.firstName} ${inspected.lastName}`;89
inspectName.textContent = `${inspected.firstName} ${inspected.lastName}`;90
inspectName.style.color = isFriendCharacter(inspected.characterId, inspected.accountId) ? FRIEND_NAME_COLOR : "";55
inspectAction.replaceChildren();91
inspectAction.replaceChildren();56
const status = relation(inspected.characterId);92
const status = relation(inspected.characterId);93
const friendAccount = friendAccountOfCharacter(inspected.characterId);57
if (status === "friends")94
if (status === "friends")58
{95
{59
inspectAction.append(actionButton("Remove friend", () =>96
inspectAction.append(actionButton("Remove friend", () =>60
{97
{61
socket.send({ type: MessageType.friendRemove, characterId: inspected.characterId });98
socket.send({99
type: MessageType.friendRemove,100
accountId: friendAccount?.accountId,101
characterId: inspected.characterId102
});62
}));103
}));63
}104
}64
else if (status === "incoming")105
else if (status === "incoming")65
{106
{107
const incoming = accountHoldingCharacter(inspected.characterId, social.incoming);66
inspectAction.append(108
inspectAction.append(67
actionButton("Accept friend request", () =>109
actionButton("Accept friend request", () =>68
{110
{69
socket.send({ type: MessageType.friendAccept, characterId: inspected.characterId });111
socket.send({112
type: MessageType.friendAccept,113
accountId: incoming?.accountId,114
characterId: inspected.characterId115
});70
}),116
}),71
actionButton("Decline", () =>117
actionButton("Decline", () =>72
{118
{73
socket.send({ type: MessageType.friendDecline, characterId: inspected.characterId });119
socket.send({120
type: MessageType.friendDecline,121
accountId: incoming?.accountId,122
characterId: inspected.characterId123
});74
})124
})75
);125
);76
}126
}77
else if (status === "outgoing")127
else if (status === "outgoing")78
{128
{129
const outgoing = accountHoldingCharacter(inspected.characterId, social.outgoing);79
const pending = document.createElement("p");130
const pending = document.createElement("p");80
pending.className = "hint";131
pending.className = "hint";81
pending.textContent = "Friend request sent.";132
pending.textContent = "Friend request sent.";@@ -83,7 +134,11 @@ export function initSocial ({ socket, MessageType })83
pending,134
pending,84
actionButton("Cancel request", () =>135
actionButton("Cancel request", () =>85
{136
{86
socket.send({ type: MessageType.friendDecline, characterId: inspected.characterId });137
socket.send({138
type: MessageType.friendDecline,139
accountId: outgoing?.accountId,140
characterId: inspected.characterId141
});87
})142
})88
);143
);89
}144
}@@ -98,39 +153,109 @@ export function initSocial ({ socket, MessageType })98
153
99
function renderLists ()154
function renderLists ()100
{155
{101
fillList(friendsList, social.friends, "No friends yet.", (entry) =>156
fillList(friendsList, social.friends, "No friends yet.", (account) => accountRow(account, {157
expanded: expandedAccountId === account.accountId,158
onToggle ()159
{160
expandedAccountId = expandedAccountId === account.accountId ? null : account.accountId;161
renderLists();162
},163
onRemove ()164
{165
socket.send({ type: MessageType.friendRemove, accountId: account.accountId });166
}167
}));168
fillList(incomingList, social.incoming, "No incoming requests.", (account) => accountRequestRow(account, {169
onAccept ()170
{171
socket.send({ type: MessageType.friendAccept, accountId: account.accountId });172
},173
onDecline ()174
{175
socket.send({ type: MessageType.friendDecline, accountId: account.accountId });176
}177
}));178
fillList(outgoingList, social.outgoing, "No outgoing requests.", (account) => accountRequestRow(account, {179
onDecline ()180
{181
socket.send({ type: MessageType.friendDecline, accountId: account.accountId });182
},183
declineLabel: "Cancel"184
}));185
}186
187
function accountRow (account, { expanded, onToggle, onRemove })188
{189
const wrap = document.createElement("div");190
wrap.className = "friend-account";191
const header = document.createElement("div");192
header.className = "social-row friend-account-header";193
const nameBtn = document.createElement("button");194
nameBtn.type = "button";195
nameBtn.className = "friend-account-name";196
nameBtn.textContent = account.username || `Account ${account.accountId}`;197
nameBtn.addEventListener("click", onToggle);198
header.append(nameBtn, actionButton("Remove", onRemove));199
wrap.append(header);200
if (expanded)102
{201
{103
const row = namedRow(entry);202
const list = document.createElement("div");104
row.append(actionButton("Remove", () =>203
list.className = "friend-character-list";204
for (const character of account.characters ?? [])205
{ list.append(characterPreviewRow(character)); }206
if (!(account.characters ?? []).length)105
{207
{106
socket.send({ type: MessageType.friendRemove, characterId: entry.characterId });208
const empty = document.createElement("p");107
}));209
empty.className = "hint";108
return row;210
empty.textContent = "No characters.";109
});211
list.append(empty);110
fillList(incomingList, social.incoming, "No incoming requests.", (entry) =>212
}213
wrap.append(list);214
}215
return wrap;216
}217
218
function accountRequestRow (account, { onAccept = null, onDecline, declineLabel = "Decline" })219
{220
const row = document.createElement("div");221
row.className = "social-row";222
const name = document.createElement("span");223
name.textContent = account.username || `Account ${account.accountId}`;224
row.append(name);225
if (onAccept)226
{ row.append(actionButton("Accept", onAccept)); }227
row.append(actionButton(declineLabel, onDecline));228
return row;229
}230
231
function characterPreviewRow (entry)232
{233
const row = document.createElement("div");234
row.className = "friend-character-row";235
row.append(characterPreview(entry.layers), (() =>111
{236
{112
const row = namedRow(entry);237
const name = document.createElement("span");113
row.append(238
name.textContent = `${entry.firstName} ${entry.lastName}`.trim();114
actionButton("Accept", () =>239
return name;115
{240
})());116
socket.send({ type: MessageType.friendAccept, characterId: entry.characterId });241
return row;117
}),242
}118
actionButton("Decline", () =>243
119
{244
function characterPreview (layers)120
socket.send({ type: MessageType.friendDecline, characterId: entry.characterId });245
{121
})246
const wrap = document.createElement("div");122
);247
wrap.className = "char-preview friend-char-preview";123
return row;248
for (const layer of layers ?? [])124
});125
fillList(outgoingList, social.outgoing, "No outgoing requests.", (entry) =>126
{249
{127
const row = namedRow(entry);250
const url = resolveSpriteUrl?.(layer.sprite);128
row.append(actionButton("Cancel", () =>251
if (!url)129
{252
{ continue; }130
socket.send({ type: MessageType.friendDecline, characterId: entry.characterId });253
const img = document.createElement("img");131
}));254
img.src = url;132
return row;255
img.alt = "";133
});256
wrap.append(img);257
}258
return wrap;134
}259
}135
260
136
return {261
return {@@ -158,13 +283,31 @@ export function initSocial ({ socket, MessageType })158
incoming: message.incoming ?? [],283
incoming: message.incoming ?? [],159
outgoing: message.outgoing ?? []284
outgoing: message.outgoing ?? []160
};285
};286
if (287
expandedAccountId != null288
&& !(social.friends ?? []).some((account) => account.accountId === expandedAccountId)289
)290
{ expandedAccountId = null; }161
renderLists();291
renderLists();162
if (open)292
if (open)163
{ renderInspect(); }293
{ renderInspect(); }164
},294
},295
/** Flat character list for pigeon send targets. */165
getFriends ()296
getFriends ()166
{297
{167
return social.friends ?? [];298
const out = [];299
for (const account of social.friends ?? [])300
{301
for (const character of account.characters ?? [])302
{ out.push(character); }303
}304
return out;305
},306
isFriendCharacter,307
setLocalIdentity ({ accountId = null, characterId = null } = {})308
{309
localAccountId = accountId | 0 || null;310
localCharacterId = characterId | 0 || null;168
},311
},169
inspect (entity)312
inspect (entity)170
{313
{@@ -172,6 +315,7 @@ export function initSocial ({ socket, MessageType })172
{ return; }315
{ return; }173
inspected = {316
inspected = {174
characterId: entity.characterId,317
characterId: entity.characterId,318
accountId: entity.accountId ?? null,175
firstName: entity.firstName ?? "",319
firstName: entity.firstName ?? "",176
lastName: entity.lastName ?? ""320
lastName: entity.lastName ?? ""177
};321
};@@ -240,6 +384,9 @@ export function initSocial ({ socket, MessageType })240
}384
}241
nametag.hidden = false;385
nametag.hidden = false;242
nametag.textContent = entity.firstName;386
nametag.textContent = entity.firstName;387
const friend = entity.characterId && isFriendCharacter(entity.characterId, entity.accountId);388
nametag.classList.toggle("friend-name", !!friend);389
nametag.style.color = friend ? FRIEND_NAME_COLOR : "";243
nametag.style.left = `${rect.left + anchor.x}px`;390
nametag.style.left = `${rect.left + anchor.x}px`;244
nametag.style.top = `${rect.top + anchor.y - 6}px`;391
nametag.style.top = `${rect.top + anchor.y - 6}px`;245
canvas.style.cursor = "pointer";392
canvas.style.cursor = "pointer";@@ -252,16 +399,6 @@ export function initSocial ({ socket, MessageType })252
};399
};253
}400
}254
401
255
function namedRow (entry)256
{257
const row = document.createElement("div");258
row.className = "social-row";259
const name = document.createElement("span");260
name.textContent = `${entry.firstName} ${entry.lastName}`;261
row.append(name);262
return row;263
}264
265
function fillList (root, entries, emptyText, renderRow)402
function fillList (root, entries, emptyText, renderRow)266
{403
{267
root.replaceChildren();404
root.replaceChildren();@@ -26,6 +26,7 @@ import
26
26
resolveDimensionSeasonId
27
27
} from "/shared/world/dimensions.js";
28
28
import { SPELL_PROJECTILE_FRAME_MS } from "/shared/spells/constants.js";
29
import { skullTintColor } from "/shared/combat/skull.js";
29
30
30
31
const LAYER_GROUND = 0;
31
32
const LAYER_EDGE = 900000;
@@ -34,6 +35,7 @@ const SORT_ENTITY = 3;
34
35
const SORT_HP_BAR = 4;
35
36
const SORT_FX = 5;
36
37
const RENDER_LAYER_BLOOM = "bloom";
38
const SKULL_SPRITE = "fx:skull:skull";
37
39
38
40
const HP_BAR_W = 14;
39
41
const HP_BAR_H = 4;
@@ -581,7 +583,7 @@ export class WorldView
581
583
this.#scheduleEdgeRebuild();
582
584
}
583
585
584
setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null)
586
setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null, skullValue = 0)
585
587
{
586
588
this.localEntityId = entityId;
587
589
this.#upsertEntity({
@@ -594,6 +596,7 @@ export class WorldView
594
596
firstName,
595
597
lastName,
596
598
layers: layers ?? undefined,
599
skullValue: skullValue | 0,
597
600
...(health != null ? { health } : {}),
598
601
...(maxHealth != null ? { maxHealth } : {})
599
602
});
@@ -717,6 +720,7 @@ export class WorldView
717
720
{ return; }
718
721
existing.object?.destroy();
719
722
existing.hpBar?.destroy();
723
existing.skullMarker?.destroy();
720
724
for (const overlay of existing.overlays ?? [])
721
725
{ overlay.destroy(); }
722
726
for (const overlay of existing.bloomOverlays ?? [])
@@ -724,6 +728,15 @@ export class WorldView
724
728
this.entities.delete(entityId);
725
729
}
726
730
731
updateEntitySkull (entityId, skullValue)
732
{
733
const entity = this.entities.get(entityId);
734
if (!entity)
735
{ return; }
736
entity.skullValue = Math.max(0, skullValue | 0);
737
this.#syncSkullMarker(entity);
738
}
739
727
740
updateEntityHealth (entityId, health, maxHealth)
728
741
{
729
742
const entity = this.entities.get(entityId);
@@ -1946,6 +1959,7 @@ export class WorldView
1946
1959
entity.gait = payload.gait;
1947
1960
entity.sex = payload.sex ?? entity.sex;
1948
1961
entity.characterId = payload.characterId ?? entity.characterId ?? null;
1962
entity.accountId = payload.accountId ?? entity.accountId ?? null;
1949
1963
entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
1950
1964
if (payload.level != null)
1951
1965
{ entity.level = payload.level | 0; }
@@ -1967,6 +1981,10 @@ export class WorldView
1967
1981
{ entity.health = payload.health; }
1968
1982
if (payload.maxHealth != null)
1969
1983
{ entity.maxHealth = payload.maxHealth; }
1984
if (payload.skullValue != null)
1985
{ entity.skullValue = Math.max(0, payload.skullValue | 0); }
1986
else if (entity.skullValue == null)
1987
{ entity.skullValue = 0; }
1970
1988
if (payload.firstName)
1971
1989
{ entity.firstName = payload.firstName; }
1972
1990
if (payload.lastName)
@@ -1994,6 +2012,7 @@ export class WorldView
1994
2012
if (payload.layers)
1995
2013
{ this.#applyLayers(entity, payload.layers); }
1996
2014
this.#syncHpBar(entity);
2015
this.#syncSkullMarker(entity);
1997
2016
this.#placeEntity(entity, performance.now());
1998
2017
}
1999
2018
@@ -2163,6 +2182,7 @@ export class WorldView
2163
2182
this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1);
2164
2183
}
2165
2184
this.#placeHpBar(entity, pivotX, pivotY);
2185
this.#placeSkullMarker(entity, pivotX, pivotY, tileShade);
2166
2186
}
2167
2187
2168
2188
#markUnlit (object)
@@ -2517,6 +2537,61 @@ export class WorldView
2517
2537
this.#markSortDirty();
2518
2538
}
2519
2539
2540
#syncSkullMarker (entity)
2541
{
2542
if (!entity?.characterId)
2543
{
2544
entity.skullMarker?.destroy();
2545
entity.skullMarker = null;
2546
return;
2547
}
2548
const tint = skullTintColor(entity.skullValue | 0);
2549
if (!tint)
2550
{
2551
entity.skullMarker?.destroy();
2552
entity.skullMarker = null;
2553
return;
2554
}
2555
const image = this.game.images[SKULL_SPRITE];
2556
if (!image)
2557
{ return; }
2558
if (!entity.skullMarker)
2559
{
2560
entity.skullMarker = new GameObject(0, 0, image, SORT_HP_BAR);
2561
this.scene.addObject(entity.skullMarker);
2562
}
2563
entity.skullTint = tint;
2564
entity.skullMarker.renderer.sprite = image;
2565
}
2566
2567
/**
2568
* Bottom edge of the skull sprite sits exactly on the character sprite's top edge.
2569
*/
2570
#placeSkullMarker (entity, pivotX, pivotY, darkness)
2571
{
2572
this.#syncSkullMarker(entity);
2573
if (!entity.skullMarker)
2574
{ return; }
2575
const body = entity.object?.renderer?.sprite;
2576
const skull = entity.skullMarker.renderer?.sprite;
2577
if (!body || !skull)
2578
{ return; }
2579
const zoom = this.zoom;
2580
const scale = entity.visualScale ?? 1;
2581
const bodyH = body.height * zoom * scale;
2582
const skullH = skull.height * zoom;
2583
const skullW = skull.width * zoom;
2584
const bodyCenterY = pivotY - (bodyH / 2 - PIVOT_FROM_BOTTOM_PX * zoom * scale);
2585
const bodyTop = bodyCenterY - bodyH / 2;
2586
// GameObject position is sprite center; bottom of skull at bodyTop ⇒ center at bodyTop - skullH/2
2587
entity.skullMarker.transform.position.x = pivotX;
2588
entity.skullMarker.transform.position.y = bodyTop - skullH / 2;
2589
entity.skullMarker.transform.size = new vector(skullW, skullH);
2590
entity.skullMarker.layer = ySortLayer(pivotY, SORT_HP_BAR);
2591
this.#syncLitSprite(entity.skullMarker, darkness, 0, false, entity.skullTint);
2592
this.#markSortDirty();
2593
}
2594
2520
2595
#rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {})
2521
2596
{
2522
2597
this.#bakeAndPlaceChunk(snapshot);
@@ -26,6 +26,7 @@ import26
resolveDimensionSeasonId26
resolveDimensionSeasonId27
} from "/shared/world/dimensions.js";27
} from "/shared/world/dimensions.js";28
import { SPELL_PROJECTILE_FRAME_MS } from "/shared/spells/constants.js";28
import { SPELL_PROJECTILE_FRAME_MS } from "/shared/spells/constants.js";29
import { skullTintColor } from "/shared/combat/skull.js";29
30
30
const LAYER_GROUND = 0;31
const LAYER_GROUND = 0;31
const LAYER_EDGE = 900000;32
const LAYER_EDGE = 900000;@@ -34,6 +35,7 @@ const SORT_ENTITY = 3;34
const SORT_HP_BAR = 4;35
const SORT_HP_BAR = 4;35
const SORT_FX = 5;36
const SORT_FX = 5;36
const RENDER_LAYER_BLOOM = "bloom";37
const RENDER_LAYER_BLOOM = "bloom";38
const SKULL_SPRITE = "fx:skull:skull";37
39
38
const HP_BAR_W = 14;40
const HP_BAR_W = 14;39
const HP_BAR_H = 4;41
const HP_BAR_H = 4;@@ -581,7 +583,7 @@ export class WorldView581
this.#scheduleEdgeRebuild();583
this.#scheduleEdgeRebuild();582
}584
}583
585
584
setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null)586
setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null, skullValue = 0)585
{587
{586
this.localEntityId = entityId;588
this.localEntityId = entityId;587
this.#upsertEntity({589
this.#upsertEntity({@@ -594,6 +596,7 @@ export class WorldView594
firstName,596
firstName,595
lastName,597
lastName,596
layers: layers ?? undefined,598
layers: layers ?? undefined,599
skullValue: skullValue | 0,597
...(health != null ? { health } : {}),600
...(health != null ? { health } : {}),598
...(maxHealth != null ? { maxHealth } : {})601
...(maxHealth != null ? { maxHealth } : {})599
});602
});@@ -717,6 +720,7 @@ export class WorldView717
{ return; }720
{ return; }718
existing.object?.destroy();721
existing.object?.destroy();719
existing.hpBar?.destroy();722
existing.hpBar?.destroy();723
existing.skullMarker?.destroy();720
for (const overlay of existing.overlays ?? [])724
for (const overlay of existing.overlays ?? [])721
{ overlay.destroy(); }725
{ overlay.destroy(); }722
for (const overlay of existing.bloomOverlays ?? [])726
for (const overlay of existing.bloomOverlays ?? [])@@ -724,6 +728,15 @@ export class WorldView724
this.entities.delete(entityId);728
this.entities.delete(entityId);725
}729
}726
730
731
updateEntitySkull (entityId, skullValue)732
{733
const entity = this.entities.get(entityId);734
if (!entity)735
{ return; }736
entity.skullValue = Math.max(0, skullValue | 0);737
this.#syncSkullMarker(entity);738
}739
727
updateEntityHealth (entityId, health, maxHealth)740
updateEntityHealth (entityId, health, maxHealth)728
{741
{729
const entity = this.entities.get(entityId);742
const entity = this.entities.get(entityId);@@ -1946,6 +1959,7 @@ export class WorldView1946
entity.gait = payload.gait;1959
entity.gait = payload.gait;1947
entity.sex = payload.sex ?? entity.sex;1960
entity.sex = payload.sex ?? entity.sex;1948
entity.characterId = payload.characterId ?? entity.characterId ?? null;1961
entity.characterId = payload.characterId ?? entity.characterId ?? null;1962
entity.accountId = payload.accountId ?? entity.accountId ?? null;1949
entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;1963
entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;1950
if (payload.level != null)1964
if (payload.level != null)1951
{ entity.level = payload.level | 0; }1965
{ entity.level = payload.level | 0; }@@ -1967,6 +1981,10 @@ export class WorldView1967
{ entity.health = payload.health; }1981
{ entity.health = payload.health; }1968
if (payload.maxHealth != null)1982
if (payload.maxHealth != null)1969
{ entity.maxHealth = payload.maxHealth; }1983
{ entity.maxHealth = payload.maxHealth; }1984
if (payload.skullValue != null)1985
{ entity.skullValue = Math.max(0, payload.skullValue | 0); }1986
else if (entity.skullValue == null)1987
{ entity.skullValue = 0; }1970
if (payload.firstName)1988
if (payload.firstName)1971
{ entity.firstName = payload.firstName; }1989
{ entity.firstName = payload.firstName; }1972
if (payload.lastName)1990
if (payload.lastName)@@ -1994,6 +2012,7 @@ export class WorldView1994
if (payload.layers)2012
if (payload.layers)1995
{ this.#applyLayers(entity, payload.layers); }2013
{ this.#applyLayers(entity, payload.layers); }1996
this.#syncHpBar(entity);2014
this.#syncHpBar(entity);2015
this.#syncSkullMarker(entity);1997
this.#placeEntity(entity, performance.now());2016
this.#placeEntity(entity, performance.now());1998
}2017
}1999
2018
@@ -2163,6 +2182,7 @@ export class WorldView2163
this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1);2182
this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1);2164
}2183
}2165
this.#placeHpBar(entity, pivotX, pivotY);2184
this.#placeHpBar(entity, pivotX, pivotY);2185
this.#placeSkullMarker(entity, pivotX, pivotY, tileShade);2166
}2186
}2167
2187
2168
#markUnlit (object)2188
#markUnlit (object)@@ -2517,6 +2537,61 @@ export class WorldView2517
this.#markSortDirty();2537
this.#markSortDirty();2518
}2538
}2519
2539
2540
#syncSkullMarker (entity)2541
{2542
if (!entity?.characterId)2543
{2544
entity.skullMarker?.destroy();2545
entity.skullMarker = null;2546
return;2547
}2548
const tint = skullTintColor(entity.skullValue | 0);2549
if (!tint)2550
{2551
entity.skullMarker?.destroy();2552
entity.skullMarker = null;2553
return;2554
}2555
const image = this.game.images[SKULL_SPRITE];2556
if (!image)2557
{ return; }2558
if (!entity.skullMarker)2559
{2560
entity.skullMarker = new GameObject(0, 0, image, SORT_HP_BAR);2561
this.scene.addObject(entity.skullMarker);2562
}2563
entity.skullTint = tint;2564
entity.skullMarker.renderer.sprite = image;2565
}2566
2567
/**2568
* Bottom edge of the skull sprite sits exactly on the character sprite's top edge.2569
*/2570
#placeSkullMarker (entity, pivotX, pivotY, darkness)2571
{2572
this.#syncSkullMarker(entity);2573
if (!entity.skullMarker)2574
{ return; }2575
const body = entity.object?.renderer?.sprite;2576
const skull = entity.skullMarker.renderer?.sprite;2577
if (!body || !skull)2578
{ return; }2579
const zoom = this.zoom;2580
const scale = entity.visualScale ?? 1;2581
const bodyH = body.height * zoom * scale;2582
const skullH = skull.height * zoom;2583
const skullW = skull.width * zoom;2584
const bodyCenterY = pivotY - (bodyH / 2 - PIVOT_FROM_BOTTOM_PX * zoom * scale);2585
const bodyTop = bodyCenterY - bodyH / 2;2586
// GameObject position is sprite center; bottom of skull at bodyTop ⇒ center at bodyTop - skullH/22587
entity.skullMarker.transform.position.x = pivotX;2588
entity.skullMarker.transform.position.y = bodyTop - skullH / 2;2589
entity.skullMarker.transform.size = new vector(skullW, skullH);2590
entity.skullMarker.layer = ySortLayer(pivotY, SORT_HP_BAR);2591
this.#syncLitSprite(entity.skullMarker, darkness, 0, false, entity.skullTint);2592
this.#markSortDirty();2593
}2594
2520
#rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {})2595
#rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {})2521
{2596
{2522
this.#bakeAndPlaceChunk(snapshot);2597
this.#bakeAndPlaceChunk(snapshot);@@ -456,6 +456,57 @@ a {
456
456
font-size: 0.85rem;
457
457
}
458
458
459
#nametag.friend-name,
460
#world-tooltip.friend-name {
461
color: #e8c84a;
462
}
463
464
.friend-account {
465
display: flex;
466
flex-direction: column;
467
gap: 0.25rem;
468
margin-bottom: 0.35rem;
469
}
470
471
.friend-account-header {
472
align-items: center;
473
}
474
475
button.friend-account-name {
476
flex: 1;
477
text-align: left;
478
background: transparent;
479
border: none;
480
color: inherit;
481
padding: 0.15rem 0;
482
cursor: pointer;
483
font: inherit;
484
}
485
486
button.friend-account-name:hover {
487
color: #e8c84a;
488
}
489
490
.friend-character-list {
491
display: flex;
492
flex-direction: column;
493
gap: 0.25rem;
494
padding-left: 0.35rem;
495
border-left: 2px solid #2c3340;
496
}
497
498
.friend-character-row {
499
display: flex;
500
align-items: center;
501
gap: 0.4rem;
502
}
503
504
.friend-char-preview {
505
width: 28px;
506
height: 28px;
507
flex: 0 0 auto;
508
}
509
459
510
#context-menu {
460
511
position: fixed;
461
512
z-index: 20;
@@ -456,6 +456,57 @@ a {456
font-size: 0.85rem;456
font-size: 0.85rem;457
}457
}458
458
459
#nametag.friend-name,460
#world-tooltip.friend-name {461
color: #e8c84a;462
}463
464
.friend-account {465
display: flex;466
flex-direction: column;467
gap: 0.25rem;468
margin-bottom: 0.35rem;469
}470
471
.friend-account-header {472
align-items: center;473
}474
475
button.friend-account-name {476
flex: 1;477
text-align: left;478
background: transparent;479
border: none;480
color: inherit;481
padding: 0.15rem 0;482
cursor: pointer;483
font: inherit;484
}485
486
button.friend-account-name:hover {487
color: #e8c84a;488
}489
490
.friend-character-list {491
display: flex;492
flex-direction: column;493
gap: 0.25rem;494
padding-left: 0.35rem;495
border-left: 2px solid #2c3340;496
}497
498
.friend-character-row {499
display: flex;500
align-items: center;501
gap: 0.4rem;502
}503
504
.friend-char-preview {505
width: 28px;506
height: 28px;507
flex: 0 0 auto;508
}509
459
#context-menu {510
#context-menu {460
position: fixed;511
position: fixed;461
z-index: 20;512
z-index: 20;@@ -142,6 +142,7 @@ export class BountyService
142
142
this.#persistBag(placerCharacterId, bag);
143
143
144
144
const nextAmount = this.stateDb.addCharacterBounty(targetId, copper);
145
this.simulation.refreshCharacterSkull?.(targetId);
145
146
this.simulation.pendingPrivate.push({
146
147
type: "toast",
147
148
characterId: targetId,
@@ -172,7 +173,8 @@ export class BountyService
172
173
}
173
174
174
175
/**
175
* Called when a player dies. PvP killer collects full bounty into vault + office letter.
176
* Called when a player dies. Non-friend PvP killer collects full bounty into vault + office letter.
177
* Friend / same-account / mob kills leave the bounty untouched.
176
178
* @returns {{ paidCopper: number, victimName: string } | null}
177
179
*/
178
180
settleKill (victimCharacterId, attackerEntityId, deathTileX, deathTileY)
@@ -185,6 +187,9 @@ export class BountyService
185
187
if (!killerCharacterId || killerCharacterId === (victimCharacterId | 0))
186
188
{ return null; }
187
189
190
if (this.stateDb.areFriends(victimCharacterId, killerCharacterId))
191
{ return null; }
192
188
193
const paidCopper = this.stateDb.takeCharacterBounty(victimCharacterId);
189
194
if (paidCopper <= 0)
190
195
{ return null; }
@@ -224,6 +229,8 @@ export class BountyService
224
229
message: `Bounty collected: ${formatBountyCopper(paidCopper)} for defeating ${victimName} (sent to vault).`
225
230
});
226
231
232
this.simulation.refreshCharacterSkull?.(victimCharacterId);
233
227
234
return { paidCopper, victimName };
228
235
}
229
236
@@ -142,6 +142,7 @@ export class BountyService142
this.#persistBag(placerCharacterId, bag);142
this.#persistBag(placerCharacterId, bag);143
143
144
const nextAmount = this.stateDb.addCharacterBounty(targetId, copper);144
const nextAmount = this.stateDb.addCharacterBounty(targetId, copper);145
this.simulation.refreshCharacterSkull?.(targetId);145
this.simulation.pendingPrivate.push({146
this.simulation.pendingPrivate.push({146
type: "toast",147
type: "toast",147
characterId: targetId,148
characterId: targetId,@@ -172,7 +173,8 @@ export class BountyService172
}173
}173
174
174
/**175
/**175
* Called when a player dies. PvP killer collects full bounty into vault + office letter.176
* Called when a player dies. Non-friend PvP killer collects full bounty into vault + office letter.177
* Friend / same-account / mob kills leave the bounty untouched.176
* @returns {{ paidCopper: number, victimName: string } | null}178
* @returns {{ paidCopper: number, victimName: string } | null}177
*/179
*/178
settleKill (victimCharacterId, attackerEntityId, deathTileX, deathTileY)180
settleKill (victimCharacterId, attackerEntityId, deathTileX, deathTileY)@@ -185,6 +187,9 @@ export class BountyService185
if (!killerCharacterId || killerCharacterId === (victimCharacterId | 0))187
if (!killerCharacterId || killerCharacterId === (victimCharacterId | 0))186
{ return null; }188
{ return null; }187
189
190
if (this.stateDb.areFriends(victimCharacterId, killerCharacterId))191
{ return null; }192
188
const paidCopper = this.stateDb.takeCharacterBounty(victimCharacterId);193
const paidCopper = this.stateDb.takeCharacterBounty(victimCharacterId);189
if (paidCopper <= 0)194
if (paidCopper <= 0)190
{ return null; }195
{ return null; }@@ -224,6 +229,8 @@ export class BountyService224
message: `Bounty collected: ${formatBountyCopper(paidCopper)} for defeating ${victimName} (sent to vault).`229
message: `Bounty collected: ${formatBountyCopper(paidCopper)} for defeating ${victimName} (sent to vault).`225
});230
});226
231
232
this.simulation.refreshCharacterSkull?.(victimCharacterId);233
227
return { paidCopper, victimName };234
return { paidCopper, victimName };228
}235
}229
236
@@ -2,31 +2,35 @@ import { Component } from "../ecs/components.js";
2
2
import { itemDefinition } from "../../../shared/definitions/items.js";
3
3
import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
4
4
import { mobDefinition } from "../../../shared/definitions/mobs.js";
5
import {
6
mobCanFightType,
7
mobCanFight,
8
mobMeleeAttackProfile,
9
mobSkillLevels,
10
mobIsAggressive,
11
mobAggroRangeTiles
12
} from "../../../shared/definitions/mobCombat.js";
5
import
6
{
7
mobCanFightType,
8
mobCanFight,
9
mobMeleeAttackProfile,
10
mobSkillLevels,
11
mobIsAggressive,
12
mobAggroRangeTiles
13
} from "../../../shared/definitions/mobCombat.js";
13
14
import { spellDefinition } from "../../../shared/definitions/spells.js";
14
15
import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
15
import {
16
effectiveHitSkillInDarkness,
17
aggroDistanceMultiplier
18
} from "../../../shared/combat/darkness.js";
19
import {
20
bakedTileLight01,
21
entityLightAtTile,
22
tileCombatLight01,
23
tileIndexLocal
24
} from "../../../shared/lighting/combatLight.js";
16
import
17
{
18
effectiveHitSkillInDarkness,
19
aggroDistanceMultiplier
20
} from "../../../shared/combat/darkness.js";
21
import
22
{
23
bakedTileLight01,
24
entityLightAtTile,
25
tileCombatLight01,
26
tileIndexLocal
27
} from "../../../shared/lighting/combatLight.js";
25
28
import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
26
import {
27
effectiveSkillLevel,
28
equipmentBonusesFromSlots
29
} from "../../../shared/equipment/stats.js";
29
import
30
{
31
effectiveSkillLevel,
32
equipmentBonusesFromSlots
33
} from "../../../shared/equipment/stats.js";
30
34
import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
31
35
import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS, SPELL_COOLDOWN_MS } from "../../../shared/spells/constants.js";
32
36
import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
@@ -1454,7 +1458,7 @@ export function finalizeMobKill (world, attackerId, targetId, targetHandle, tile
1454
1458
scheduleSpawnerRespawn(
1455
1459
world,
1456
1460
origin.spawnerId,
1457
origin.respawnDelaySeconds ?? 0,
1461
origin.respawnDelaySeconds ?? 25,
1458
1462
now
1459
1463
);
1460
1464
}
@@ -2,31 +2,35 @@ import { Component } from "../ecs/components.js";2
import { itemDefinition } from "../../../shared/definitions/items.js";2
import { itemDefinition } from "../../../shared/definitions/items.js";3
import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";3
import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";4
import { mobDefinition } from "../../../shared/definitions/mobs.js";4
import { mobDefinition } from "../../../shared/definitions/mobs.js";5
import {5
import6
mobCanFightType,6
{7
mobCanFight,7
mobCanFightType,8
mobMeleeAttackProfile,8
mobCanFight,9
mobSkillLevels,9
mobMeleeAttackProfile,10
mobIsAggressive,10
mobSkillLevels,11
mobAggroRangeTiles11
mobIsAggressive,12
} from "../../../shared/definitions/mobCombat.js";12
mobAggroRangeTiles13
} from "../../../shared/definitions/mobCombat.js";13
import { spellDefinition } from "../../../shared/definitions/spells.js";14
import { spellDefinition } from "../../../shared/definitions/spells.js";14
import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";15
import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";15
import {16
import16
effectiveHitSkillInDarkness,17
{17
aggroDistanceMultiplier18
effectiveHitSkillInDarkness,18
} from "../../../shared/combat/darkness.js";19
aggroDistanceMultiplier19
import {20
} from "../../../shared/combat/darkness.js";20
bakedTileLight01,21
import21
entityLightAtTile,22
{22
tileCombatLight01,23
bakedTileLight01,23
tileIndexLocal24
entityLightAtTile,24
} from "../../../shared/lighting/combatLight.js";25
tileCombatLight01,26
tileIndexLocal27
} from "../../../shared/lighting/combatLight.js";25
import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";28
import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";26
import {29
import27
effectiveSkillLevel,30
{28
equipmentBonusesFromSlots31
effectiveSkillLevel,29
} from "../../../shared/equipment/stats.js";32
equipmentBonusesFromSlots33
} from "../../../shared/equipment/stats.js";30
import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";34
import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";31
import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS, SPELL_COOLDOWN_MS } from "../../../shared/spells/constants.js";35
import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS, SPELL_COOLDOWN_MS } from "../../../shared/spells/constants.js";32
import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";36
import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";@@ -1454,7 +1458,7 @@ export function finalizeMobKill (world, attackerId, targetId, targetHandle, tile1454
scheduleSpawnerRespawn(1458
scheduleSpawnerRespawn(1455
world,1459
world,1456
origin.spawnerId,1460
origin.spawnerId,1457
origin.respawnDelaySeconds ?? 0,1461
origin.respawnDelaySeconds ?? 25,1458
now1462
now1459
);1463
);1460
}1464
}@@ -4,20 +4,22 @@ import { CraftingStationId, CRAFT_DURATION_MS, COOK_BURN_CHANCE_OVEN, COOK_BURN_
4
4
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5
5
import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
6
6
import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
7
import {
8
recipeDefinition,
9
canStartCraft,
10
canCraftFitInventory,
11
hasRecipeInputs
12
} from "../../../shared/crafting/recipes.js";
7
import
8
{
9
recipeDefinition,
10
canStartCraft,
11
canCraftFitInventory,
12
hasRecipeInputs
13
} from "../../../shared/crafting/recipes.js";
13
14
import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";
14
15
import { craftDurationMs, craftXpForConsumedInputs } from "../../../shared/definitions/gathering.js";
15
16
import { takeFromSlot, insertStack, stackQuantity, consumeFillCharge } from "../../../shared/items/inventory.js";
16
import {
17
attachOrigins,
18
craftOrigin,
19
craftOriginVerbForStation
20
} from "../../../shared/items/origin.js";
17
import
18
{
19
attachOrigins,
20
craftOrigin,
21
craftOriginVerbForStation
22
} from "../../../shared/items/origin.js";
21
23
import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
22
24
import { bagView } from "../items/bags.js";
23
25
import { tileToChunk, tileToLocal } from "../world/coordinates.js";
@@ -66,6 +68,8 @@ function stationBlockType (stationId)
66
68
{ return BlockType.furnace; }
67
69
if (stationId === CraftingStationId.anvil)
68
70
{ return BlockType.anvil; }
71
if (stationId === CraftingStationId.jeweleringStation)
72
{ return BlockType.jeweleringStation; }
69
73
if (stationId === CraftingStationId.woodworkingBench)
70
74
{ return BlockType.woodworkingBench; }
71
75
if (stationId === CraftingStationId.craftingBench)
@@ -4,20 +4,22 @@ import { CraftingStationId, CRAFT_DURATION_MS, COOK_BURN_CHANCE_OVEN, COOK_BURN_4
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";4
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";5
import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";5
import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";6
import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";6
import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";7
import {7
import8
recipeDefinition,8
{9
canStartCraft,9
recipeDefinition,10
canCraftFitInventory,10
canStartCraft,11
hasRecipeInputs11
canCraftFitInventory,12
} from "../../../shared/crafting/recipes.js";12
hasRecipeInputs13
} from "../../../shared/crafting/recipes.js";13
import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";14
import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";14
import { craftDurationMs, craftXpForConsumedInputs } from "../../../shared/definitions/gathering.js";15
import { craftDurationMs, craftXpForConsumedInputs } from "../../../shared/definitions/gathering.js";15
import { takeFromSlot, insertStack, stackQuantity, consumeFillCharge } from "../../../shared/items/inventory.js";16
import { takeFromSlot, insertStack, stackQuantity, consumeFillCharge } from "../../../shared/items/inventory.js";16
import {17
import17
attachOrigins,18
{18
craftOrigin,19
attachOrigins,19
craftOriginVerbForStation20
craftOrigin,20
} from "../../../shared/items/origin.js";21
craftOriginVerbForStation22
} from "../../../shared/items/origin.js";21
import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";23
import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";22
import { bagView } from "../items/bags.js";24
import { bagView } from "../items/bags.js";23
import { tileToChunk, tileToLocal } from "../world/coordinates.js";25
import { tileToChunk, tileToLocal } from "../world/coordinates.js";@@ -66,6 +68,8 @@ function stationBlockType (stationId)66
{ return BlockType.furnace; }68
{ return BlockType.furnace; }67
if (stationId === CraftingStationId.anvil)69
if (stationId === CraftingStationId.anvil)68
{ return BlockType.anvil; }70
{ return BlockType.anvil; }71
if (stationId === CraftingStationId.jeweleringStation)72
{ return BlockType.jeweleringStation; }69
if (stationId === CraftingStationId.woodworkingBench)73
if (stationId === CraftingStationId.woodworkingBench)70
{ return BlockType.woodworkingBench; }74
{ return BlockType.woodworkingBench; }71
if (stationId === CraftingStationId.craftingBench)75
if (stationId === CraftingStationId.craftingBench)@@ -93,6 +93,7 @@ export function publicEntityView (ecs, entityId)
93
93
firstName: appearance?.firstName ?? "",
94
94
lastName: appearance?.lastName ?? "",
95
95
characterId: character?.characterId ?? null,
96
accountId: character?.accountId ?? null,
96
97
mobTypeId: creature?.mobTypeId ?? null,
97
98
canFight: mob ? mobCanFight(mob) : !!character,
98
99
hostile: !!mob?.hostile,
@@ -126,6 +127,7 @@ export function replicationSpawn (view)
126
127
type: "entity-spawn",
127
128
entityId: view.entityId,
128
129
characterId: view.characterId,
130
accountId: view.accountId ?? null,
129
131
tileX: view.tileX,
130
132
tileY: view.tileY,
131
133
worldX: view.worldX,
@@ -148,7 +150,8 @@ export function replicationSpawn (view)
148
150
health: view.health,
149
151
maxHealth: view.maxHealth,
150
152
lightRadiusTiles: view.lightRadiusTiles ?? 0,
151
visualScale: view.visualScale ?? 1
153
visualScale: view.visualScale ?? 1,
154
skullValue: view.skullValue | 0
152
155
};
153
156
}
154
157
@@ -93,6 +93,7 @@ export function publicEntityView (ecs, entityId)93
firstName: appearance?.firstName ?? "",93
firstName: appearance?.firstName ?? "",94
lastName: appearance?.lastName ?? "",94
lastName: appearance?.lastName ?? "",95
characterId: character?.characterId ?? null,95
characterId: character?.characterId ?? null,96
accountId: character?.accountId ?? null,96
mobTypeId: creature?.mobTypeId ?? null,97
mobTypeId: creature?.mobTypeId ?? null,97
canFight: mob ? mobCanFight(mob) : !!character,98
canFight: mob ? mobCanFight(mob) : !!character,98
hostile: !!mob?.hostile,99
hostile: !!mob?.hostile,@@ -126,6 +127,7 @@ export function replicationSpawn (view)126
type: "entity-spawn",127
type: "entity-spawn",127
entityId: view.entityId,128
entityId: view.entityId,128
characterId: view.characterId,129
characterId: view.characterId,130
accountId: view.accountId ?? null,129
tileX: view.tileX,131
tileX: view.tileX,130
tileY: view.tileY,132
tileY: view.tileY,131
worldX: view.worldX,133
worldX: view.worldX,@@ -148,7 +150,8 @@ export function replicationSpawn (view)148
health: view.health,150
health: view.health,149
maxHealth: view.maxHealth,151
maxHealth: view.maxHealth,150
lightRadiusTiles: view.lightRadiusTiles ?? 0,152
lightRadiusTiles: view.lightRadiusTiles ?? 0,151
visualScale: view.visualScale ?? 1153
visualScale: view.visualScale ?? 1,154
skullValue: view.skullValue | 0152
};155
};153
}156
}154
157
@@ -1,3 +1,9 @@
1
import { layersFromBag } from "../../../shared/appearance/layers.js";
2
3
/**
4
* Account-wide friends: requests and friendships key on account_id.
5
* Same-account characters are always treated as friends.
6
*/
1
7
export class FriendService
2
8
{
3
9
constructor (stateDb)
@@ -7,16 +13,46 @@ export class FriendService
7
13
8
14
snapshot (characterId)
9
15
{
16
const accountId = this.#accountId(characterId);
10
17
return {
11
friends: this.listFriends(characterId),
12
incoming: this.#namedRequests(this.stateDb.listIncomingRequests(characterId), "from_character_id"),
13
outgoing: this.#namedRequests(this.stateDb.listOutgoingRequests(characterId), "to_character_id")
18
friends: this.listFriendAccounts(accountId),
19
incoming: this.#namedAccountRequests(
20
this.stateDb.listIncomingAccountRequests(accountId),
21
"from_account_id"
22
),
23
outgoing: this.#namedAccountRequests(
24
this.stateDb.listOutgoingAccountRequests(accountId),
25
"to_account_id"
26
)
14
27
};
15
28
}
16
29
30
/** Flat character list for pigeon address book (all chars on friend accounts). */
17
31
listFriends (characterId)
18
32
{
19
return this.stateDb.listFriendRecords(characterId).map((row) => this.#publicCharacter(row.character_id)).filter(Boolean);
33
const accounts = this.listFriendAccounts(this.#accountId(characterId));
34
const out = [];
35
for (const account of accounts)
36
{
37
for (const character of account.characters ?? [])
38
{ out.push(character); }
39
}
40
return out;
41
}
42
43
listFriendAccounts (accountId)
44
{
45
const id = accountId | 0;
46
if (!id)
47
{ return []; }
48
return this.stateDb.listAccountFriendRecords(id)
49
.map((row) => this.#publicAccount(row.account_id))
50
.filter(Boolean);
51
}
52
53
areFriends (characterId, otherCharacterId)
54
{
55
return this.stateDb.areFriends(characterId, otherCharacterId);
20
56
}
21
57
22
58
request (fromCharacterId, toCharacterId)
@@ -25,54 +61,98 @@ export class FriendService
25
61
const toId = Number(toCharacterId);
26
62
if (fromId === toId)
27
63
{ throw userError("You cannot friend yourself."); }
28
this.#requireCharacter(fromId);
29
this.#requireCharacter(toId);
30
if (this.stateDb.areFriends(fromId, toId))
64
const from = this.#requireCharacter(fromId);
65
const to = this.#requireCharacter(toId);
66
const fromAccount = from.account_id | 0;
67
const toAccount = to.account_id | 0;
68
if (fromAccount === toAccount)
69
{ throw userError("You are already friends with your own characters."); }
70
if (this.stateDb.areAccountFriends(fromAccount, toAccount))
31
71
{ throw userError("You are already friends."); }
32
if (this.stateDb.getFriendRequest(fromId, toId))
72
if (this.stateDb.getAccountFriendRequest(fromAccount, toAccount))
33
73
{ throw userError("Friend request already sent."); }
34
if (this.stateDb.getFriendRequest(toId, fromId))
74
if (this.stateDb.getAccountFriendRequest(toAccount, fromAccount))
35
75
{
36
this.stateDb.deleteFriendRequest(toId, fromId);
37
this.stateDb.insertFriendship(fromId, toId);
76
this.stateDb.deleteAccountFriendRequest(toAccount, fromAccount);
77
this.stateDb.insertAccountFriendship(fromAccount, toAccount);
38
78
return this.snapshot(fromId);
39
79
}
40
this.stateDb.insertFriendRequest(fromId, toId);
80
this.stateDb.insertAccountFriendRequest(fromAccount, toAccount);
41
81
return this.snapshot(fromId);
42
82
}
43
83
44
84
accept (characterId, fromCharacterId)
45
85
{
46
const toId = Number(characterId);
47
const fromId = Number(fromCharacterId);
48
this.#requireCharacter(toId);
49
this.#requireCharacter(fromId);
50
if (!this.stateDb.getFriendRequest(fromId, toId))
86
const toChar = this.#requireCharacter(characterId);
87
const fromChar = this.#requireCharacter(fromCharacterId);
88
const toAccount = toChar.account_id | 0;
89
const fromAccount = fromChar.account_id | 0;
90
if (!this.stateDb.getAccountFriendRequest(fromAccount, toAccount))
91
{ throw userError("There is no friend request to accept."); }
92
this.stateDb.deleteAccountFriendRequest(fromAccount, toAccount);
93
this.stateDb.deleteAccountFriendRequest(toAccount, fromAccount);
94
if (!this.stateDb.areAccountFriends(fromAccount, toAccount))
95
{ this.stateDb.insertAccountFriendship(fromAccount, toAccount); }
96
return this.snapshot(toChar.character_id);
97
}
98
99
/** Accept / decline / remove by target account id (friends panel). */
100
acceptAccount (characterId, fromAccountId)
101
{
102
const toChar = this.#requireCharacter(characterId);
103
const toAccount = toChar.account_id | 0;
104
const fromAccount = fromAccountId | 0;
105
if (!this.stateDb.getAccountFriendRequest(fromAccount, toAccount))
51
106
{ throw userError("There is no friend request to accept."); }
52
this.stateDb.deleteFriendRequest(fromId, toId);
53
this.stateDb.deleteFriendRequest(toId, fromId);
54
if (!this.stateDb.areFriends(fromId, toId))
55
{ this.stateDb.insertFriendship(fromId, toId); }
56
return this.snapshot(toId);
107
this.stateDb.deleteAccountFriendRequest(fromAccount, toAccount);
108
this.stateDb.deleteAccountFriendRequest(toAccount, fromAccount);
109
if (!this.stateDb.areAccountFriends(fromAccount, toAccount))
110
{ this.stateDb.insertAccountFriendship(fromAccount, toAccount); }
111
return this.snapshot(toChar.character_id);
57
112
}
58
113
59
114
decline (characterId, otherCharacterId)
60
115
{
61
const actorId = Number(characterId);
62
const otherId = Number(otherCharacterId);
63
this.stateDb.deleteFriendRequest(actorId, otherId);
64
this.stateDb.deleteFriendRequest(otherId, actorId);
65
return this.snapshot(actorId);
116
const actor = this.#requireCharacter(characterId);
117
const other = this.stateDb.getCharacter(otherCharacterId);
118
if (!other)
119
{ return this.snapshot(actor.character_id); }
120
this.stateDb.deleteAccountFriendRequest(actor.account_id, other.account_id);
121
this.stateDb.deleteAccountFriendRequest(other.account_id, actor.account_id);
122
return this.snapshot(actor.character_id);
123
}
124
125
declineAccount (characterId, otherAccountId)
126
{
127
const actor = this.#requireCharacter(characterId);
128
const otherAccount = otherAccountId | 0;
129
this.stateDb.deleteAccountFriendRequest(actor.account_id, otherAccount);
130
this.stateDb.deleteAccountFriendRequest(otherAccount, actor.account_id);
131
return this.snapshot(actor.character_id);
66
132
}
67
133
68
134
remove (characterId, otherCharacterId)
69
135
{
70
const actorId = Number(characterId);
71
const otherId = Number(otherCharacterId);
72
if (!this.stateDb.areFriends(actorId, otherId))
136
const actor = this.#requireCharacter(characterId);
137
const other = this.#requireCharacter(otherCharacterId);
138
if (!this.stateDb.areAccountFriends(actor.account_id, other.account_id))
139
{ throw userError("You are not friends with that player."); }
140
if ((actor.account_id | 0) === (other.account_id | 0))
141
{ throw userError("You cannot unfriend your own characters."); }
142
this.stateDb.deleteAccountFriendship(actor.account_id, other.account_id);
143
return this.snapshot(actor.character_id);
144
}
145
146
removeAccount (characterId, otherAccountId)
147
{
148
const actor = this.#requireCharacter(characterId);
149
const otherAccount = otherAccountId | 0;
150
if ((actor.account_id | 0) === otherAccount)
151
{ throw userError("You cannot unfriend your own characters."); }
152
if (!this.stateDb.areAccountFriends(actor.account_id, otherAccount))
73
153
{ throw userError("You are not friends with that player."); }
74
this.stateDb.deleteFriendship(actorId, otherId);
75
return this.snapshot(actorId);
154
this.stateDb.deleteAccountFriendship(actor.account_id, otherAccount);
155
return this.snapshot(actor.character_id);
76
156
}
77
157
78
158
findByFullName (firstName, lastName)
@@ -81,9 +161,25 @@ export class FriendService
81
161
return row ? this.#publicCharacter(row.character_id) : null;
82
162
}
83
163
84
#namedRequests (rows, idField)
164
#namedAccountRequests (rows, idField)
165
{
166
return rows.map((row) => this.#publicAccount(row[idField])).filter(Boolean);
167
}
168
169
#publicAccount (accountId)
85
170
{
86
return rows.map((row) => this.#publicCharacter(row[idField])).filter(Boolean);
171
const account = this.stateDb.getAccount(accountId);
172
if (!account)
173
{ return null; }
174
const characters = this.stateDb.listCharacters(account.account_id)
175
.filter((row) => !row.deletion_scheduled_at)
176
.map((row) => this.#publicCharacter(row.character_id))
177
.filter(Boolean);
178
return {
179
accountId: account.account_id,
180
username: this.stateDb.accountDisplayName(account.account_id),
181
characters
182
};
87
183
}
88
184
89
185
#publicCharacter (characterId)
@@ -91,17 +187,28 @@ export class FriendService
91
187
const row = this.stateDb.getCharacter(characterId);
92
188
if (!row)
93
189
{ return null; }
190
const bag = this.stateDb.getBag(characterId);
94
191
return {
95
192
characterId: row.character_id,
193
accountId: row.account_id,
96
194
firstName: row.first_name,
97
lastName: row.last_name
195
lastName: row.last_name,
196
sex: row.sex,
197
layers: layersFromBag(row.sex, bag)
98
198
};
99
199
}
100
200
201
#accountId (characterId)
202
{
203
return this.#requireCharacter(characterId).account_id | 0;
204
}
205
101
206
#requireCharacter (characterId)
102
207
{
103
if (!this.stateDb.getCharacter(characterId))
208
const row = this.stateDb.getCharacter(characterId);
209
if (!row)
104
210
{ throw userError("That player does not exist."); }
211
return row;
105
212
}
106
213
}
107
214
@@ -1,3 +1,9 @@1
import { layersFromBag } from "../../../shared/appearance/layers.js";2
3
/**4
* Account-wide friends: requests and friendships key on account_id.5
* Same-account characters are always treated as friends.6
*/1
export class FriendService7
export class FriendService2
{8
{3
constructor (stateDb)9
constructor (stateDb)@@ -7,16 +13,46 @@ export class FriendService7
13
8
snapshot (characterId)14
snapshot (characterId)9
{15
{16
const accountId = this.#accountId(characterId);10
return {17
return {11
friends: this.listFriends(characterId),18
friends: this.listFriendAccounts(accountId),12
incoming: this.#namedRequests(this.stateDb.listIncomingRequests(characterId), "from_character_id"),19
incoming: this.#namedAccountRequests(13
outgoing: this.#namedRequests(this.stateDb.listOutgoingRequests(characterId), "to_character_id")20
this.stateDb.listIncomingAccountRequests(accountId),21
"from_account_id"22
),23
outgoing: this.#namedAccountRequests(24
this.stateDb.listOutgoingAccountRequests(accountId),25
"to_account_id"26
)14
};27
};15
}28
}16
29
30
/** Flat character list for pigeon address book (all chars on friend accounts). */17
listFriends (characterId)31
listFriends (characterId)18
{32
{19
return this.stateDb.listFriendRecords(characterId).map((row) => this.#publicCharacter(row.character_id)).filter(Boolean);33
const accounts = this.listFriendAccounts(this.#accountId(characterId));34
const out = [];35
for (const account of accounts)36
{37
for (const character of account.characters ?? [])38
{ out.push(character); }39
}40
return out;41
}42
43
listFriendAccounts (accountId)44
{45
const id = accountId | 0;46
if (!id)47
{ return []; }48
return this.stateDb.listAccountFriendRecords(id)49
.map((row) => this.#publicAccount(row.account_id))50
.filter(Boolean);51
}52
53
areFriends (characterId, otherCharacterId)54
{55
return this.stateDb.areFriends(characterId, otherCharacterId);20
}56
}21
57
22
request (fromCharacterId, toCharacterId)58
request (fromCharacterId, toCharacterId)@@ -25,54 +61,98 @@ export class FriendService25
const toId = Number(toCharacterId);61
const toId = Number(toCharacterId);26
if (fromId === toId)62
if (fromId === toId)27
{ throw userError("You cannot friend yourself."); }63
{ throw userError("You cannot friend yourself."); }28
this.#requireCharacter(fromId);64
const from = this.#requireCharacter(fromId);29
this.#requireCharacter(toId);65
const to = this.#requireCharacter(toId);30
if (this.stateDb.areFriends(fromId, toId))66
const fromAccount = from.account_id | 0;67
const toAccount = to.account_id | 0;68
if (fromAccount === toAccount)69
{ throw userError("You are already friends with your own characters."); }70
if (this.stateDb.areAccountFriends(fromAccount, toAccount))31
{ throw userError("You are already friends."); }71
{ throw userError("You are already friends."); }32
if (this.stateDb.getFriendRequest(fromId, toId))72
if (this.stateDb.getAccountFriendRequest(fromAccount, toAccount))33
{ throw userError("Friend request already sent."); }73
{ throw userError("Friend request already sent."); }34
if (this.stateDb.getFriendRequest(toId, fromId))74
if (this.stateDb.getAccountFriendRequest(toAccount, fromAccount))35
{75
{36
this.stateDb.deleteFriendRequest(toId, fromId);76
this.stateDb.deleteAccountFriendRequest(toAccount, fromAccount);37
this.stateDb.insertFriendship(fromId, toId);77
this.stateDb.insertAccountFriendship(fromAccount, toAccount);38
return this.snapshot(fromId);78
return this.snapshot(fromId);39
}79
}40
this.stateDb.insertFriendRequest(fromId, toId);80
this.stateDb.insertAccountFriendRequest(fromAccount, toAccount);41
return this.snapshot(fromId);81
return this.snapshot(fromId);42
}82
}43
83
44
accept (characterId, fromCharacterId)84
accept (characterId, fromCharacterId)45
{85
{46
const toId = Number(characterId);86
const toChar = this.#requireCharacter(characterId);47
const fromId = Number(fromCharacterId);87
const fromChar = this.#requireCharacter(fromCharacterId);48
this.#requireCharacter(toId);88
const toAccount = toChar.account_id | 0;49
this.#requireCharacter(fromId);89
const fromAccount = fromChar.account_id | 0;50
if (!this.stateDb.getFriendRequest(fromId, toId))90
if (!this.stateDb.getAccountFriendRequest(fromAccount, toAccount))91
{ throw userError("There is no friend request to accept."); }92
this.stateDb.deleteAccountFriendRequest(fromAccount, toAccount);93
this.stateDb.deleteAccountFriendRequest(toAccount, fromAccount);94
if (!this.stateDb.areAccountFriends(fromAccount, toAccount))95
{ this.stateDb.insertAccountFriendship(fromAccount, toAccount); }96
return this.snapshot(toChar.character_id);97
}98
99
/** Accept / decline / remove by target account id (friends panel). */100
acceptAccount (characterId, fromAccountId)101
{102
const toChar = this.#requireCharacter(characterId);103
const toAccount = toChar.account_id | 0;104
const fromAccount = fromAccountId | 0;105
if (!this.stateDb.getAccountFriendRequest(fromAccount, toAccount))51
{ throw userError("There is no friend request to accept."); }106
{ throw userError("There is no friend request to accept."); }52
this.stateDb.deleteFriendRequest(fromId, toId);107
this.stateDb.deleteAccountFriendRequest(fromAccount, toAccount);53
this.stateDb.deleteFriendRequest(toId, fromId);108
this.stateDb.deleteAccountFriendRequest(toAccount, fromAccount);54
if (!this.stateDb.areFriends(fromId, toId))109
if (!this.stateDb.areAccountFriends(fromAccount, toAccount))55
{ this.stateDb.insertFriendship(fromId, toId); }110
{ this.stateDb.insertAccountFriendship(fromAccount, toAccount); }56
return this.snapshot(toId);111
return this.snapshot(toChar.character_id);57
}112
}58
113
59
decline (characterId, otherCharacterId)114
decline (characterId, otherCharacterId)60
{115
{61
const actorId = Number(characterId);116
const actor = this.#requireCharacter(characterId);62
const otherId = Number(otherCharacterId);117
const other = this.stateDb.getCharacter(otherCharacterId);63
this.stateDb.deleteFriendRequest(actorId, otherId);118
if (!other)64
this.stateDb.deleteFriendRequest(otherId, actorId);119
{ return this.snapshot(actor.character_id); }65
return this.snapshot(actorId);120
this.stateDb.deleteAccountFriendRequest(actor.account_id, other.account_id);121
this.stateDb.deleteAccountFriendRequest(other.account_id, actor.account_id);122
return this.snapshot(actor.character_id);123
}124
125
declineAccount (characterId, otherAccountId)126
{127
const actor = this.#requireCharacter(characterId);128
const otherAccount = otherAccountId | 0;129
this.stateDb.deleteAccountFriendRequest(actor.account_id, otherAccount);130
this.stateDb.deleteAccountFriendRequest(otherAccount, actor.account_id);131
return this.snapshot(actor.character_id);66
}132
}67
133
68
remove (characterId, otherCharacterId)134
remove (characterId, otherCharacterId)69
{135
{70
const actorId = Number(characterId);136
const actor = this.#requireCharacter(characterId);71
const otherId = Number(otherCharacterId);137
const other = this.#requireCharacter(otherCharacterId);72
if (!this.stateDb.areFriends(actorId, otherId))138
if (!this.stateDb.areAccountFriends(actor.account_id, other.account_id))139
{ throw userError("You are not friends with that player."); }140
if ((actor.account_id | 0) === (other.account_id | 0))141
{ throw userError("You cannot unfriend your own characters."); }142
this.stateDb.deleteAccountFriendship(actor.account_id, other.account_id);143
return this.snapshot(actor.character_id);144
}145
146
removeAccount (characterId, otherAccountId)147
{148
const actor = this.#requireCharacter(characterId);149
const otherAccount = otherAccountId | 0;150
if ((actor.account_id | 0) === otherAccount)151
{ throw userError("You cannot unfriend your own characters."); }152
if (!this.stateDb.areAccountFriends(actor.account_id, otherAccount))73
{ throw userError("You are not friends with that player."); }153
{ throw userError("You are not friends with that player."); }74
this.stateDb.deleteFriendship(actorId, otherId);154
this.stateDb.deleteAccountFriendship(actor.account_id, otherAccount);75
return this.snapshot(actorId);155
return this.snapshot(actor.character_id);76
}156
}77
157
78
findByFullName (firstName, lastName)158
findByFullName (firstName, lastName)@@ -81,9 +161,25 @@ export class FriendService81
return row ? this.#publicCharacter(row.character_id) : null;161
return row ? this.#publicCharacter(row.character_id) : null;82
}162
}83
163
84
#namedRequests (rows, idField)164
#namedAccountRequests (rows, idField)165
{166
return rows.map((row) => this.#publicAccount(row[idField])).filter(Boolean);167
}168
169
#publicAccount (accountId)85
{170
{86
return rows.map((row) => this.#publicCharacter(row[idField])).filter(Boolean);171
const account = this.stateDb.getAccount(accountId);172
if (!account)173
{ return null; }174
const characters = this.stateDb.listCharacters(account.account_id)175
.filter((row) => !row.deletion_scheduled_at)176
.map((row) => this.#publicCharacter(row.character_id))177
.filter(Boolean);178
return {179
accountId: account.account_id,180
username: this.stateDb.accountDisplayName(account.account_id),181
characters182
};87
}183
}88
184
89
#publicCharacter (characterId)185
#publicCharacter (characterId)@@ -91,17 +187,28 @@ export class FriendService91
const row = this.stateDb.getCharacter(characterId);187
const row = this.stateDb.getCharacter(characterId);92
if (!row)188
if (!row)93
{ return null; }189
{ return null; }190
const bag = this.stateDb.getBag(characterId);94
return {191
return {95
characterId: row.character_id,192
characterId: row.character_id,193
accountId: row.account_id,96
firstName: row.first_name,194
firstName: row.first_name,97
lastName: row.last_name195
lastName: row.last_name,196
sex: row.sex,197
layers: layersFromBag(row.sex, bag)98
};198
};99
}199
}100
200
201
#accountId (characterId)202
{203
return this.#requireCharacter(characterId).account_id | 0;204
}205
101
#requireCharacter (characterId)206
#requireCharacter (characterId)102
{207
{103
if (!this.stateDb.getCharacter(characterId))208
const row = this.stateDb.getCharacter(characterId);209
if (!row)104
{ throw userError("That player does not exist."); }210
{ throw userError("That player does not exist."); }211
return row;105
}212
}106
}213
}107
214
@@ -202,18 +202,27 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
202
202
break;
203
203
case MessageType.friendAccept:
204
204
requirePlaying(session);
205
friends.accept(session.characterId, message.characterId);
206
pushFriends(session.characterId, message.characterId);
205
if (message.accountId)
206
{ friends.acceptAccount(session.characterId, message.accountId); }
207
else
208
{ friends.accept(session.characterId, message.characterId); }
209
pushFriends(session.characterId, message.characterId, message.accountId);
207
210
break;
208
211
case MessageType.friendDecline:
209
212
requirePlaying(session);
210
friends.decline(session.characterId, message.characterId);
211
pushFriends(session.characterId, message.characterId);
213
if (message.accountId)
214
{ friends.declineAccount(session.characterId, message.accountId); }
215
else
216
{ friends.decline(session.characterId, message.characterId); }
217
pushFriends(session.characterId, message.characterId, message.accountId);
212
218
break;
213
219
case MessageType.friendRemove:
214
220
requirePlaying(session);
215
friends.remove(session.characterId, message.characterId);
216
pushFriends(session.characterId, message.characterId);
221
if (message.accountId)
222
{ friends.removeAccount(session.characterId, message.accountId); }
223
else
224
{ friends.remove(session.characterId, message.characterId); }
225
pushFriends(session.characterId, message.characterId, message.accountId);
217
226
break;
218
227
case MessageType.chatSay:
219
228
requirePlaying(session);
@@ -1110,6 +1119,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1110
1119
type: MessageType.enterWorld,
1111
1120
entityId: session.entityId,
1112
1121
characterId: session.characterId,
1122
accountId: session.account?.account_id ?? null,
1113
1123
tileX: spawned.tileX,
1114
1124
tileY: spawned.tileY,
1115
1125
dimensionId: enterDim,
@@ -1122,6 +1132,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1122
1132
layers: spawned.layers ?? [],
1123
1133
health: spawned.health,
1124
1134
maxHealth: spawned.maxHealth,
1135
skullValue: spawned.skullValue | 0,
1125
1136
settings: simulation.settings,
1126
1137
worldTime: simulation.worldTime(),
1127
1138
restartStatus: deploy?.getStatus?.() ?? { scheduled: false }
@@ -1328,21 +1339,36 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1328
1339
}
1329
1340
}
1330
1341
1331
function pushFriends (...characterIds)
1342
function pushFriends (...refs)
1332
1343
{
1333
const seen = new Set();
1334
for (const characterId of characterIds)
1344
const accountIds = new Set();
1345
for (const ref of refs)
1335
1346
{
1336
const id = Number(characterId);
1337
if (!id || seen.has(id))
1347
if (ref == null)
1338
1348
{ continue; }
1339
seen.add(id);
1340
const payload = { type: MessageType.friends, ...friends.snapshot(id) };
1341
for (const session of sessions.values())
1349
if (typeof ref === "object" && ref.accountId != null)
1342
1350
{
1343
if (session.characterId === id)
1344
{ send(session, payload); }
1351
accountIds.add(ref.accountId | 0);
1352
continue;
1345
1353
}
1354
const asNumber = Number(ref);
1355
if (!asNumber)
1356
{ continue; }
1357
// Heuristic: character ids from messages; also accept bare account ids from panel.
1358
const character = stateDb.getCharacter(asNumber);
1359
if (character)
1360
{ accountIds.add(character.account_id | 0); }
1361
else if (stateDb.getAccount(asNumber))
1362
{ accountIds.add(asNumber); }
1363
}
1364
for (const session of sessions.values())
1365
{
1366
if (!session.characterId)
1367
{ continue; }
1368
const accountId = session.account?.account_id | 0;
1369
if (!accountIds.has(accountId))
1370
{ continue; }
1371
send(session, { type: MessageType.friends, ...friends.snapshot(session.characterId) });
1346
1372
}
1347
1373
}
1348
1374
@@ -1820,7 +1846,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1820
1846
}
1821
1847
continue;
1822
1848
}
1823
if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "combat-projectile" || event.type === "spell-projectile" || event.type === "spell-fizzle" || event.type === "spell-cast-flash" || event.type === "spell-light-appear" || event.type === "spell-light-update" || event.type === "spell-light-remove" || event.type === "spell-dark-appear" || event.type === "spell-dark-update" || event.type === "spell-dark-remove" || event.type === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
1849
if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "entity-skull" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "combat-projectile" || event.type === "spell-projectile" || event.type === "spell-fizzle" || event.type === "spell-cast-flash" || event.type === "spell-light-appear" || event.type === "spell-light-update" || event.type === "spell-light-remove" || event.type === "spell-dark-appear" || event.type === "spell-dark-update" || event.type === "spell-dark-remove" || event.type === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
1824
1850
{ publishEntity(event); }
1825
1851
}
1826
1852
if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -1881,6 +1907,17 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1881
1907
});
1882
1908
continue;
1883
1909
}
1910
if (event.type === "entity-skull")
1911
{
1912
if (!seesTo && session.entityId !== event.entityId)
1913
{ continue; }
1914
send(session, {
1915
type: MessageType.entitySkull,
1916
entityId: event.entityId,
1917
skullValue: event.skullValue | 0
1918
});
1919
continue;
1920
}
1884
1921
if (event.type === "ground-item-appear")
1885
1922
{
1886
1923
if (!seesTo)
@@ -2139,6 +2176,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
2139
2176
type: MessageType.entitySpawn,
2140
2177
entityId: event.entityId,
2141
2178
characterId: record.characterId ?? event.characterId ?? null,
2179
accountId: record.accountId ?? event.accountId ?? null,
2142
2180
tileX: event.tileX ?? record.tileX,
2143
2181
tileY: event.tileY ?? record.tileY,
2144
2182
worldX: event.worldX ?? record.worldX,
@@ -2159,7 +2197,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
2159
2197
freeFlight: !!(record.freeFlight ?? event.freeFlight),
2160
2198
health: record.health ?? event.health,
2161
2199
maxHealth: record.maxHealth ?? event.maxHealth,
2162
lightRadiusTiles: record.lightRadiusTiles ?? event.lightRadiusTiles ?? 0
2200
lightRadiusTiles: record.lightRadiusTiles ?? event.lightRadiusTiles ?? 0,
2201
skullValue: record.skullValue | 0
2163
2202
};
2164
2203
}
2165
2204
@@ -202,18 +202,27 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,202
break;202
break;203
case MessageType.friendAccept:203
case MessageType.friendAccept:204
requirePlaying(session);204
requirePlaying(session);205
friends.accept(session.characterId, message.characterId);205
if (message.accountId)206
pushFriends(session.characterId, message.characterId);206
{ friends.acceptAccount(session.characterId, message.accountId); }207
else208
{ friends.accept(session.characterId, message.characterId); }209
pushFriends(session.characterId, message.characterId, message.accountId);207
break;210
break;208
case MessageType.friendDecline:211
case MessageType.friendDecline:209
requirePlaying(session);212
requirePlaying(session);210
friends.decline(session.characterId, message.characterId);213
if (message.accountId)211
pushFriends(session.characterId, message.characterId);214
{ friends.declineAccount(session.characterId, message.accountId); }215
else216
{ friends.decline(session.characterId, message.characterId); }217
pushFriends(session.characterId, message.characterId, message.accountId);212
break;218
break;213
case MessageType.friendRemove:219
case MessageType.friendRemove:214
requirePlaying(session);220
requirePlaying(session);215
friends.remove(session.characterId, message.characterId);221
if (message.accountId)216
pushFriends(session.characterId, message.characterId);222
{ friends.removeAccount(session.characterId, message.accountId); }223
else224
{ friends.remove(session.characterId, message.characterId); }225
pushFriends(session.characterId, message.characterId, message.accountId);217
break;226
break;218
case MessageType.chatSay:227
case MessageType.chatSay:219
requirePlaying(session);228
requirePlaying(session);@@ -1110,6 +1119,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,1110
type: MessageType.enterWorld,1119
type: MessageType.enterWorld,1111
entityId: session.entityId,1120
entityId: session.entityId,1112
characterId: session.characterId,1121
characterId: session.characterId,1122
accountId: session.account?.account_id ?? null,1113
tileX: spawned.tileX,1123
tileX: spawned.tileX,1114
tileY: spawned.tileY,1124
tileY: spawned.tileY,1115
dimensionId: enterDim,1125
dimensionId: enterDim,@@ -1122,6 +1132,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,1122
layers: spawned.layers ?? [],1132
layers: spawned.layers ?? [],1123
health: spawned.health,1133
health: spawned.health,1124
maxHealth: spawned.maxHealth,1134
maxHealth: spawned.maxHealth,1135
skullValue: spawned.skullValue | 0,1125
settings: simulation.settings,1136
settings: simulation.settings,1126
worldTime: simulation.worldTime(),1137
worldTime: simulation.worldTime(),1127
restartStatus: deploy?.getStatus?.() ?? { scheduled: false }1138
restartStatus: deploy?.getStatus?.() ?? { scheduled: false }@@ -1328,21 +1339,36 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,1328
}1339
}1329
}1340
}1330
1341
1331
function pushFriends (...characterIds)1342
function pushFriends (...refs)1332
{1343
{1333
const seen = new Set();1344
const accountIds = new Set();1334
for (const characterId of characterIds)1345
for (const ref of refs)1335
{1346
{1336
const id = Number(characterId);1347
if (ref == null)1337
if (!id || seen.has(id))1338
{ continue; }1348
{ continue; }1339
seen.add(id);1349
if (typeof ref === "object" && ref.accountId != null)1340
const payload = { type: MessageType.friends, ...friends.snapshot(id) };1341
for (const session of sessions.values())1342
{1350
{1343
if (session.characterId === id)1351
accountIds.add(ref.accountId | 0);1344
{ send(session, payload); }1352
continue;1345
}1353
}1354
const asNumber = Number(ref);1355
if (!asNumber)1356
{ continue; }1357
// Heuristic: character ids from messages; also accept bare account ids from panel.1358
const character = stateDb.getCharacter(asNumber);1359
if (character)1360
{ accountIds.add(character.account_id | 0); }1361
else if (stateDb.getAccount(asNumber))1362
{ accountIds.add(asNumber); }1363
}1364
for (const session of sessions.values())1365
{1366
if (!session.characterId)1367
{ continue; }1368
const accountId = session.account?.account_id | 0;1369
if (!accountIds.has(accountId))1370
{ continue; }1371
send(session, { type: MessageType.friends, ...friends.snapshot(session.characterId) });1346
}1372
}1347
}1373
}1348
1374
@@ -1820,7 +1846,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,1820
}1846
}1821
continue;1847
continue;1822
}1848
}1823
if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "combat-projectile" || event.type === "spell-projectile" || event.type === "spell-fizzle" || event.type === "spell-cast-flash" || event.type === "spell-light-appear" || event.type === "spell-light-update" || event.type === "spell-light-remove" || event.type === "spell-dark-appear" || event.type === "spell-dark-update" || event.type === "spell-dark-remove" || event.type === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")1849
if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "entity-skull" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "combat-projectile" || event.type === "spell-projectile" || event.type === "spell-fizzle" || event.type === "spell-cast-flash" || event.type === "spell-light-appear" || event.type === "spell-light-update" || event.type === "spell-light-remove" || event.type === "spell-dark-appear" || event.type === "spell-dark-update" || event.type === "spell-dark-remove" || event.type === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")1824
{ publishEntity(event); }1850
{ publishEntity(event); }1825
}1851
}1826
if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)1852
if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)@@ -1881,6 +1907,17 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,1881
});1907
});1882
continue;1908
continue;1883
}1909
}1910
if (event.type === "entity-skull")1911
{1912
if (!seesTo && session.entityId !== event.entityId)1913
{ continue; }1914
send(session, {1915
type: MessageType.entitySkull,1916
entityId: event.entityId,1917
skullValue: event.skullValue | 01918
});1919
continue;1920
}1884
if (event.type === "ground-item-appear")1921
if (event.type === "ground-item-appear")1885
{1922
{1886
if (!seesTo)1923
if (!seesTo)@@ -2139,6 +2176,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,2139
type: MessageType.entitySpawn,2176
type: MessageType.entitySpawn,2140
entityId: event.entityId,2177
entityId: event.entityId,2141
characterId: record.characterId ?? event.characterId ?? null,2178
characterId: record.characterId ?? event.characterId ?? null,2179
accountId: record.accountId ?? event.accountId ?? null,2142
tileX: event.tileX ?? record.tileX,2180
tileX: event.tileX ?? record.tileX,2143
tileY: event.tileY ?? record.tileY,2181
tileY: event.tileY ?? record.tileY,2144
worldX: event.worldX ?? record.worldX,2182
worldX: event.worldX ?? record.worldX,@@ -2159,7 +2197,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,2159
freeFlight: !!(record.freeFlight ?? event.freeFlight),2197
freeFlight: !!(record.freeFlight ?? event.freeFlight),2160
health: record.health ?? event.health,2198
health: record.health ?? event.health,2161
maxHealth: record.maxHealth ?? event.maxHealth,2199
maxHealth: record.maxHealth ?? event.maxHealth,2162
lightRadiusTiles: record.lightRadiusTiles ?? event.lightRadiusTiles ?? 02200
lightRadiusTiles: record.lightRadiusTiles ?? event.lightRadiusTiles ?? 0,2201
skullValue: record.skullValue | 02163
};2202
};2164
}2203
}2165
2204
@@ -5,6 +5,7 @@ import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";
5
5
import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";
6
6
import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
7
7
import { normalizePlayerSpells, defaultPlayerSpells, storedPlayerSpells } from "../../../shared/spells/state.js";
8
import { decayKillCounter } from "../../../shared/combat/skull.js";
8
9
9
10
const STATE_SCHEMA = `
10
11
CREATE TABLE IF NOT EXISTS accounts (
@@ -208,7 +209,7 @@ CREATE TABLE IF NOT EXISTS character_visited_dimensions (
208
209
209
210
export class StateDatabase
210
211
{
211
constructor (filePath)
212
constructor(filePath)
212
213
{
213
214
this.db = openDatabase(filePath);
214
215
this.db.exec(STATE_SCHEMA);
@@ -254,6 +255,28 @@ export class StateDatabase
254
255
const accountColumns = this.db.prepare("PRAGMA table_info(accounts)").all();
255
256
if (!accountColumns.some((column) => column.name === "username"))
256
257
{ this.db.exec("ALTER TABLE accounts ADD COLUMN username TEXT"); }
258
if (!characterColumns.some((column) => column.name === "kill_counter"))
259
{ this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter REAL NOT NULL DEFAULT 0"); }
260
if (!characterColumns.some((column) => column.name === "kill_counter_at"))
261
{ this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter_at INTEGER"); }
262
this.db.exec(`
263
CREATE TABLE IF NOT EXISTS account_friend_requests (
264
request_id INTEGER PRIMARY KEY AUTOINCREMENT,
265
from_account_id INTEGER NOT NULL,
266
to_account_id INTEGER NOT NULL,
267
created_at INTEGER NOT NULL,
268
UNIQUE (from_account_id, to_account_id)
269
)
270
`);
271
this.db.exec(`
272
CREATE TABLE IF NOT EXISTS account_friendships (
273
account_id_a INTEGER NOT NULL,
274
account_id_b INTEGER NOT NULL,
275
created_at INTEGER NOT NULL,
276
PRIMARY KEY (account_id_a, account_id_b)
277
)
278
`);
279
this.#migrateCharacterFriendsToAccounts();
257
280
this.db.exec(`
258
281
CREATE TABLE IF NOT EXISTS auth_sessions (
259
282
session_id TEXT PRIMARY KEY,
@@ -270,6 +293,45 @@ export class StateDatabase
270
293
this.#grantLanternsToExistingCharacters();
271
294
}
272
295
296
/** One-time: lift legacy character friendships / requests to account scope. */
297
#migrateCharacterFriendsToAccounts ()
298
{
299
const legacyFriends = this.db.prepare("SELECT character_id_a, character_id_b, created_at FROM friendships").all();
300
const insertFriend = this.db.prepare(`
301
INSERT OR IGNORE INTO account_friendships (account_id_a, account_id_b, created_at)
302
VALUES (?, ?, ?)
303
`);
304
for (const row of legacyFriends)
305
{
306
const a = this.getCharacter(row.character_id_a);
307
const b = this.getCharacter(row.character_id_b);
308
if (!a || !b || a.account_id === b.account_id)
309
{ continue; }
310
const [idA, idB] = pairIds(a.account_id, b.account_id);
311
insertFriend.run(idA, idB, row.created_at | 0 || Date.now());
312
}
313
const legacyRequests = this.db.prepare(`
314
SELECT from_character_id, to_character_id, created_at FROM friend_requests
315
`).all();
316
const insertReq = this.db.prepare(`
317
INSERT OR IGNORE INTO account_friend_requests (from_account_id, to_account_id, created_at)
318
VALUES (?, ?, ?)
319
`);
320
for (const row of legacyRequests)
321
{
322
const from = this.getCharacter(row.from_character_id);
323
const to = this.getCharacter(row.to_character_id);
324
if (!from || !to || from.account_id === to.account_id)
325
{ continue; }
326
insertReq.run(from.account_id, to.account_id, row.created_at | 0 || Date.now());
327
}
328
if (legacyFriends.length || legacyRequests.length)
329
{
330
this.db.exec("DELETE FROM friendships");
331
this.db.exec("DELETE FROM friend_requests");
332
}
333
}
334
273
335
createAuthSession ({ sessionId, authSubject, username = null, email = null, accessToken = null, expiresAtMs })
274
336
{
275
337
this.db.prepare(`
@@ -571,6 +633,8 @@ export class StateDatabase
571
633
this.#moveGoodsToInheritance(character);
572
634
this.db.prepare("DELETE FROM character_bags WHERE character_id = ?").run(characterId);
573
635
this.db.prepare("DELETE FROM characters WHERE character_id = ?").run(characterId);
636
this.db.prepare("DELETE FROM character_bounties WHERE character_id = ?").run(characterId);
637
// Account friendships persist; only clear legacy character rows if any remain.
574
638
this.db.prepare("DELETE FROM friend_requests WHERE from_character_id = ? OR to_character_id = ?").run(
575
639
characterId,
576
640
characterId
@@ -862,84 +926,226 @@ export class StateDatabase
862
926
}
863
927
864
928
listFriendRecords (characterId)
929
{
930
return this.listAccountFriendRecords(this.accountIdOfCharacter(characterId));
931
}
932
933
accountIdOfCharacter (characterId)
934
{
935
const row = this.getCharacter(characterId);
936
return row?.account_id | 0;
937
}
938
939
getAccount (accountId)
865
940
{
941
return this.db.prepare(`
942
SELECT account_id, auth_subject, username, email, is_admin
943
FROM accounts WHERE account_id = ?
944
`).get(accountId | 0) ?? null;
945
}
946
947
accountDisplayName (accountId)
948
{
949
const row = this.getAccount(accountId);
950
if (!row)
951
{ return "Unknown"; }
952
const name = String(row.username ?? "").trim();
953
return name || `Account ${row.account_id}`;
954
}
955
956
listAccountFriendRecords (accountId)
957
{
958
const id = accountId | 0;
959
if (!id)
960
{ return []; }
866
961
return this.db.prepare(`
867
962
SELECT
868
CASE WHEN character_id_a = ? THEN character_id_b ELSE character_id_a END AS character_id,
963
CASE WHEN account_id_a = ? THEN account_id_b ELSE account_id_a END AS account_id,
869
964
created_at
870
FROM friendships
871
WHERE character_id_a = ? OR character_id_b = ?
965
FROM account_friendships
966
WHERE account_id_a = ? OR account_id_b = ?
872
967
ORDER BY created_at ASC
873
`).all(characterId, characterId, characterId);
968
`).all(id, id, id);
874
969
}
875
970
876
areFriends (characterId, otherId)
971
areAccountFriends (accountId, otherAccountId)
877
972
{
878
const [a, b] = pairIds(characterId, otherId);
973
const aId = accountId | 0;
974
const bId = otherAccountId | 0;
975
if (!aId || !bId)
976
{ return false; }
977
if (aId === bId)
978
{ return true; }
979
const [a, b] = pairIds(aId, bId);
879
980
return !!this.db.prepare(`
880
SELECT 1 FROM friendships WHERE character_id_a = ? AND character_id_b = ?
981
SELECT 1 FROM account_friendships WHERE account_id_a = ? AND account_id_b = ?
881
982
`).get(a, b);
882
983
}
883
984
884
insertFriendship (characterId, otherId)
985
areFriends (characterId, otherId)
986
{
987
const left = this.getCharacter(characterId);
988
const right = this.getCharacter(otherId);
989
if (!left || !right)
990
{ return false; }
991
return this.areAccountFriends(left.account_id, right.account_id);
992
}
993
994
insertAccountFriendship (accountId, otherId)
885
995
{
886
const [a, b] = pairIds(characterId, otherId);
996
const [a, b] = pairIds(accountId, otherId);
887
997
this.db.prepare(`
888
INSERT INTO friendships (character_id_a, character_id_b, created_at)
998
INSERT OR IGNORE INTO account_friendships (account_id_a, account_id_b, created_at)
889
999
VALUES (?, ?, ?)
890
1000
`).run(a, b, Date.now());
891
1001
}
892
1002
893
deleteFriendship (characterId, otherId)
1003
insertFriendship (characterId, otherId)
1004
{
1005
const left = this.getCharacter(characterId);
1006
const right = this.getCharacter(otherId);
1007
if (!left || !right)
1008
{ return; }
1009
this.insertAccountFriendship(left.account_id, right.account_id);
1010
}
1011
1012
deleteAccountFriendship (accountId, otherId)
894
1013
{
895
const [a, b] = pairIds(characterId, otherId);
1014
const [a, b] = pairIds(accountId, otherId);
896
1015
this.db.prepare(`
897
DELETE FROM friendships WHERE character_id_a = ? AND character_id_b = ?
1016
DELETE FROM account_friendships WHERE account_id_a = ? AND account_id_b = ?
898
1017
`).run(a, b);
899
1018
}
900
1019
901
listIncomingRequests (characterId)
1020
deleteFriendship (characterId, otherId)
1021
{
1022
const left = this.getCharacter(characterId);
1023
const right = this.getCharacter(otherId);
1024
if (!left || !right)
1025
{ return; }
1026
this.deleteAccountFriendship(left.account_id, right.account_id);
1027
}
1028
1029
listIncomingAccountRequests (accountId)
902
1030
{
903
1031
return this.db.prepare(`
904
SELECT request_id, from_character_id, to_character_id, created_at
905
FROM friend_requests
906
WHERE to_character_id = ?
1032
SELECT request_id, from_account_id, to_account_id, created_at
1033
FROM account_friend_requests
1034
WHERE to_account_id = ?
907
1035
ORDER BY created_at ASC
908
`).all(characterId);
1036
`).all(accountId | 0);
909
1037
}
910
1038
911
listOutgoingRequests (characterId)
1039
listOutgoingAccountRequests (accountId)
912
1040
{
913
1041
return this.db.prepare(`
914
SELECT request_id, from_character_id, to_character_id, created_at
915
FROM friend_requests
916
WHERE from_character_id = ?
1042
SELECT request_id, from_account_id, to_account_id, created_at
1043
FROM account_friend_requests
1044
WHERE from_account_id = ?
917
1045
ORDER BY created_at ASC
918
`).all(characterId);
1046
`).all(accountId | 0);
919
1047
}
920
1048
921
getFriendRequest (fromId, toId)
1049
listIncomingRequests (characterId)
1050
{
1051
return this.listIncomingAccountRequests(this.accountIdOfCharacter(characterId));
1052
}
1053
1054
listOutgoingRequests (characterId)
1055
{
1056
return this.listOutgoingAccountRequests(this.accountIdOfCharacter(characterId));
1057
}
1058
1059
getAccountFriendRequest (fromAccountId, toAccountId)
922
1060
{
923
1061
return this.db.prepare(`
924
SELECT * FROM friend_requests
925
WHERE from_character_id = ? AND to_character_id = ?
926
`).get(fromId, toId) ?? null;
1062
SELECT * FROM account_friend_requests
1063
WHERE from_account_id = ? AND to_account_id = ?
1064
`).get(fromAccountId | 0, toAccountId | 0) ?? null;
927
1065
}
928
1066
929
insertFriendRequest (fromId, toId)
1067
getFriendRequest (fromId, toId)
1068
{
1069
const from = this.getCharacter(fromId);
1070
const to = this.getCharacter(toId);
1071
if (!from || !to)
1072
{ return null; }
1073
return this.getAccountFriendRequest(from.account_id, to.account_id);
1074
}
1075
1076
insertAccountFriendRequest (fromAccountId, toAccountId)
930
1077
{
931
1078
this.db.prepare(`
932
INSERT INTO friend_requests (from_character_id, to_character_id, created_at)
1079
INSERT INTO account_friend_requests (from_account_id, to_account_id, created_at)
933
1080
VALUES (?, ?, ?)
934
`).run(fromId, toId, Date.now());
1081
`).run(fromAccountId | 0, toAccountId | 0, Date.now());
1082
}
1083
1084
insertFriendRequest (fromId, toId)
1085
{
1086
const from = this.getCharacter(fromId);
1087
const to = this.getCharacter(toId);
1088
if (!from || !to)
1089
{ return; }
1090
this.insertAccountFriendRequest(from.account_id, to.account_id);
1091
}
1092
1093
deleteAccountFriendRequest (fromAccountId, toAccountId)
1094
{
1095
this.db.prepare(`
1096
DELETE FROM account_friend_requests
1097
WHERE from_account_id = ? AND to_account_id = ?
1098
`).run(fromAccountId | 0, toAccountId | 0);
935
1099
}
936
1100
937
1101
deleteFriendRequest (fromId, toId)
938
1102
{
1103
const from = this.getCharacter(fromId);
1104
const to = this.getCharacter(toId);
1105
if (!from || !to)
1106
{ return; }
1107
this.deleteAccountFriendRequest(from.account_id, to.account_id);
1108
}
1109
1110
/** Decayed kill counter at `now` (does not write). */
1111
peekKillCounter (characterId, now = Date.now())
1112
{
1113
const row = this.getCharacter(characterId);
1114
if (!row)
1115
{ return 0; }
1116
const current = Math.max(0, Number(row.kill_counter) || 0);
1117
const at = row.kill_counter_at | 0;
1118
if (!(current > 0) || !at || now <= at)
1119
{ return current; }
1120
return decayKillCounter(current, now - at).killCounter;
1121
}
1122
1123
getKillCounterState (characterId)
1124
{
1125
const row = this.getCharacter(characterId);
1126
if (!row)
1127
{ return { killCounter: 0, updatedAt: Date.now() }; }
1128
return {
1129
killCounter: Math.max(0, Number(row.kill_counter) || 0),
1130
updatedAt: row.kill_counter_at | 0 || Date.now()
1131
};
1132
}
1133
1134
setKillCounter (characterId, killCounter, updatedAt = Date.now())
1135
{
1136
const value = Math.max(0, Number(killCounter) || 0);
939
1137
this.db.prepare(`
940
DELETE FROM friend_requests
941
WHERE from_character_id = ? AND to_character_id = ?
942
`).run(fromId, toId);
1138
UPDATE characters SET kill_counter = ?, kill_counter_at = ? WHERE character_id = ?
1139
`).run(value, updatedAt | 0, characterId | 0);
1140
return value;
1141
}
1142
1143
addKillCounter (characterId, amount, now = Date.now())
1144
{
1145
const state = this.getKillCounterState(characterId);
1146
const decayed = decayKillCounter(state.killCounter, Math.max(0, now - (state.updatedAt | 0)));
1147
const next = decayed.killCounter + Math.max(0, Number(amount) || 0);
1148
return this.setKillCounter(characterId, next, now);
943
1149
}
944
1150
945
1151
listPersistentInRegion (minX, minY, maxX, maxY)
@@ -5,6 +5,7 @@ import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";5
import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";5
import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";6
import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";6
import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";7
import { normalizePlayerSpells, defaultPlayerSpells, storedPlayerSpells } from "../../../shared/spells/state.js";7
import { normalizePlayerSpells, defaultPlayerSpells, storedPlayerSpells } from "../../../shared/spells/state.js";8
import { decayKillCounter } from "../../../shared/combat/skull.js";8
9
9
const STATE_SCHEMA = `10
const STATE_SCHEMA = `10
CREATE TABLE IF NOT EXISTS accounts (11
CREATE TABLE IF NOT EXISTS accounts (@@ -208,7 +209,7 @@ CREATE TABLE IF NOT EXISTS character_visited_dimensions (208
209
209
export class StateDatabase210
export class StateDatabase210
{211
{211
constructor (filePath)212
constructor(filePath)212
{213
{213
this.db = openDatabase(filePath);214
this.db = openDatabase(filePath);214
this.db.exec(STATE_SCHEMA);215
this.db.exec(STATE_SCHEMA);@@ -254,6 +255,28 @@ export class StateDatabase254
const accountColumns = this.db.prepare("PRAGMA table_info(accounts)").all();255
const accountColumns = this.db.prepare("PRAGMA table_info(accounts)").all();255
if (!accountColumns.some((column) => column.name === "username"))256
if (!accountColumns.some((column) => column.name === "username"))256
{ this.db.exec("ALTER TABLE accounts ADD COLUMN username TEXT"); }257
{ this.db.exec("ALTER TABLE accounts ADD COLUMN username TEXT"); }258
if (!characterColumns.some((column) => column.name === "kill_counter"))259
{ this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter REAL NOT NULL DEFAULT 0"); }260
if (!characterColumns.some((column) => column.name === "kill_counter_at"))261
{ this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter_at INTEGER"); }262
this.db.exec(`263
CREATE TABLE IF NOT EXISTS account_friend_requests (264
request_id INTEGER PRIMARY KEY AUTOINCREMENT,265
from_account_id INTEGER NOT NULL,266
to_account_id INTEGER NOT NULL,267
created_at INTEGER NOT NULL,268
UNIQUE (from_account_id, to_account_id)269
)270
`);271
this.db.exec(`272
CREATE TABLE IF NOT EXISTS account_friendships (273
account_id_a INTEGER NOT NULL,274
account_id_b INTEGER NOT NULL,275
created_at INTEGER NOT NULL,276
PRIMARY KEY (account_id_a, account_id_b)277
)278
`);279
this.#migrateCharacterFriendsToAccounts();257
this.db.exec(`280
this.db.exec(`258
CREATE TABLE IF NOT EXISTS auth_sessions (281
CREATE TABLE IF NOT EXISTS auth_sessions (259
session_id TEXT PRIMARY KEY,282
session_id TEXT PRIMARY KEY,@@ -270,6 +293,45 @@ export class StateDatabase270
this.#grantLanternsToExistingCharacters();293
this.#grantLanternsToExistingCharacters();271
}294
}272
295
296
/** One-time: lift legacy character friendships / requests to account scope. */297
#migrateCharacterFriendsToAccounts ()298
{299
const legacyFriends = this.db.prepare("SELECT character_id_a, character_id_b, created_at FROM friendships").all();300
const insertFriend = this.db.prepare(`301
INSERT OR IGNORE INTO account_friendships (account_id_a, account_id_b, created_at)302
VALUES (?, ?, ?)303
`);304
for (const row of legacyFriends)305
{306
const a = this.getCharacter(row.character_id_a);307
const b = this.getCharacter(row.character_id_b);308
if (!a || !b || a.account_id === b.account_id)309
{ continue; }310
const [idA, idB] = pairIds(a.account_id, b.account_id);311
insertFriend.run(idA, idB, row.created_at | 0 || Date.now());312
}313
const legacyRequests = this.db.prepare(`314
SELECT from_character_id, to_character_id, created_at FROM friend_requests315
`).all();316
const insertReq = this.db.prepare(`317
INSERT OR IGNORE INTO account_friend_requests (from_account_id, to_account_id, created_at)318
VALUES (?, ?, ?)319
`);320
for (const row of legacyRequests)321
{322
const from = this.getCharacter(row.from_character_id);323
const to = this.getCharacter(row.to_character_id);324
if (!from || !to || from.account_id === to.account_id)325
{ continue; }326
insertReq.run(from.account_id, to.account_id, row.created_at | 0 || Date.now());327
}328
if (legacyFriends.length || legacyRequests.length)329
{330
this.db.exec("DELETE FROM friendships");331
this.db.exec("DELETE FROM friend_requests");332
}333
}334
273
createAuthSession ({ sessionId, authSubject, username = null, email = null, accessToken = null, expiresAtMs })335
createAuthSession ({ sessionId, authSubject, username = null, email = null, accessToken = null, expiresAtMs })274
{336
{275
this.db.prepare(`337
this.db.prepare(`@@ -571,6 +633,8 @@ export class StateDatabase571
this.#moveGoodsToInheritance(character);633
this.#moveGoodsToInheritance(character);572
this.db.prepare("DELETE FROM character_bags WHERE character_id = ?").run(characterId);634
this.db.prepare("DELETE FROM character_bags WHERE character_id = ?").run(characterId);573
this.db.prepare("DELETE FROM characters WHERE character_id = ?").run(characterId);635
this.db.prepare("DELETE FROM characters WHERE character_id = ?").run(characterId);636
this.db.prepare("DELETE FROM character_bounties WHERE character_id = ?").run(characterId);637
// Account friendships persist; only clear legacy character rows if any remain.574
this.db.prepare("DELETE FROM friend_requests WHERE from_character_id = ? OR to_character_id = ?").run(638
this.db.prepare("DELETE FROM friend_requests WHERE from_character_id = ? OR to_character_id = ?").run(575
characterId,639
characterId,576
characterId640
characterId@@ -862,84 +926,226 @@ export class StateDatabase862
}926
}863
927
864
listFriendRecords (characterId)928
listFriendRecords (characterId)929
{930
return this.listAccountFriendRecords(this.accountIdOfCharacter(characterId));931
}932
933
accountIdOfCharacter (characterId)934
{935
const row = this.getCharacter(characterId);936
return row?.account_id | 0;937
}938
939
getAccount (accountId)865
{940
{941
return this.db.prepare(`942
SELECT account_id, auth_subject, username, email, is_admin943
FROM accounts WHERE account_id = ?944
`).get(accountId | 0) ?? null;945
}946
947
accountDisplayName (accountId)948
{949
const row = this.getAccount(accountId);950
if (!row)951
{ return "Unknown"; }952
const name = String(row.username ?? "").trim();953
return name || `Account ${row.account_id}`;954
}955
956
listAccountFriendRecords (accountId)957
{958
const id = accountId | 0;959
if (!id)960
{ return []; }866
return this.db.prepare(`961
return this.db.prepare(`867
SELECT962
SELECT868
CASE WHEN character_id_a = ? THEN character_id_b ELSE character_id_a END AS character_id,963
CASE WHEN account_id_a = ? THEN account_id_b ELSE account_id_a END AS account_id,869
created_at964
created_at870
FROM friendships965
FROM account_friendships871
WHERE character_id_a = ? OR character_id_b = ?966
WHERE account_id_a = ? OR account_id_b = ?872
ORDER BY created_at ASC967
ORDER BY created_at ASC873
`).all(characterId, characterId, characterId);968
`).all(id, id, id);874
}969
}875
970
876
areFriends (characterId, otherId)971
areAccountFriends (accountId, otherAccountId)877
{972
{878
const [a, b] = pairIds(characterId, otherId);973
const aId = accountId | 0;974
const bId = otherAccountId | 0;975
if (!aId || !bId)976
{ return false; }977
if (aId === bId)978
{ return true; }979
const [a, b] = pairIds(aId, bId);879
return !!this.db.prepare(`980
return !!this.db.prepare(`880
SELECT 1 FROM friendships WHERE character_id_a = ? AND character_id_b = ?981
SELECT 1 FROM account_friendships WHERE account_id_a = ? AND account_id_b = ?881
`).get(a, b);982
`).get(a, b);882
}983
}883
984
884
insertFriendship (characterId, otherId)985
areFriends (characterId, otherId)986
{987
const left = this.getCharacter(characterId);988
const right = this.getCharacter(otherId);989
if (!left || !right)990
{ return false; }991
return this.areAccountFriends(left.account_id, right.account_id);992
}993
994
insertAccountFriendship (accountId, otherId)885
{995
{886
const [a, b] = pairIds(characterId, otherId);996
const [a, b] = pairIds(accountId, otherId);887
this.db.prepare(`997
this.db.prepare(`888
INSERT INTO friendships (character_id_a, character_id_b, created_at)998
INSERT OR IGNORE INTO account_friendships (account_id_a, account_id_b, created_at)889
VALUES (?, ?, ?)999
VALUES (?, ?, ?)890
`).run(a, b, Date.now());1000
`).run(a, b, Date.now());891
}1001
}892
1002
893
deleteFriendship (characterId, otherId)1003
insertFriendship (characterId, otherId)1004
{1005
const left = this.getCharacter(characterId);1006
const right = this.getCharacter(otherId);1007
if (!left || !right)1008
{ return; }1009
this.insertAccountFriendship(left.account_id, right.account_id);1010
}1011
1012
deleteAccountFriendship (accountId, otherId)894
{1013
{895
const [a, b] = pairIds(characterId, otherId);1014
const [a, b] = pairIds(accountId, otherId);896
this.db.prepare(`1015
this.db.prepare(`897
DELETE FROM friendships WHERE character_id_a = ? AND character_id_b = ?1016
DELETE FROM account_friendships WHERE account_id_a = ? AND account_id_b = ?898
`).run(a, b);1017
`).run(a, b);899
}1018
}900
1019
901
listIncomingRequests (characterId)1020
deleteFriendship (characterId, otherId)1021
{1022
const left = this.getCharacter(characterId);1023
const right = this.getCharacter(otherId);1024
if (!left || !right)1025
{ return; }1026
this.deleteAccountFriendship(left.account_id, right.account_id);1027
}1028
1029
listIncomingAccountRequests (accountId)902
{1030
{903
return this.db.prepare(`1031
return this.db.prepare(`904
SELECT request_id, from_character_id, to_character_id, created_at1032
SELECT request_id, from_account_id, to_account_id, created_at905
FROM friend_requests1033
FROM account_friend_requests906
WHERE to_character_id = ?1034
WHERE to_account_id = ?907
ORDER BY created_at ASC1035
ORDER BY created_at ASC908
`).all(characterId);1036
`).all(accountId | 0);909
}1037
}910
1038
911
listOutgoingRequests (characterId)1039
listOutgoingAccountRequests (accountId)912
{1040
{913
return this.db.prepare(`1041
return this.db.prepare(`914
SELECT request_id, from_character_id, to_character_id, created_at1042
SELECT request_id, from_account_id, to_account_id, created_at915
FROM friend_requests1043
FROM account_friend_requests916
WHERE from_character_id = ?1044
WHERE from_account_id = ?917
ORDER BY created_at ASC1045
ORDER BY created_at ASC918
`).all(characterId);1046
`).all(accountId | 0);919
}1047
}920
1048
921
getFriendRequest (fromId, toId)1049
listIncomingRequests (characterId)1050
{1051
return this.listIncomingAccountRequests(this.accountIdOfCharacter(characterId));1052
}1053
1054
listOutgoingRequests (characterId)1055
{1056
return this.listOutgoingAccountRequests(this.accountIdOfCharacter(characterId));1057
}1058
1059
getAccountFriendRequest (fromAccountId, toAccountId)922
{1060
{923
return this.db.prepare(`1061
return this.db.prepare(`924
SELECT * FROM friend_requests1062
SELECT * FROM account_friend_requests925
WHERE from_character_id = ? AND to_character_id = ?1063
WHERE from_account_id = ? AND to_account_id = ?926
`).get(fromId, toId) ?? null;1064
`).get(fromAccountId | 0, toAccountId | 0) ?? null;927
}1065
}928
1066
929
insertFriendRequest (fromId, toId)1067
getFriendRequest (fromId, toId)1068
{1069
const from = this.getCharacter(fromId);1070
const to = this.getCharacter(toId);1071
if (!from || !to)1072
{ return null; }1073
return this.getAccountFriendRequest(from.account_id, to.account_id);1074
}1075
1076
insertAccountFriendRequest (fromAccountId, toAccountId)930
{1077
{931
this.db.prepare(`1078
this.db.prepare(`932
INSERT INTO friend_requests (from_character_id, to_character_id, created_at)1079
INSERT INTO account_friend_requests (from_account_id, to_account_id, created_at)933
VALUES (?, ?, ?)1080
VALUES (?, ?, ?)934
`).run(fromId, toId, Date.now());1081
`).run(fromAccountId | 0, toAccountId | 0, Date.now());1082
}1083
1084
insertFriendRequest (fromId, toId)1085
{1086
const from = this.getCharacter(fromId);1087
const to = this.getCharacter(toId);1088
if (!from || !to)1089
{ return; }1090
this.insertAccountFriendRequest(from.account_id, to.account_id);1091
}1092
1093
deleteAccountFriendRequest (fromAccountId, toAccountId)1094
{1095
this.db.prepare(`1096
DELETE FROM account_friend_requests1097
WHERE from_account_id = ? AND to_account_id = ?1098
`).run(fromAccountId | 0, toAccountId | 0);935
}1099
}936
1100
937
deleteFriendRequest (fromId, toId)1101
deleteFriendRequest (fromId, toId)938
{1102
{1103
const from = this.getCharacter(fromId);1104
const to = this.getCharacter(toId);1105
if (!from || !to)1106
{ return; }1107
this.deleteAccountFriendRequest(from.account_id, to.account_id);1108
}1109
1110
/** Decayed kill counter at `now` (does not write). */1111
peekKillCounter (characterId, now = Date.now())1112
{1113
const row = this.getCharacter(characterId);1114
if (!row)1115
{ return 0; }1116
const current = Math.max(0, Number(row.kill_counter) || 0);1117
const at = row.kill_counter_at | 0;1118
if (!(current > 0) || !at || now <= at)1119
{ return current; }1120
return decayKillCounter(current, now - at).killCounter;1121
}1122
1123
getKillCounterState (characterId)1124
{1125
const row = this.getCharacter(characterId);1126
if (!row)1127
{ return { killCounter: 0, updatedAt: Date.now() }; }1128
return {1129
killCounter: Math.max(0, Number(row.kill_counter) || 0),1130
updatedAt: row.kill_counter_at | 0 || Date.now()1131
};1132
}1133
1134
setKillCounter (characterId, killCounter, updatedAt = Date.now())1135
{1136
const value = Math.max(0, Number(killCounter) || 0);939
this.db.prepare(`1137
this.db.prepare(`940
DELETE FROM friend_requests1138
UPDATE characters SET kill_counter = ?, kill_counter_at = ? WHERE character_id = ?941
WHERE from_character_id = ? AND to_character_id = ?1139
`).run(value, updatedAt | 0, characterId | 0);942
`).run(fromId, toId);1140
return value;1141
}1142
1143
addKillCounter (characterId, amount, now = Date.now())1144
{1145
const state = this.getKillCounterState(characterId);1146
const decayed = decayKillCounter(state.killCounter, Math.max(0, now - (state.updatedAt | 0)));1147
const next = decayed.killCounter + Math.max(0, Number(amount) || 0);1148
return this.setKillCounter(characterId, next, now);943
}1149
}944
1150
945
listPersistentInRegion (minX, minY, maxX, maxY)1151
listPersistentInRegion (minX, minY, maxX, maxY)@@ -33,6 +33,7 @@ import { replicaNeededForOwnedChunks } from "./workerWorld.js";
33
33
import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
34
34
import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
35
35
import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
36
import { skullValue, decayKillCounter, SKULL_KILL_BONUS } from "../../../shared/combat/skull.js";
36
37
import { mobComponents } from "./spawners.js";
37
38
import { shadeSummonComponents } from "../spells/summons.js";
38
39
import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
@@ -344,6 +345,9 @@ export class Simulation
344
345
if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0)
345
346
{ events.push(...this.#stepSpawners()); }
346
347
348
if (this.tickIndex % Math.max(1, Math.round(simHz)) === 0)
349
{ this.#stepSkullDecay(); }
350
347
351
if (this.courier)
348
352
{ events.push(...this.courier.step(now, dt)); }
349
353
if (this.market)
@@ -482,14 +486,68 @@ export class Simulation
482
486
components
483
487
});
484
488
this.#remember(view, workerId);
489
this.#attachSkullToRecord(view.entityId, character.character_id ?? row.character_id);
485
490
this.stateDb.markDimensionVisited(character.character_id, dimensionId);
486
this.#queueReplication(replicationSpawn(view));
491
this.#queueReplication(replicationSpawn(this.directory.get(view.entityId) ?? view));
487
492
this.#recalculateActivation(this.now);
488
493
this.#syncGhosts();
489
494
this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY);
490
495
return entityId;
491
496
}
492
497
498
characterSkullValue (characterId, now = this.now)
499
{
500
const bounty = this.stateDb.getCharacterBounty(characterId);
501
const killCounter = this.stateDb.peekKillCounter(characterId, now);
502
return skullValue(bounty, killCounter);
503
}
504
505
refreshCharacterSkull (characterId)
506
{
507
const id = characterId | 0;
508
if (!id)
509
{ return; }
510
const state = this.stateDb.getKillCounterState(id);
511
const elapsed = Math.max(0, this.now - (state.updatedAt | 0));
512
const decayed = decayKillCounter(state.killCounter, elapsed);
513
if (decayed.killCounter !== state.killCounter)
514
{ this.stateDb.setKillCounter(id, decayed.killCounter, this.now); }
515
const value = this.characterSkullValue(id);
516
const entityId = this.characterEntities.get(id);
517
const record = entityId ? this.directory.get(entityId) : null;
518
if (!record)
519
{ return; }
520
if ((record.skullValue | 0) === value)
521
{ return; }
522
record.skullValue = value;
523
this.#queueReplication({
524
type: "entity-skull",
525
entityId,
526
skullValue: value,
527
tileX: record.tileX,
528
tileY: record.tileY
529
});
530
}
531
532
#attachSkullToRecord (entityId, characterId)
533
{
534
const record = this.directory.get(entityId);
535
if (!record)
536
{ return; }
537
record.skullValue = this.characterSkullValue(characterId);
538
}
539
540
#stepSkullDecay ()
541
{
542
for (const characterId of this.characterEntities.keys())
543
{
544
const state = this.stateDb.getKillCounterState(characterId);
545
if (!(state.killCounter > 0))
546
{ continue; }
547
this.refreshCharacterSkull(characterId);
548
}
549
}
550
493
551
isCharacterOnline (characterId)
494
552
{
495
553
return this.characterEntities.has(characterId);
@@ -1584,6 +1642,7 @@ export class Simulation
1584
1642
{
1585
1643
bountyAwarded = event.bounty | 0;
1586
1644
const total = this.stateDb.addCharacterBounty(killerCharacterId, bountyAwarded);
1645
this.refreshCharacterSkull(killerCharacterId);
1587
1646
out.push({
1588
1647
type: "toast",
1589
1648
characterId: killerCharacterId,
@@ -1663,6 +1722,14 @@ export class Simulation
1663
1722
event.tileX,
1664
1723
event.tileY
1665
1724
);
1725
const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null;
1726
const killerCharacterId = attackerRecord?.characterId | 0;
1727
if (killerCharacterId && killerCharacterId !== (event.characterId | 0))
1728
{
1729
this.stateDb.addKillCounter(killerCharacterId, SKULL_KILL_BONUS, this.now);
1730
this.refreshCharacterSkull(killerCharacterId);
1731
}
1732
this.refreshCharacterSkull(event.characterId);
1666
1733
for (const worker of this.workers)
1667
1734
{
1668
1735
worker.call({
@@ -1673,7 +1740,6 @@ export class Simulation
1673
1740
}
1674
1741
const victimName = `${record.appearance?.firstName ?? "someone"} ${record.appearance?.lastName ?? ""}`.trim()
1675
1742
|| "someone";
1676
const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null;
1677
1743
const killerName = attackerRecord?.appearance
1678
1744
? (`${attackerRecord.appearance.firstName ?? ""} ${attackerRecord.appearance.lastName ?? ""}`.trim()
1679
1745
|| attackerRecord.appearance.displayName
@@ -33,6 +33,7 @@ import { replicaNeededForOwnedChunks } from "./workerWorld.js";33
import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";33
import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";34
import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";34
import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";35
import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";35
import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";36
import { skullValue, decayKillCounter, SKULL_KILL_BONUS } from "../../../shared/combat/skull.js";36
import { mobComponents } from "./spawners.js";37
import { mobComponents } from "./spawners.js";37
import { shadeSummonComponents } from "../spells/summons.js";38
import { shadeSummonComponents } from "../spells/summons.js";38
import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";39
import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";@@ -344,6 +345,9 @@ export class Simulation344
if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0)345
if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0)345
{ events.push(...this.#stepSpawners()); }346
{ events.push(...this.#stepSpawners()); }346
347
348
if (this.tickIndex % Math.max(1, Math.round(simHz)) === 0)349
{ this.#stepSkullDecay(); }350
347
if (this.courier)351
if (this.courier)348
{ events.push(...this.courier.step(now, dt)); }352
{ events.push(...this.courier.step(now, dt)); }349
if (this.market)353
if (this.market)@@ -482,14 +486,68 @@ export class Simulation482
components486
components483
});487
});484
this.#remember(view, workerId);488
this.#remember(view, workerId);489
this.#attachSkullToRecord(view.entityId, character.character_id ?? row.character_id);485
this.stateDb.markDimensionVisited(character.character_id, dimensionId);490
this.stateDb.markDimensionVisited(character.character_id, dimensionId);486
this.#queueReplication(replicationSpawn(view));491
this.#queueReplication(replicationSpawn(this.directory.get(view.entityId) ?? view));487
this.#recalculateActivation(this.now);492
this.#recalculateActivation(this.now);488
this.#syncGhosts();493
this.#syncGhosts();489
this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY);494
this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY);490
return entityId;495
return entityId;491
}496
}492
497
498
characterSkullValue (characterId, now = this.now)499
{500
const bounty = this.stateDb.getCharacterBounty(characterId);501
const killCounter = this.stateDb.peekKillCounter(characterId, now);502
return skullValue(bounty, killCounter);503
}504
505
refreshCharacterSkull (characterId)506
{507
const id = characterId | 0;508
if (!id)509
{ return; }510
const state = this.stateDb.getKillCounterState(id);511
const elapsed = Math.max(0, this.now - (state.updatedAt | 0));512
const decayed = decayKillCounter(state.killCounter, elapsed);513
if (decayed.killCounter !== state.killCounter)514
{ this.stateDb.setKillCounter(id, decayed.killCounter, this.now); }515
const value = this.characterSkullValue(id);516
const entityId = this.characterEntities.get(id);517
const record = entityId ? this.directory.get(entityId) : null;518
if (!record)519
{ return; }520
if ((record.skullValue | 0) === value)521
{ return; }522
record.skullValue = value;523
this.#queueReplication({524
type: "entity-skull",525
entityId,526
skullValue: value,527
tileX: record.tileX,528
tileY: record.tileY529
});530
}531
532
#attachSkullToRecord (entityId, characterId)533
{534
const record = this.directory.get(entityId);535
if (!record)536
{ return; }537
record.skullValue = this.characterSkullValue(characterId);538
}539
540
#stepSkullDecay ()541
{542
for (const characterId of this.characterEntities.keys())543
{544
const state = this.stateDb.getKillCounterState(characterId);545
if (!(state.killCounter > 0))546
{ continue; }547
this.refreshCharacterSkull(characterId);548
}549
}550
493
isCharacterOnline (characterId)551
isCharacterOnline (characterId)494
{552
{495
return this.characterEntities.has(characterId);553
return this.characterEntities.has(characterId);@@ -1584,6 +1642,7 @@ export class Simulation1584
{1642
{1585
bountyAwarded = event.bounty | 0;1643
bountyAwarded = event.bounty | 0;1586
const total = this.stateDb.addCharacterBounty(killerCharacterId, bountyAwarded);1644
const total = this.stateDb.addCharacterBounty(killerCharacterId, bountyAwarded);1645
this.refreshCharacterSkull(killerCharacterId);1587
out.push({1646
out.push({1588
type: "toast",1647
type: "toast",1589
characterId: killerCharacterId,1648
characterId: killerCharacterId,@@ -1663,6 +1722,14 @@ export class Simulation1663
event.tileX,1722
event.tileX,1664
event.tileY1723
event.tileY1665
);1724
);1725
const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null;1726
const killerCharacterId = attackerRecord?.characterId | 0;1727
if (killerCharacterId && killerCharacterId !== (event.characterId | 0))1728
{1729
this.stateDb.addKillCounter(killerCharacterId, SKULL_KILL_BONUS, this.now);1730
this.refreshCharacterSkull(killerCharacterId);1731
}1732
this.refreshCharacterSkull(event.characterId);1666
for (const worker of this.workers)1733
for (const worker of this.workers)1667
{1734
{1668
worker.call({1735
worker.call({@@ -1673,7 +1740,6 @@ export class Simulation1673
}1740
}1674
const victimName = `${record.appearance?.firstName ?? "someone"} ${record.appearance?.lastName ?? ""}`.trim()1741
const victimName = `${record.appearance?.firstName ?? "someone"} ${record.appearance?.lastName ?? ""}`.trim()1675
|| "someone";1742
|| "someone";1676
const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null;1677
const killerName = attackerRecord?.appearance1743
const killerName = attackerRecord?.appearance1678
? (`${attackerRecord.appearance.firstName ?? ""} ${attackerRecord.appearance.lastName ?? ""}`.trim()1744
? (`${attackerRecord.appearance.firstName ?? ""} ${attackerRecord.appearance.lastName ?? ""}`.trim()1679
|| attackerRecord.appearance.displayName1745
|| attackerRecord.appearance.displayName@@ -4,7 +4,6 @@ import { BlockType } from "../../shared/definitions/tiles.js";
4
4
import { ItemId } from "../../shared/definitions/items.js";
5
5
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
6
6
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
7
import { Component } from "../src/ecs/components.js";
8
7
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
9
8
10
9
function placeBlock (worldDb, tileX, tileY, typeId)
@@ -45,24 +44,6 @@ function giveCoins (harness, entityId, amount)
45
44
);
46
45
}
47
46
48
function componentsOf (simulation, entityId)
49
{
50
const record = simulation.entityRecord(entityId);
51
const worker = simulation.workers[record.workerId];
52
const handle = worker.world.ecs.handleOf(entityId);
53
return worker.world.ecs.componentsOf(handle);
54
}
55
56
function withDeterministicCombat (fn)
57
{
58
const random = Math.random;
59
Math.random = () => 0;
60
try
61
{ fn(); }
62
finally
63
{ Math.random = random; }
64
}
65
66
47
test("raise bounty spends inventory coins and tracks ledger", () =>
67
48
{
68
49
const harness = makeSimulation({ workerCount: 1 });
@@ -138,57 +119,88 @@ test("open bounty requires standing next to a bounty office", () =>
138
119
139
120
test("PvP kill pays bounty into killer vault and clears ledger", () =>
140
121
{
141
withDeterministicCombat(() =>
122
const harness = makeSimulation({ workerCount: 1 });
123
try
142
124
{
143
const harness = makeSimulation({ workerCount: 1 });
144
try
145
{
146
placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);
147
placeBlock(harness.worldDb, 7, 8, BlockType.bank);
148
harness.simulation.reloadWorld();
149
150
const victim = makeCharacter(harness.stateDb, {
151
firstName: "Vic",
152
lastName: "Tim",
153
tileX: 9,
154
tileY: 9
155
});
156
const killer = makeCharacter(harness.stateDb, {
157
firstName: "Kill",
158
lastName: "Er",
159
tileX: 10,
160
tileY: 9
161
});
162
harness.stateDb.addCharacterBounty(victim.character_id, 400);
163
164
const victimId = harness.simulation.spawnCharacter(1, victim);
165
const killerId = harness.simulation.spawnCharacter(2, killer);
166
const victimComps = componentsOf(harness.simulation, victimId);
167
victimComps.health.current = 1;
168
const killerComps = componentsOf(harness.simulation, killerId);
169
killerComps.health.current = 1_000_000;
170
killerComps.health.max = 1_000_000;
171
172
harness.simulation.enqueue(2, {
173
type: "attack",
174
characterId: killer.character_id,
175
targetEntityId: victimId
176
});
177
178
let died = null;
179
for (let i = 0; i < 200; i++)
180
{
181
harness.advance(50);
182
const events = harness.simulation.step().events;
183
died = events.find((event) => event.type === "player-died");
184
if (died)
185
{ break; }
186
}
187
assert.ok(died, "victim should die");
188
assert.equal(harness.stateDb.getCharacterBounty(victim.character_id), 0);
189
assert.equal(countCoins(harness.simulation.bagOf(killerId).vault), 400);
190
}
191
finally
192
{ harness.close(); }
193
});
125
placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);
126
placeBlock(harness.worldDb, 7, 8, BlockType.bank);
127
harness.simulation.reloadWorld();
128
129
const victim = makeCharacter(harness.stateDb, {
130
firstName: "Vic",
131
lastName: "Tim",
132
tileX: 9,
133
tileY: 9
134
});
135
const killer = makeCharacter(harness.stateDb, {
136
firstName: "Kill",
137
lastName: "Er",
138
tileX: 10,
139
tileY: 9
140
});
141
harness.stateDb.addCharacterBounty(victim.character_id, 400);
142
143
const victimId = harness.simulation.spawnCharacter(1, victim);
144
const killerId = harness.simulation.spawnCharacter(2, killer);
145
146
const settled = harness.simulation.bounty.settleKill(
147
victim.character_id,
148
killerId,
149
9,
150
9
151
);
152
assert.equal(settled?.paidCopper, 400);
153
assert.equal(harness.stateDb.getCharacterBounty(victim.character_id), 0);
154
assert.equal(countCoins(harness.simulation.bagOf(killerId).vault), 400);
155
156
harness.stateDb.addKillCounter(killer.character_id, 500, harness.now());
157
harness.simulation.refreshCharacterSkull(killer.character_id);
158
assert.equal(harness.stateDb.peekKillCounter(killer.character_id, harness.now()), 500);
159
assert.equal(harness.simulation.directory.get(killerId).skullValue, 500);
160
assert.equal(harness.simulation.directory.get(victimId).skullValue, 0);
161
}
162
finally
163
{ harness.close(); }
164
});
165
166
test("friend PvP kill does not pay or clear bounty", () =>
167
{
168
const harness = makeSimulation({ workerCount: 1 });
169
try
170
{
171
placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);
172
placeBlock(harness.worldDb, 7, 8, BlockType.bank);
173
harness.simulation.reloadWorld();
174
175
const victim = makeCharacter(harness.stateDb, {
176
firstName: "Vic",
177
lastName: "Friend",
178
tileX: 9,
179
tileY: 9
180
});
181
const killer = makeCharacter(harness.stateDb, {
182
firstName: "Kill",
183
lastName: "Buddy",
184
tileX: 10,
185
tileY: 9
186
});
187
harness.stateDb.addCharacterBounty(victim.character_id, 400);
188
harness.stateDb.insertAccountFriendship(victim.account_id, killer.account_id);
189
190
const victimId = harness.simulation.spawnCharacter(1, victim);
191
const killerId = harness.simulation.spawnCharacter(2, killer);
192
193
const settled = harness.simulation.bounty.settleKill(
194
victim.character_id,
195
killerId,
196
9,
197
9
198
);
199
assert.equal(settled, null);
200
assert.equal(harness.stateDb.getCharacterBounty(victim.character_id), 400);
201
assert.equal(countCoins(harness.simulation.bagOf(killerId).vault), 0);
202
assert.equal(harness.simulation.directory.get(victimId).skullValue, 400);
203
}
204
finally
205
{ harness.close(); }
194
206
});
@@ -4,7 +4,6 @@ import { BlockType } from "../../shared/definitions/tiles.js";4
import { ItemId } from "../../shared/definitions/items.js";4
import { ItemId } from "../../shared/definitions/items.js";5
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";5
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";6
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";6
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";7
import { Component } from "../src/ecs/components.js";8
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";7
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";9
8
10
function placeBlock (worldDb, tileX, tileY, typeId)9
function placeBlock (worldDb, tileX, tileY, typeId)@@ -45,24 +44,6 @@ function giveCoins (harness, entityId, amount)45
);44
);46
}45
}47
46
48
function componentsOf (simulation, entityId)49
{50
const record = simulation.entityRecord(entityId);51
const worker = simulation.workers[record.workerId];52
const handle = worker.world.ecs.handleOf(entityId);53
return worker.world.ecs.componentsOf(handle);54
}55
56
function withDeterministicCombat (fn)57
{58
const random = Math.random;59
Math.random = () => 0;60
try61
{ fn(); }62
finally63
{ Math.random = random; }64
}65
66
test("raise bounty spends inventory coins and tracks ledger", () =>47
test("raise bounty spends inventory coins and tracks ledger", () =>67
{48
{68
const harness = makeSimulation({ workerCount: 1 });49
const harness = makeSimulation({ workerCount: 1 });@@ -138,57 +119,88 @@ test("open bounty requires standing next to a bounty office", () =>138
119
139
test("PvP kill pays bounty into killer vault and clears ledger", () =>120
test("PvP kill pays bounty into killer vault and clears ledger", () =>140
{121
{141
withDeterministicCombat(() =>122
const harness = makeSimulation({ workerCount: 1 });123
try142
{124
{143
const harness = makeSimulation({ workerCount: 1 });125
placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);144
try126
placeBlock(harness.worldDb, 7, 8, BlockType.bank);145
{127
harness.simulation.reloadWorld();146
placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);128
147
placeBlock(harness.worldDb, 7, 8, BlockType.bank);129
const victim = makeCharacter(harness.stateDb, {148
harness.simulation.reloadWorld();130
firstName: "Vic",149
131
lastName: "Tim",150
const victim = makeCharacter(harness.stateDb, {132
tileX: 9,151
firstName: "Vic",133
tileY: 9152
lastName: "Tim",134
});153
tileX: 9,135
const killer = makeCharacter(harness.stateDb, {154
tileY: 9136
firstName: "Kill",155
});137
lastName: "Er",156
const killer = makeCharacter(harness.stateDb, {138
tileX: 10,157
firstName: "Kill",139
tileY: 9158
lastName: "Er",140
});159
tileX: 10,141
harness.stateDb.addCharacterBounty(victim.character_id, 400);160
tileY: 9142
161
});143
const victimId = harness.simulation.spawnCharacter(1, victim);162
harness.stateDb.addCharacterBounty(victim.character_id, 400);144
const killerId = harness.simulation.spawnCharacter(2, killer);163
145
164
const victimId = harness.simulation.spawnCharacter(1, victim);146
const settled = harness.simulation.bounty.settleKill(165
const killerId = harness.simulation.spawnCharacter(2, killer);147
victim.character_id,166
const victimComps = componentsOf(harness.simulation, victimId);148
killerId,167
victimComps.health.current = 1;149
9,168
const killerComps = componentsOf(harness.simulation, killerId);150
9169
killerComps.health.current = 1_000_000;151
);170
killerComps.health.max = 1_000_000;152
assert.equal(settled?.paidCopper, 400);171
153
assert.equal(harness.stateDb.getCharacterBounty(victim.character_id), 0);172
harness.simulation.enqueue(2, {154
assert.equal(countCoins(harness.simulation.bagOf(killerId).vault), 400);173
type: "attack",155
174
characterId: killer.character_id,156
harness.stateDb.addKillCounter(killer.character_id, 500, harness.now());175
targetEntityId: victimId157
harness.simulation.refreshCharacterSkull(killer.character_id);176
});158
assert.equal(harness.stateDb.peekKillCounter(killer.character_id, harness.now()), 500);177
159
assert.equal(harness.simulation.directory.get(killerId).skullValue, 500);178
let died = null;160
assert.equal(harness.simulation.directory.get(victimId).skullValue, 0);179
for (let i = 0; i < 200; i++)161
}180
{162
finally181
harness.advance(50);163
{ harness.close(); }182
const events = harness.simulation.step().events;164
});183
died = events.find((event) => event.type === "player-died");165
184
if (died)166
test("friend PvP kill does not pay or clear bounty", () =>185
{ break; }167
{186
}168
const harness = makeSimulation({ workerCount: 1 });187
assert.ok(died, "victim should die");169
try188
assert.equal(harness.stateDb.getCharacterBounty(victim.character_id), 0);170
{189
assert.equal(countCoins(harness.simulation.bagOf(killerId).vault), 400);171
placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);190
}172
placeBlock(harness.worldDb, 7, 8, BlockType.bank);191
finally173
harness.simulation.reloadWorld();192
{ harness.close(); }174
193
});175
const victim = makeCharacter(harness.stateDb, {176
firstName: "Vic",177
lastName: "Friend",178
tileX: 9,179
tileY: 9180
});181
const killer = makeCharacter(harness.stateDb, {182
firstName: "Kill",183
lastName: "Buddy",184
tileX: 10,185
tileY: 9186
});187
harness.stateDb.addCharacterBounty(victim.character_id, 400);188
harness.stateDb.insertAccountFriendship(victim.account_id, killer.account_id);189
190
const victimId = harness.simulation.spawnCharacter(1, victim);191
const killerId = harness.simulation.spawnCharacter(2, killer);192
193
const settled = harness.simulation.bounty.settleKill(194
victim.character_id,195
killerId,196
9,197
9198
);199
assert.equal(settled, null);200
assert.equal(harness.stateDb.getCharacterBounty(victim.character_id), 400);201
assert.equal(countCoins(harness.simulation.bagOf(killerId).vault), 0);202
assert.equal(harness.simulation.directory.get(victimId).skullValue, 400);203
}204
finally205
{ harness.close(); }194
});206
});@@ -5,13 +5,14 @@ import { CraftingStationId, CRAFT_DURATION_MS } from "../../shared/definitions/c
5
5
import { ItemId } from "../../shared/definitions/items.js";
6
6
import { ArmourItemId } from "../../shared/definitions/armourItems.js";
7
7
import { SkillId } from "../../shared/definitions/skills.js";
8
import {
9
MaterialTier,
10
GatherMaterialId,
11
tierSmeltSkillLevel,
12
smeltingDurationMs,
13
associatedBarTier
14
} from "../../shared/definitions/materialTiers.js";
8
import
9
{
10
MaterialTier,
11
GatherMaterialId,
12
tierSmeltSkillLevel,
13
smeltingDurationMs,
14
associatedBarTier
15
} from "../../shared/definitions/materialTiers.js";
15
16
import { craftDurationMs } from "../../shared/definitions/gathering.js";
16
17
import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";
17
18
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
@@ -107,6 +108,17 @@ test("furnace recipes: bronze is tin+copper; steel is iron+coal; high tiers need
107
108
assert.equal(gold.output.itemId, ItemId.goldBar);
108
109
assert.equal(gold.minSkillLevel, tierSmeltSkillLevel(GatherMaterialId.gold));
109
110
111
const electrum = recipesForStation(CraftingStationId.furnace)
112
.find((recipe) => recipe.recipeId === "smelt-electrum");
113
assert.ok(electrum);
114
assert.deepEqual(electrum.inputs.map((row) => row.itemId).sort(), [
115
ItemId.coal,
116
ItemId.goldOre,
117
ItemId.silverOre
118
].sort());
119
assert.equal(electrum.output.itemId, ItemId.electrumBar);
120
assert.equal(electrum.minSkillLevel, tierSmeltSkillLevel(GatherMaterialId.electrum));
121
110
122
const adamantium = recipeDefinition("smelt-adamantium");
111
123
assert.deepEqual(adamantium.inputs, [
112
124
{ itemId: ItemId.adamantiumOre, quantity: 1 },
@@ -5,13 +5,14 @@ import { CraftingStationId, CRAFT_DURATION_MS } from "../../shared/definitions/c5
import { ItemId } from "../../shared/definitions/items.js";5
import { ItemId } from "../../shared/definitions/items.js";6
import { ArmourItemId } from "../../shared/definitions/armourItems.js";6
import { ArmourItemId } from "../../shared/definitions/armourItems.js";7
import { SkillId } from "../../shared/definitions/skills.js";7
import { SkillId } from "../../shared/definitions/skills.js";8
import {8
import9
MaterialTier,9
{10
GatherMaterialId,10
MaterialTier,11
tierSmeltSkillLevel,11
GatherMaterialId,12
smeltingDurationMs,12
tierSmeltSkillLevel,13
associatedBarTier13
smeltingDurationMs,14
} from "../../shared/definitions/materialTiers.js";14
associatedBarTier15
} from "../../shared/definitions/materialTiers.js";15
import { craftDurationMs } from "../../shared/definitions/gathering.js";16
import { craftDurationMs } from "../../shared/definitions/gathering.js";16
import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";17
import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";17
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";18
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";@@ -107,6 +108,17 @@ test("furnace recipes: bronze is tin+copper; steel is iron+coal; high tiers need107
assert.equal(gold.output.itemId, ItemId.goldBar);108
assert.equal(gold.output.itemId, ItemId.goldBar);108
assert.equal(gold.minSkillLevel, tierSmeltSkillLevel(GatherMaterialId.gold));109
assert.equal(gold.minSkillLevel, tierSmeltSkillLevel(GatherMaterialId.gold));109
110
111
const electrum = recipesForStation(CraftingStationId.furnace)112
.find((recipe) => recipe.recipeId === "smelt-electrum");113
assert.ok(electrum);114
assert.deepEqual(electrum.inputs.map((row) => row.itemId).sort(), [115
ItemId.coal,116
ItemId.goldOre,117
ItemId.silverOre118
].sort());119
assert.equal(electrum.output.itemId, ItemId.electrumBar);120
assert.equal(electrum.minSkillLevel, tierSmeltSkillLevel(GatherMaterialId.electrum));121
110
const adamantium = recipeDefinition("smelt-adamantium");122
const adamantium = recipeDefinition("smelt-adamantium");111
assert.deepEqual(adamantium.inputs, [123
assert.deepEqual(adamantium.inputs, [112
{ itemId: ItemId.adamantiumOre, quantity: 1 },124
{ itemId: ItemId.adamantiumOre, quantity: 1 },@@ -1,22 +1,27 @@
1
1
import test from "node:test";
2
2
import assert from "node:assert/strict";
3
import {
4
CraftingStationId,
5
FIREPLACE_DURATION_MS,
6
CRAFT_DURATION_MS,
7
craftingStationDefinition
8
} from "../../shared/definitions/craftingStations.js";
3
import
4
{
5
CraftingStationId,
6
FIREPLACE_DURATION_MS,
7
CRAFT_DURATION_MS,
8
craftingStationDefinition
9
} from "../../shared/definitions/craftingStations.js";
9
10
import { SkillId } from "../../shared/definitions/skills.js";
10
11
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
11
12
import { emptySlots } from "../../shared/items/inventory.js";
12
13
import { canCraftFitInventory, CRAFT_DURATION_MS as RECIPE_CRAFT_MS, canStartCraft } from "../../shared/crafting/recipes.js";
13
14
import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";
14
15
import { CraftingItemId } from "../../shared/definitions/craftingItems.js";
16
import { GemItemId, JEWELRY_RECIPE_GUIDELINES } from "../../shared/definitions/gemItems.js";
17
import { GatherMaterialId, GemTier, tierSmeltSkillLevel } from "../../shared/definitions/materialTiers.js";
18
import { MetalItemId } from "../../shared/definitions/metalItems.js";
15
19
16
20
test("crafting stations map to the expected skills", () =>
17
21
{
18
22
assert.equal(craftingStationDefinition(CraftingStationId.furnace).skillId, SkillId.smithing);
19
23
assert.equal(craftingStationDefinition(CraftingStationId.anvil).skillId, SkillId.smithing);
24
assert.equal(craftingStationDefinition(CraftingStationId.jeweleringStation).skillId, SkillId.jewelering);
20
25
assert.equal(craftingStationDefinition(CraftingStationId.loom).skillId, SkillId.tailoring);
21
26
assert.equal(craftingStationDefinition(CraftingStationId.craftingBench).skillId, SkillId.crafting);
22
27
assert.equal(craftingStationDefinition(CraftingStationId.oven).skillId, SkillId.cooking);
@@ -124,3 +129,33 @@ test("woodworking, anvil, and crafting bench expose pickaxe and axe chain recipe
124
129
assert.equal(itemDefinition(ItemId.bronzeAxe)?.stub, undefined);
125
130
assert.equal(itemDefinition(ItemId.bronzeAxe)?.equipment?.kind, "axeTool");
126
131
});
132
133
test("jewelering cuts rough gems; staff recipes need cut gems", () =>
134
{
135
const cut = recipeDefinition("cut-tourmaline");
136
assert.ok(cut);
137
assert.equal(cut.stationId, CraftingStationId.jeweleringStation);
138
assert.equal(cut.skillId, SkillId.jewelering);
139
assert.equal(cut.minSkillLevel, tierSmeltSkillLevel(GemTier.tourmaline));
140
assert.deepEqual(cut.inputs, [{ itemId: GemItemId.tourmaline, quantity: 1 }]);
141
assert.equal(cut.output.itemId, GemItemId.tourmalineCut);
142
assert.equal(itemDefinition(GemItemId.tourmaline)?.gemForm, "rough");
143
assert.equal(itemDefinition(GemItemId.tourmalineCut)?.gemForm, "cut");
144
assert.equal(itemDefinition(GemItemId.tourmaline)?.defaultState, "rough");
145
assert.equal(itemDefinition(GemItemId.tourmalineCut)?.defaultState, "cut");
146
147
const staff = recipeDefinition("staff-pine");
148
assert.ok(staff);
149
assert.ok(staff.inputs.some((row) => row.itemId === GemItemId.tourmalineCut));
150
assert.ok(!staff.inputs.some((row) => row.itemId === GemItemId.tourmaline));
151
152
assert.equal(recipesForStation(CraftingStationId.jeweleringStation).length, 7);
153
assert.equal(JEWELRY_RECIPE_GUIDELINES.length, 7);
154
assert.equal(JEWELRY_RECIPE_GUIDELINES[0].metalId, GatherMaterialId.silver);
155
assert.equal(JEWELRY_RECIPE_GUIDELINES[0].metalQuantity, 1);
156
assert.equal(JEWELRY_RECIPE_GUIDELINES[3].metalId, GatherMaterialId.gold);
157
assert.equal(JEWELRY_RECIPE_GUIDELINES[3].metalQuantity, 4);
158
assert.equal(JEWELRY_RECIPE_GUIDELINES[6].metalId, GatherMaterialId.electrum);
159
assert.equal(JEWELRY_RECIPE_GUIDELINES[6].metalBarItemId, MetalItemId.electrumBar);
160
assert.equal(JEWELRY_RECIPE_GUIDELINES[6].metalQuantity, 7);
161
});
@@ -1,22 +1,27 @@1
import test from "node:test";1
import test from "node:test";2
import assert from "node:assert/strict";2
import assert from "node:assert/strict";3
import {3
import4
CraftingStationId,4
{5
FIREPLACE_DURATION_MS,5
CraftingStationId,6
CRAFT_DURATION_MS,6
FIREPLACE_DURATION_MS,7
craftingStationDefinition7
CRAFT_DURATION_MS,8
} from "../../shared/definitions/craftingStations.js";8
craftingStationDefinition9
} from "../../shared/definitions/craftingStations.js";9
import { SkillId } from "../../shared/definitions/skills.js";10
import { SkillId } from "../../shared/definitions/skills.js";10
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";11
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";11
import { emptySlots } from "../../shared/items/inventory.js";12
import { emptySlots } from "../../shared/items/inventory.js";12
import { canCraftFitInventory, CRAFT_DURATION_MS as RECIPE_CRAFT_MS, canStartCraft } from "../../shared/crafting/recipes.js";13
import { canCraftFitInventory, CRAFT_DURATION_MS as RECIPE_CRAFT_MS, canStartCraft } from "../../shared/crafting/recipes.js";13
import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";14
import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";14
import { CraftingItemId } from "../../shared/definitions/craftingItems.js";15
import { CraftingItemId } from "../../shared/definitions/craftingItems.js";16
import { GemItemId, JEWELRY_RECIPE_GUIDELINES } from "../../shared/definitions/gemItems.js";17
import { GatherMaterialId, GemTier, tierSmeltSkillLevel } from "../../shared/definitions/materialTiers.js";18
import { MetalItemId } from "../../shared/definitions/metalItems.js";15
19
16
test("crafting stations map to the expected skills", () =>20
test("crafting stations map to the expected skills", () =>17
{21
{18
assert.equal(craftingStationDefinition(CraftingStationId.furnace).skillId, SkillId.smithing);22
assert.equal(craftingStationDefinition(CraftingStationId.furnace).skillId, SkillId.smithing);19
assert.equal(craftingStationDefinition(CraftingStationId.anvil).skillId, SkillId.smithing);23
assert.equal(craftingStationDefinition(CraftingStationId.anvil).skillId, SkillId.smithing);24
assert.equal(craftingStationDefinition(CraftingStationId.jeweleringStation).skillId, SkillId.jewelering);20
assert.equal(craftingStationDefinition(CraftingStationId.loom).skillId, SkillId.tailoring);25
assert.equal(craftingStationDefinition(CraftingStationId.loom).skillId, SkillId.tailoring);21
assert.equal(craftingStationDefinition(CraftingStationId.craftingBench).skillId, SkillId.crafting);26
assert.equal(craftingStationDefinition(CraftingStationId.craftingBench).skillId, SkillId.crafting);22
assert.equal(craftingStationDefinition(CraftingStationId.oven).skillId, SkillId.cooking);27
assert.equal(craftingStationDefinition(CraftingStationId.oven).skillId, SkillId.cooking);@@ -124,3 +129,33 @@ test("woodworking, anvil, and crafting bench expose pickaxe and axe chain recipe124
assert.equal(itemDefinition(ItemId.bronzeAxe)?.stub, undefined);129
assert.equal(itemDefinition(ItemId.bronzeAxe)?.stub, undefined);125
assert.equal(itemDefinition(ItemId.bronzeAxe)?.equipment?.kind, "axeTool");130
assert.equal(itemDefinition(ItemId.bronzeAxe)?.equipment?.kind, "axeTool");126
});131
});132
133
test("jewelering cuts rough gems; staff recipes need cut gems", () =>134
{135
const cut = recipeDefinition("cut-tourmaline");136
assert.ok(cut);137
assert.equal(cut.stationId, CraftingStationId.jeweleringStation);138
assert.equal(cut.skillId, SkillId.jewelering);139
assert.equal(cut.minSkillLevel, tierSmeltSkillLevel(GemTier.tourmaline));140
assert.deepEqual(cut.inputs, [{ itemId: GemItemId.tourmaline, quantity: 1 }]);141
assert.equal(cut.output.itemId, GemItemId.tourmalineCut);142
assert.equal(itemDefinition(GemItemId.tourmaline)?.gemForm, "rough");143
assert.equal(itemDefinition(GemItemId.tourmalineCut)?.gemForm, "cut");144
assert.equal(itemDefinition(GemItemId.tourmaline)?.defaultState, "rough");145
assert.equal(itemDefinition(GemItemId.tourmalineCut)?.defaultState, "cut");146
147
const staff = recipeDefinition("staff-pine");148
assert.ok(staff);149
assert.ok(staff.inputs.some((row) => row.itemId === GemItemId.tourmalineCut));150
assert.ok(!staff.inputs.some((row) => row.itemId === GemItemId.tourmaline));151
152
assert.equal(recipesForStation(CraftingStationId.jeweleringStation).length, 7);153
assert.equal(JEWELRY_RECIPE_GUIDELINES.length, 7);154
assert.equal(JEWELRY_RECIPE_GUIDELINES[0].metalId, GatherMaterialId.silver);155
assert.equal(JEWELRY_RECIPE_GUIDELINES[0].metalQuantity, 1);156
assert.equal(JEWELRY_RECIPE_GUIDELINES[3].metalId, GatherMaterialId.gold);157
assert.equal(JEWELRY_RECIPE_GUIDELINES[3].metalQuantity, 4);158
assert.equal(JEWELRY_RECIPE_GUIDELINES[6].metalId, GatherMaterialId.electrum);159
assert.equal(JEWELRY_RECIPE_GUIDELINES[6].metalBarItemId, MetalItemId.electrumBar);160
assert.equal(JEWELRY_RECIPE_GUIDELINES[6].metalQuantity, 7);161
});@@ -10,15 +10,21 @@ function setup ()
10
10
{
11
11
const dir = mkdtempSync(join(tmpdir(), "mmo-friends-"));
12
12
const stateDb = new StateDatabase(join(dir, "state.sqlite"));
13
const accountA = stateDb.createAccount("admin-1", true);
14
const accountB = stateDb.createAccount("admin-2", true);
13
const accountA = stateDb.createAccount("admin-1", true, null, "ada_acc");
14
const accountB = stateDb.createAccount("admin-2", true, null, "ben_acc");
15
15
const left = stateDb.createCharacter(accountA.account_id, "Ada", "West", "female", 8, 8);
16
const leftAlt = stateDb.createCharacter(accountA.account_id, "Ada", "Alt", "female", 8, 8);
16
17
const right = stateDb.createCharacter(accountB.account_id, "Ben", "East", "male", 8, 8);
18
const rightAlt = stateDb.createCharacter(accountB.account_id, "Ben", "Twin", "male", 8, 8);
17
19
return {
18
20
stateDb,
19
21
friends: new FriendService(stateDb),
20
22
leftId: left.character_id,
21
rightId: right.character_id
23
leftAltId: leftAlt.character_id,
24
rightId: right.character_id,
25
rightAltId: rightAlt.character_id,
26
accountA: accountA.account_id,
27
accountB: accountB.account_id
22
28
};
23
29
}
24
30
@@ -30,11 +36,11 @@ test("a friend request must be accepted before both sides are friends", () =>
30
36
const pending = friends.request(leftId, rightId);
31
37
assert.equal(pending.outgoing.length, 1);
32
38
assert.equal(pending.friends.length, 0);
33
assert.equal(friends.snapshot(rightId).incoming[0].firstName, "Ada");
39
assert.equal(friends.snapshot(rightId).incoming[0].username, "ada_acc");
34
40
35
41
friends.accept(rightId, leftId);
36
42
assert.equal(friends.snapshot(leftId).friends.length, 1);
37
assert.equal(friends.snapshot(rightId).friends[0].lastName, "West");
43
assert.equal(friends.snapshot(rightId).friends[0].username, "ada_acc");
38
44
assert.equal(friends.snapshot(leftId).outgoing.length, 0);
39
45
assert.equal(friends.snapshot(rightId).incoming.length, 0);
40
46
}
@@ -42,7 +48,25 @@ test("a friend request must be accepted before both sides are friends", () =>
42
48
{ stateDb.close(); }
43
49
});
44
50
45
test("removing a friend removes them for both characters", () =>
51
test("account friendship covers all characters on both accounts", () =>
52
{
53
const { stateDb, friends, leftId, leftAltId, rightId, rightAltId } = setup();
54
try
55
{
56
friends.request(leftId, rightId);
57
friends.accept(rightId, leftId);
58
assert.equal(friends.areFriends(leftId, rightId), true);
59
assert.equal(friends.areFriends(leftAltId, rightAltId), true);
60
assert.equal(friends.areFriends(leftId, leftAltId), true);
61
const flat = friends.listFriends(leftId);
62
assert.ok(flat.some((entry) => entry.characterId === rightId));
63
assert.ok(flat.some((entry) => entry.characterId === rightAltId));
64
}
65
finally
66
{ stateDb.close(); }
67
});
68
69
test("removing a friend removes them for both accounts", () =>
46
70
{
47
71
const { stateDb, friends, leftId, rightId } = setup();
48
72
try
@@ -80,7 +104,7 @@ test("friends list is the pigeon address book of first and last names", () =>
80
104
friends.accept(rightId, leftId);
81
105
const found = friends.findByFullName("Ben", "East");
82
106
assert.equal(found.characterId, rightId);
83
assert.deepEqual(friends.listFriends(leftId)[0], found);
107
assert.ok(friends.listFriends(leftId).some((entry) => entry.characterId === found.characterId));
84
108
}
85
109
finally
86
110
{ stateDb.close(); }
@@ -10,15 +10,21 @@ function setup ()10
{10
{11
const dir = mkdtempSync(join(tmpdir(), "mmo-friends-"));11
const dir = mkdtempSync(join(tmpdir(), "mmo-friends-"));12
const stateDb = new StateDatabase(join(dir, "state.sqlite"));12
const stateDb = new StateDatabase(join(dir, "state.sqlite"));13
const accountA = stateDb.createAccount("admin-1", true);13
const accountA = stateDb.createAccount("admin-1", true, null, "ada_acc");14
const accountB = stateDb.createAccount("admin-2", true);14
const accountB = stateDb.createAccount("admin-2", true, null, "ben_acc");15
const left = stateDb.createCharacter(accountA.account_id, "Ada", "West", "female", 8, 8);15
const left = stateDb.createCharacter(accountA.account_id, "Ada", "West", "female", 8, 8);16
const leftAlt = stateDb.createCharacter(accountA.account_id, "Ada", "Alt", "female", 8, 8);16
const right = stateDb.createCharacter(accountB.account_id, "Ben", "East", "male", 8, 8);17
const right = stateDb.createCharacter(accountB.account_id, "Ben", "East", "male", 8, 8);18
const rightAlt = stateDb.createCharacter(accountB.account_id, "Ben", "Twin", "male", 8, 8);17
return {19
return {18
stateDb,20
stateDb,19
friends: new FriendService(stateDb),21
friends: new FriendService(stateDb),20
leftId: left.character_id,22
leftId: left.character_id,21
rightId: right.character_id23
leftAltId: leftAlt.character_id,24
rightId: right.character_id,25
rightAltId: rightAlt.character_id,26
accountA: accountA.account_id,27
accountB: accountB.account_id22
};28
};23
}29
}24
30
@@ -30,11 +36,11 @@ test("a friend request must be accepted before both sides are friends", () =>30
const pending = friends.request(leftId, rightId);36
const pending = friends.request(leftId, rightId);31
assert.equal(pending.outgoing.length, 1);37
assert.equal(pending.outgoing.length, 1);32
assert.equal(pending.friends.length, 0);38
assert.equal(pending.friends.length, 0);33
assert.equal(friends.snapshot(rightId).incoming[0].firstName, "Ada");39
assert.equal(friends.snapshot(rightId).incoming[0].username, "ada_acc");34
40
35
friends.accept(rightId, leftId);41
friends.accept(rightId, leftId);36
assert.equal(friends.snapshot(leftId).friends.length, 1);42
assert.equal(friends.snapshot(leftId).friends.length, 1);37
assert.equal(friends.snapshot(rightId).friends[0].lastName, "West");43
assert.equal(friends.snapshot(rightId).friends[0].username, "ada_acc");38
assert.equal(friends.snapshot(leftId).outgoing.length, 0);44
assert.equal(friends.snapshot(leftId).outgoing.length, 0);39
assert.equal(friends.snapshot(rightId).incoming.length, 0);45
assert.equal(friends.snapshot(rightId).incoming.length, 0);40
}46
}@@ -42,7 +48,25 @@ test("a friend request must be accepted before both sides are friends", () =>42
{ stateDb.close(); }48
{ stateDb.close(); }43
});49
});44
50
45
test("removing a friend removes them for both characters", () =>51
test("account friendship covers all characters on both accounts", () =>52
{53
const { stateDb, friends, leftId, leftAltId, rightId, rightAltId } = setup();54
try55
{56
friends.request(leftId, rightId);57
friends.accept(rightId, leftId);58
assert.equal(friends.areFriends(leftId, rightId), true);59
assert.equal(friends.areFriends(leftAltId, rightAltId), true);60
assert.equal(friends.areFriends(leftId, leftAltId), true);61
const flat = friends.listFriends(leftId);62
assert.ok(flat.some((entry) => entry.characterId === rightId));63
assert.ok(flat.some((entry) => entry.characterId === rightAltId));64
}65
finally66
{ stateDb.close(); }67
});68
69
test("removing a friend removes them for both accounts", () =>46
{70
{47
const { stateDb, friends, leftId, rightId } = setup();71
const { stateDb, friends, leftId, rightId } = setup();48
try72
try@@ -80,7 +104,7 @@ test("friends list is the pigeon address book of first and last names", () =>80
friends.accept(rightId, leftId);104
friends.accept(rightId, leftId);81
const found = friends.findByFullName("Ben", "East");105
const found = friends.findByFullName("Ben", "East");82
assert.equal(found.characterId, rightId);106
assert.equal(found.characterId, rightId);83
assert.deepEqual(friends.listFriends(leftId)[0], found);107
assert.ok(friends.listFriends(leftId).some((entry) => entry.characterId === found.characterId));84
}108
}85
finally109
finally86
{ stateDb.close(); }110
{ stateDb.close(); }@@ -1,21 +1,22 @@
1
1
import test from "node:test";
2
2
import assert from "node:assert/strict";
3
import {
4
ItemOriginKind,
5
GatherOriginVerb,
6
CraftOriginVerb,
7
gatherOrigin,
8
lootOrigin,
9
craftOrigin,
10
craftOriginVerbForStation,
11
royalTreasuryOrigin,
12
ROYAL_TREASURY_ORIGIN_LABEL,
13
originLabel,
14
formatOriginBreakdown,
15
mergeOriginLists,
16
normalizeOrigins,
17
splitOrigins
18
} from "../../shared/items/origin.js";
3
import
4
{
5
ItemOriginKind,
6
GatherOriginVerb,
7
CraftOriginVerb,
8
gatherOrigin,
9
lootOrigin,
10
craftOrigin,
11
craftOriginVerbForStation,
12
royalTreasuryOrigin,
13
ROYAL_TREASURY_ORIGIN_LABEL,
14
originLabel,
15
formatOriginBreakdown,
16
mergeOriginLists,
17
normalizeOrigins,
18
splitOrigins
19
} from "../../shared/items/origin.js";
19
20
import { CraftingStationId } from "../../shared/definitions/craftingStations.js";
20
21
import { emptySlots, insertStack, takeFromSlot, insertStackGrowable, singleItemFromStack } from "../../shared/items/inventory.js";
21
22
import { stackRulesFor } from "../../shared/items/stackRules.js";
@@ -66,6 +67,7 @@ test("craft origins use station verbs", () =>
66
67
{
67
68
assert.equal(craftOriginVerbForStation(CraftingStationId.furnace), CraftOriginVerb.forged);
68
69
assert.equal(craftOriginVerbForStation(CraftingStationId.anvil), CraftOriginVerb.smithed);
70
assert.equal(craftOriginVerbForStation(CraftingStationId.jeweleringStation), CraftOriginVerb.cut);
69
71
assert.equal(craftOriginVerbForStation(CraftingStationId.woodworkingBench), CraftOriginVerb.carved);
70
72
assert.equal(craftOriginVerbForStation(CraftingStationId.craftingBench), CraftOriginVerb.assembled);
71
73
assert.equal(originLabel(craftOrigin(CraftOriginVerb.forged, "Ada")), "Forged by Ada");
@@ -1,21 +1,22 @@1
import test from "node:test";1
import test from "node:test";2
import assert from "node:assert/strict";2
import assert from "node:assert/strict";3
import {3
import4
ItemOriginKind,4
{5
GatherOriginVerb,5
ItemOriginKind,6
CraftOriginVerb,6
GatherOriginVerb,7
gatherOrigin,7
CraftOriginVerb,8
lootOrigin,8
gatherOrigin,9
craftOrigin,9
lootOrigin,10
craftOriginVerbForStation,10
craftOrigin,11
royalTreasuryOrigin,11
craftOriginVerbForStation,12
ROYAL_TREASURY_ORIGIN_LABEL,12
royalTreasuryOrigin,13
originLabel,13
ROYAL_TREASURY_ORIGIN_LABEL,14
formatOriginBreakdown,14
originLabel,15
mergeOriginLists,15
formatOriginBreakdown,16
normalizeOrigins,16
mergeOriginLists,17
splitOrigins17
normalizeOrigins,18
} from "../../shared/items/origin.js";18
splitOrigins19
} from "../../shared/items/origin.js";19
import { CraftingStationId } from "../../shared/definitions/craftingStations.js";20
import { CraftingStationId } from "../../shared/definitions/craftingStations.js";20
import { emptySlots, insertStack, takeFromSlot, insertStackGrowable, singleItemFromStack } from "../../shared/items/inventory.js";21
import { emptySlots, insertStack, takeFromSlot, insertStackGrowable, singleItemFromStack } from "../../shared/items/inventory.js";21
import { stackRulesFor } from "../../shared/items/stackRules.js";22
import { stackRulesFor } from "../../shared/items/stackRules.js";@@ -66,6 +67,7 @@ test("craft origins use station verbs", () =>66
{67
{67
assert.equal(craftOriginVerbForStation(CraftingStationId.furnace), CraftOriginVerb.forged);68
assert.equal(craftOriginVerbForStation(CraftingStationId.furnace), CraftOriginVerb.forged);68
assert.equal(craftOriginVerbForStation(CraftingStationId.anvil), CraftOriginVerb.smithed);69
assert.equal(craftOriginVerbForStation(CraftingStationId.anvil), CraftOriginVerb.smithed);70
assert.equal(craftOriginVerbForStation(CraftingStationId.jeweleringStation), CraftOriginVerb.cut);69
assert.equal(craftOriginVerbForStation(CraftingStationId.woodworkingBench), CraftOriginVerb.carved);71
assert.equal(craftOriginVerbForStation(CraftingStationId.woodworkingBench), CraftOriginVerb.carved);70
assert.equal(craftOriginVerbForStation(CraftingStationId.craftingBench), CraftOriginVerb.assembled);72
assert.equal(craftOriginVerbForStation(CraftingStationId.craftingBench), CraftOriginVerb.assembled);71
assert.equal(originLabel(craftOrigin(CraftOriginVerb.forged, "Ada")), "Forged by Ada");73
assert.equal(originLabel(craftOrigin(CraftOriginVerb.forged, "Ada")), "Forged by Ada");@@ -0,0 +1,35 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import
4
{
5
skullValue,
6
skullTintColor,
7
decayKillCounter,
8
SKULL_PURE_RED_VALUE,
9
SKULL_DARK_RED_VALUE,
10
SKULL_KILL_BONUS
11
} from "../../shared/combat/skull.js";
12
13
test("skull value is bounty plus kill counter", () =>
14
{
15
assert.equal(skullValue(100, 400), 500);
16
assert.equal(skullValue(0, 0), 0);
17
assert.equal(SKULL_KILL_BONUS, 500);
18
});
19
20
test("kill counter decays one point per second", () =>
21
{
22
assert.deepEqual(decayKillCounter(10, 3500), { killCounter: 7, consumedMs: 3000 });
23
assert.deepEqual(decayKillCounter(2, 10_000), { killCounter: 0, consumedMs: 2000 });
24
});
25
26
test("skull tint: invisible, white, red, dark red", () =>
27
{
28
assert.equal(skullTintColor(0), null);
29
assert.deepEqual(skullTintColor(1), { r: 1, g: 1, b: 1 });
30
assert.deepEqual(skullTintColor(SKULL_PURE_RED_VALUE), { r: 1, g: 0, b: 0 });
31
const dark = skullTintColor(SKULL_DARK_RED_VALUE);
32
assert.ok(Math.abs(dark.r - 128 / 255) < 1e-9);
33
assert.equal(dark.g, 0);
34
assert.equal(dark.b, 0);
35
});
@@ -0,0 +1,35 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import4
{5
skullValue,6
skullTintColor,7
decayKillCounter,8
SKULL_PURE_RED_VALUE,9
SKULL_DARK_RED_VALUE,10
SKULL_KILL_BONUS11
} from "../../shared/combat/skull.js";12
13
test("skull value is bounty plus kill counter", () =>14
{15
assert.equal(skullValue(100, 400), 500);16
assert.equal(skullValue(0, 0), 0);17
assert.equal(SKULL_KILL_BONUS, 500);18
});19
20
test("kill counter decays one point per second", () =>21
{22
assert.deepEqual(decayKillCounter(10, 3500), { killCounter: 7, consumedMs: 3000 });23
assert.deepEqual(decayKillCounter(2, 10_000), { killCounter: 0, consumedMs: 2000 });24
});25
26
test("skull tint: invisible, white, red, dark red", () =>27
{28
assert.equal(skullTintColor(0), null);29
assert.deepEqual(skullTintColor(1), { r: 1, g: 1, b: 1 });30
assert.deepEqual(skullTintColor(SKULL_PURE_RED_VALUE), { r: 1, g: 0, b: 0 });31
const dark = skullTintColor(SKULL_DARK_RED_VALUE);32
assert.ok(Math.abs(dark.r - 128 / 255) < 1e-9);33
assert.equal(dark.g, 0);34
assert.equal(dark.b, 0);35
});