Add read-only world boss tracking (AVA2 uitrack port)

Each game core snapshots its timed boss regens once a second and shares
them over the original HEADER_GG_RELAY addressed to "#mt_boss", so old
cores just miss the player lookup instead of dropping the P2P link.
New /mt_features query kind "bosses" (capability bit 256, mask 511)
lists the player's channel plus the shared channel 99.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-10-15 22:36:04 +09:00
co-authored by Claude Opus 5.5
parent a5293945b7
commit 400e44fae4
10 changed files with 322 additions and 5 deletions
+72
View File
@@ -0,0 +1,72 @@
# PORT world boss tracking, v1
Date: 2026-10-15. Read-only port of the AVA2 uitrack world-boss tab. Source: `src/server/game/src/port_boss_track.h` (board, wire format), `port_boss_track.cpp` (regen scan, relay, query), hooks in `main.cpp` (1 s tick), `input_p2p.cpp` (`Relay`) and `port_features.h` (query kind `bosses`, capability bit 256). No new packet header, no DB schema, no gameplay change. AVA2's teleport button is not ported, and its dungeon tab is already covered by the `dungeons` query.
## Which regens are listed
A regen is a boss regen when all of these hold:
- type `MOB`, `GROUP` or `ANYWHERE`;
- `time > 0` (it respawns on a timer);
- its leader (the mob itself, or member 0 of the group, which `SpawnGroup` makes the master) is a `CHAR_TYPE_MONSTER` with `bRank >= MOB_RANK_BOSS`.
Each row carries:
| Field | Source |
| --- | --- |
| VNUM | leader vnum |
| MAP | `regen->lMapIndex` |
| X, Y | centre of the regen box minus the map base (map-local units); `0 0` for `ANYWHERE` |
| ALIVE, MAX | `regen->count`, `regen->max_count` (capped at 255) |
| NEXT | server time when `regen_event` fires next (`now + event_time / passes_per_sec`); 0 when there is no event |
| PERIOD | `regen->time` in seconds |
The regen timer is the original one; the board only reads it. `regen_event` tops the regen up to `max_count` each time it fires, so ALIVE < MAX with a NEXT in the past means "about to spawn".
## Sharing between cores
Each game core (not the auth core) scans its own regen list once a second, keeping at most 64 rows. It broadcasts the snapshot when it changes (vnum/map/alive/max/period differ, or NEXT moves by more than 2 s) and otherwise every 60 s as a heartbeat.
The snapshot goes over the original `HEADER_GG_RELAY`, addressed to the name `#mt_boss`, which no player can have:
```
TPacketGGRelay { header, szName "#mt_boss", lSize }
PortBossHeader { uint16 p2p_port; uint8 channel; uint8 count } 4 bytes
PortBossWire { uint32 vnum, map; int32 x, y; uint32 period, next; uint8 alive, max } 26 bytes x count
```
A new GG header was not used on purpose: a core without this code would hit "UNKNOWN HEADER" and close the P2P link. An old core instead looks the name up with `FindPC`, finds nobody and drops the payload, logging one `InputP2P::Relay : #mt_boss size N` line per snapshot. A new core consumes the relay before the player lookup. Malformed payloads (short, size mismatch, more than 64 rows) are rejected with one syserr line.
Remote snapshots are keyed by sender host + P2P port; a newer one replaces the older, and a core that has been silent for 150 s drops out.
## Query
```
/mt_features 1 REQUEST bosses
MTF1 begin REQUEST bosses 0 0 TOTAL 0 SERVER_TIME
MTF1 boss REQUEST INDEX VNUM MAP X Y CHANNEL ALIVE MAX NEXT PERIOD
MTF1 end REQUEST ROW_COUNT
```
A player sees the rows of their own channel plus channel 99 (the shared core). Rows are sorted by map, vnum and channel, and capped at 128. The usual query rules (throttle, own PC, version check) apply. `bosses` with extra arguments returns `MTF1 error REQUEST unsupported`.
## Evidence
- `tests/features/test_bosses.py`:
- wiring checks for the Makefile, the main tick, the relay hook order and the query dispatch;
- a compiled test of the board covering the broadcast throttle, encode/decode round trip, channel filter, sort, replace, expiry, malformed payloads and the caps.
- `tests/features/test_queries.py`: cap 511, dispatch and the extra-argument error.
- FreeBSD build in `/root/metin2-features-dev`. 2026-10-15 test on 203 with two channel5 cores:
- `first` on 13040 served maps 1/21/41/68; a temporary `second` on 13041 served maps 72/5.
- A query on either core returned all 5 boss rows of both cores:
- pirate 5001 `ANYWHERE` on maps 21/41;
- 2307 on map 68;
- 1192 on map 72;
- 5161 on map 5.
- NEXT values were identical from both sides.
- The live channel 1-4 cores and game99 (old binary) each logged the relay line and kept their P2P links; no P2P errors in syserr.
- The Makefile has no header dependencies. After changing `port_features.h`, touch `cmd_general.cpp` (its only includer) or the old object is linked. The first test build hit this and still advertised cap 255.
## Deployment
Every game core must run the new binary for every boss to be listed; mixing is safe in both directions. Channel 99 rows appear only once game99 runs it.
+3 -1
View File
@@ -13,6 +13,7 @@ Request through existing CG chat command:
/mt_features 1 REQUEST stats /mt_features 1 REQUEST stats
/mt_features 1 REQUEST dungeons /mt_features 1 REQUEST dungeons
/mt_features 1 REQUEST calendar 1 OFFSET /mt_features 1 REQUEST calendar 1 OFFSET
/mt_features 1 REQUEST bosses
``` ```
REQUEST: 1..2147483647, independent for each game session's pending command. Subject: unsigned 32-bit nonzero ID. OFFSET: 0..4096. Other versions, excess arguments, oversized tokens, signed/overflow identifiers are rejected. Queries require an own PC descriptor. Per-character throttle: 250 ms. No gameplay mutation, consumption, random draws or database write. REQUEST: 1..2147483647, independent for each game session's pending command. Subject: unsigned 32-bit nonzero ID. OFFSET: 0..4096. Other versions, excess arguments, oversized tokens, signed/overflow identifiers are rejected. Queries require an own PC descriptor. Per-character throttle: 250 ms. No gameplay mutation, consumption, random draws or database write.
@@ -25,11 +26,12 @@ MTF1 begin REQUEST KIND SUBJECT OFFSET TOTAL MODE SERVER_TIME
MTF1 row REQUEST INDEX ITEM COUNT RULE MIN MAX WEIGHT GROUP_TOTAL RARE MTF1 row REQUEST INDEX ITEM COUNT RULE MIN MAX WEIGHT GROUP_TOTAL RARE
MTF1 stat REQUEST INDEX KEY SIGNED_VALUE MTF1 stat REQUEST INDEX KEY SIGNED_VALUE
MTF1 event REQUEST INDEX EVENT_ID KIND START END CHANNEL EMPIRE ACTIVE MTF1 event REQUEST INDEX EVENT_ID KIND START END CHANNEL EMPIRE ACTIVE
MTF1 boss REQUEST INDEX VNUM MAP X Y CHANNEL ALIVE MAX NEXT PERIOD
MTF1 end REQUEST ROW_COUNT MTF1 end REQUEST ROW_COUNT
MTF1 error REQUEST ERROR MTF1 error REQUEST ERROR
``` ```
MASK: 1 mob drops, 2 chest preview, 4 own stats, 8 item sources, 16 dungeon snapshots, 32 scheduled calendar, 64 switchbot (separate `/mt_switchbot` / `MTSB1` protocol, see FEATURE-SWITCHBOT.md). Unknown capability bits are ignored; unknown versions are rejected. Capability advertises the query implementation; missing quest/config can still return unsupported/schedule_unavailable. The client negotiates before business queries; old servers time out to unsupported, not an empty result. MASK: 1 mob drops, 2 chest preview, 4 own stats, 8 item sources, 16 dungeon snapshots, 32 scheduled calendar, 64 switchbot (separate `/mt_switchbot` / `MTSB1` protocol, see FEATURE-SWITCHBOT.md), 256 world bosses (see FEATURE-BOSS-TRACK.md). The current mask is 511. Unknown capability bits are ignored; unknown versions are rejected. Capability advertises the query implementation; missing quest/config can still return unsupported/schedule_unavailable. The client negotiates before business queries; old servers time out to unsupported, not an empty result.
Each drop/chest/source page contains at most 8 rows, with consecutive absolute indices. TOTAL is capped at 4096; stats are one complete bounded snapshot (currently the named keys in kPortStats, less than 128). Client commits only a complete, matching begin/rows/end sequence. Unknown/stale request IDs cannot overwrite the current selection. Each line is bounded below 512 bytes; rows contain IDs and values, not server-provided script/names/markup. Each drop/chest/source page contains at most 8 rows, with consecutive absolute indices. TOTAL is capped at 4096; stats are one complete bounded snapshot (currently the named keys in kPortStats, less than 128). Client commits only a complete, matching begin/rows/end sequence. Unknown/stale request IDs cannot overwrite the current selection. Each line is bounded below 512 bytes; rows contain IDs and values, not server-provided script/names/markup.
+1 -1
View File
@@ -61,7 +61,7 @@ CPPFILE = BattleArena.cpp FSM.cpp MarkConvert.cpp MarkImage.cpp MarkManager.cpp
desc_client.cpp desc_manager.cpp desc_p2p.cpp dev_log.cpp dungeon.cpp empire_text_convert.cpp entity.cpp\ desc_client.cpp desc_manager.cpp desc_p2p.cpp dev_log.cpp dungeon.cpp empire_text_convert.cpp entity.cpp\
entity_view.cpp event.cpp event_queue.cpp exchange.cpp file_loader.cpp fishing.cpp gm.cpp guild.cpp\ entity_view.cpp event.cpp event_queue.cpp exchange.cpp file_loader.cpp fishing.cpp gm.cpp guild.cpp\
guild_manager.cpp guild_war.cpp horse_rider.cpp horsename_manager.cpp input.cpp input_auth.cpp input_db.cpp\ guild_manager.cpp guild_war.cpp horse_rider.cpp horsename_manager.cpp input.cpp input_auth.cpp input_db.cpp\
input_login.cpp input_main.cpp input_p2p.cpp input_teen.cpp input_udp.cpp ip_ban.cpp\ input_login.cpp input_main.cpp input_p2p.cpp port_boss_track.cpp input_teen.cpp input_udp.cpp ip_ban.cpp\
item.cpp item_addon.cpp item_attribute.cpp item_manager.cpp item_manager_idrange.cpp locale.cpp\ item.cpp item_addon.cpp item_attribute.cpp item_manager.cpp item_manager_idrange.cpp locale.cpp\
locale_service.cpp log.cpp login_data.cpp lzo_manager.cpp marriage.cpp matrix_card.cpp\ locale_service.cpp log.cpp login_data.cpp lzo_manager.cpp marriage.cpp matrix_card.cpp\
messenger_manager.cpp mining.cpp mob_manager.cpp monarch.cpp motion.cpp over9refine.cpp p2p.cpp packet_info.cpp\ messenger_manager.cpp mining.cpp mob_manager.cpp monarch.cpp motion.cpp over9refine.cpp p2p.cpp packet_info.cpp\
+5
View File
@@ -41,6 +41,8 @@ void CInputP2P::Logout(LPDESC d, const char * c_pData)
P2P_MANAGER::instance().Logout(p->szName); P2P_MANAGER::instance().Logout(p->szName);
} }
bool PortBossRelay(LPDESC d, const char* name, const char* data, long size);
int CInputP2P::Relay(LPDESC d, const char * c_pData, size_t uiBytes) int CInputP2P::Relay(LPDESC d, const char * c_pData, size_t uiBytes)
{ {
TPacketGGRelay * p = (TPacketGGRelay *) c_pData; TPacketGGRelay * p = (TPacketGGRelay *) c_pData;
@@ -55,6 +57,9 @@ int CInputP2P::Relay(LPDESC d, const char * c_pData, size_t uiBytes)
return -1; return -1;
} }
if (PortBossRelay(d, p->szName, c_pData + sizeof(TPacketGGRelay), p->lSize))
return p->lSize;
sys_log(0, "InputP2P::Relay : %s size %d", p->szName, p->lSize); sys_log(0, "InputP2P::Relay : %s size %d", p->szName, p->lSize);
LPCHARACTER pkChr = CHARACTER_MANAGER::instance().FindPC(p->szName); LPCHARACTER pkChr = CHARACTER_MANAGER::instance().FindPC(p->szName);
+4
View File
@@ -237,6 +237,8 @@ extern std::map<DWORD, CLoginSim *> g_simByPID;
extern std::vector<TPlayerTable> g_vec_save; extern std::vector<TPlayerTable> g_vec_save;
unsigned int save_idx = 0; unsigned int save_idx = 0;
void PortBossTick();
void heartbeat(LPHEART ht, int pulse) void heartbeat(LPHEART ht, int pulse)
{ {
DWORD t; DWORD t;
@@ -262,6 +264,8 @@ void heartbeat(LPHEART ht, int pulse)
if (!g_bAuthServer) if (!g_bAuthServer)
{ {
PortBossTick();
TPlayerCountPacket pack; TPlayerCountPacket pack;
pack.dwCount = DESC_MANAGER::instance().GetLocalUserCount(); pack.dwCount = DESC_MANAGER::instance().GetLocalUserCount();
db_clientdesc->DBPacket(HEADER_GD_PLAYER_COUNT, 0, &pack, sizeof(TPlayerCountPacket)); db_clientdesc->DBPacket(HEADER_GD_PLAYER_COUNT, 0, &pack, sizeof(TPlayerCountPacket));
+77
View File
@@ -0,0 +1,77 @@
#include "stdafx.h"
#include "utils.h"
#include "config.h"
#include "char.h"
#include "desc.h"
#include "event.h"
#include "mob_manager.h"
#include "p2p.h"
#include "packet.h"
#include "regen.h"
#include "sectree_manager.h"
#include "port_boss_track.h"
extern LPREGEN regen_list;
static PortBossBoard s_portBoss;
// Leader of a boss regen (the mob itself, or member 0 of the group, which SpawnGroup makes the master),
// or 0 when the regen is not a timed boss regen.
static DWORD PortBossLeader(const REGEN* regen) {
if(!regen->time || (regen->type!=REGEN_TYPE_MOB && regen->type!=REGEN_TYPE_GROUP && regen->type!=REGEN_TYPE_ANYWHERE))return 0;
DWORD vnum=regen->vnum;
if(regen->type==REGEN_TYPE_GROUP) {
CMobGroup* group=CMobManager::instance().GetGroup(regen->vnum);
if(!group || group->GetMemberVector().empty())return 0;
vnum=group->GetMemberVector()[0];
}
const CMob* mob=CMobManager::instance().Get(vnum);
if(!mob || mob->m_table.bType!=CHAR_TYPE_MONSTER || mob->m_table.bRank<MOB_RANK_BOSS)return 0;
return vnum;
}
void PortBossTick() {
const long long now=get_global_time();
std::vector<PortBossWire> rows;
for(LPREGEN regen=regen_list;regen && rows.size()<kPortBossMaxRows;regen=regen->next) {
const DWORD vnum=PortBossLeader(regen);
if(!vnum)continue;
PIXEL_POSITION base;
if(!SECTREE_MANAGER::instance().GetMapBasePositionByMapIndex(regen->lMapIndex,base))continue;
PortBossWire w;
w.vnum=vnum;w.map=regen->lMapIndex;w.period=regen->time;
w.x=regen->type==REGEN_TYPE_ANYWHERE?0:(regen->sx+regen->ex)/2-base.x;
w.y=regen->type==REGEN_TYPE_ANYWHERE?0:(regen->sy+regen->ey)/2-base.y;
w.alive=(unsigned char)std::min(std::max(regen->count,0),255);w.max=(unsigned char)std::min(std::max(regen->max_count,0),255);
// regen_event tops the regen up to max_count each time it fires.
w.next=regen->event?(unsigned)(now+event_time(regen->event)/passes_per_sec):0;
rows.push_back(w);
}
if(!s_portBoss.SetLocal(rows,g_bChannel,now))return;
const std::string payload=s_portBoss.Encode(p2p_port);
std::string packet(sizeof(TPacketGGRelay),'\0');
TPacketGGRelay* p=(TPacketGGRelay*)&packet[0];
p->bHeader=HEADER_GG_RELAY;strlcpy(p->szName,kPortBossRelayName,sizeof(p->szName));p->lSize=payload.size();
packet+=payload;
P2P_MANAGER::instance().Send(packet.data(),packet.size());
}
// Called by CInputP2P::Relay for every relay; true when it was a boss snapshot (consumed here).
bool PortBossRelay(LPDESC d,const char* name,const char* data,long size) {
if(strcmp(name,kPortBossRelayName))return false;
if(!s_portBoss.Receive(d->GetHostName(),data,size,get_global_time()))
sys_err("PortBossRelay: bad snapshot from %s size %ld",d->GetHostName(),size);
return true;
}
// MTF1 begin REQ bosses 0 0 TOTAL 0 TIME / boss REQ INDEX VNUM MAP X Y CHANNEL ALIVE MAX NEXT PERIOD / end REQ SENT
void PortBossQuery(LPCHARACTER ch,unsigned request) {
const long long now=get_global_time();
const std::vector<PortBossRow> rows=s_portBoss.Rows(g_bChannel,now);
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 begin %u bosses 0 0 %u 0 %lld",request,unsigned(rows.size()),now);
for(unsigned i=0;i<rows.size();++i) {
const PortBossWire& w=rows[i].wire;
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 boss %u %u %u %u %d %d %u %u %u %u %u",request,i,w.vnum,w.map,w.x,w.y,
rows[i].channel,unsigned(w.alive),unsigned(w.max),w.next,w.period);
}
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 end %u %u",request,unsigned(rows.size()));
}
+86
View File
@@ -0,0 +1,86 @@
#ifndef PORT_BOSS_TRACK_H
#define PORT_BOSS_TRACK_H
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <map>
#include <string>
#include <vector>
// World boss tracking (AVA2 uitrack world-boss tab), read-only. Every core snapshots its own boss regens once a
// second and shares them over the original HEADER_GG_RELAY addressed to a name no player can have, so cores
// without this code just find no such player and skip the payload (a new GG header would make them close the link).
static const char kPortBossRelayName[]="#mt_boss";
static const unsigned kPortBossSharedChannel=99; // the shared core (game99) serves every channel
static const unsigned kPortBossMaxRows=64; // per core
static const unsigned kPortBossMaxTotal=128; // per query
static const long long kPortBossExpire=150; // a peer that stopped sending (crash, shutdown) drops out
static const long long kPortBossHeartbeat=60;
#pragma pack(push,1)
struct PortBossWire {
unsigned vnum,map;int x,y;unsigned period,next;unsigned char alive,max;
};
struct PortBossHeader {
unsigned short port;unsigned char channel,count;
};
#pragma pack(pop)
struct PortBossRow {
PortBossWire wire;unsigned channel;
};
static bool PortBossSame(const std::vector<PortBossWire>& a,const std::vector<PortBossWire>& b) {
if(a.size()!=b.size())return false;
for(size_t i=0;i<a.size();++i) {
const PortBossWire& x=a[i];const PortBossWire& y=b[i];
// next is now + remaining pulses, so it may move by a second between two snapshots.
if(x.vnum!=y.vnum || x.map!=y.map || x.alive!=y.alive || x.max!=y.max || x.period!=y.period ||
std::llabs((long long)x.next-(long long)y.next)>2)return false;
}
return true;
}
class PortBossBoard {
public:
// Returns true when the new local snapshot should be broadcast.
bool SetLocal(const std::vector<PortBossWire>& rows,unsigned channel,long long now) {
local=rows;if(local.size()>kPortBossMaxRows)local.resize(kPortBossMaxRows);localChannel=channel;
if(sentAt && PortBossSame(local,sent) && now-sentAt<kPortBossHeartbeat)return false;
sent=local;sentAt=now;return true;
}
std::string Encode(unsigned short port) const {
PortBossHeader h={port,(unsigned char)localChannel,(unsigned char)local.size()};
std::string out((const char*)&h,sizeof(h));
if(!local.empty())out.append((const char*)&local[0],local.size()*sizeof(PortBossWire));
return out;
}
// host is the sender's address; host+port names one core. False for a malformed payload.
bool Receive(const std::string& host,const char* data,long size,long long now) {
if(size<(long)sizeof(PortBossHeader))return false;
PortBossHeader h;memcpy(&h,data,sizeof(h));
if(h.count>kPortBossMaxRows || size!=(long)(sizeof(h)+h.count*sizeof(PortBossWire)))return false;
Remote& r=remote[host+":"+std::to_string(h.port)];
r.channel=h.channel;r.at=now;r.rows.resize(h.count);
if(h.count)memcpy(&r.rows[0],data+sizeof(h),h.count*sizeof(PortBossWire));
return true;
}
// Rows a player of channel sees: that channel and the shared core, sorted by map then boss.
std::vector<PortBossRow> Rows(unsigned channel,long long now) {
std::vector<PortBossRow> out;
auto add=[&](const std::vector<PortBossWire>& rows,unsigned c) {
if(c!=channel && c!=kPortBossSharedChannel)return;
for(const auto& w:rows)out.push_back({w,c});
};
add(local,localChannel);
for(auto it=remote.begin();it!=remote.end();) {
if(now-it->second.at>kPortBossExpire){it=remote.erase(it);continue;}
add(it->second.rows,it->second.channel);++it;
}
std::stable_sort(out.begin(),out.end(),[](const PortBossRow& a,const PortBossRow& b) {
return a.wire.map!=b.wire.map?a.wire.map<b.wire.map:a.wire.vnum!=b.wire.vnum?a.wire.vnum<b.wire.vnum:a.channel<b.channel;
});
if(out.size()>kPortBossMaxTotal)out.resize(kPortBossMaxTotal);
return out;
}
private:
struct Remote {unsigned channel=0;long long at=0;std::vector<PortBossWire> rows;};
std::vector<PortBossWire> local,sent;unsigned localChannel=0;long long sentAt=0;
std::map<std::string,Remote> remote;
};
#endif
+4 -2
View File
@@ -4,7 +4,8 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include <limits> #include <limits>
// Own-player read-only protocol v1. Capability bits: drops, chests, stats, reverse sources, dungeon snapshots. // Own-player read-only protocol v1. Capability bits: drops, chests, stats, reverse sources, dungeon snapshots; 256 = world bosses.
void PortBossQuery(LPCHARACTER ch,unsigned request);
static bool PortFeatureNumber(const std::string& text,unsigned& value) { static bool PortFeatureNumber(const std::string& text,unsigned& value) {
if (text.empty() || text.size()>10) return false; if (text.empty() || text.size()>10) return false;
unsigned long long result=0; unsigned long long result=0;
@@ -43,8 +44,9 @@ ACMD(do_port_features) {
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u rate",request);return; ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u rate",request);return;
} }
ch->m_portFeatureLastQuery=get_dword_time(); ch->m_portFeatureLastQuery=get_dword_time();
if(kind=="cap" && args.size()==3) {ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 cap %u 1 255 %lld",request,(long long)get_global_time());return;} if(kind=="cap" && args.size()==3) {ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 cap %u 1 511 %lld",request,(long long)get_global_time());return;}
if(kind=="dungeons" && args.size()==3) {PortDungeonQuery(ch,request);return;} if(kind=="dungeons" && args.size()==3) {PortDungeonQuery(ch,request);return;}
if(kind=="bosses" && args.size()==3) {PortBossQuery(ch,request);return;}
if(kind=="stats" && args.size()==3) { if(kind=="stats" && args.size()==3) {
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 begin %u stats 0 0 %u 0 %lld",request,unsigned(sizeof(kPortStats)/sizeof(kPortStats[0])),(long long)get_global_time()); ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 begin %u stats 0 0 %u 0 %lld",request,unsigned(sizeof(kPortStats)/sizeof(kPortStats[0])),(long long)get_global_time());
for(unsigned i=0;i<sizeof(kPortStats)/sizeof(kPortStats[0]);++i) { for(unsigned i=0;i<sizeof(kPortStats)/sizeof(kPortStats[0]);++i) {
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""Compile the world-boss board (port_boss_track.h) and check how the game wires it in."""
from pathlib import Path
import subprocess
import tempfile
ROOT=Path(__file__).resolve().parents[2]
SRC=ROOT/'src/server/game/src'
def text(name):return (SRC/name).read_bytes().decode('latin1')
features=text('port_features.h');glue=text('port_boss_track.cpp');p2p=text('input_p2p.cpp');main=text('main.cpp')
assert 'if(kind=="bosses" && args.size()==3) {PortBossQuery(ch,request);return;}' in features
assert '"MTF1 cap %u 1 511 %lld"' in features
assert 'port_boss_track.cpp' in text('Makefile')
assert 'PortBossTick();' in main.split('if (!g_bAuthServer)',1)[1].split('}',1)[0] # 1 s block, game cores only
# Relay hook runs after the size checks and before the player lookup; old cores just miss the name.
relay=p2p.split('int CInputP2P::Relay',1)[1].split('\n}\n',1)[0]
assert relay.index('p->lSize < 0')<relay.index('PortBossRelay(d, p->szName')<relay.index('FindPC(p->szName)')
assert 'HEADER_GG_RELAY' in glue and 'P2P_MANAGER::instance().Send' in glue
assert 'regen->type==REGEN_TYPE_GROUP' in glue and 'GetMemberVector()[0]' in glue and 'bRank<MOB_RANK_BOSS' in glue
code=r'''
#include <cassert>
#include <cstdio>
#include "port_boss_track.h"
static PortBossWire W(unsigned vnum,unsigned map,unsigned alive,unsigned next){PortBossWire w={vnum,map,100,200,1800,next,(unsigned char)alive,1};return w;}
int main(){
static_assert(sizeof(PortBossWire)==26 && sizeof(PortBossHeader)==4,"wire layout");
assert(sizeof(kPortBossRelayName)<=25 && kPortBossRelayName[0]=='#'); // fits szName, never a player name
PortBossBoard a,b;
// Broadcast on the first snapshot, on alive changes, on next moving by more than 2 s, and every 60 s.
std::vector<PortBossWire> rows={W(2307,68,1,1000),W(1192,72,0,5000)};
assert(a.SetLocal(rows,1,100));assert(!a.SetLocal(rows,1,101));
rows[1].next=5002;assert(!a.SetLocal(rows,1,102));rows[1].next=5003;assert(a.SetLocal(rows,1,103));
rows[0].alive=0;assert(a.SetLocal(rows,1,104));
assert(!a.SetLocal(rows,1,163));assert(a.SetLocal(rows,1,164));
// Round trip to another core of the same channel, plus the shared core and another channel.
std::string packet=a.Encode(13001);assert(packet.size()==4+2*26);
assert(b.Receive("10.0.0.1",packet.data(),packet.size(),200));
PortBossBoard shared,other;
shared.SetLocal({W(2191,125,1,0)},99,200);other.SetLocal({W(591,3,1,0)},2,200);
std::string s=shared.Encode(13099),o=other.Encode(13011);
assert(b.Receive("10.0.0.1",s.data(),s.size(),200)&&b.Receive("10.0.0.1",o.data(),o.size(),200));
b.SetLocal({W(2091,104,1,0)},1,200);
auto seen=b.Rows(1,200);
assert(seen.size()==4); // CH2 rows hidden from CH1
assert(seen[0].wire.map==68&&seen[1].wire.map==72&&seen[2].wire.map==104&&seen[3].wire.map==125&&seen[3].channel==99);
assert(seen[0].wire.alive==0&&seen[1].wire.next==5003&&seen[0].wire.x==100&&seen[0].wire.period==1800);
assert(b.Rows(2,200).size()==2); // a CH2 player sees CH2 + shared, not CH1
// A newer snapshot from the same core replaces the old one; silent cores expire after 150 s.
a.SetLocal({W(2307,68,1,1000)},1,300);packet=a.Encode(13001);assert(b.Receive("10.0.0.1",packet.data(),packet.size(),300));
assert(b.Rows(1,300).size()==3);
assert(b.Rows(1,351).size()==2); // shared (last heard at 200) dropped, 13001 still fresh
assert(b.Rows(1,451).size()==1); // only the local snapshot remains
// Malformed payloads are rejected.
assert(!b.Receive("x",packet.data(),3,300));
assert(!b.Receive("x",packet.data(),packet.size()-1,300));
std::string big(4+65*26,'\0');big[3]=65;assert(!b.Receive("x",big.data(),big.size(),300));
// Local rows are capped per core; a query never exceeds 128 rows.
PortBossBoard many;std::vector<PortBossWire> lots;for(unsigned i=0;i<80;++i)lots.push_back(W(1000+i,1,1,0));
many.SetLocal(lots,1,0);assert(many.Encode(1).size()==4+64*26);
for(unsigned port=0;port<3;++port){std::string p=many.Encode(port);assert(b.Receive("y",p.data(),p.size(),452));}
assert(b.Rows(1,452).size()==128);
puts("PASS: broadcast throttle, encode/decode, channel filter, sort, replace, expiry, validation, caps");
}
'''
with tempfile.TemporaryDirectory(prefix='mt-boss-') 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)
+3 -1
View File
@@ -70,6 +70,7 @@ using LPCHARACTER=Character*;
#include <cstring> #include <cstring>
static void PortCalendarQuery(LPCHARACTER,unsigned,unsigned){} static void PortCalendarQuery(LPCHARACTER,unsigned,unsigned){}
static bool PortDungeonQuery(LPCHARACTER,unsigned){return true;} static bool PortDungeonQuery(LPCHARACTER,unsigned){return true;}
static unsigned bossQueries=0;void PortBossQuery(LPCHARACTER,unsigned request){bossQueries=request;}
#include "port_features.h" #include "port_features.h"
#include "port_dungeon_rules.h" #include "port_dungeon_rules.h"
static void query(Character& ch,const char* text){clockms+=300;do_port_features(&ch,text);} static void query(Character& ch,const char* text){clockms+=300;do_port_features(&ch,text);}
@@ -106,7 +107,7 @@ int main(){
assert(rewards[0].total==100 && rewards[0].rule==WIKI_SINGLE); assert(rewards[0].total==100 && rewards[0].rule==WIKI_SINGLE);
rewards=items.PortWikiChest(50012);assert(rewards[1].rule==WIKI_INDEPENDENT && rewards[1].weight==150 && rewards[1].total==100); rewards=items.PortWikiChest(50012);assert(rewards[1].rule==WIKI_INDEPENDENT && rewards[1].weight==150 && rewards[1].total==100);
assert(items.PortWikiChest(50013).empty() && items.PortWikiChest(19).empty()); assert(items.PortWikiChest(50013).empty() && items.PortWikiChest(19).empty());
Character ch;query(ch,"1 1 cap");assert(ch.messages.back()=="MTF1 cap 1 1 255 1700000000"); Character ch;query(ch,"1 1 cap");assert(ch.messages.back()=="MTF1 cap 1 1 511 1700000000");
ch.messages.clear();query(ch,"1 2 mob 101 0");assert(ch.messages.size()==10 && ch.messages.back()=="MTF1 end 2 8"); ch.messages.clear();query(ch,"1 2 mob 101 0");assert(ch.messages.size()==10 && ch.messages.back()=="MTF1 end 2 8");
query(ch,"1 3 mob 101 999");assert(ch.messages.back()=="MTF1 error 3 offset"); query(ch,"1 3 mob 101 999");assert(ch.messages.back()=="MTF1 error 3 offset");
query(ch,"1 4 mob 9001 0");assert(ch.messages.back()=="MTF1 error 4 missing"); query(ch,"1 4 mob 9001 0");assert(ch.messages.back()=="MTF1 error 4 missing");
@@ -116,6 +117,7 @@ int main(){
bool stone=false,hp=false;for(auto& line:ch.messages){stone|=line.find(" stone 10")!=std::string::npos;hp|=line.find(" hp 123")!=std::string::npos;} bool stone=false,hp=false;for(auto& line:ch.messages){stone|=line.find(" stone 10")!=std::string::npos;hp|=line.find(" hp 123")!=std::string::npos;}
assert(stone && hp && ch.messages.size()==sizeof(kPortStats)/sizeof(kPortStats[0])+2); assert(stone && hp && ch.messages.size()==sizeof(kPortStats)/sizeof(kPortStats[0])+2);
do_port_features(&ch,"1 8 stats");assert(ch.messages.back()=="MTF1 error 8 rate"); do_port_features(&ch,"1 8 stats");assert(ch.messages.back()=="MTF1 error 8 rate");
query(ch,"1 11 bosses");assert(bossQueries==11);query(ch,"1 12 bosses 1 0");assert(bossQueries==11 && ch.messages.back()=="MTF1 error 12 unsupported");
for(auto bad:{"2 9 stats","1 0 cap","1 -1 cap","1 4294967296 cap","1 10 cap too many extra"}) { for(auto bad:{"2 9 stats","1 0 cap","1 -1 cap","1 4294967296 cap","1 10 cap too many extra"}) {
auto size=ch.messages.size();query(ch,bad);assert(ch.messages.size()==size); auto size=ch.messages.size();query(ch,bad);assert(ch.messages.size()==size);
} }