diff --git a/docs/FEATURE-BATTLEPASS.md b/docs/FEATURE-BATTLEPASS.md new file mode 100644 index 00000000..7d77cfb0 --- /dev/null +++ b/docs/FEATURE-BATTLEPASS.md @@ -0,0 +1,111 @@ +# PORT battle pass + +A monthly mission pass, ported from AVA2's `ENABLE_BATTLE_PASS` (the window behind `uibattlepassex.py`). A season is a time window with up to ten missions. Each mission has its own reward, and a final reward unlocks once every mission is done. The pass is free for every player; AVA2 sold a ticket item (25150–25161), and this port has none. + +Source: +- `src/server/game/src/port_battlepass.h`: config, per-player state and bag fit; standard C++ only. +- `port_battlepass_runtime.h`: game side, included only by cmd_general.cpp. +- `port_battlepass_hooks.h`: hook declarations for the other files. + +Tables: `tools/battlepass/schema.sql`. Season file: `tools/battlepass/port_battlepass.tsv`. Test: `tests/features/test_battlepass.py`. + +## Season file + +The file is `/port_battlepass.tsv`, for example `share/locale/newcibn/port_battlepass.tsv`. Every core checks it at most once every 5 s and reloads it when its mtime, size or inode changes, the same rule the event calendar uses. Replace it atomically with a temporary file and `mv`. + +``` +MTBATTLEPASS 1 +season ID START END unix seconds, [START, END) +mission SLOT TYPE SUB TARGET [VNUM COUNT]x0..3 +final VNUM COUNT [VNUM COUNT]x0..5 +``` + +- Any error disables the whole file; the game logs `PORT_BP: port_battlepass.tsv disabled: line N: why`. Errors include: + - a bad number or a duplicate slot; + - overlapping seasons; + - a season without missions; + - a sub on a type that takes none. +- Slot numbers are 1..10. A season ID must never be reused: progress and claims are stored per season ID. +- A reward must be a bag item: + - not a dragon soul stone; + - size 1..3; + - at most 24 stacks per claim. + + A bad reward is caught when someone claims it: the answer is `config`, `sys_err` logs it, and the slot stays claimable after the file is fixed. + +| Type | Counts | SUB | +|---|---|---| +| 1 | monster kills (not boss, not stone) | mob vnum or 0 | +| 2 | boss kills (rank ≥ boss) | mob vnum or 0 | +| 3 | metin stone kills | stone vnum or 0 | +| 4 | seconds online | 0 | +| 5 | fish caught | item vnum or 0 | +| 6 | successful refines | resulting item vnum or 0 | +| 7 | levels gained | 0 | +| 8 | gold paid to NPC shops | 0 | +| 9 | items sold to NPC shops | item vnum (required) | + +A kill counts for the player that `CHARACTER::Reward` gives the quest kill event to, which is the `DistributeExp` attacker. As in AVA2, it counts only when the monster is within 20 levels of the player. A party member who is not that attacker gets nothing. Type 9 needs a vnum because selling any item could be farmed with cheap shop items. + +The shipped file has seasons 202610–202612, starting at local midnight on the first of each month (Europe/Berlin, the server's zone). Each has: +- eight missions, rewards taken from 40250 items; +- a final reward of the three pearls and 70024. + +The targets follow the scale of AVA2's month 10 (`player.battle_pass`). + +## Storage + +``` +player.mt_battlepass_progress (pid, season, slot, value, target) PRIMARY KEY (pid, season, slot) +player.mt_battlepass_claim (pid, season, slot, claimed_at) PRIMARY KEY (pid, season, slot); slot 0 = final +``` + +**Counting.** Events are counted in memory, as the delta per slot. `CHARACTER::SaveReal`, which covers the periodic save, logout and warp, adds play time, then queues one upsert on the game's ordered SQL connection: + +`value = LEAST(value + delta, target)` + +Because the write adds, a core does not need to have read the row first. Two cores that both see the player during a warp add their own deltas, with no overwrite. + +**Loading.** At the first event or `/mt_bp`, a `FuncQuery` reads the stored values and claims. Flushes queued after that read are added on top. A generation number drops the answers of a session that has already ended. + +**Season change.** The counts of the old season are written while that season is still in the file. The new season then loads its own rows. + +**Claims.** A claim checks four things before writing anything: +1. the state is loaded; +2. the mission is complete; +3. the slot is not claimed yet; +4. all the stacks fit in the bag. The fit is first-fit in `GetEmptyInventory` order, and a size-2 or size-3 item stays inside one 45-cell page. + +Only then does it run `INSERT IGNORE` into the claim table synchronously. Only the request whose insert affected a row creates the items, into the cells checked before. A double click, a retry or another core finds the row already there and gets `claimed`. Each item gets an `MT_BP_CLAIM` item log with the hint `SEASON SLOT`, and the character is saved right away. + +Known limits: +- If the core crashes between the claim row and the item save, that reward is lost. The claim row and the item log are there for a GM to compensate. +- While a warp is in flight, the window can show slightly less progress than is stored. Nothing is lost or counted twice. + +## Protocol + +``` +/mt_bp 1 info | 1 claim SLOT | 1 close +MTBP1 season ID START END NOW COUNT +MTBP1 mission SLOT TYPE SUB TARGET VALUE CLAIMED [VNUM COUNT]... +MTBP1 final CLAIMED ALLDONE [VNUM COUNT]... +MTBP1 end +MTBP1 none no season running (or no valid file) +MTBP1 progress SLOT VALUE pushed while the window is open +MTBP1 done SLOT a mission was finished (always sent) +MTBP1 claimed SLOT the reward is in the bag; a full info follows +MTBP1 error loading|slot|claimed|incomplete|space|config|db|rate|invalid +``` + +- `info` before the load is answered as soon as the load arrives. +- A `done` for a mission that an event finished before the load is sent when the load arrives. +- `info` and `claim` share a 300 ms gap per player (`rate`). +- A wrong version, more than three tokens, or a token longer than 10 characters gets no answer. + +## Setup + +1. Apply `tools/battlepass/schema.sql` once. +2. Copy `port_battlepass.tsv` to the locale base directory. +3. Restart the cores with the new binary. + +Without the file, every `/mt_bp` answers `none` and nothing is counted or written. diff --git a/src/server/game/src/char.cpp b/src/server/game/src/char.cpp index 1e556ed3..0191d403 100755 --- a/src/server/game/src/char.cpp +++ b/src/server/game/src/char.cpp @@ -57,6 +57,7 @@ // #include "HackShield.h" #include "skill_power.h" #include "buff_on_attributes.h" +#include "port_battlepass_hooks.h" #ifdef __PET_SYSTEM__ #include "PetSystem.h" @@ -1304,6 +1305,8 @@ void CHARACTER::SaveReal() marriage::TMarriage* pMarriage = marriage::CManager::instance().Get(GetPlayerID()); if (pMarriage) pMarriage->Save(); + + PortBpSave(this); // PORT: battle pass progress } void CHARACTER::FlushDelayedSaveItem() @@ -1393,6 +1396,7 @@ void CHARACTER::Disconnect(const char * c_pszReason) SaveAffect(); m_bIsLoadedAffect = false; + PortBpLogout(this); // PORT: battle pass, after the last save m_bSkipSave = true; // ÀÌ ÀÌÈÄ¿¡´Â ´õÀÌ»ó ÀúÀåÇÏ¸é ¾ÈµÈ´Ù. @@ -3063,6 +3067,8 @@ void CHARACTER::PointChange(BYTE type, int amount, bool bAmount, bool bBroadcast if (amount) { + if (amount > 0) + PortBpCount(this, PORT_BP_LEVEL_UP, 0, amount); // PORT: battle pass quest::CQuestManager::instance().LevelUp(GetPlayerID()); LogManager::instance().LevelLog(this, val, GetRealPoint(POINT_PLAYTIME) + (get_dword_time() - m_dwPlayStartTime) / 60000); diff --git a/src/server/game/src/char_battle.cpp b/src/server/game/src/char_battle.cpp index f78a9dcc..b7d841a9 100755 --- a/src/server/game/src/char_battle.cpp +++ b/src/server/game/src/char_battle.cpp @@ -40,6 +40,7 @@ #include "BlueDragon.h" #include "DragonLair.h" #include +#include "port_battlepass_hooks.h" #include DWORD AdjustExpByLevel(const LPCHARACTER ch, const DWORD exp) { @@ -785,6 +786,8 @@ void CHARACTER::Reward(bool bItemDrop) pkAttacker->UpdateAlignment(2); pkAttacker->SetQuestNPCID(GetVID()); + // PORT: battle pass kill, credited like the quest kill below (port_battlepass_runtime.h). + PortBpKill(pkAttacker, this); quest::CQuestManager::instance().Kill(pkAttacker->GetPlayerID(), GetRaceNum()); CHARACTER_MANAGER::instance().KillLog(GetRaceNum()); diff --git a/src/server/game/src/char_item.cpp b/src/server/game/src/char_item.cpp index c0784c58..1dfbe9c0 100755 --- a/src/server/game/src/char_item.cpp +++ b/src/server/game/src/char_item.cpp @@ -51,6 +51,7 @@ #include "auction_manager.h" #endif #include "port_premium.h" +#include "port_battlepass_hooks.h" const int ITEM_BROKEN_METIN_VNUM = 28960; // CHANGE_ITEM_ATTRIBUTES @@ -924,6 +925,7 @@ bool CHARACTER::DoRefine(LPITEM item, bool bMoneyOnly) { ITEM_MANAGER::CopyAllAttrTo(item, pkNewItem); LogManager::instance().ItemLog(this, pkNewItem, "REFINE SUCCESS", pkNewItem->GetName()); + PortBpCount(this, PORT_BP_REFINE, pkNewItem->GetVnum(), 1); // PORT: battle pass WORD bCell = item->GetCell(); @@ -1197,6 +1199,7 @@ bool CHARACTER::DoRefineWithScroll(LPITEM item) { ITEM_MANAGER::CopyAllAttrTo(item, pkNewItem); LogManager::instance().ItemLog(this, pkNewItem, "REFINE SUCCESS", pkNewItem->GetName()); + PortBpCount(this, PORT_BP_REFINE, pkNewItem->GetVnum(), 1); // PORT: battle pass WORD bCell = item->GetCell(); diff --git a/src/server/game/src/cmd.cpp b/src/server/game/src/cmd.cpp index bd9ccf4b..99c4fad1 100755 --- a/src/server/game/src/cmd.cpp +++ b/src/server/game/src/cmd.cpp @@ -14,6 +14,7 @@ ACMD(do_port_switchbot); ACMD(do_port_pickup); ACMD(do_port_chest); ACMD(do_port_vip); +ACMD(do_port_bp); ACMD(do_user_horse_ride); ACMD(do_user_horse_back); ACMD(do_user_horse_feed); @@ -607,6 +608,7 @@ struct command_info cmd_info[] = { "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 }, + { "mt_bp", do_port_bp, 0, POS_DEAD, GM_PLAYER }, { "\n", NULL, 0, POS_DEAD, GM_IMPLEMENTOR } /* ¹Ýµå½Ã ÀÌ °ÍÀÌ ¸¶Áö¸·À̾î¾ß ÇÑ´Ù. */ }; diff --git a/src/server/game/src/cmd_general.cpp b/src/server/game/src/cmd_general.cpp index 913cf8f8..9dbb8016 100755 --- a/src/server/game/src/cmd_general.cpp +++ b/src/server/game/src/cmd_general.cpp @@ -47,6 +47,7 @@ #include "port_pickup.h" #include "port_chest.h" #include "port_premium.h" +#include "port_battlepass_runtime.h" ACMD(do_port_vip) { @@ -55,6 +56,14 @@ ACMD(do_port_vip) PortVipCommand(ch, argument); } +// PORT: battle pass (port_battlepass_runtime.h) +ACMD(do_port_bp) +{ + if (!ch || !ch->IsPC() || !ch->GetDesc()) + return; + PortBpCommand(ch, argument); +} + extern int g_server_id; extern int g_nPortalLimitTime; diff --git a/src/server/game/src/fishing.cpp b/src/server/game/src/fishing.cpp index 20b2a216..f9e5c290 100755 --- a/src/server/game/src/fishing.cpp +++ b/src/server/game/src/fishing.cpp @@ -23,6 +23,7 @@ #include "affect.h" #include "unique_item.h" +#include "port_battlepass_hooks.h" #endif namespace fishing @@ -634,6 +635,7 @@ void Take(fishing_event_info* info, LPCHARACTER ch) if (item_vnum) { FishingSuccess(ch); + PortBpCount(ch, PORT_BP_CATCH_FISH, item_vnum, 1); // PORT: battle pass TPacketGCFishing p; p.header = HEADER_GC_FISHING; diff --git a/src/server/game/src/port_battlepass.h b/src/server/game/src/port_battlepass.h new file mode 100644 index 00000000..0807d3b9 --- /dev/null +++ b/src/server/game/src/port_battlepass.h @@ -0,0 +1,226 @@ +#ifndef PORT_BATTLEPASS_H +#define PORT_BATTLEPASS_H +// PORT: battle pass, from AVA2's ENABLE_BATTLE_PASS (the monthly mission pass behind uibattlepassex.py). A season +// is a time window from port_battlepass.tsv with up to ten missions, each with its own reward, and a final reward +// once every mission is done. Only real server events count: kills, fishing, refines, level ups, NPC shop trades +// and play time; the client only asks and claims. Progress and claims live in player.mt_battlepass_progress and +// player.mt_battlepass_claim (unique per player, season and slot). Design: docs/FEATURE-BATTLEPASS.md. +// This header holds the game-independent part: the config, the per-player state and the bag fit. +#include +#include +#include +#include +#include +#include +#include +#include +#include + +enum PortBpType { + PORT_BP_NONE, + PORT_BP_KILL_MONSTER, // sub: mob vnum, 0 = any normal monster (not a boss or a stone) + PORT_BP_KILL_BOSS, // sub: mob vnum, 0 = any boss + PORT_BP_KILL_STONE, // sub: stone vnum, 0 = any metin stone + PORT_BP_PLAYTIME, // seconds online + PORT_BP_CATCH_FISH, // sub: caught item vnum, 0 = any + PORT_BP_REFINE, // successful refines; sub: resulting item vnum, 0 = any + PORT_BP_LEVEL_UP, // levels gained + PORT_BP_NPC_SPEND, // gold paid to NPC shops + PORT_BP_NPC_SELL, // items sold to NPC shops; sub (required): item vnum + PORT_BP_TYPE_MAX +}; +static const unsigned kPortBpSlots=10; // mission slots 1..10; slot 0 is the final reward +static const unsigned kPortBpMissionRewards=3; // AVA2 BATTLE_SUB_REWARD +static const unsigned kPortBpFinalRewards=6; // AVA2 BATTLE_REWARD_MAX +static const unsigned long long kPortBpMaxTarget=1000000000000ULL; +static const unsigned kPortBpMaxRewardCount=10000; + +struct PortBpReward {unsigned vnum,count;}; +struct PortBpMission { + unsigned slot,type,sub;unsigned long long target;std::vector rewards; + bool Matches(unsigned kind,unsigned what)const{return type==kind && (!sub || sub==what);} +}; +struct PortBpSeason { + unsigned id,start,end;std::vector missions;std::vector final; + const PortBpMission* Slot(unsigned slot)const { + for(const auto& m:missions)if(m.slot==slot)return &m; + return nullptr; + } + bool Has(unsigned kind)const { + for(const auto& m:missions)if(m.type==kind)return true; + return false; + } +}; + +// Whole-file config: any error disables the battle pass rather than running half a season. +class PortBpConfig { +public: + std::vector seasons; + bool valid=false; + std::string error; + bool Parse(std::istream& input) { + std::vector next;std::string line;unsigned bytes=0,number=0;bool header=false; + error.clear(); + auto fail=[&](const char* why){error="line "+std::to_string(number)+": "+why;return false;}; + auto run=[&]()->bool { + while(std::getline(input,line)) { + ++number;bytes+=unsigned(line.size()+1); + if(bytes>65536)return fail("file too large"); + if(!line.empty() && line.back()=='\r')line.pop_back(); + if(line.empty() || line[0]=='#')continue; + if(!header){if(line!="MTBATTLEPASS 1")return fail("header");header=true;continue;} + std::istringstream row(line);std::string word,token;std::vector v; + row>>word; + while(row>>token) { + unsigned long long value=0; + if(token.size()>13)return fail("number too long"); + for(char c:token){if(c<'0'||c>'9')return fail("not a number");value=value*10+unsigned(c-'0');} + v.push_back(value); + } + if(word=="season") { + if(v.size()!=3 || !v[0] || v[0]>0xffffffffULL || v[1]>=v[2] || v[2]>0xffffffffULL)return fail("season ID START END"); + if(next.size()>=64)return fail("too many seasons"); + for(const auto& s:next)if(s.id==v[0])return fail("duplicate season id"); + next.push_back(PortBpSeason{unsigned(v[0]),unsigned(v[1]),unsigned(v[2]),{},{}}); + continue; + } + if(next.empty())return fail("mission or final before season"); + PortBpSeason& season=next.back(); + std::vector rewards; + auto pairs=[&](size_t from,unsigned most)->bool { + if((v.size()-from)%2 || (v.size()-from)/2>most)return false; + for(size_t i=from;i0xffffffffULL || !v[i+1] || v[i+1]>kPortBpMaxRewardCount)return false; + rewards.push_back(PortBpReward{unsigned(v[i]),unsigned(v[i+1])}); + } + return true; + }; + if(word=="mission") { + if(v.size()<4 || !pairs(4,kPortBpMissionRewards))return fail("mission SLOT TYPE SUB TARGET [VNUM COUNT]x0..3"); + if(!v[0] || v[0]>kPortBpSlots || season.Slot(unsigned(v[0])))return fail("slot 1..10, once per season"); + if(!v[1] || v[1]>=PORT_BP_TYPE_MAX)return fail("type"); + if(v[2]>0xffffffffULL)return fail("sub"); + const unsigned type=unsigned(v[1]); + const bool subAllowed=type!=PORT_BP_PLAYTIME && type!=PORT_BP_LEVEL_UP && type!=PORT_BP_NPC_SPEND; + if(v[2] && !subAllowed)return fail("this type takes sub 0"); + if(!v[2] && type==PORT_BP_NPC_SELL)return fail("NPC sell needs an item vnum"); + if(!v[3] || v[3]>kPortBpMaxTarget)return fail("target"); + season.missions.push_back(PortBpMission{unsigned(v[0]),type,unsigned(v[2]),v[3],rewards}); + continue; + } + if(word=="final") { + if(!season.final.empty() || !pairs(0,kPortBpFinalRewards) || rewards.empty())return fail("final VNUM COUNT x1..6, once per season"); + season.final=rewards; + continue; + } + return fail("unknown line"); + } + if(input.bad())return fail("read error"); + if(!header)return fail("header"); + if(next.empty())return fail("no season"); + std::sort(next.begin(),next.end(),[](const PortBpSeason& a,const PortBpSeason& b){return a.start=s.start && now65536 || size<0){valid=false;seasons.clear();error="file too large";return true;} + std::ifstream file(path);Parse(file); + return true; + } +private: + bool checked=false,loaded=false;unsigned lastCheck=0;time_t modified=0;off_t size=0;ino_t inode=0; +}; + +// One player's view of the active season. base is what the database held when the load was queued, plus every +// flush queued after it; delta is counted here and not flushed yet. Flushes add, so a missed load never loses +// progress and the stored value is capped at the target by the database itself. +struct PortBpState { + unsigned season=0,generation=0; + bool loaded=false,watching=false,wantInfo=false; + unsigned long long base[kPortBpSlots+1]={},delta[kPortBpSlots+1]={},inflight[kPortBpSlots+1]={}; + std::set claimed; // slots; 0 = final + unsigned playtimeMark=0; // get_dword_time() up to which play time has been counted + unsigned lastCommand=0; + unsigned long long Value(const PortBpMission& m)const {return std::min(m.target,base[m.slot]+delta[m.slot]);} + bool Done(const PortBpMission& m)const {return base[m.slot]+delta[m.slot]>=m.target;} + bool AllDone(const PortBpSeason& s)const { + for(const auto& m:s.missions)if(!Done(m))return false; + return true; + } + void Reset(unsigned id) { + season=id;loaded=false;wantInfo=false;claimed.clear(); + std::fill(base,base+kPortBpSlots+1,0ULL);std::fill(delta,delta+kPortBpSlots+1,0ULL);std::fill(inflight,inflight+kPortBpSlots+1,0ULL); + } +}; + +// Adds amount to every unfinished mission of this kind; returns the slots that changed and those it finished. +inline void PortBpAdd(const PortBpSeason& season,PortBpState& state,unsigned kind,unsigned what,unsigned long long amount, + std::vector& changed,std::vector& finished) { + if(!amount)return; + for(const auto& m:season.missions) { + if(!m.Matches(kind,what) || state.Done(m))continue; + const unsigned long long left=m.target-(state.base[m.slot]+state.delta[m.slot]); + state.delta[m.slot]+=std::min(left,amount); + changed.push_back(m.slot); + if(state.Done(m))finished.push_back(m.slot); + } +} + +// Why a claim of slot (0 = final) cannot go ahead, or nullptr. +inline const char* PortBpClaimError(const PortBpSeason& season,const PortBpState& state,unsigned slot) { + if(!state.loaded)return "loading"; + if(slot>kPortBpSlots)return "slot"; + if(slot) { + const PortBpMission* m=season.Slot(slot); + if(!m)return "slot"; + if(state.claimed.count(slot))return "claimed"; + if(!state.Done(*m))return "incomplete"; + if(m->rewards.empty())return "slot"; + } else { + if(season.final.empty())return "slot"; + if(state.claimed.count(0))return "claimed"; + if(!state.AllDone(season))return "incomplete"; + } + return nullptr; +} + +// First-fit placement of item sizes into a bag of pages, the order CHARACTER::GetEmptyInventory searches: an item +// of size s at cell c takes c, c+width, ... c+width*(s-1), all in c's page. free is updated with the cells taken. +inline bool PortBpFit(std::vector& free,unsigned page,unsigned width,const std::vector& sizes,std::vector& cells) { + cells.clear(); + for(unsigned size:sizes) { + bool placed=false; + for(unsigned c=0;c=page)continue; + bool ok=true; + for(unsigned k=0;k +#include +#include +#include +#include +#include "port_battlepass_hooks.h" + +static const unsigned kPortBpGapMs=300; // per-player gap between /mt_bp commands +static const unsigned kPortBpMaxStacks=24; // reward items one claim may put in the bag +static const int kPortBpKillLevelDelta=20; // AVA2: kills count only within 20 levels of the monster + +inline PortBpConfig& PortBpConfigFile() {static PortBpConfig config;return config;} +inline const PortBpSeason* PortBpSeasonNow() { + PortBpConfig& config=PortBpConfigFile(); + if(config.Refresh(LocaleService_GetBasePath()+"/port_battlepass.tsv",get_dword_time()) && !config.valid && config.error!="missing") + sys_err("PORT_BP: port_battlepass.tsv disabled: %s",config.error.c_str()); + return config.Active(get_global_time()); +} +inline std::map& PortBpStates() {static std::map states;return states;} + +inline void PortBpSendRewards(std::string& line,const std::vector& rewards) { + for(const auto& r:rewards)line+=" "+std::to_string(r.vnum)+" "+std::to_string(r.count); +} + +inline void PortBpSendInfo(LPCHARACTER ch,const PortBpSeason& season,PortBpState& state) { + state.watching=true;state.wantInfo=false; + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 season %u %u %u %lld %u",season.id,season.start,season.end,(long long)get_global_time(),unsigned(season.missions.size())); + for(const auto& m:season.missions) { + std::string line="MTBP1 mission "+std::to_string(m.slot)+" "+std::to_string(m.type)+" "+std::to_string(m.sub)+" "+ + std::to_string(m.target)+" "+std::to_string(state.Value(m))+" "+std::to_string(state.claimed.count(m.slot)); + PortBpSendRewards(line,m.rewards); + ch->ChatPacket(CHAT_TYPE_COMMAND,"%s",line.c_str()); + } + std::string line="MTBP1 final "+std::to_string(state.claimed.count(0))+" "+std::to_string(int(state.AllDone(season))); + PortBpSendRewards(line,season.final); + ch->ChatPacket(CHAT_TYPE_COMMAND,"%s",line.c_str()); + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 end"); +} + +// Queues the deltas as one additive, capped upsert on the game's ordered SQL connection. +inline void PortBpFlush(DWORD pid,PortBpState& state,const PortBpSeason* season) { + if(!state.season || !season || season->id!=state.season)return; + std::string values; + for(const auto& m:season->missions) { + const unsigned long long d=state.delta[m.slot]; + if(!d)continue; + values+=std::string(values.empty()?"":",")+"("+std::to_string(pid)+","+std::to_string(state.season)+","+std::to_string(m.slot)+","+ + std::to_string(std::min(d,m.target))+","+std::to_string(m.target)+")"; + state.base[m.slot]+=d;state.delta[m.slot]=0; + if(!state.loaded)state.inflight[m.slot]+=d; + } + if(values.empty())return; + DBManager::instance().Query("INSERT INTO player.mt_battlepass_progress (pid,season,slot,value,target) VALUES %s " + "ON DUPLICATE KEY UPDATE value=LEAST(value+VALUES(value),VALUES(target)),target=VALUES(target)",values.c_str()); +} + +inline void PortBpLoad(DWORD pid,PortBpState& state) { + static unsigned generations=0; + state.generation=++generations; + std::fill(state.inflight,state.inflight+kPortBpSlots+1,0ULL); + const unsigned season=state.season,generation=state.generation; + DBManager::instance().FuncQuery([pid,season,generation](SQLMsg* msg) { + auto it=PortBpStates().find(pid); + if(it==PortBpStates().end() || it->second.generation!=generation || it->second.season!=season)return; + PortBpState& state=it->second; + if(!msg->Get()){sys_err("PORT_BP: load failed pid %u season %u",pid,season);return;} + unsigned long long stored[kPortBpSlots+1]={}; + for(unsigned i=0;iGet()->uiNumRows;++i) { + MYSQL_ROW row=mysql_fetch_row(msg->Get()->pSQLResult); + if(!row || !row[0] || !row[1] || !row[2])continue; + const unsigned slot=unsigned(strtoul(row[1],nullptr,10)); + if(slot>kPortBpSlots)continue; + if(row[0][0]=='p')state.base[slot]=(stored[slot]=strtoull(row[2],nullptr,10))+state.inflight[slot]; + else state.claimed.insert(slot); + } + state.loaded=true; + LPCHARACTER ch=CHARACTER_MANAGER::instance().FindByPID(pid); + const PortBpSeason* now=PortBpConfigFile().Active(get_global_time()); + if(!ch || !now || now->id!=season)return; + // PortBpNotify held back the done notices of events counted before the load; send those now. + for(const auto& m:now->missions) + if(stored[m.slot]ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 done %u",m.slot); + if(state.wantInfo)PortBpSendInfo(ch,*now,state); + },"SELECT 'p',slot,value FROM player.mt_battlepass_progress WHERE pid=%u AND season=%u " + "UNION ALL SELECT 'c',slot,0 FROM player.mt_battlepass_claim WHERE pid=%u AND season=%u",pid,season,pid,season); +} + +inline const PortBpSeason* PortBpFindSeason(unsigned id) { + for(const auto& s:PortBpConfigFile().seasons)if(s.id==id)return &s; + return nullptr; +} + +// The player's state for the active season, or nullptr when no season runs. A season change first writes what +// was counted for the old season, while its definition is still in the file, then starts a fresh load. +inline PortBpState* PortBpSync(LPCHARACTER ch,const PortBpSeason*& season) { + if(!ch || !ch->IsPC() || !ch->GetDesc())return nullptr; + season=PortBpSeasonNow(); + const DWORD pid=ch->GetPlayerID(); + auto& states=PortBpStates(); + auto it=states.find(pid); + if(!season && it==states.end())return nullptr; + if(it==states.end()) { + it=states.emplace(pid,PortBpState()).first; + it->second.playtimeMark=get_dword_time(); + } + PortBpState& state=it->second; + const unsigned id=season?season->id:0; + if(state.season!=id) { + if(state.season)PortBpFlush(pid,state,PortBpFindSeason(state.season)); + const bool watching=state.watching; + state.Reset(id);state.watching=watching; + state.playtimeMark=get_dword_time(); + if(id)PortBpLoad(pid,state); + } + return season?&state:nullptr; +} + +inline void PortBpNotify(LPCHARACTER ch,const PortBpSeason& season,PortBpState& state,const std::vector& changed,const std::vector& finished) { + if(state.watching) + for(unsigned slot:changed)ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 progress %u %llu",slot,state.Value(*season.Slot(slot))); + if(!state.loaded)return; // values are not known yet; the window shows them once it is loaded + for(unsigned slot:finished)ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 done %u",slot); +} + +inline void PortBpAccruePlaytime(LPCHARACTER ch,const PortBpSeason& season,PortBpState& state) { + const unsigned now=get_dword_time(),seconds=(now-state.playtimeMark)/1000; + if(!seconds)return; + state.playtimeMark+=seconds*1000; + if(!season.Has(PORT_BP_PLAYTIME))return; + std::vector changed,finished; + PortBpAdd(season,state,PORT_BP_PLAYTIME,0,seconds,changed,finished); + PortBpNotify(ch,season,state,changed,finished); +} + +// Every hook calls this with a real event; amount is a count, gold or levels, never scaled by an event rate. +void PortBpCount(LPCHARACTER ch,unsigned kind,unsigned what,unsigned long long amount) { + const PortBpSeason* season=nullptr; + PortBpState* state=PortBpSync(ch,season); + if(!state || !amount || !season->Has(kind))return; + std::vector changed,finished; + PortBpAdd(*season,*state,kind,what,amount,changed,finished); + PortBpNotify(ch,*season,*state,changed,finished); +} + +// CHARACTER::Reward: the attacker DistributeExp picked, the one the quest kill event goes to. +void PortBpKill(LPCHARACTER attacker,LPCHARACTER victim) { + if(!attacker || !victim || !attacker->IsPC() || victim->IsPC())return; + const int gap=int(victim->GetLevel())-int(attacker->GetLevel()); + if(gap>kPortBpKillLevelDelta || gap<-kPortBpKillLevelDelta)return; + const unsigned kind=victim->IsStone()?PORT_BP_KILL_STONE:victim->GetMobRank()>=MOB_RANK_BOSS?PORT_BP_KILL_BOSS:PORT_BP_KILL_MONSTER; + PortBpCount(attacker,kind,victim->GetRaceNum(),1); +} + +// CHARACTER::SaveReal: the periodic and logout save also writes the battle pass. +void PortBpSave(LPCHARACTER ch) { + const PortBpSeason* season=nullptr; + PortBpState* state=PortBpSync(ch,season); + if(!state)return; + PortBpAccruePlaytime(ch,*season,*state); + PortBpFlush(ch->GetPlayerID(),*state,season); +} + +// CHARACTER::Disconnect, after the last save. +void PortBpLogout(LPCHARACTER ch) { + if(ch && ch->IsPC())PortBpStates().erase(ch->GetPlayerID()); +} + +struct PortBpStack {unsigned vnum,count,size;}; +inline const char* PortBpStacks(const std::vector& rewards,std::vector& stacks) { + stacks.clear(); + for(const auto& r:rewards) { + const TItemTable* table=ITEM_MANAGER::instance().GetTable(r.vnum); + if(!table || table->bType==ITEM_DS || !table->bSize || table->bSize>3)return "config"; + const bool stackable=IS_SET(table->dwFlags,ITEM_FLAG_STACKABLE) && !IS_SET(table->dwAntiFlags,ITEM_ANTIFLAG_STACK); + for(unsigned left=r.count;left;) { + const unsigned count=stackable?std::min(left,ITEM_MAX_COUNT):1; + stacks.push_back(PortBpStack{r.vnum,count,table->bSize});left-=count; + if(stacks.size()>kPortBpMaxStacks)return "config"; + } + } + return nullptr; +} + +// /mt_bp 1 claim SLOT. The claim row is written first and synchronously; only the request that inserted it hands +// out the items, into cells checked free beforehand, so retries, double clicks and other cores cannot pay twice. +inline void PortBpClaim(LPCHARACTER ch,const PortBpSeason& season,PortBpState& state,unsigned slot) { + if(const char* error=PortBpClaimError(season,state,slot)){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error %s",error);return;} + const std::vector& rewards=slot?season.Slot(slot)->rewards:season.final; + std::vector stacks; + if(const char* error=PortBpStacks(rewards,stacks)){ + sys_err("PORT_BP: season %u slot %u has a reward that cannot go to the bag",season.id,slot); + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error %s",error);return; + } + std::vector free(INVENTORY_MAX_NUM); + for(unsigned c=0;cIsEmptyItemGrid(TItemPos(INVENTORY,c),1); + std::vector sizes,cells; + for(const auto& s:stacks)sizes.push_back(s.size); + if(!PortBpFit(free,INVENTORY_PAGE_SIZE,5,sizes,cells)){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error space");return;} + const DWORD pid=ch->GetPlayerID(); + std::unique_ptr msg(DBManager::instance().DirectQuery( + "INSERT IGNORE INTO player.mt_battlepass_claim (pid,season,slot,claimed_at) VALUES (%u,%u,%u,%lld)",pid,season.id,slot,(long long)get_global_time())); + if(!msg || !msg->Get()){sys_err("PORT_BP: claim insert failed pid %u season %u slot %u",pid,season.id,slot);ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error db");return;} + state.claimed.insert(slot); + if(msg->Get()->uiAffectedRows!=1){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error claimed");return;} + const std::string hint=std::to_string(season.id)+" "+std::to_string(slot); + for(size_t i=0;iAddToCharacter(ch,TItemPos(INVENTORY,cells[i])); + ITEM_MANAGER::instance().FlushDelayedSave(item); + LogManager::instance().ItemLog(ch,item,"MT_BP_CLAIM",hint.c_str()); + } + sys_log(0,"PORT_BP: %s claimed season %u slot %u (%u stacks)",ch->GetName(),season.id,slot,unsigned(stacks.size())); + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 claimed %u",slot); + ch->Save(); +} + +// /mt_bp 1 info | /mt_bp 1 claim SLOT | /mt_bp 1 close +inline void PortBpCommand(LPCHARACTER ch,const char* argument) { + std::istringstream input(argument);std::vector 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; + const PortBpSeason* season=nullptr; + PortBpState* state=PortBpSync(ch,season); + const bool info=args.size()==2 && args[1]=="info",close=args.size()==2 && args[1]=="close"; + const bool claim=args.size()==3 && args[1]=="claim" && args[2].size()<=2 && args[2].find_first_not_of("0123456789")==std::string::npos; + if(!info && !close && !claim){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error invalid");return;} + if(!state){if(!close)ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 none");return;} + if(close){state->watching=false;return;} + if(state->lastCommand && get_dword_time()-state->lastCommandChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error rate");return;} + state->lastCommand=get_dword_time(); + PortBpAccruePlaytime(ch,*season,*state); + if(info) { + if(state->loaded)PortBpSendInfo(ch,*season,*state); + else {state->wantInfo=true;state->watching=true;} + return; + } + PortBpClaim(ch,*season,*state,unsigned(atoi(args[2].c_str()))); + if(state->loaded)PortBpSendInfo(ch,*season,*state); +} +#endif diff --git a/src/server/game/src/shop.cpp b/src/server/game/src/shop.cpp index f3694e05..981f9668 100755 --- a/src/server/game/src/shop.cpp +++ b/src/server/game/src/shop.cpp @@ -19,6 +19,7 @@ #include "mob_manager.h" #include "locale_service.h" #include "unique_item.h" +#include "port_battlepass_hooks.h" // MT: the sockets ITEM_MANAGER::CreateItem gives a new item of this vnum (its remaining time), sent // with an NPC shop's items so the client tooltip shows how long a bought one lasts instead of 0. @@ -341,6 +342,8 @@ int CShop::Buy(LPCHARACTER ch, BYTE pos) } ch->PointChange(POINT_GOLD, -dwPrice, false); + if (!m_pkPC) + PortBpCount(ch, PORT_BP_NPC_SPEND, 0, dwPrice); // PORT: battle pass, NPC shops only //¼¼±Ý °è»ê DWORD dwTax = 0; diff --git a/src/server/game/src/shop_manager.cpp b/src/server/game/src/shop_manager.cpp index 37d623f6..4c7aeee8 100755 --- a/src/server/game/src/shop_manager.cpp +++ b/src/server/game/src/shop_manager.cpp @@ -25,6 +25,7 @@ #include #include "shop_manager.h" #include +#include "port_battlepass_hooks.h" CShopManager::CShopManager() { @@ -347,6 +348,7 @@ void CShopManager::Sell(LPCHARACTER ch, BYTE bCell, BYTE bCount) ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("ÆÇ¸Å±Ý¾×ÀÇ %d %% °¡ ¼¼±ÝÀ¸·Î ³ª°¡°ÔµË´Ï´Ù"), iVal); DBManager::instance().SendMoneyLog(MONEY_LOG_SHOP, item->GetVnum(), dwPrice); + PortBpCount(ch, PORT_BP_NPC_SELL, item->GetVnum(), bCount); // PORT: battle pass if (bCount == item->GetCount()) { diff --git a/tests/features/test_battlepass.py b/tests/features/test_battlepass.py new file mode 100644 index 00000000..529ce18d --- /dev/null +++ b/tests/features/test_battlepass.py @@ -0,0 +1,272 @@ +#!/usr/bin/env python3 +"""Battle pass: the wiring of the hooks, then the production headers compiled against stubs of the characters, +the bag, the item table and an in-memory player database (ordered async queue plus synchronous direct queries).""" +from pathlib import Path +import subprocess +import tempfile +ROOT=Path(__file__).resolve().parents[2] +SRC=ROOT/'src/server/game/src' +TSV=ROOT/'tools/battlepass/port_battlepass.tsv' +def source(name):return (SRC/name).read_bytes().decode('latin1') +cmd=source('cmd.cpp') +assert 'ACMD(do_port_bp);' in cmd +entry=cmd.index('{ "mt_bp", do_port_bp, 0, POS_DEAD, GM_PLAYER },') +assert entryGetPlayerID(), GetRaceNum());',reward) +assert battle.count('PortBpKill(')==1 +item=source('char_item.cpp') +assert item.count('PortBpCount(this, PORT_BP_REFINE, pkNewItem->GetVnum(), 1);')==2==item.count('"REFINE SUCCESS"') +assert '#endif\n#include "port_premium.h"\n#include "port_battlepass_hooks.h"\n' in item # outside __AUCTION__ +fishing=source('fishing.cpp') +assert fishing.index('FishingSuccess(ch);\n\t\t\t\t\tPortBpCount(ch, PORT_BP_CATCH_FISH, item_vnum, 1);')>fishing.index('void Take(') +shop=source('shop.cpp') +assert 'ch->PointChange(POINT_GOLD, -dwPrice, false);\n\tif (!m_pkPC)\n\t\tPortBpCount(ch, PORT_BP_NPC_SPEND, 0, dwPrice);' in shop +sell=source('shop_manager.cpp') +assert sell.index('void CShopManager::Sell(')GetVnum(), bCount);') +char=source('char.cpp') +save=char.index('void CHARACTER::SaveReal()') +assert save +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using DWORD=unsigned;using BYTE=unsigned char;using WORD=unsigned short; +enum {CHAT_TYPE_INFO=1,CHAT_TYPE_COMMAND=5,MOB_RANK_BOSS=4,ITEM_DS=29,ITEM_FLAG_STACKABLE=1<<2,ITEM_ANTIFLAG_STACK=1<<15, + ITEM_MAX_COUNT=200,INVENTORY=1,INVENTORY_PAGE_SIZE=45,INVENTORY_MAX_NUM=225}; +#define IS_SET(flag,bit) ((flag)&(bit)) +static long long now=1790900000;static DWORD clockms=1000; +long long get_global_time(){return now;}DWORD get_dword_time(){return clockms;} +static std::string basePath;std::string LocaleService_GetBasePath(){return basePath;} +static std::vector logs; +void sys_log(int,const char* f,...){char o[1024];va_list a;va_start(a,f);vsnprintf(o,sizeof(o),f,a);va_end(a);logs.push_back(o);} +void sys_err(const char* f,...){char o[1024];va_list a;va_start(a,f);vsnprintf(o,sizeof(o),f,a);va_end(a);logs.push_back(std::string("ERR ")+o);} +static std::string format(const char* f,va_list a){char o[8192];vsnprintf(o,sizeof(o),f,a);return o;} +struct TItemPos{BYTE window_type;WORD cell;TItemPos(BYTE w,WORD c):window_type(w),cell(c){}}; +struct TItemTable{BYTE bType,bSize;DWORD dwFlags,dwAntiFlags;}; +// --- player database +static std::map,std::pair> progress; // value,target +static std::set> claims; +static bool dbDown=false; +using MYSQL_ROW=char**; +struct Result{std::vector> rows;size_t next=0;std::vector cells;}; +struct SQLResult{unsigned uiNumRows=0,uiAffectedRows=0;Result* pSQLResult=nullptr;}; +struct SQLMsg{SQLResult result;Result data;bool ok=true;SQLResult* Get(){return ok?&result:nullptr;}}; +MYSQL_ROW mysql_fetch_row(Result* r){ + if(r->next>=r->rows.size())return nullptr;auto& row=r->rows[r->next++];r->cells.clear(); + for(auto& c:row)r->cells.push_back(&c[0]);return r->cells.data();} +static int selects=0; +struct DBManager{ + std::deque> queue;std::vector 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]{ + assert(q.rfind("INSERT INTO player.mt_battlepass_progress (pid,season,slot,value,target) VALUES (",0)==0); + assert(q.find("ON DUPLICATE KEY UPDATE value=LEAST(value+VALUES(value),VALUES(target)),target=VALUES(target)")!=std::string::npos); + const char* p=q.c_str()+q.find("VALUES (")+7;unsigned pid,season,slot;unsigned long long v,t;int n; + while(sscanf(p,"(%u,%u,%u,%llu,%llu)%n",&pid,&season,&slot,&v,&t,&n)==5){ + auto& row=progress[std::make_tuple(pid,season,slot)];row.first=std::min(row.first+v,t);row.second=t;p+=n;if(*p==',')++p;else break;} + });} + template 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);++selects; + queue.push_back([f,q]{unsigned pid,season,pid2,season2; + assert(sscanf(q.c_str(),"SELECT 'p',slot,value FROM player.mt_battlepass_progress WHERE pid=%u AND season=%u " + "UNION ALL SELECT 'c',slot,0 FROM player.mt_battlepass_claim WHERE pid=%u AND season=%u",&pid,&season,&pid2,&season2)==4); + assert(pid==pid2 && season==season2); + SQLMsg m;m.ok=!dbDown;m.result.pSQLResult=&m.data; + for(auto& e:progress)if(std::get<0>(e.first)==pid && std::get<1>(e.first)==season) + m.data.rows.push_back({"p",std::to_string(std::get<2>(e.first)),std::to_string(e.second.first)}); + for(auto& e:claims)if(std::get<0>(e)==pid && std::get<1>(e)==season)m.data.rows.push_back({"c",std::to_string(std::get<2>(e)),"0"}); + m.result.uiNumRows=unsigned(m.data.rows.size());f(&m);});} + SQLMsg* DirectQuery(const char* f,...){va_list a;va_start(a,f);std::string q=format(f,a);va_end(a);queries.push_back(q); + SQLMsg* m=new SQLMsg;m->ok=!dbDown;unsigned pid,season,slot;long long at; + assert(sscanf(q.c_str(),"INSERT IGNORE INTO player.mt_battlepass_claim (pid,season,slot,claimed_at) VALUES (%u,%u,%u,%lld)",&pid,&season,&slot,&at)==4 && at==now); + if(m->ok)m->result.uiAffectedRows=claims.insert(std::make_tuple(pid,season,slot)).second?1:0; + return m;} + void Run(){while(!queue.empty()){auto job=queue.front();queue.pop_front();job();}} +}; +// --- characters, bag and items +class CHARACTER; +struct CItem{DWORD vnum,count;CHARACTER* owner=nullptr;unsigned cell=0;bool AddToCharacter(CHARACTER* ch,TItemPos pos);DWORD GetVnum(){return vnum;}}; +using LPITEM=CItem*; +struct DESC{}; +class CHARACTER{public: + DESC desc;bool online=true,pc=true,stone=false;DWORD pid=7,race=101;int level=50;BYTE rank=0;int saves=0; + std::vector messages;std::vector used=std::vector(INVENTORY_MAX_NUM,false);std::vector bag; + const char* GetName(){return "Admin";}bool IsPC(){return pc;}DESC* GetDesc(){return online?&desc:nullptr;}DWORD GetPlayerID(){return pid;} + int GetLevel(){return level;}bool IsStone(){return stone;}BYTE GetMobRank(){return rank;}DWORD GetRaceNum(){return race;} + bool IsEmptyItemGrid(TItemPos p,BYTE size){assert(p.window_type==INVENTORY && size==1);return !used[p.cell];} + void Save(){++saves;} + 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 std::map tables={{70043,{1,1,0,0}},{71153,{3,1,ITEM_FLAG_STACKABLE,0}},{25041,{3,1,ITEM_FLAG_STACKABLE,0}}, + {71032,{3,1,ITEM_FLAG_STACKABLE,0}},{50513,{3,1,ITEM_FLAG_STACKABLE,0}},{27992,{3,1,ITEM_FLAG_STACKABLE,0}},{27993,{3,1,ITEM_FLAG_STACKABLE,0}}, + {27994,{3,1,ITEM_FLAG_STACKABLE,0}},{70024,{3,1,ITEM_FLAG_STACKABLE,0}},{19,{1,2,0,0}},{11299,{2,3,0,0}},{110000,{ITEM_DS,1,0,0}}, + {71084,{3,1,ITEM_FLAG_STACKABLE,ITEM_ANTIFLAG_STACK}},{71094,{3,1,ITEM_FLAG_STACKABLE,0}},{27987,{3,1,ITEM_FLAG_STACKABLE,0}}, + {25040,{3,1,ITEM_FLAG_STACKABLE,0}}}; +bool CItem::AddToCharacter(CHARACTER* ch,TItemPos pos){ + const unsigned size=tables[vnum].bSize; + for(unsigned k=0;kused[pos.cell+5*k]);ch->used[pos.cell+5*k]=true;} + assert(pos.cell/45==(pos.cell+5*(size-1))/45);owner=ch;cell=pos.cell;ch->bag.push_back(this);return true;} +static int flushedItems=0; +struct ITEM_MANAGER{static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;} + TItemTable* GetTable(DWORD v){auto it=tables.find(v);return it==tables.end()?nullptr:&it->second;} + LPITEM CreateItem(DWORD v,DWORD c){return new CItem{v,c};} + void FlushDelayedSave(LPITEM){++flushedItems;}}; +static std::vector itemlog; +struct LogManager{static LogManager& instance(){static LogManager m;return m;} + void ItemLog(LPCHARACTER,LPITEM item,const char* what,const char* hint){itemlog.push_back(std::string(what)+" "+std::to_string(item->vnum)+"x"+std::to_string(item->count)+" "+hint);}}; +static std::map online; +struct CHARACTER_MANAGER{static CHARACTER_MANAGER& instance(){static CHARACTER_MANAGER m;return m;} + LPCHARACTER FindByPID(DWORD pid){auto it=online.find(pid);return it==online.end()?nullptr:it->second;}}; +#include "port_battlepass_runtime.h" +#include +#include + +static DBManager& db=DBManager::instance(); +static void tick(unsigned ms=1000){clockms+=ms;} +static std::string Last(CHARACTER* c){return c->messages.empty()?"":c->messages.back();} +static bool Said(CHARACTER* c,const std::string& line,size_t from=0){for(size_t i=from;imessages.size();++i)if(c->messages[i]==line)return true;return false;} +static void WriteConfig(const std::string& text){std::ofstream(basePath+"/port_battlepass.tsv.tmp")< free(90,true);std::vector cells; + for(unsigned c=0;c<45;++c)if(c<40)free[c]=false; // first page: only its last row (40..44) is free + assert(PortBpFit(free,45,5,{1,3,1},cells) && cells==std::vector({40,45,41})); + std::vector none(45,false);none[44]=true;assert(!PortBpFit(none,45,5,{2},cells));} + + // --- no file: no season + CHARACTER* a=new CHARACTER;online[7]=a; + PortBpCommand(a,"1 info");assert(Last(a)=="MTBP1 none");Kill(a,101);db.Run();assert(progress.empty() && PortBpStates().empty()); + // --- a season running now with small targets + const std::string cfg="MTBATTLEPASS 1\nseason 77 "+std::to_string(now-100)+" "+std::to_string(now+100000)+"\n" + "mission 1 1 0 5 70043 1 71153 450\nmission 2 2 0 2 25041 2\nmission 3 3 0 1 11299 1\nmission 4 4 0 3600 71032 1\n" + "mission 5 1 2493 2 19 3\nmission 6 7 0 2 110000 1\nfinal 27992 2 27993 1 27994 1 70024 1\n" + "season 78 "+std::to_string(now+100000)+" "+std::to_string(now+200000)+"\nmission 1 1 0 5 70043 1\n"; + WriteConfig(cfg); + // info before the load answers once it arrives; counting before the load is kept + PortBpCommand(a,"1 info");assert(a->messages.size()==1 && PortBpStates()[7].wantInfo); + Kill(a,101);Kill(a,101); + db.Run();assert(Said(a,"MTBP1 season 77 "+std::to_string(now-100)+" "+std::to_string(now+100000)+" "+std::to_string(now)+" 6")); + assert(Said(a,"MTBP1 mission 1 1 0 5 2 0 70043 1 71153 450") && Said(a,"MTBP1 final 0 0 27992 2 27993 1 27994 1 70024 1") && Last(a)=="MTBP1 end"); + // kill kinds: normal / boss / stone / level gap / specific vnum / a player victim + size_t mark=a->messages.size(); + Kill(a,101);assert(Last(a)=="MTBP1 progress 1 3"); + Kill(a,691,MOB_RANK_BOSS);assert(Last(a)=="MTBP1 progress 2 1"); + Kill(a,8001,0,true);assert(Said(a,"MTBP1 progress 3 1",mark) && Last(a)=="MTBP1 done 3"); + Kill(a,101,0,false,71);Kill(a,101,0,false,29);assert(PortBpStates()[7].Value(*PortBpConfigFile().seasons[0].Slot(1))==3); + Kill(a,101,0,false,70);assert(Last(a)=="MTBP1 progress 1 4"); + Kill(a,2493,MOB_RANK_BOSS);assert(Said(a,"MTBP1 progress 2 2",mark) && Last(a)=="MTBP1 done 2" && !Said(a,"MTBP1 progress 5 1",mark)); + {CHARACTER pc;pc.pid=8;PortBpKill(a,&pc);CHARACTER mob;mob.pc=false;PortBpKill(&mob,a);} + // a boss of the specific vnum counts for slot 5 only through its own kind: slot 5 is "kill monster 2493" + assert(PortBpStates()[7].Value(*PortBpConfigFile().seasons[0].Slot(5))==0); + // close stops the progress pushes; a finished mission is still announced + PortBpCommand(a,"1 close");mark=a->messages.size();Kill(a,101);assert(Last(a)=="MTBP1 done 1" && a->messages.size()==mark+1); + // 2493 counts for its own slot (any-monster slot 1 is full already) + mark=a->messages.size();Kill(a,2493);Kill(a,2493);Kill(a,2493); + assert(PortBpStates()[7].Value(*PortBpConfigFile().seasons[0].Slot(5))==2 && a->messages.size()==mark+1 && Last(a)=="MTBP1 done 5"); + // --- save writes deltas additively, capped in the database + a->saves=0;PortBpSave(a);db.Run(); + assert(progress[std::make_tuple(7u,77u,1u)].first==5 && progress[std::make_tuple(7u,77u,2u)].first==2 && progress[std::make_tuple(7u,77u,3u)].first==1); + const size_t queries=db.queries.size();PortBpSave(a);db.Run();assert(db.queries.size()==queries); // nothing new, no query + // play time: an hour online + tick(3600*1000);PortBpSave(a);db.Run();assert(progress[std::make_tuple(7u,77u,4u)].first==3600); + // --- claims + tick();PortBpCommand(a,"1 claim 6");assert(Said(a,"MTBP1 error incomplete")); + tick();PortBpCommand(a,"1 claim 1"); + assert(Said(a,"MTBP1 claimed 1") && claims.count(std::make_tuple(7u,77u,1u)) && a->bag.size()==1+3); // 70043 + 200,200,50 + assert(a->bag[1]->vnum==71153 && a->bag[1]->count==200 && a->bag[3]->count==50 && itemlog.back()=="MT_BP_CLAIM 71153x50 77 1" && flushedItems==4); + assert(Said(a,"MTBP1 mission 1 1 0 5 5 1 70043 1 71153 450")); + PortBpCommand(a,"1 claim 1");assert(Last(a)=="MTBP1 error rate"); + tick();PortBpCommand(a,"1 claim 1");assert(Said(a,"MTBP1 error claimed") && a->bag.size()==4); + // another core already paid slot 2: the insert finds the row and nothing is given + claims.insert(std::make_tuple(7u,77u,2u));tick();PortBpCommand(a,"1 claim 2");assert(Said(a,"MTBP1 error claimed") && a->bag.size()==4); + // the database is down: no items + dbDown=true;tick();PortBpCommand(a,"1 claim 3");assert(Said(a,"MTBP1 error db") && a->bag.size()==4);dbDown=false; + claims.erase(std::make_tuple(7u,77u,3u));PortBpStates()[7].claimed.erase(3); + // full bag: the size-3 armor does not fit, no claim row + for(unsigned c=0;cused[c]=true; + tick();PortBpCommand(a,"1 claim 3");assert(Said(a,"MTBP1 error space") && !claims.count(std::make_tuple(7u,77u,3u))); + for(unsigned c=0;c=45)a->used[c]=false; + tick();PortBpCommand(a,"1 claim 3");assert(Said(a,"MTBP1 claimed 3") && a->bag.back()->vnum==11299 && a->bag.back()->cell==45); + // a dragon soul stone in the config is refused at claim time (and logged), the slot stays claimable + {PortBpState& s=PortBpStates()[7];s.delta[6]=2;} + tick();PortBpCommand(a,"1 claim 6");assert(Said(a,"MTBP1 error config") && !claims.count(std::make_tuple(7u,77u,6u))); + assert(logs.back()=="ERR PORT_BP: season 77 slot 6 has a reward that cannot go to the bag"); + // the final reward needs every mission + tick();PortBpCommand(a,"1 claim 0");assert(Said(a,"MTBP1 error incomplete")); + tick();PortBpCommand(a,"1 claim 11");assert(Said(a,"MTBP1 error slot")); + for(auto bad:{"1 claim","1 claim x","1 claim 123","1 open"}){tick();mark=a->messages.size();PortBpCommand(a,bad);assert(a->messages.size()==mark+1 && Last(a)=="MTBP1 error invalid");} + mark=a->messages.size();PortBpCommand(a,"2 info");PortBpCommand(a,"1 a b c");PortBpCommand(a,"1 claim 1 2");PortBpCommand(a,"1 claim 12345678901");assert(a->messages.size()==mark); + {PortBpState& s=PortBpStates()[7];for(unsigned i=1;i<=6;++i)s.delta[i]+=100000;} // everything done + tick();PortBpCommand(a,"1 claim 0");assert(Said(a,"MTBP1 claimed 0") && Said(a,"MTBP1 final 1 1 27992 2 27993 1 27994 1 70024 1")); + // --- logout writes and forgets; a new session loads the claims + PortBpSave(a);PortBpLogout(a);db.Run();assert(!PortBpStates().count(7) && progress[std::make_tuple(7u,77u,6u)].first==2); + assert(progress[std::make_tuple(7u,77u,4u)].first==3600); + tick();mark=a->messages.size();PortBpCommand(a,"1 info");db.Run(); + assert(Said(a,"MTBP1 mission 1 1 0 5 5 1 70043 1 71153 450",mark) && Said(a,"MTBP1 mission 3 3 0 1 1 1 11299 1",mark) && Said(a,"MTBP1 final 1 1 27992 2 27993 1 27994 1 70024 1",mark)); + // --- a flush queued before the load answers is not counted twice + CHARACTER* b=new CHARACTER;b->pid=9;online[9]=b; + progress[std::make_tuple(9u,77u,1u)]={2,5}; + Kill(b,101);PortBpSave(b);Kill(b,101);db.Run(); + assert(progress[std::make_tuple(9u,77u,1u)].first==3 && PortBpStates()[9].Value(*PortBpConfigFile().seasons[0].Slot(1))==4); + // a stale load (logout and back before the answer) is ignored + PortBpLogout(b);Kill(b,101);PortBpLogout(b);Kill(b,101);db.Run(); + assert(PortBpStates()[9].loaded && PortBpStates()[9].Value(*PortBpConfigFile().seasons[0].Slot(1))==4); // 3 stored + 1, the lost delta of the dropped session aside + // a mission finished before the load answers is announced once the load arrives; one already stored done is not + {CHARACTER* c=new CHARACTER;c->pid=10;online[10]=c;progress[std::make_tuple(10u,77u,2u)]={2,2}; + Kill(c,8001,0,true);Kill(c,691,MOB_RANK_BOSS);assert(!Said(c,"MTBP1 done 3") && !Said(c,"MTBP1 done 2")); + db.Run();assert(Said(c,"MTBP1 done 3") && !Said(c,"MTBP1 done 2"));} + // --- season change: the old season's deltas are written, the new one starts from its own rows + Kill(b,101);now+=100000;tick(5001);Kill(b,101);db.Run(); + assert(progress[std::make_tuple(9u,77u,1u)].first==5 && progress.count(std::make_tuple(9u,78u,1u))==0 && PortBpStates()[9].season==78); + PortBpSave(b);db.Run();assert(progress[std::make_tuple(9u,78u,1u)].first==1); + // --- the file is removed: no season, nothing counted + std::remove((basePath+"/port_battlepass.tsv").c_str());tick(5001);mark=b->messages.size(); + PortBpCommand(b,"1 info");assert(Last(b)=="MTBP1 none"); + WriteConfig("MTBATTLEPASS 1\nseason 1 1 2\n");tick();PortBpCommand(b,"1 info");assert(Last(b)=="MTBP1 none" && logs.back().find("ERR PORT_BP: port_battlepass.tsv disabled: ")==0); + puts("PASS: config, fit, kills, pushes, save, play time, claims (idempotent, space, db, config), final, reload, load race, season change"); +} +''' +with tempfile.TemporaryDirectory(prefix='mt-bp-') as folder: + path=Path(folder);(path/'test.cpp').write_text(code);(path/'locale').mkdir() + 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'),str(path/'locale'),str(TSV)],check=True) diff --git a/tools/battlepass/port_battlepass.tsv b/tools/battlepass/port_battlepass.tsv new file mode 100644 index 00000000..00abd891 --- /dev/null +++ b/tools/battlepass/port_battlepass.tsv @@ -0,0 +1,50 @@ +# PORT battle pass seasons (docs/FEATURE-BATTLEPASS.md). Installed as share/locale/newcibn/port_battlepass.tsv; +# every core rereads it within 5 s of an atomic replace. Any error disables the battle pass (see syserr PORT_BP). +# +# season ID START END unix seconds, START inclusive, END exclusive; seasons must not overlap +# mission SLOT TYPE SUB TARGET [VNUM COUNT]x0..3 +# SLOT 1..10. Progress and claims are stored per season and slot: do not reuse a slot for another mission +# within a running season. +# TYPE 1 kill monster (SUB mob vnum or 0 = any normal monster) 2 kill boss (SUB vnum or 0) +# 3 kill metin stone (SUB vnum or 0) 4 seconds online 5 catch fish (SUB item vnum or 0) +# 6 successful refine (SUB result vnum or 0) 7 levels gained 8 gold paid to NPC shops +# 9 items sold to NPC shops (SUB item vnum, required) +# Kills count for the player the quest kill goes to, within 20 levels of the monster. +# final VNUM COUNT x1..6 once every mission of the season is done +MTBATTLEPASS 1 + +# 2026-10 (Europe/Berlin) +season 202610 1790805600 1793487600 +mission 1 1 0 20000 70043 1 71153 5 +mission 2 2 0 30 25041 2 71032 1 +mission 3 3 0 300 50513 3 +mission 4 4 0 172800 71094 2 +mission 5 5 0 100 27987 5 +mission 6 6 0 50 25040 2 +mission 7 7 0 5 71153 5 +mission 8 8 0 50000000 71084 20 +final 27992 2 27993 1 27994 1 70024 1 + +# 2026-11 (Europe/Berlin) +season 202611 1793487600 1796079600 +mission 1 1 0 20000 70043 1 71153 5 +mission 2 2 0 30 25041 2 71032 1 +mission 3 3 0 300 50513 3 +mission 4 4 0 172800 71094 2 +mission 5 5 0 100 27987 5 +mission 6 6 0 50 25040 2 +mission 7 7 0 5 71153 5 +mission 8 8 0 50000000 71084 20 +final 27992 2 27993 1 27994 1 70024 1 + +# 2026-12 (Europe/Berlin) +season 202612 1796079600 1798758000 +mission 1 1 0 20000 70043 1 71153 5 +mission 2 2 0 30 25041 2 71032 1 +mission 3 3 0 300 50513 3 +mission 4 4 0 172800 71094 2 +mission 5 5 0 100 27987 5 +mission 6 6 0 50 25040 2 +mission 7 7 0 5 71153 5 +mission 8 8 0 50000000 71084 20 +final 27992 2 27993 1 27994 1 70024 1 diff --git a/tools/battlepass/schema.sql b/tools/battlepass/schema.sql new file mode 100644 index 00000000..67b04056 --- /dev/null +++ b/tools/battlepass/schema.sql @@ -0,0 +1,20 @@ +-- PORT: battle pass tables (docs/FEATURE-BATTLEPASS.md). Idempotent; run once on the player database. +-- Progress: one row per player, season and mission slot; the game adds deltas and MySQL caps them at target. +CREATE TABLE IF NOT EXISTS player.mt_battlepass_progress ( + pid INT UNSIGNED NOT NULL, + season INT UNSIGNED NOT NULL, + slot TINYINT UNSIGNED NOT NULL, + value BIGINT UNSIGNED NOT NULL DEFAULT 0, + target BIGINT UNSIGNED NOT NULL DEFAULT 0, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (pid, season, slot) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +-- Claims: the primary key is the idempotency guard; only the request whose INSERT IGNORE adds the row pays out. +-- slot 0 is the final reward. +CREATE TABLE IF NOT EXISTS player.mt_battlepass_claim ( + pid INT UNSIGNED NOT NULL, + season INT UNSIGNED NOT NULL, + slot TINYINT UNSIGNED NOT NULL, + claimed_at INT UNSIGNED NOT NULL, + PRIMARY KEY (pid, season, slot) +) ENGINE=InnoDB DEFAULT CHARSET=latin1;