Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
69e335ba9c | ||
|
|
3590a06946 | ||
|
|
06b96c62d1 | ||
|
|
bc32475742 | ||
|
|
4b4f32ed58 | ||
|
|
bcd318791e |
@@ -68,4 +68,16 @@ MTSB1 error lock CODE item equipped no_attr busy running slot max
|
||||
- a new client session showed `lock 19 11209 10` (reloaded from the table);
|
||||
- unlocking → 8 → 0, and the row was deleted;
|
||||
- `log` has four `ATTR_LOCK` rows (hints 2, 10, 8, 0).
|
||||
- Not done: Android device test and production deploy.
|
||||
- Not done: Android device test.
|
||||
|
||||
## Production deployment
|
||||
|
||||
- 2026-10-15 16:08, approved by the user. All 203 live cores now run main `dc71593` (`game` sha256 `a8556bdc…`, the exact binary the channel-5 core was tested with, built in `/root/metin2-features-dev`). The db binary is unchanged. 0 players were online.
|
||||
- Package `/root/deploy-features/20261015-attrlock` (`deploy.sh check|go|rollback`, `SHA256SUMS`). The previous `game`/`db` (boss deploy, `400e44f`) are in `/root/backup-bin/20261015-160813`. The 8 changed files were synced into `/usr/metin2/src`, and the replaced ones are in `src-before/`. Because `item.h` changed, a later `rebuild.sh build` must touch every game .cpp. `sh deploy.sh rollback` restores both; the `mt_item_attr_lock` table can stay, since old binaries ignore it.
|
||||
- CH2–CH4 and the channel-5 core were started by hand after `start.sh 1`, giving 14 game cores plus db and auth.
|
||||
- Live acceptance on CH1 (13000), same armour 11209 (item 20000178), scroll 71084:
|
||||
- lock slot 1 → 2, slot 3 → 10, slot 0 → `error lock max`;
|
||||
- 10 switchbot rolls (scrolls 133 → 123): (23,10) and (39,10) unchanged on every roll, the other slots changed;
|
||||
- the row read `20000178 10`; a new session showed `lock 19 11209 10`;
|
||||
- unlocking → 8 → 0 deleted the row, and four new `ATTR_LOCK` log rows were written;
|
||||
- no `PortAttrLock` syserr entries.
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# PORT batch chest opening, v1
|
||||
|
||||
Date: 2026-10-15. AVA2-style batch opening of gift boxes (reference: AVA2 `ENABLE_MULTI_CHEST`, `/chest_drop`, `CHARACTER::OpenChest`). Source: `src/server/game/src/port_chest.h` (header-only, included from `cmd_general.cpp`), command `mt_chest` (cmd.cpp). It reuses the quiet-INFO hook (`m_portQuietInfo` / `m_portLastInfo`) added for the switchbot. No packet header, no DB schema, no char.h/item.h change.
|
||||
|
||||
AVA2 rewrote the drop loop (`GiveItemFromSpecialItemGroupNew`, `AutoGiveItemChest`, cap 1000). That rewrite is not ported. Here every box goes through the original `CHARACTER::UseItem` → `UseItemEx` `ITEM_GIFTBOX` path, one box at a time, so the original checks, the `special_item_group` roll, gold/exp, `ItemLog` and consumption stay exactly as they are.
|
||||
|
||||
## Rules
|
||||
|
||||
- Only `ITEM_GIFTBOX` items whose special item group exists, is not empty and contains none of the give types `MOB`, `SLOW`, `DRAIN_HP`, `POISON`, `MOB_GROUP`. Boxes that spawn monsters or apply debuffs stay single-use (`error kind`). Other item types (e.g. `ITEM_USE` chests with quest scripts) are not batchable.
|
||||
- The chosen cell is opened first while it still holds the box vnum; after that, any other bag cell with the same vnum. Most gift boxes on 203 have no stack flag, so a batch normally spans many cells. Items being exchanged are skipped.
|
||||
- At most 200 boxes per command.
|
||||
- Before each box the character must still have 3 free bag cells (`GetEmptyInventory(3)`). This keeps room for any reward, so `AutoGiveItem` never has to drop one on the ground. The loop stops with reason `full`.
|
||||
- Busy: dead, stunned, warping, observer, `!CanHandleItem`, exchange, own shop, shop open, safebox, cube. Checked before the command and before each box.
|
||||
- A box counts as opened only when the bag count of its vnum went down by exactly one. Anything else (the original path refused it, e.g. the dragon soul qualification) stops the loop with reason `rejected`. The last INFO line of that refusal is forwarded once.
|
||||
- Per-box INFO lines are held back while the batch runs.
|
||||
- Throttle: one command per 500 ms per player id.
|
||||
|
||||
## Protocol (CHAT_TYPE_COMMAND, version 1)
|
||||
|
||||
```
|
||||
/mt_chest 1 open CELL COUNT CELL = bag cell, COUNT = 1..200, digits only (at most 5)
|
||||
MTCH1 got VNUM COUNT one line per gained vnum (box vnum excluded), at most 40 lines
|
||||
MTCH1 done VNUM ASKED OPENED REASON GOLD
|
||||
MTCH1 error rate|invalid|busy|item|kind|full
|
||||
```
|
||||
|
||||
- REASON: `done` (all asked boxes opened), `empty` (no box of this vnum left), `full` (fewer than 3 free cells), `busy`, `rejected`.
|
||||
- GOLD: gold balance change over the batch.
|
||||
- Gains are the difference between bag + dragon soul bag counts before and after the batch.
|
||||
- A request with a version other than `1`, a token longer than 10 characters or more than 5 tokens is ignored silently.
|
||||
|
||||
There is no MTF1 capability bit (the mask stays 511). The client marks the server unsupported when no `MTCH1` reply arrives within 3 s and falls back to normal single use.
|
||||
|
||||
## Verification
|
||||
|
||||
- `tests/features/test_chest.py` compiles the production header against stubs of the `UseItem` gift-box contract (consume one box, gold, stacking reward, dragon soul reward, INFO lines). It covers:
|
||||
- cross-cell order and the gains/gold summary with INFO held back;
|
||||
- a stack, fewer asked than held, more asked than held (`empty`);
|
||||
- the 3-free-cell stop (`full`, `error full`);
|
||||
- refusal by the original path (`rejected`, INFO forwarded once);
|
||||
- non-gift box, monster box, missing and empty group (`kind`);
|
||||
- missing/exchanging item, busy, invalid input, silently ignored version, throttle.
|
||||
- It also checks the cmd.cpp / cmd_general.cpp wiring.
|
||||
- All `tests/features/test_*.py` pass.
|
||||
- FreeBSD build of the game target in `/root/metin2-features-dev` (log `chest-build.log`, binary sha256 `412977c7d7fda073493533d5bee43812a8f48dcb63399f747db6180d24803853`). The live `/usr/metin2` binary was not replaced and no live service was restarted.
|
||||
- Live test on 2026-10-15 against the channel-5 test core (port 13040, isolated binary) with the macOS native client as [SA]Admin, boxes created with `/item`:
|
||||
- 50037 (stacking, 30 held), 10 asked → `done 50037 10 10 done 0`, 6 gained vnums matching the bag difference exactly;
|
||||
- 50070 (not stacking, 4 boxes in 4 cells), all → `done 50070 4 4 done 100000`, gold balance +100000;
|
||||
- 71036 (group spawns a monster) → `error kind`, nothing consumed; an immediate second command → `error rate`;
|
||||
- remaining 20 of 50037 → `done 50037 20 20 done 0`, 11 gained vnums;
|
||||
- plain right click without Ctrl still uses one box the original way.
|
||||
- `log.log` only has the original path's rows (`SYSTEM`, `TREASURE_EXP`, `TREASURE_GOLD`). syserr shows only the pre-existing `new_quest_lv52` LUA_ERROR.
|
||||
|
||||
## Production deployment
|
||||
|
||||
- Deployed 2026-10-15 16:43 with the user's approval, 0 players online. Server main bc32475, game sha256 `412977c7…` (the channel-5 tested binary), db unchanged. Package `/root/deploy-features/20261015-chest`, backup `/root/backup-bin/20261015-164314`, rollback `sh /root/deploy-features/20261015-chest/deploy.sh rollback`. `/usr/metin2/src` was synced (cmd.cpp, cmd_general.cpp, port_chest.h).
|
||||
- On the first start the db core exited at boot (`QueryLocaleSet: ... errno 2013 Lost connection to MySQL server during query`, db.core kept as `db.core.164339` in the package). MySQL itself had not restarted and the db binary is unchanged. A clean stop of every core and a db-first start (db, auth, CH1–CH4, game99, then channel5) came up normally: 14 game, 1 db, 1 auth, port 15000 listening. If this repeats, check `ps` for `./db` after every deploy, not only the game count.
|
||||
- CH1 (13000) acceptance with the channel-5 scenario: 50037 ×10 → `done 50037 10 10 done 0` (8 vnums, equal to the bag difference); 50070 ×4 in 4 cells → `done 50070 4 4 done 100000`; 71036 → `error kind`, then `error rate`; remaining 20 → `done 50037 20 20 done 0`; plain use unchanged. syserr only has the pre-existing `new_quest_lv52` LUA_ERROR.
|
||||
@@ -0,0 +1,84 @@
|
||||
# PORT VIP card
|
||||
|
||||
A card extends all seven original premium services of the account. 40250 has the services but no in-game way to grant them. Source: `src/server/game/src/port_premium.h`, the hook in `CHARACTER::UseItem` (char_item.cpp), the enter-game refresh in input_login.cpp, `CHARACTER::PortSetPremiumTime` (char.h) and `/mt_vip` (cmd_general.cpp, cmd.cpp). Item data (size, flags, names, shop): metin2-client `tools/server/vip-card`.
|
||||
|
||||
## Services
|
||||
|
||||
`account.account` holds one end time per service. The game keeps them in `m_aiPremiumTimes` and shows affect `AFFECT_PREMIUM_START + i` (500..506) as the icon.
|
||||
|
||||
| i | Premium | Column | Effect on newcibn |
|
||||
|---|---|---|---|
|
||||
| 0 | `PREMIUM_EXP` | `silver_expire` | monster exp ×1.2 × `mob_exp_buyer`/100 (char_battle.cpp) |
|
||||
| 1 | `PREMIUM_ITEM` | `gold_expire` | item drop rate |
|
||||
| 2 | `PREMIUM_SAFEBOX` | `safebox_expire` | safebox size 3 (input_db.cpp) |
|
||||
| 3 | `PREMIUM_AUTOLOOT` | `autoloot_expire` | gold goes straight to the bag (char_battle.cpp) |
|
||||
| 4 | `PREMIUM_FISH_MIND` | `fish_mind_expire` | fishing |
|
||||
| 5 | `PREMIUM_MARRIAGE_FAST` | `marriage_fast_expire` | marriage love points |
|
||||
| 6 | `PREMIUM_GOLD` | `money_drop_rate_expire` | gold drop rate |
|
||||
|
||||
## Cards
|
||||
|
||||
| Vnum | Days |
|
||||
|---|---|
|
||||
| 38001 | 7 |
|
||||
| 38002 | 30 |
|
||||
|
||||
Both are unused `ITEM_NONE` rows in 40250. `PortVipUseCard` runs in `UseItem` after the sex check, before any type handling, so the item type does not matter.
|
||||
|
||||
When a card is used:
|
||||
|
||||
1. The card is refused, and not consumed, in two cases:
|
||||
- the player used a card or `/mt_vip` less than 1 s ago (`rate`);
|
||||
- for any service, the remaining time plus the card would exceed 400 days (`full`). The `int` end times stay far below 2038.
|
||||
2. Otherwise one card is consumed, with an `MT_VIP_CARD` item log whose hint is the number of days.
|
||||
3. One `UPDATE` moves every column to `GREATEST(UNIX_TIMESTAMP(col), UNIX_TIMESTAMP()) + days × 86400`. A service that has expired restarts from now; a running one is extended.
|
||||
|
||||
## Freshness
|
||||
|
||||
Auth reads the columns only at login and passes them to the db core's `CLoginData`. Every later player load, such as a warp or a core change, fills `TPlayerTable.aiPremiumTimes` from that login-time copy. So after a card, and on every enter-game, the game reads the row itself.
|
||||
|
||||
`PortVipRefresh` handles this:
|
||||
- It queues `SELECT UNIX_TIMESTAMP(col)... FROM account.account WHERE id=` through `DBManager::FuncQuery`. That is the same ordered queue and connection as the card's `UPDATE`, so the read sees the update.
|
||||
- The answer finds the player again by PID and checks the account ID; if the player has left, nothing happens.
|
||||
- For each service whose end changed, it sets `m_aiPremiumTimes[i]`, then either adds the affect with the remaining duration or removes it if the service has expired.
|
||||
- It logs `PORT_VIP: <name> type <i> end <unix>`.
|
||||
|
||||
The db core is not changed.
|
||||
|
||||
## Protocol
|
||||
|
||||
```
|
||||
/mt_vip 1 status ask for the remaining time
|
||||
MTVIP1 times R0 R1 R2 R3 R4 R5 R6 remaining seconds per service (0 = none), PREMIUM_EXP .. PREMIUM_GOLD
|
||||
MTVIP1 added VNUM DAYS a card was consumed; a times line follows once the row is read back
|
||||
MTVIP1 error CODE rate full invalid
|
||||
```
|
||||
|
||||
- `status` and card use share the 1 s throttle per player.
|
||||
- A wrong version, or more than three tokens, gets no answer; an old client never sends one.
|
||||
- The client (metin2-client `src/platform/ScriptLib/VipScript.inc`, module `mt_vip`) treats a `status` with no answer within 3 s as a server without the feature.
|
||||
|
||||
## Exp bonus
|
||||
|
||||
On newcibn the premium exp branch multiplies by 1.2 and then by `GetMobExpRate`, which returns event flag `mob_exp_buyer` (default 100). `/e mob_exp_buyer 167` gives 1.2 × 1.67 ≈ 2.0, that is +100 %. Event flags live in `player.quest` (pid 0) and every core shares them, so the flag is set once, by a GM, at deploy.
|
||||
|
||||
## Verification
|
||||
|
||||
- `tests/features/test_vip.py` checks the wiring:
|
||||
- the command entry is at the end of `cmd_info`;
|
||||
- the include is outside the `__AUCTION__` block;
|
||||
- the hook sits between the sex check and the summon-item block;
|
||||
- the refresh runs after the login affect loop.
|
||||
- It also compiles the production header against a stub account table, the ordered SQL queue and the affects. It covers:
|
||||
- a 7-day card, the read-back and the icons;
|
||||
- the gap refusal, then a 30-day card stacked onto the current end;
|
||||
- the 400-day cap: no card consumed, no query;
|
||||
- other items left untouched;
|
||||
- the enter-game refresh over stale values;
|
||||
- a service expired by hand, and the `status` command;
|
||||
- a player who leaves before the answer, and a missing account row.
|
||||
- Live test, channel5 (2026-10-15), Admin account with all expire values reset to 0:
|
||||
- 38002 (30 days) set all seven columns to now + 30 days, added affects 500..506 and returned `times 2592000…`.
|
||||
- Two 38001 used through the inventory right-click, 2 s apart, extended to 44 days.
|
||||
- A same-map `/warp` reloaded the player with the login-time 30 days. The refresh logged the seven `PORT_VIP` corrections to 44 days, and the panel showed "剩余 43 天 23 小时" for every service.
|
||||
- Earlier, with premium, autoloot gold went straight to the bag; without it, the gold stayed on the ground.
|
||||
@@ -1746,6 +1746,8 @@ class CHARACTER : public CEntity, public CFSM, public CHorseRider
|
||||
|
||||
public:
|
||||
int GetPremiumRemainSeconds(BYTE bType) const;
|
||||
// PORT: the VIP card re-reads the account end times (port_premium.h).
|
||||
void PortSetPremiumTime(BYTE bType, int iTime) { if (bType < PREMIUM_MAX_NUM) m_aiPremiumTimes[bType] = iTime; }
|
||||
|
||||
private:
|
||||
int m_aiPremiumTimes[PREMIUM_MAX_NUM];
|
||||
|
||||
@@ -50,6 +50,7 @@
|
||||
#ifdef __AUCTION__
|
||||
#include "auction_manager.h"
|
||||
#endif
|
||||
#include "port_premium.h"
|
||||
const int ITEM_BROKEN_METIN_VNUM = 28960;
|
||||
|
||||
// CHANGE_ITEM_ATTRIBUTES
|
||||
@@ -5207,6 +5208,10 @@ bool CHARACTER::UseItem(TItemPos Cell, TItemPos DestCell)
|
||||
return false;
|
||||
}
|
||||
|
||||
// PORT: VIP card (port_premium.h)
|
||||
if (PortVipUseCard(this, item))
|
||||
return true;
|
||||
|
||||
//PREVENT_TRADE_WINDOW
|
||||
if (IS_SUMMON_ITEM(item->GetVnum()))
|
||||
{
|
||||
|
||||
@@ -12,6 +12,8 @@ ACMD(do_port_biolog);
|
||||
ACMD(do_port_features);
|
||||
ACMD(do_port_switchbot);
|
||||
ACMD(do_port_pickup);
|
||||
ACMD(do_port_chest);
|
||||
ACMD(do_port_vip);
|
||||
ACMD(do_user_horse_ride);
|
||||
ACMD(do_user_horse_back);
|
||||
ACMD(do_user_horse_feed);
|
||||
@@ -286,9 +288,6 @@ struct command_info cmd_info[] =
|
||||
{
|
||||
{ "!RESERVED!", NULL, 0, POS_DEAD, GM_IMPLEMENTOR }, /* 반드시 이 것이 처음이어야 한다. */
|
||||
{ "autohunt_pull", do_autohunt_pull, 0, POS_STANDING, GM_PLAYER },
|
||||
{ "mt_features", do_port_features, 0, POS_DEAD, GM_PLAYER },
|
||||
{ "mt_switchbot", do_port_switchbot, 0, POS_DEAD, GM_PLAYER },
|
||||
{ "mt_pickup", do_port_pickup, 0, POS_DEAD, GM_PLAYER },
|
||||
{ "bio", do_port_biolog, 0, POS_DEAD, GM_PLAYER },
|
||||
{ "biolog", do_port_biolog, 0, POS_DEAD, GM_PLAYER },
|
||||
{ "server_bonuses", do_server_bonuses, 0, POS_DEAD, GM_PLAYER },
|
||||
@@ -601,6 +600,13 @@ struct command_info cmd_info[] =
|
||||
{ "ds_list", do_ds_list, 0, POS_DEAD, GM_PLAYER },
|
||||
{ "do_clear_affect", do_clear_affect, 0, POS_DEAD, GM_LOW_WIZARD},
|
||||
|
||||
// PORT: feature commands stay at the end: commands are prefix matched in table order, so an entry placed
|
||||
// earlier would take over abbreviations of original commands (/m -> mob, /mt -> mto).
|
||||
{ "mt_features", do_port_features, 0, POS_DEAD, GM_PLAYER },
|
||||
{ "mt_switchbot", do_port_switchbot, 0, POS_DEAD, GM_PLAYER },
|
||||
{ "mt_pickup", do_port_pickup, 0, POS_DEAD, GM_PLAYER },
|
||||
{ "mt_chest", do_port_chest, 0, POS_DEAD, GM_PLAYER },
|
||||
{ "mt_vip", do_port_vip, 0, POS_DEAD, GM_PLAYER },
|
||||
{ "\n", NULL, 0, POS_DEAD, GM_IMPLEMENTOR } /* 반드시 이 것이 마지막이어야 한다. */
|
||||
};
|
||||
|
||||
|
||||
@@ -45,6 +45,15 @@
|
||||
#include "port_features.h"
|
||||
#include "port_switchbot.h"
|
||||
#include "port_pickup.h"
|
||||
#include "port_chest.h"
|
||||
#include "port_premium.h"
|
||||
|
||||
ACMD(do_port_vip)
|
||||
{
|
||||
if (!ch || !ch->IsPC() || !ch->GetDesc())
|
||||
return;
|
||||
PortVipCommand(ch, argument);
|
||||
}
|
||||
|
||||
extern int g_server_id;
|
||||
|
||||
|
||||
@@ -28,6 +28,9 @@
|
||||
#include "block_country.h"
|
||||
#include "dev_log.h"
|
||||
#include "log.h"
|
||||
#include "db.h"
|
||||
#include "item.h"
|
||||
#include "port_premium.h"
|
||||
#include "horsename_manager.h"
|
||||
#include "MarkManager.h"
|
||||
// #include "HackShield.h"
|
||||
@@ -642,6 +645,8 @@ void CInputLogin::Entergame(LPDESC d, const char * data)
|
||||
ch->AddAffect(AFFECT_PREMIUM_START + i, POINT_NONE, 0, 0, remain, 0, true);
|
||||
sys_log(0, "PREMIUM: %s type %d %dmin", ch->GetName(), i, remain);
|
||||
}
|
||||
// PORT: the db core keeps the login-time premium ends; a VIP card used since then is in the account table.
|
||||
PortVipRefresh(ch, false);
|
||||
|
||||
if (LC_IsEurope())
|
||||
{
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
#ifndef METIN2_PORT_CHEST_H
|
||||
#define METIN2_PORT_CHEST_H
|
||||
// PORT: AVA2-style batch chest opening (ENABLE_MULTI_CHEST /chest_drop). AVA2 rewrote the drop loop
|
||||
// (GiveItemFromSpecialItemGroupNew); here every box goes through the original CHARACTER::UseItem gift-box path,
|
||||
// so its checks, special_item_group roll, gold/exp, ItemLog and consumption are unchanged. Boxes of one vnum are
|
||||
// opened from the chosen cell first, then from any other cell (most gift boxes do not stack). Per-box INFO lines
|
||||
// are held back and the gains are reported once as MTCH1 lines. Protocol: docs/FEATURE-CHEST.md.
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
static const unsigned kPortChestMax=200, kPortChestReportVnums=40, kPortChestFreeCells=3;
|
||||
static const DWORD kPortChestGapMs=500;
|
||||
static std::map<DWORD,DWORD> g_portChestLastCommand;
|
||||
|
||||
static bool PortChestNumber(const std::string& text,unsigned& value) {
|
||||
if(text.empty() || text.size()>5)return false;
|
||||
value=0;
|
||||
for(char c:text){if(c<'0'||c>'9')return false;value=value*10+unsigned(c-'0');}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Gift boxes whose group only hands out items, gold or exp. Groups that spawn monsters, slow, poison or drain
|
||||
// HP stay single-use: opening a stack of them at once would spawn every group around the player in one tick.
|
||||
static bool PortChestBatchable(LPITEM item) {
|
||||
if(item->GetType()!=ITEM_GIFTBOX)return false;
|
||||
const CSpecialItemGroup* group=ITEM_MANAGER::instance().GetSpecialItemGroup(item->GetVnum());
|
||||
if(!group || group->IsEmpty())return false;
|
||||
const DWORD unsafe[]={CSpecialItemGroup::MOB,CSpecialItemGroup::SLOW,CSpecialItemGroup::DRAIN_HP,
|
||||
CSpecialItemGroup::POISON,CSpecialItemGroup::MOB_GROUP};
|
||||
for(DWORD kind:unsafe)if(group->Contains(kind))return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool PortChestBusy(LPCHARACTER ch) {
|
||||
return ch->IsDead() || ch->IsStun() || ch->IsWarping() || ch->IsObserverMode() || !ch->CanHandleItem() ||
|
||||
ch->GetExchange() || ch->GetMyShop() || ch->GetShopOwner() || ch->IsOpenSafebox() || ch->IsCubeOpen();
|
||||
}
|
||||
|
||||
// Item counts by vnum over the bag and the dragon soul bag, where AutoGiveItem puts what a box gives.
|
||||
static std::map<DWORD,long long> PortChestSnapshot(LPCHARACTER ch) {
|
||||
std::map<DWORD,long long> counts;
|
||||
for(int i=0;i<INVENTORY_MAX_NUM;++i)if(LPITEM item=ch->GetInventoryItem(i))counts[item->GetVnum()]+=item->GetCount();
|
||||
for(int i=0;i<DRAGON_SOUL_INVENTORY_MAX_NUM;++i)
|
||||
if(LPITEM item=ch->GetItem(TItemPos(DRAGON_SOUL_INVENTORY,i)))counts[item->GetVnum()]+=item->GetCount();
|
||||
return counts;
|
||||
}
|
||||
|
||||
// The box to open next: the chosen cell while it still holds this vnum, otherwise any bag cell that does.
|
||||
static LPITEM PortChestNext(LPCHARACTER ch,unsigned cell,DWORD vnum) {
|
||||
LPITEM item=ch->GetInventoryItem(cell);
|
||||
if(item && item->GetVnum()==vnum && !item->IsExchanging())return item;
|
||||
for(int i=0;i<INVENTORY_MAX_NUM;++i) {
|
||||
item=ch->GetInventoryItem(i);
|
||||
if(item && item->GetVnum()==vnum && !item->IsExchanging())return item;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static const char* PortChestOpen(LPCHARACTER ch,unsigned cell,unsigned asked) {
|
||||
if(cell>=unsigned(INVENTORY_MAX_NUM) || !asked || asked>kPortChestMax)return "invalid";
|
||||
if(PortChestBusy(ch))return "busy";
|
||||
LPITEM first=ch->GetInventoryItem(cell);
|
||||
if(!first || first->IsExchanging())return "item";
|
||||
if(!PortChestBatchable(first))return "kind";
|
||||
if(ch->GetEmptyInventory(kPortChestFreeCells)==-1)return "full";
|
||||
const DWORD vnum=first->GetVnum();
|
||||
const std::map<DWORD,long long> before=PortChestSnapshot(ch);
|
||||
const long long goldBefore=ch->GetGold();
|
||||
unsigned opened=0;const char* reason="done";std::string rejection;
|
||||
while(opened<asked) {
|
||||
if(PortChestBusy(ch)){reason="busy";break;}
|
||||
// Stop while a whole weapon still fits, so AutoGiveItem never has to drop a reward on the ground.
|
||||
if(ch->GetEmptyInventory(kPortChestFreeCells)==-1){reason="full";break;}
|
||||
LPITEM box=PortChestNext(ch,cell,vnum);
|
||||
if(!box){reason="empty";break;}
|
||||
const int count=ch->CountSpecifyItem(vnum);
|
||||
ch->m_portQuietInfo=true;ch->m_portLastInfo.clear();
|
||||
ch->UseItem(TItemPos(INVENTORY,box->GetCell()));
|
||||
ch->m_portQuietInfo=false;
|
||||
// Success is judged by the original path consuming exactly one box, not by its return value.
|
||||
if(ch->CountSpecifyItem(vnum)!=count-1){reason="rejected";rejection=ch->m_portLastInfo;break;}
|
||||
++opened;
|
||||
}
|
||||
if(!rejection.empty())ch->ChatPacket(CHAT_TYPE_INFO,"%s",rejection.c_str());
|
||||
const std::map<DWORD,long long> after=PortChestSnapshot(ch);
|
||||
unsigned reported=0;
|
||||
for(const auto& entry:after) {
|
||||
if(entry.first==vnum)continue;
|
||||
auto it=before.find(entry.first);
|
||||
const long long gained=entry.second-(it==before.end()?0:it->second);
|
||||
if(gained<=0)continue;
|
||||
if(++reported>kPortChestReportVnums)break;
|
||||
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTCH1 got %u %lld",unsigned(entry.first),gained);
|
||||
}
|
||||
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTCH1 done %u %u %u %s %lld",unsigned(vnum),asked,opened,reason,
|
||||
(long long)ch->GetGold()-goldBefore);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
ACMD(do_port_chest) {
|
||||
if(!ch || !ch->IsPC() || !ch->GetDesc())return;
|
||||
std::istringstream input(argument);std::vector<std::string> args;std::string token;
|
||||
while(input>>token){if(token.size()>10 || args.size()>=5)return;args.push_back(token);}
|
||||
if(args.size()<2 || args[0]!="1")return;
|
||||
DWORD& last=g_portChestLastCommand[ch->GetPlayerID()];
|
||||
if(last && get_dword_time()-last<kPortChestGapMs){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTCH1 error rate");return;}
|
||||
last=get_dword_time();
|
||||
unsigned cell=0,count=0;const char* error="invalid";
|
||||
if(args[1]=="open" && args.size()==4 && PortChestNumber(args[2],cell) && PortChestNumber(args[3],count))
|
||||
error=PortChestOpen(ch,cell,count);
|
||||
if(error)ch->ChatPacket(CHAT_TYPE_COMMAND,"MTCH1 error %s",error);
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,103 @@
|
||||
#ifndef METIN2_PORT_PREMIUM_H
|
||||
#define METIN2_PORT_PREMIUM_H
|
||||
// PORT: VIP card. Using card 38001 (7 days) or 38002 (30 days) extends all seven premium services of the account
|
||||
// (account.account *_expire) from the later of now and their current end. The original server reads these columns
|
||||
// only when auth logs the account in, and the db core hands those login-time values to every later player load
|
||||
// (CLoginData), so after a card and on every enter-game the game re-reads them and updates m_aiPremiumTimes and the
|
||||
// AFFECT_PREMIUM_START+i icons. Protocol: docs/FEATURE-VIP.md.
|
||||
#include <cstdlib>
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
static const int kPortVipTypes=7; // PREMIUM_EXP .. PREMIUM_GOLD, in account column order
|
||||
static const char* const kPortVipColumns[kPortVipTypes]={"silver_expire","gold_expire","safebox_expire",
|
||||
"autoloot_expire","fish_mind_expire","marriage_fast_expire","money_drop_rate_expire"};
|
||||
static const DWORD kPortVipCards[][2]={{38001,7},{38002,30}};
|
||||
static const int kPortVipMaxDays=400; // remaining time a card may reach, far from the 2038 limit of the int times
|
||||
static const DWORD kPortVipGapMs=1000;
|
||||
|
||||
inline int PortVipCardDays(DWORD vnum) {
|
||||
for(const auto& card:kPortVipCards)if(card[0]==vnum)return int(card[1]);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// One throttle per player id for card use and status requests: both queue a query whose answer updates memory.
|
||||
inline bool PortVipThrottled(LPCHARACTER ch) {
|
||||
static std::map<DWORD,DWORD> last;
|
||||
DWORD& at=last[ch->GetPlayerID()];
|
||||
if(at && get_dword_time()-at<kPortVipGapMs)return true;
|
||||
at=get_dword_time();
|
||||
return false;
|
||||
}
|
||||
|
||||
// The account's end times (unix seconds) are the truth: premium state, icons, and on request the client.
|
||||
inline void PortVipApply(LPCHARACTER ch,const int* times,bool report) {
|
||||
const int now=get_global_time();
|
||||
std::string line="MTVIP1 times";
|
||||
for(int i=0;i<kPortVipTypes;++i) {
|
||||
const int remain=times[i]-now;
|
||||
if(times[i]!=ch->GetPremiumRemainSeconds(i)+now) {
|
||||
ch->PortSetPremiumTime(i,times[i]);
|
||||
if(remain>0)ch->AddAffect(AFFECT_PREMIUM_START+i,POINT_NONE,0,0,remain,0,true);
|
||||
else ch->RemoveAffect(AFFECT_PREMIUM_START+i);
|
||||
sys_log(0,"PORT_VIP: %s type %d end %d",ch->GetName(),i,times[i]);
|
||||
}
|
||||
line+=" "+std::to_string(remain>0?remain:0);
|
||||
}
|
||||
if(report)ch->ChatPacket(CHAT_TYPE_COMMAND,"%s",line.c_str());
|
||||
}
|
||||
|
||||
inline void PortVipRefresh(LPCHARACTER ch,bool report) {
|
||||
if(!ch->GetDesc())return;
|
||||
const DWORD pid=ch->GetPlayerID(),account=ch->GetDesc()->GetAccountTable().id;
|
||||
std::string columns;
|
||||
for(int i=0;i<kPortVipTypes;++i)columns+=std::string(i?",":"")+"UNIX_TIMESTAMP("+kPortVipColumns[i]+")";
|
||||
DBManager::instance().FuncQuery([pid,account,report](SQLMsg* msg) {
|
||||
LPCHARACTER ch=CHARACTER_MANAGER::instance().FindByPID(pid);
|
||||
if(!ch || !ch->GetDesc() || ch->GetDesc()->GetAccountTable().id!=account)return;
|
||||
if(!msg->Get() || msg->Get()->uiNumRows!=1){sys_err("PORT_VIP: account %u not found",account);return;}
|
||||
MYSQL_ROW row=mysql_fetch_row(msg->Get()->pSQLResult);
|
||||
int times[kPortVipTypes];
|
||||
for(int i=0;i<kPortVipTypes;++i)times[i]=row[i]?atoi(row[i]):0;
|
||||
PortVipApply(ch,times,report);
|
||||
},"SELECT %s FROM account.account WHERE id=%u",columns.c_str(),account);
|
||||
}
|
||||
|
||||
// Called by CHARACTER::UseItem before the original item handling: true when the item is a VIP card, used or not.
|
||||
inline bool PortVipUseCard(LPCHARACTER ch,LPITEM item) {
|
||||
const int days=PortVipCardDays(item->GetVnum());
|
||||
if(!days)return false;
|
||||
if(!ch->IsPC() || !ch->GetDesc())return true;
|
||||
if(PortVipThrottled(ch)){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTVIP1 error rate");return true;}
|
||||
for(int i=0;i<kPortVipTypes;++i) {
|
||||
const int remain=ch->GetPremiumRemainSeconds(i);
|
||||
if((remain>0?remain:0)+days*86400>kPortVipMaxDays*86400){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTVIP1 error full");return true;}
|
||||
}
|
||||
const DWORD vnum=item->GetVnum(),account=ch->GetDesc()->GetAccountTable().id;
|
||||
std::string sets;
|
||||
for(int i=0;i<kPortVipTypes;++i) {
|
||||
const std::string column=kPortVipColumns[i];
|
||||
sets+=(i?",":"")+column+"=FROM_UNIXTIME(GREATEST(UNIX_TIMESTAMP("+column+"),UNIX_TIMESTAMP())+"+
|
||||
std::to_string(days*86400)+")";
|
||||
}
|
||||
LogManager::instance().ItemLog(ch,item,"MT_VIP_CARD",std::to_string(days).c_str());
|
||||
item->SetCount(item->GetCount()-1);
|
||||
// Same connection as the refresh, which therefore reads the updated row.
|
||||
DBManager::instance().Query("UPDATE account.account SET %s WHERE id=%u",sets.c_str(),account);
|
||||
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTVIP1 added %u %d",unsigned(vnum),days);
|
||||
PortVipRefresh(ch,true);
|
||||
return true;
|
||||
}
|
||||
|
||||
// /mt_vip 1 status -> MTVIP1 times (seven remaining seconds, PREMIUM_EXP .. PREMIUM_GOLD)
|
||||
inline void PortVipCommand(LPCHARACTER ch,const char* argument) {
|
||||
std::istringstream input(argument);std::vector<std::string> args;std::string token;
|
||||
while(input>>token){if(token.size()>10 || args.size()>=3)return;args.push_back(token);}
|
||||
if(args.empty() || args[0]!="1")return;
|
||||
if(args.size()!=2 || args[1]!="status"){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTVIP1 error invalid");return;}
|
||||
if(PortVipThrottled(ch)){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTVIP1 error rate");return;}
|
||||
PortVipRefresh(ch,true);
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,116 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compile the production batch-chest header against stubs of the original UseItem gift-box contract."""
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
SRC=ROOT/'src/server/game/src'
|
||||
cmd=(SRC/'cmd.cpp').read_bytes().decode('latin1')
|
||||
assert 'ACMD(do_port_chest);' in cmd and '"mt_chest", do_port_chest, 0, POS_DEAD, GM_PLAYER' in cmd
|
||||
assert '#include "port_chest.h"' in (SRC/'cmd_general.cpp').read_bytes().decode('latin1')
|
||||
code=r'''
|
||||
#include <cassert>
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
using DWORD=unsigned;using BYTE=unsigned char;using WORD=unsigned short;using INT=int;
|
||||
enum {ITEM_USE=3,ITEM_GIFTBOX=23,INVENTORY=1,DRAGON_SOUL_INVENTORY=3,INVENTORY_MAX_NUM=10,DRAGON_SOUL_INVENTORY_MAX_NUM=4};
|
||||
enum {CHAT_TYPE_INFO=1,CHAT_TYPE_COMMAND=5};
|
||||
static DWORD clockms=1000;DWORD get_dword_time(){return clockms;}
|
||||
struct TItemPos{BYTE window_type;WORD cell;TItemPos(BYTE w,WORD c):window_type(w),cell(c){}};
|
||||
struct CItem{DWORD vnum;int count;BYTE type;bool exchanging=false;WORD cell=0;
|
||||
DWORD GetVnum(){return vnum;}int GetCount(){return count;}BYTE GetType(){return type;}bool IsExchanging(){return exchanging;}WORD GetCell(){return cell;}};
|
||||
using LPITEM=CItem*;
|
||||
struct CSpecialItemGroup{
|
||||
enum EGiveType{NONE,GOLD,EXP,MOB,SLOW,DRAIN_HP,POISON,MOB_GROUP};
|
||||
std::vector<DWORD> vnums;bool IsEmpty()const{return vnums.empty();}
|
||||
bool Contains(DWORD v)const{for(DWORD x:vnums)if(x==v)return true;return false;}
|
||||
};
|
||||
static std::map<DWORD,CSpecialItemGroup> groups;
|
||||
struct ITEM_MANAGER{static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;}
|
||||
const CSpecialItemGroup* GetSpecialItemGroup(DWORD v){auto it=groups.find(v);return it==groups.end()?nullptr:&it->second;}};
|
||||
struct CHARACTER{
|
||||
bool m_portQuietInfo=false;std::string m_portLastInfo;
|
||||
LPITEM bag[INVENTORY_MAX_NUM]={};LPITEM ds[DRAGON_SOUL_INVENTORY_MAX_NUM]={};std::vector<CItem*> owned;
|
||||
int gold=0;bool dead=false,shop=false,refuse=false;int uses=0;std::vector<std::string> messages,info;
|
||||
bool IsPC(){return true;}void* GetDesc(){return this;}DWORD GetPlayerID(){return 7;}
|
||||
bool IsDead(){return dead;}bool IsStun()const{return false;}bool IsWarping()const{return false;}bool IsObserverMode(){return false;}
|
||||
bool CanHandleItem(){return true;}void* GetExchange(){return nullptr;}void* GetMyShop(){return shop?this:nullptr;}
|
||||
void* GetShopOwner(){return nullptr;}bool IsOpenSafebox(){return false;}bool IsCubeOpen(){return false;}
|
||||
INT GetGold()const{return gold;}
|
||||
LPITEM GetInventoryItem(WORD c)const{return c<INVENTORY_MAX_NUM?bag[c]:nullptr;}
|
||||
LPITEM GetItem(TItemPos p){return p.window_type==DRAGON_SOUL_INVENTORY?ds[p.cell]:bag[p.cell];}
|
||||
int GetEmptyInventory(BYTE size)const{int free=0;for(auto* i:bag)free+=!i;return free>=size?0:-1;}
|
||||
int CountSpecifyItem(DWORD v)const{int n=0;for(auto* i:bag)if(i&&i->vnum==v)n+=i->count;return n;}
|
||||
LPITEM Put(DWORD v,int n,BYTE t=ITEM_USE,int at=-1){
|
||||
for(int c=0;c<INVENTORY_MAX_NUM;++c)if(at<0?!bag[c]:c==at){CItem* i=new CItem{v,n,t};i->cell=c;bag[c]=i;owned.push_back(i);return i;}
|
||||
return nullptr;}
|
||||
void ChatPacket(BYTE type,const char* format,...){
|
||||
char out[513];va_list a;va_start(a,format);vsnprintf(out,sizeof(out),format,a);va_end(a);
|
||||
if(m_portQuietInfo&&type==CHAT_TYPE_INFO){m_portLastInfo=out;return;}
|
||||
(type==CHAT_TYPE_INFO?info:messages).emplace_back(out);
|
||||
}
|
||||
// Original gift-box contract: one box consumed, 100 gold + one 27001 (stacking) + a dragon soul for box 50100,
|
||||
// one INFO line per reward; the DS-quest style refusal returns false with an INFO line and consumes nothing.
|
||||
bool UseItem(TItemPos p){
|
||||
++uses;LPITEM box=GetItem(p);assert(box && p.window_type==INVENTORY && m_portQuietInfo);
|
||||
if(refuse){ChatPacket(CHAT_TYPE_INFO,"finish the dragon soul quest first");return false;}
|
||||
gold+=100;ChatPacket(CHAT_TYPE_INFO,"gold 100");
|
||||
if(--box->count==0)bag[p.cell]=nullptr;
|
||||
bool stacked=false;for(auto* i:bag)if(i&&i->vnum==27001){++i->count;stacked=true;break;}
|
||||
if(!stacked)Put(27001,1);
|
||||
if(box->vnum==50100)for(auto*& d:ds)if(!d){d=new CItem{110000,1,ITEM_USE};owned.push_back(d);break;}
|
||||
ChatPacket(CHAT_TYPE_INFO,"got potion");
|
||||
return true;
|
||||
}
|
||||
};
|
||||
using LPCHARACTER=CHARACTER*;
|
||||
#define ACMD(name) void name(LPCHARACTER ch,const char* argument)
|
||||
#include "port_chest.h"
|
||||
static CHARACTER* ch;
|
||||
static void cmd(const char* text){clockms+=600;ch->messages.clear();ch->info.clear();ch->uses=0;do_port_chest(ch,text);}
|
||||
static const std::string& last(){return ch->messages.back();}
|
||||
static void fresh(){ch=new CHARACTER;}
|
||||
int main(){
|
||||
groups[50100].vnums={27001,1,110000};groups[50200].vnums={27001,CSpecialItemGroup::MOB};groups[50300].vnums={};
|
||||
// Non-stacking boxes spread over cells: chosen cell first, then the others; gains summed, INFO held back.
|
||||
fresh();ch->Put(50100,1,ITEM_GIFTBOX,0);ch->Put(50100,1,ITEM_GIFTBOX,4);ch->Put(50100,1,ITEM_GIFTBOX,5);
|
||||
cmd("1 open 4 3");
|
||||
assert(ch->messages.size()==3 && ch->messages[0]=="MTCH1 got 27001 3" && ch->messages[1]=="MTCH1 got 110000 3");
|
||||
assert(last()=="MTCH1 done 50100 3 3 done 300" && ch->info.empty() && !ch->m_portQuietInfo && ch->CountSpecifyItem(50100)==0);
|
||||
// Stacked box, fewer asked than held; then more asked than held -> empty.
|
||||
fresh();ch->Put(50100,5,ITEM_GIFTBOX);cmd("1 open 0 2");assert(last()=="MTCH1 done 50100 2 2 done 200" && ch->bag[0]->count==3);
|
||||
cmd("1 open 0 200");assert(last()=="MTCH1 done 50100 200 3 empty 300" && ch->uses==3);
|
||||
// Single boxes free their own cell for the reward, so free space never shrinks.
|
||||
fresh();for(int i=0;i<7;++i)ch->Put(50100,1,ITEM_GIFTBOX);
|
||||
cmd("1 open 0 7");assert(last()=="MTCH1 done 50100 7 7 done 700");
|
||||
// A stack + 6 fillers leaves exactly 3 free cells: the first reward takes one, then it stops at 2 free.
|
||||
fresh();ch->Put(50100,7,ITEM_GIFTBOX);for(int i=0;i<6;++i)ch->Put(1,1);
|
||||
cmd("1 open 0 7");assert(last()=="MTCH1 done 50100 7 1 full 100" && ch->uses==1);
|
||||
cmd("1 open 0 1");assert(last()=="MTCH1 error full" && ch->uses==0);
|
||||
// Refusal by the original path: stops, forwards its INFO once.
|
||||
fresh();ch->Put(50100,3,ITEM_GIFTBOX);ch->refuse=true;cmd("1 open 0 3");
|
||||
assert(last()=="MTCH1 done 50100 3 0 rejected 0" && ch->info.size()==1 && ch->info[0]=="finish the dragon soul quest first");
|
||||
// Kinds: not a gift box, monster group box, no/empty group.
|
||||
fresh();ch->Put(27001,5);cmd("1 open 0 1");assert(last()=="MTCH1 error kind");
|
||||
ch->Put(50200,2,ITEM_GIFTBOX);cmd("1 open 1 1");assert(last()=="MTCH1 error kind");
|
||||
ch->Put(50300,2,ITEM_GIFTBOX);cmd("1 open 2 1");assert(last()=="MTCH1 error kind");
|
||||
ch->Put(50400,2,ITEM_GIFTBOX);cmd("1 open 3 1");assert(last()=="MTCH1 error kind" && ch->uses==0);
|
||||
// Item, exchange, busy, validation, throttle.
|
||||
cmd("1 open 9 1");assert(last()=="MTCH1 error item");
|
||||
LPITEM box=ch->Put(50100,2,ITEM_GIFTBOX);box->exchanging=true;cmd("1 open 4 1");assert(last()=="MTCH1 error item");box->exchanging=false;
|
||||
ch->shop=true;cmd("1 open 4 1");assert(last()=="MTCH1 error busy");ch->shop=false;
|
||||
for(auto bad:{"1 open 4 0","1 open 4 201","1 open 10 1","1 open 4","1 open x 1","1 open 4 1 1","1 close 4 1","1 open 4 999999"}){cmd(bad);assert(last()=="MTCH1 error invalid");}
|
||||
cmd("2 open 4 1");assert(ch->messages.empty());
|
||||
cmd("1 open 4 1");assert(last()=="MTCH1 done 50100 1 1 done 100");
|
||||
do_port_chest(ch,"1 open 4 1");assert(last()=="MTCH1 error rate" && ch->CountSpecifyItem(50100)==1);
|
||||
cmd("1 open 4 1");assert(last()=="MTCH1 done 50100 1 1 done 100");
|
||||
puts("PASS: cross-cell order, stacks, gains summary, free-cell stop, refusal, kinds, item/busy/validation/throttle");
|
||||
}
|
||||
'''
|
||||
with tempfile.TemporaryDirectory(prefix='mt-chest-') as folder:
|
||||
path=Path(folder);(path/'test.cpp').write_text(code)
|
||||
subprocess.run(['c++','-std=c++17','-Wall','-I'+str(SRC),str(path/'test.cpp'),'-o',str(path/'test')],check=True)
|
||||
subprocess.run([str(path/'test')],check=True)
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Port commands must not take over abbreviations of the original commands.
|
||||
|
||||
interpret_command (cmd.cpp) picks the first table entry whose name starts with the typed command
|
||||
(strncmp over the typed length; do_cmd entries need an exact match). A port command placed before an
|
||||
original one would steal its abbreviations, as mt_features once did with /m (mob) and /mt (mto).
|
||||
"""
|
||||
from pathlib import Path
|
||||
import re
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
text=(ROOT/'src/server/game/src/cmd.cpp').read_bytes().decode('latin1')
|
||||
table=text.split('struct command_info cmd_info[] =',1)[1]
|
||||
entries=re.findall(r'\{\s*"((?:[^"\\]|\\.)*)",\s*([A-Za-z_0-9]+|NULL)',table)
|
||||
assert entries[0][0]=='!RESERVED!'
|
||||
end=[i for i,(name,_) in enumerate(entries) if name=='\\n']
|
||||
assert end,'table sentinel not found'
|
||||
entries=entries[1:end[0]]
|
||||
PORT=lambda name:name.startswith('mt_')
|
||||
port=[name for name,_ in entries if PORT(name)]
|
||||
assert {'mt_features','mt_switchbot','mt_pickup','mt_chest'}<=set(port),port
|
||||
|
||||
def resolve(rows,cmd):
|
||||
for name,fn in rows:
|
||||
if fn=='do_cmd':
|
||||
if name==cmd:return name
|
||||
elif name.startswith(cmd):return name
|
||||
return None
|
||||
|
||||
original=[(name,fn) for name,fn in entries if not PORT(name)]
|
||||
for name in port:assert resolve(entries,name)==name,name
|
||||
for name,_ in original:
|
||||
for k in range(1,len(name)+1):
|
||||
typed=name[:k]
|
||||
assert resolve(entries,typed)==resolve(original,typed),'/%s now runs %s instead of %s'%(typed,resolve(entries,typed),resolve(original,typed))
|
||||
for typed in ('m','mt','mo'):assert not PORT(resolve(entries,typed) or ''),typed
|
||||
assert resolve(entries,'m')=='mob' and resolve(entries,'mt')=='mto'
|
||||
print('cmd prefix ok: %d commands, %d port'%(len(entries),len(port)))
|
||||
@@ -0,0 +1,137 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compile the production VIP card header against stubs of the account table, the ordered async SQL queue and
|
||||
the premium affects."""
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
SRC=ROOT/'src/server/game/src'
|
||||
def source(name):return (SRC/name).read_bytes().decode('latin1')
|
||||
cmd=source('cmd.cpp')
|
||||
assert 'ACMD(do_port_vip);' in cmd and '"mt_vip", do_port_vip, 0, POS_DEAD, GM_PLAYER' in cmd
|
||||
general=source('cmd_general.cpp')
|
||||
assert '#include "port_premium.h"' in general and 'PortVipCommand(ch, argument);' in general
|
||||
item=source('char_item.cpp')
|
||||
use=item.index('bool CHARACTER::UseItem(TItemPos Cell, TItemPos DestCell)')
|
||||
hook=item.index('if (PortVipUseCard(this, item))',use)
|
||||
assert '#endif\n#include "port_premium.h"\n' in item # not inside the __AUCTION__ block
|
||||
assert item.index('FN_check_item_sex(this, item)',use)<hook<item.index('IS_SUMMON_ITEM(item->GetVnum())',use)
|
||||
login=source('input_login.cpp')
|
||||
assert login.index('AFFECT_PREMIUM_START + i')<login.index('PortVipRefresh(ch, false);')
|
||||
assert 'void\t\t\t\tPortSetPremiumTime(BYTE bType, int iTime)' in source('char.h')
|
||||
code=r'''
|
||||
#include <cassert>
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
using DWORD=unsigned;using BYTE=unsigned char;
|
||||
enum {CHAT_TYPE_INFO=1,CHAT_TYPE_COMMAND=5,POINT_NONE=0,AFFECT_PREMIUM_START=500,PREMIUM_MAX_NUM=9};
|
||||
static int now=1700000000;static DWORD clockms=1000;
|
||||
int get_global_time(){return now;}DWORD get_dword_time(){return clockms;}
|
||||
static std::vector<std::string> logs;
|
||||
void sys_log(int,const char* format,...){char out[512];va_list a;va_start(a,format);vsnprintf(out,sizeof(out),format,a);va_end(a);logs.push_back(out);}
|
||||
void sys_err(const char* format,...){char out[512];va_list a;va_start(a,format);vsnprintf(out,sizeof(out),format,a);va_end(a);logs.push_back(std::string("ERR ")+out);}
|
||||
static std::string format(const char* f,va_list a){char out[4096];vsnprintf(out,sizeof(out),f,a);return out;}
|
||||
// Account table: id -> seven end times (0 = never), as UNIX_TIMESTAMP reads them.
|
||||
static std::map<DWORD,std::vector<int>> accounts;
|
||||
using MYSQL_ROW=char**;
|
||||
struct Rows{char* cells[7];char text[7][16];};
|
||||
struct SQLResult{unsigned uiNumRows;Rows* pSQLResult;Rows rows;};
|
||||
struct SQLMsg{SQLResult result;bool ok=true;SQLResult* Get(){return ok?&result:nullptr;}};
|
||||
MYSQL_ROW mysql_fetch_row(Rows* r){return r->cells;}
|
||||
struct DBManager{
|
||||
std::deque<std::function<void()>> queue;std::vector<std::string> queries;
|
||||
static DBManager& instance(){static DBManager m;return m;}
|
||||
void Query(const char* f,...){va_list a;va_start(a,f);std::string q=format(f,a);va_end(a);queries.push_back(q);
|
||||
queue.push_back([q]{DWORD id;int secs;
|
||||
const char* where=strstr(q.c_str()," WHERE id=");assert(where && sscanf(where," WHERE id=%u",&id)==1);
|
||||
const char* add=strstr(q.c_str(),"UNIX_TIMESTAMP())+");assert(add && sscanf(add,"UNIX_TIMESTAMP())+%d)",&secs)==1);
|
||||
for(int& t:accounts[id])t=(t>now?t:now)+secs;});}
|
||||
template<class F> void FuncQuery(F f,const char* fmt,...){va_list a;va_start(a,fmt);std::string q=format(fmt,a);va_end(a);queries.push_back(q);
|
||||
queue.push_back([f,q]{DWORD id;assert(sscanf(strstr(q.c_str()," WHERE id="), " WHERE id=%u",&id)==1);
|
||||
SQLMsg m{};auto it=accounts.find(id);m.result.uiNumRows=it==accounts.end()?0:1;m.result.pSQLResult=&m.result.rows;
|
||||
for(int i=0;i<7;++i){m.result.rows.cells[i]=m.result.rows.text[i];snprintf(m.result.rows.text[i],16,"%d",it==accounts.end()?0:it->second[i]);}
|
||||
f(&m);});}
|
||||
void Run(){while(!queue.empty()){auto job=queue.front();queue.pop_front();job();}}
|
||||
};
|
||||
struct CItem{DWORD vnum;int count;DWORD GetVnum(){return vnum;}int GetCount(){return count;}void SetCount(int c){count=c;}};
|
||||
using LPITEM=CItem*;
|
||||
struct TAccountTable{DWORD id;};
|
||||
struct DESC{TAccountTable table;TAccountTable& GetAccountTable(){return table;}};
|
||||
struct CHARACTER{
|
||||
DESC desc;bool online=true;int premium[PREMIUM_MAX_NUM]={};std::map<DWORD,long> affects;std::vector<std::string> messages;
|
||||
const char* GetName(){return "Admin";}bool IsPC(){return true;}DESC* GetDesc(){return online?&desc:nullptr;}DWORD GetPlayerID(){return 7;}
|
||||
int GetPremiumRemainSeconds(BYTE t)const{return t<PREMIUM_MAX_NUM?premium[t]-now:0;}
|
||||
void PortSetPremiumTime(BYTE t,int v){if(t<PREMIUM_MAX_NUM)premium[t]=v;}
|
||||
bool AddAffect(DWORD type,BYTE,long,DWORD,long duration,long,bool override){assert(override);affects[type]=duration;return true;}
|
||||
bool RemoveAffect(DWORD type){return affects.erase(type)>0;}
|
||||
void ChatPacket(BYTE type,const char* f,...){va_list a;va_start(a,f);std::string s=format(f,a);va_end(a);assert(type==CHAT_TYPE_COMMAND);messages.push_back(s);}
|
||||
};
|
||||
using LPCHARACTER=CHARACTER*;
|
||||
static CHARACTER* player=nullptr;
|
||||
struct CHARACTER_MANAGER{static CHARACTER_MANAGER& instance(){static CHARACTER_MANAGER m;return m;}
|
||||
LPCHARACTER FindByPID(DWORD pid){return player && pid==7?player:nullptr;}};
|
||||
static std::vector<std::string> itemlog;
|
||||
struct LogManager{static LogManager& instance(){static LogManager m;return m;}
|
||||
void ItemLog(LPCHARACTER,LPITEM item,const char* how,const char* hint){assert(item->count>0);itemlog.push_back(std::string(how)+" "+std::to_string(item->vnum)+" "+hint);}};
|
||||
#include "port_premium.h"
|
||||
static DBManager& db=DBManager::instance();
|
||||
static const std::string& last(){return player->messages.back();}
|
||||
static void tick(){clockms+=1100;}
|
||||
int main(){
|
||||
const int DAY=86400;
|
||||
accounts[1]=std::vector<int>(7,0);
|
||||
player=new CHARACTER;player->desc.table.id=1;
|
||||
// Fresh account: 7 days from now on all seven columns, one card consumed, icons 500..506 for 7 days.
|
||||
CItem card{38001,2};
|
||||
assert(PortVipUseCard(player,&card) && card.count==1 && itemlog.back()=="MT_VIP_CARD 38001 7");
|
||||
assert(db.queries[0].rfind("UPDATE account.account SET silver_expire=FROM_UNIXTIME(GREATEST(UNIX_TIMESTAMP(silver_expire),UNIX_TIMESTAMP())+604800),gold_expire=",0)==0);
|
||||
assert(db.queries[0].find("money_drop_rate_expire=FROM_UNIXTIME(GREATEST(UNIX_TIMESTAMP(money_drop_rate_expire),UNIX_TIMESTAMP())+604800) WHERE id=1")!=std::string::npos);
|
||||
assert(db.queries[1]=="SELECT UNIX_TIMESTAMP(silver_expire),UNIX_TIMESTAMP(gold_expire),UNIX_TIMESTAMP(safebox_expire),UNIX_TIMESTAMP(autoloot_expire),UNIX_TIMESTAMP(fish_mind_expire),UNIX_TIMESTAMP(marriage_fast_expire),UNIX_TIMESTAMP(money_drop_rate_expire) FROM account.account WHERE id=1");
|
||||
assert(last()=="MTVIP1 added 38001 7" && player->premium[0]==0); // memory waits for the read-back
|
||||
db.Run();
|
||||
assert(last()=="MTVIP1 times 604800 604800 604800 604800 604800 604800 604800");
|
||||
for(int i=0;i<7;++i)assert(player->premium[i]==now+7*DAY && player->affects[500+i]==7*DAY && accounts[1][i]==now+7*DAY);
|
||||
assert(!player->affects.count(507) && player->premium[7]==0);
|
||||
// A second card inside the gap is refused and kept; after it, 30 days add to the current end.
|
||||
CItem month{38002,1};
|
||||
assert(PortVipUseCard(player,&month) && last()=="MTVIP1 error rate" && month.count==1);
|
||||
tick();now+=DAY;assert(PortVipUseCard(player,&month) && month.count==0);db.Run();
|
||||
assert(last()=="MTVIP1 times 3110400 3110400 3110400 3110400 3110400 3110400 3110400" && player->premium[3]==now-DAY+37*DAY);
|
||||
// Past the 400-day cap: refused before anything is consumed or queried.
|
||||
const size_t queries=db.queries.size();CItem many{38002,20};
|
||||
for(int k=0;k<13;++k){tick();assert(PortVipUseCard(player,&many));db.Run();} // 36 days left: 12 cards reach 396
|
||||
assert(last()=="MTVIP1 error full" && many.count==8 && db.queries.size()==queries+24);
|
||||
// Not a card: untouched, nothing queried.
|
||||
CItem other{27001,5};assert(!PortVipUseCard(player,&other) && other.count==5 && db.queries.size()==queries+24);
|
||||
// Enter-game on another core: the db core still has the login-time ends (here, none); the refresh restores them.
|
||||
tick();const auto stale=player->messages.size();
|
||||
for(int i=0;i<PREMIUM_MAX_NUM;++i)player->premium[i]=0;player->affects.clear();
|
||||
PortVipRefresh(player,false);db.Run();
|
||||
assert(player->messages.size()==stale && player->premium[6]==accounts[1][6] && player->affects[506]==accounts[1][6]-now);
|
||||
// Expired in the account (edited by hand): state and icon go away; unchanged types keep their icon untouched.
|
||||
accounts[1][2]=now-5;player->affects[502]=1;player->affects[503]=12345;
|
||||
PortVipRefresh(player,false);db.Run();
|
||||
assert(player->GetPremiumRemainSeconds(2)<0 && !player->affects.count(502) && player->affects[503]==12345);
|
||||
// Status command: version, validation, throttle, report of remaining seconds (0 when expired).
|
||||
tick();PortVipCommand(player,"1 status");db.Run();assert(last().rfind("MTVIP1 times ",0)==0 && last().find(" 0 ")!=std::string::npos);
|
||||
PortVipCommand(player,"1 status");assert(last()=="MTVIP1 error rate");
|
||||
for(auto bad:{"1 stats","1","1 status x"}){tick();PortVipCommand(player,bad);assert(last()=="MTVIP1 error invalid");}
|
||||
const auto quiet=player->messages.size();tick();PortVipCommand(player,"2 status");PortVipCommand(player,"1 status x y z");
|
||||
assert(player->messages.size()==quiet);
|
||||
// The player left before the read-back: nothing is touched.
|
||||
tick();PortVipCommand(player,"1 status");CHARACTER* gone=player;player=nullptr;db.Run();assert(gone->messages.size()==quiet);
|
||||
// Missing account row: logged, no state change.
|
||||
player=gone;player->desc.table.id=99;tick();PortVipRefresh(player,true);db.Run();assert(logs.back()=="ERR PORT_VIP: account 99 not found");
|
||||
puts("PASS: card use and read-back, stacking, gap, cap, other items, enter-game refresh, expiry, status command");
|
||||
}
|
||||
'''
|
||||
with tempfile.TemporaryDirectory(prefix='mt-vip-') as folder:
|
||||
path=Path(folder);(path/'test.cpp').write_text(code)
|
||||
subprocess.run(['c++','-std=c++17','-Wall','-I'+str(SRC),str(path/'test.cpp'),'-o',str(path/'test')],check=True)
|
||||
subprocess.run([str(path/'test')],check=True)
|
||||
Reference in New Issue
Block a user