forked from jewalky/redhat
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathshelf.cpp
More file actions
415 lines (322 loc) · 13.8 KB
/
shelf.cpp
File metadata and controls
415 lines (322 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
#include "shelf.hpp"
#include <cstdint>
#include <unordered_map>
#include <inttypes.h>
#include <limits>
#include "login.hpp"
#include "utils.hpp"
// This should be defined in inttypes.h, but some old compilers don't have that.
#ifndef PRId64
#define PRId64 "lld"
#endif // PRId64
namespace shelf {
bool CanDeposit(const CCharacter& chr) {
return !IsLegend(chr) && !IsPure(chr);
}
bool CanWithdraw(const CCharacter& chr) {
return !IsLegend(chr) && !IsPure(chr);
}
bool SQLUpsertOneRow(std::string query) {
if (SQL_Query(query) != 0) {
return false;
}
int affected_rows = SQL_AffectedRows();
if (affected_rows != 1) {
Printf(LOG_Error, "[shelf] Concurrent modification? SQL query '%s' affected %d rows, wanted 1", query.c_str(), affected_rows);
return false;
}
return true;
}
bool ItemsToSavingsBook(const CCharacter& chr, ServerIDType server_id, std::vector<CItem>& inventory) {
return impl::ItemsToSavingsBookImpl(chr, server_id, inventory, impl::LoadShelf, SQLUpsertOneRow);
}
bool ItemsFromSavingsBook(const CCharacter& chr, ServerIDType server_id, std::vector<CItem>& inventory) {
return impl::ItemsFromSavingsBookImpl(chr, server_id, inventory, impl::LoadShelf, SQLUpsertOneRow);
}
int32_t MoneyToSavingsBook(const CCharacter& chr, ServerIDType server_id, std::vector<CItem>& inventory, int32_t current_money, int32_t amount) {
return impl::MoneyToSavingsBookImpl(chr, server_id, inventory, current_money, amount, impl::LoadShelf, SQLUpsertOneRow);
}
int32_t MoneyFromSavingsBook(const CCharacter& chr, ServerIDType server_id, std::vector<CItem>& inventory, int32_t current_money, int32_t amount) {
return impl::MoneyFromSavingsBookImpl(chr, server_id, inventory, current_money, amount, impl::LoadShelf, SQLUpsertOneRow);
}
bool StoreOnShelf(const CCharacter& chr, ServerIDType server_id, std::vector<CItem> inventory, int64_t money) {
return impl::StoreOnShelfImpl(chr, server_id, std::move(inventory), money, impl::LoadShelf, SQLUpsertOneRow);
}
bool PickFromShelf(const CCharacter& chr, int shelf_number, int32_t* mutex, std::string* items_repr, int64_t* money, bool& shelf_exists) {
return impl::LoadShelf(chr, shelf_number, impl::Field::BOTH, mutex, items_repr, money, shelf_exists);
}
namespace impl {
bool IsSavingsBook(const CItem& item) {
return item.Id == 3587 && // Book of Fire
item.IsMagic &&
item.Effects.size() == 1 && item.Effects[0].Id1 == 42 && item.Effects[0].Value1 == 1; // Casts fire arrow spell.
}
std::vector<CItem>::const_iterator FindSavingsBook(const std::vector<CItem>& inventory) {
for (auto it = inventory.begin(); it != inventory.end(); ++it) {
if (IsSavingsBook(*it)) {
return it;
}
}
return inventory.end();
}
int FixServerID(ServerIDType server_id) {
// Nightmare+ servers use the same shelf.
if (server_id >= NIGHTMARE) {
server_id = NIGHTMARE;
}
return server_id;
}
// We can support different cabinets for different character types. Right now we use a single one.
int Cabinet(const CCharacter& chr) {
return 0;
}
// Merge piles of identical items (example: item of 20 health potions and item
// of 40 same health potions will be merged to one item of 60 health potions).
// Maybe the engine can handle duplicate piles, but I'm too lazy to test.
// Modifies items in-place.
void MergeItemPiles(std::vector<CItem>& items, const std::vector<CItem>& add_items) {
// Ensure that `items` won't be reallocated when adding elements. This is faster and also preserves iterators.
items.reserve(items.size() + add_items.size());
// Remember every non-magic pile.
std::unordered_map<uint16_t, std::vector<CItem>::iterator> piles;
for (auto it = items.begin(); it != items.end(); ++it) {
if (!it->IsMagic) {
piles[it->Id] = it;
}
}
for (const auto& item : add_items) {
if (item.Id == 0) {
continue; // Empty dress slots.
}
if (item.IsMagic || piles.count(item.Id) == 0) {
items.push_back(item);
} else {
// There's an existing pile of this item --- add to it.
piles[item.Id]->Count += item.Count;
}
}
}
bool LoadShelf(const CCharacter& chr, int shelf_number, Field field, int32_t* mutex, std::string* items, int64_t* money, bool& shelf_exists) {
int cabinet = Cabinet(chr);
const char* field_names = "";
switch (field) {
case ITEMS:
field_names = "items";
break;
case MONEY:
field_names = "money";
break;
case BOTH:
field_names = "items, money";
break;
}
std::string query = Format("SELECT mutex, %s FROM shelf WHERE login_id = %d AND server_id = %d AND cabinet = %d", field_names, chr.LoginID, shelf_number, cabinet);
if (SQL_Query(query) != 0) {
Printf(LOG_Error, "Failed to query shelf content for player %d, shelf %d, cabinet %d: %s\n", chr.LoginID, shelf_number, cabinet, SQL_Error().c_str());
return false;
}
auto result = SQL_StoreResult();
if (!result) {
Printf(LOG_Error, "Failed to get query result for shelf content for player %d, shelf %d, cabinet %d: %s\n", chr.LoginID, shelf_number, cabinet, SQL_Error().c_str());
return false;
}
shelf_exists = false;
if (SQL_NumRows(result) != 0) {
shelf_exists = true;
auto row = SQL_FetchRow(result);
if (mutex != nullptr) {
*mutex = SQL_FetchInt(row, result, "mutex");
}
if (field & Field::ITEMS && items != nullptr) {
*items = SQL_FetchString(row, result, "items");
}
if (field & Field::MONEY && money != nullptr) {
*money = SQL_FetchInt64(row, result, "money");
}
}
SQL_FreeResult(result);
return true;
}
bool SaveShelf(const CCharacter& chr, int shelf_number, Field field, int32_t mutex, std::vector<CItem> new_items, int64_t money, bool shelf_exists, SQLQueryFunction sql_query) {
int cabinet = Cabinet(chr);
std::string items;
if (field & Field::ITEMS) {
CItemList item_list{.Items = std::move(new_items)};
items = SQL_Escape(Login_SerializeItems(item_list));
}
std::string query;
std::string field_values;
if (shelf_exists) {
switch (field) {
case ITEMS:
field_values = Format("items = '%s'", items.c_str());
break;
case MONEY:
field_values = Format("money = %" PRId64, money);
break;
case BOTH:
field_values = Format("items = '%s', money = %d", items.c_str(), money);
break;
}
query = Format("UPDATE shelf SET mutex = %d, %s WHERE login_id = %d AND server_id = %d AND cabinet = %d AND mutex = %d", mutex + 1, field_values.c_str(), chr.LoginID, shelf_number, cabinet, mutex);
} else {
std::string field_names;
switch (field) {
case ITEMS:
field_names = "items";
field_values = Format("'%s'", items.c_str());
break;
case MONEY:
field_names = "money";
field_values = Format("%" PRId64, money);
break;
case BOTH:
field_names = "items, money";
field_values = Format("'%s', %" PRId64, items.c_str(), money);
break;
}
query = Format("INSERT INTO shelf (login_id, server_id, cabinet, mutex, %s) VALUES (%d, %d, %d, %d, %s)", field_names.c_str(), chr.LoginID, shelf_number, cabinet, mutex, field_values.c_str());
}
if (!sql_query(query)) {
Printf(LOG_Error, "[shelf] Failed to save new shelf content for player %d, server %d, cabinet %d: '%s' (shelf existed: %d, new fields: %s)\n", chr.LoginID, shelf_number, cabinet, SQL_Error().c_str(), shelf_exists, field_values.c_str());
return false;
}
Printf(LOG_Info, "[shelf] Saved new shelf content for login %d on server %d at cabinet %d: %s\n", chr.LoginID, shelf_number, cabinet, field_values.c_str());
return true;
}
bool ItemsToSavingsBookImpl(const CCharacter& chr, ServerIDType server_id, std::vector<CItem>& inventory, LoadShelfFunction load_shelf, SQLQueryFunction sql_query) {
if (!CanDeposit(chr)) {
return true;
}
int shelf_number = FixServerID(server_id);
auto savings_book = FindSavingsBook(inventory);
if (savings_book == inventory.end()) {
return true;
}
std::vector<CItem> to_shelf(inventory.cbegin(), savings_book);
int32_t mutex = 0;
std::string shelf_content;
bool shelf_exists = false;
if (!load_shelf(chr, shelf_number, Field::ITEMS, &mutex, &shelf_content, nullptr, shelf_exists)) {
return false;
}
std::vector<CItem> current_items = Login_UnserializeItems(shelf_content).Items;
MergeItemPiles(current_items, to_shelf);
if (!SaveShelf(chr, shelf_number, Field::ITEMS, mutex, std::move(current_items), 0, shelf_exists, sql_query)) {
return false;
}
// +1 to remove the book too.
inventory.erase(inventory.begin(), savings_book + 1);
return true;
}
bool ItemsFromSavingsBookImpl(const CCharacter& chr, ServerIDType server_id, std::vector<CItem>& inventory, LoadShelfFunction load_shelf, SQLQueryFunction sql_query) {
if (!CanWithdraw(chr)) {
return true;
}
int shelf_number = FixServerID(server_id);
auto savings_book = FindSavingsBook(inventory);
if (savings_book == inventory.end()) {
return true;
}
int32_t mutex = 0;
std::string shelf_content;
bool shelf_exists;
if (!load_shelf(chr, shelf_number, Field::ITEMS, &mutex, &shelf_content, nullptr, shelf_exists)) {
return false;
}
std::vector<CItem> shelved_items = Login_UnserializeItems(shelf_content).Items;
if (!shelf_exists || shelved_items.empty()) {
return true;
}
if (!SaveShelf(chr, shelf_number, Field::ITEMS, mutex, {}, 0, shelf_exists, sql_query)) {
return false;
}
Printf(LOG_Info, "[shelf] Loaded items for login %d on server %d at cabinet %d: '%s'\n", chr.LoginID, server_id, shelf_number, SQL_Escape(shelf_content).c_str());
// Remove the book.
inventory.erase(savings_book);
// Put items from the shelf into the inventory.
MergeItemPiles(inventory, shelved_items);
return true;
}
int32_t MoneyToSavingsBookImpl(const CCharacter& chr, ServerIDType server_id, std::vector<CItem>& inventory, int32_t current_money, int32_t amount, LoadShelfFunction load_shelf, SQLQueryFunction sql_query) {
if (!CanDeposit(chr)) {
return current_money;
}
int shelf_number = FixServerID(server_id);
if (amount == 0) {
return current_money;
}
int32_t deposit = amount;
if (deposit > current_money) {
deposit = current_money;
}
auto savings_book = FindSavingsBook(inventory);
if (savings_book == inventory.end()) {
return current_money;
}
int32_t mutex = 0;
int64_t shelved_money = 0;
bool shelf_exists;
if (!load_shelf(chr, shelf_number, Field::MONEY, &mutex, nullptr, &shelved_money, shelf_exists)) {
return current_money;
}
int64_t money = shelved_money + deposit;
if (!SaveShelf(chr, shelf_number, Field::MONEY, mutex, {}, money, shelf_exists, sql_query)) {
return current_money;
}
Printf(LOG_Info, "[shelf] Stored money for login %d on server %d: %d stashed (tried %d), total %" PRId64 "\n", chr.LoginID, shelf_number, deposit, amount, money);
// Remove the book.
inventory.erase(savings_book);
return current_money - deposit;
}
int32_t MoneyFromSavingsBookImpl(const CCharacter& chr, ServerIDType server_id, std::vector<CItem>& inventory, int32_t current_money, int32_t amount, LoadShelfFunction load_shelf, SQLQueryFunction sql_query) {
if (!CanWithdraw(chr)) {
return current_money;
}
int shelf_number = FixServerID(server_id);
if (amount == 0) {
return current_money;
}
auto savings_book = FindSavingsBook(inventory);
if (savings_book == inventory.end()) {
return current_money;
}
int32_t mutex = 0;
int64_t shelved_money = 0;
bool shelf_exists;
if (!load_shelf(chr, shelf_number, Field::MONEY, &mutex, nullptr, &shelved_money, shelf_exists)) {
return current_money;
}
int32_t withdraw = std::min(amount, std::numeric_limits<int32_t>::max() - current_money);
if (static_cast<int64_t>(withdraw) > shelved_money) {
withdraw = static_cast<int32_t>(shelved_money);
}
if (withdraw == 0) {
return current_money;
}
int64_t money = shelved_money - static_cast<int64_t>(withdraw);
if (!SaveShelf(chr, shelf_number, Field::MONEY, mutex, {}, money, shelf_exists, sql_query)) {
return current_money;
}
Printf(LOG_Info, "[shelf] Loaded money for login %d on server %d: %d withdrawn (tried %d), left %" PRId64 " stashed\n", chr.LoginID, shelf_number, withdraw, amount, money);
// Remove the book.
inventory.erase(savings_book);
return current_money + withdraw;
}
bool StoreOnShelfImpl(const CCharacter& chr, ServerIDType server_id, std::vector<CItem> inventory, int64_t money, LoadShelfFunction load_shelf, SQLQueryFunction sql_query) {
// Legend characters cannot deposit anything, we store everything into the regular character cabinet.
int shelf_number = FixServerID(server_id);
int32_t mutex = 0;
std::string shelved_items_repr;
int64_t shelved_money = 0;
bool shelf_exists;
if (!load_shelf(chr, shelf_number, Field::BOTH, &mutex, &shelved_items_repr, &shelved_money, shelf_exists)) {
return false;
}
std::vector<CItem> shelved_items = Login_UnserializeItems(shelved_items_repr).Items;
int64_t save_money = shelved_money + money;
MergeItemPiles(shelved_items, inventory);
return SaveShelf(chr, shelf_number, Field::BOTH, mutex, shelved_items, save_money, shelf_exists, sql_query);
}
} // namespace impl
} // namespace shelf