Author SHA1 Message Date
shenleiandClaude Opus 5.5 dc7159338e Add attribute lock (AVA2 ENABLE_LOCK_ATTR port)
Up to two normal attribute slots (addon pair = one group) keep their
type and value through CItem::ChangeAttribute, so scroll rerolls, the
switchbot and GM rerolls all respect it. The mask lives in the new
player.mt_item_attr_lock table (created at boot), cached per CItem and
written synchronously; CopyAttributeTo carries it to refined items.
No item struct, db cache or client packet change. Toggled with
/mt_switchbot 1 lock CELL SLOT; MTSB1 lock line follows attrs_end.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 23:06:00 +09:00
12 changed files with 367 additions and 13 deletions
+71
View File
@@ -0,0 +1,71 @@
# PORT attribute lock
AVA2 `ENABLE_LOCK_ATTR`, rebuilt for this server's item layout. Up to two of the five normal attribute slots keep their type and value when the item is rerolled. Source: `src/server/game/src/port_attr_lock.{h,cpp}`, `CItem::ChangeAttribute` / `CopyAttributeTo` (item_attribute.cpp), the cache fields in item.h/item.cpp, the boot hook in main.cpp, and the `lock` verb of `mt_switchbot` (port_switchbot.h).
## Storage
AVA2 keeps up to two 1-based slot indices as attribute values at indices 7 and 8 of its 15-slot attribute array. This server has `ITEM_ATTRIBUTE_MAX_NUM = 7` (5 normal + 2 rare) and `ITEM_SOCKET_MAX_NUM = 3`, which metin stones use. The `item` table does have `socket3..socket5`, but `TPlayerItem` and the client packets only carry 3 sockets, so using them would change both the db↔game and client wire formats. The `item` row is also rewritten with `REPLACE INTO`, so a column written behind the db cache would be lost.
The lock therefore lives in its own table, which no packet or db-cache structure carries:
```sql
CREATE TABLE IF NOT EXISTS mt_item_attr_lock (item_id INT UNSIGNED NOT NULL PRIMARY KEY, mask TINYINT UNSIGNED NOT NULL) ENGINE=MyISAM
```
- Each game core creates it at boot (`PortAttrLockBoot`, auth cores skip it). No manual migration is needed.
- Bit i of `mask` is normal slot i (0..4). A mask of 0 deletes the row.
- `PortAttrLockGet` reads the mask once per `CItem` with a synchronous `DBManager::DirectQuery` by primary key and caches it on the item (`m_portAttrLock`, `m_portAttrLockLoaded`). Exchanges on the same core keep the object and its cache. A warp or relog creates a new object, which reads the row again.
- `PortAttrLockSet` writes synchronously, so the next core always sees the new value, and writes an `ATTR_LOCK` item log (hint = new mask).
- A failed lookup logs a syserr, returns 0 and is retried next time. A failed write leaves the cache unchanged and returns the `db` error.
- `CopyAttributeTo` (refine, upgrade, over9 refine, quest item swaps) copies the lock to the new item ID together with the attributes.
- Rows of destroyed items stay behind. They are harmless because item IDs are not reused.
## Rules
- Only the five normal slots can be locked; the rare slots 5/6 are not affected. The item must sit in the inventory, not be equipped or in an exchange, not be a costume, and have an attribute set. The slot must hold an attribute.
- At most 2 lock groups, and at least one filled slot must stay unlocked. On items with an addon type (`sAddonType`, weapons whose slots 0/1 are the skill / normal hit bonus pair), slots 0 and 1 lock and unlock together and count as one group.
- The bot's own item cannot be locked or unlocked while the bot is rolling it (`running`).
- Locking is free. AVA2 consumes 50348/50349 per lock or unlock; those vnums do not exist in 203 `item_proto`.
- `CItem::ChangeAttribute` (scroll rerolls, the switchbot, the GM command):
1. take the effective mask: stored mask ∩ filled slots, with the addon pair kept whole;
2. clear the normal slots;
3. apply the addon only if the addon pair is not locked;
4. put back the locked slots at their indices;
5. reroll the remaining count with the original `PutAttribute`. It writes to the first empty slot and skips types already present, so the gaps fill in order without duplicating a locked type.
With no lock, the effective mask is 0 and the sequence equals the original. The attribute count is kept, and the rare slots are untouched.
- Adding an attribute (71085) and rare-attribute scrolls do not look at the lock.
## Protocol (part of mt_switchbot v1)
```
/mt_switchbot 1 lock CELL SLOT toggle the lock on normal slot SLOT (0..4)
MTSB1 lock CELL VNUM MASK effective mask; also sent after every attrs_end
MTSB1 error lock CODE item equipped no_attr busy running slot max db rate invalid
```
`slot` means out of range or empty. `max` means a third group, or every filled slot locked. `db` means the write failed. Older servers never send a `lock` line, so the client shows no lock buttons there.
## Verification
- `tests/features/test_attr_lock.py` cuts the production `CItem::ChangeAttribute` body out of item_attribute.cpp and compiles it against a stub item. It checks that:
- with no lock every slot changes;
- locked slots 1+3 are kept in place and the gaps are refilled;
- a locked type is not rolled again;
- a lock on an empty slot is ignored;
- a locked addon pair skips `ApplyAddon`, while an unlocked one is rerolled;
- the rare slot is untouched and the count is kept;
- there is no DB lookup when there are no attributes;
- every toggle, effective-mask and group-count rule holds.
- It also checks the boot hook, the Makefile, the cache initialisation and that `CopyAttributeTo` copies the lock.
- `tests/features/test_switchbot.py` covers the `lock` verb (toggle, `slot`, `max`, `db`, `running`, `no_attr`, `item`, `invalid`, the addon pair) and the lock line after `attrs_end`.
- FreeBSD: full rebuild of game in `/root/metin2-features-dev` (log `attrlock-build.log`; `item.h` changed, so every .cpp was touched).
- Live on 2026-10-15, channel-5 test core (13040) with the isolated binary, macOS client, [SA]Admin, armour 11209 (item 20000178, 5 attributes), scroll 71084:
- the first boot created the table;
- locking slot 1 → mask 2, then slot 3 → mask 10, then slot 0 → `error lock max`;
- 10 switchbot rolls (`limit`, scrolls 143 → 133): (23,10) in slot 1 and (39,10) in slot 3 stayed the same on every roll, slots 0/2/4 changed every roll, and there were no duplicate types;
- the row read `20000178 10`;
- 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.
+3 -1
View File
@@ -27,6 +27,7 @@ Requests (250 ms per-character throttle; tokens <= 10 chars, <= 30 tokens):
/mt_switchbot 1 start CELL SCROLL_VNUM LIMIT N1 (APPLY MIN)*N1 [N2 (APPLY MIN)*N2]
/mt_switchbot 1 stop
/mt_switchbot 1 status
/mt_switchbot 1 lock CELL SLOT (attribute lock, see FEATURE-ATTR-LOCK.md)
```
Replies:
@@ -36,6 +37,7 @@ MTSB1 attrs CELL VNUM COUNT
MTSB1 attr INDEX APPLY MAX (COUNT rows, INDEX 0..COUNT-1)
MTSB1 attrs_end CELL COUNT
MTSB1 state ACTIVE CELL VNUM ROLLS LIMIT SCROLL SCROLLS REASON
MTSB1 lock CELL VNUM MASK (after every attrs_end, and as the reply to lock)
MTSB1 error VERB CODE
```
@@ -87,5 +89,5 @@ Capability: the MTF1 cap mask advertises bit 64 (63 -> 127). Clients that don't
## Open items
- Attribute lock: AVA2 stores it at attribute index 7, which the current 7-slot layout cannot hold. It needs its own storage design (see the client migration plan, phase 6).
- Attribute lock: done separately in `FEATURE-ATTR-LOCK.md` (table `mt_item_attr_lock`, applied inside `CItem::ChangeAttribute`, so every bot roll keeps the locked slots). The bot's own item cannot be locked or unlocked while it rolls.
- In 203 `player.item_proto`, 71084, 71151, 76014, 76023 and 39028 are USE/USE_CHANGE_ATTRIBUTE (subtype 18); 71302 (the AVA2 talisman scroll) does not exist. The bot accepts any `USE_CHANGE_ATTRIBUTE` scroll and leaves item rules to the original path.
+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\
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\
input_login.cpp input_main.cpp input_p2p.cpp port_boss_track.cpp input_teen.cpp input_udp.cpp ip_ban.cpp\
input_login.cpp input_main.cpp input_p2p.cpp port_boss_track.cpp port_attr_lock.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\
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\
+2
View File
@@ -51,6 +51,8 @@ void CItem::Initialize()
m_bExchanging = false;
memset(&m_alSockets, 0, sizeof(m_alSockets));
memset(&m_aAttr, 0, sizeof(m_aAttr));
m_portAttrLock = 0;
m_portAttrLockLoaded = false;
m_pkDestroyEvent = NULL;
m_pkOwnershipEvent = NULL;
+3
View File
@@ -171,6 +171,9 @@ class CItem : public CEntity
int GetAttributeCount();
void ClearAttribute();
void ChangeAttribute(const int* aiChangeProb=NULL);
// PORT: attribute lock cache, see port_attr_lock.h.
BYTE m_portAttrLock;
bool m_portAttrLockLoaded;
void AddAttribute();
void AddAttribute(BYTE bType, short sValue);
+25 -4
View File
@@ -5,6 +5,7 @@
#include "char.h"
#include "desc.h"
#include "item_manager.h"
#include "port_attr_lock.h"
const int MAX_NORM_ATTR_NUM = ITEM_MANAGER::MAX_NORM_ATTR_NUM;
const int MAX_RARE_ATTR_NUM = ITEM_MANAGER::MAX_RARE_ATTR_NUM;
@@ -189,24 +190,40 @@ void CItem::ChangeAttribute(const int* aiChangeProb)
{
int iAttributeCount = GetAttributeCount();
// PORT: locked slots (port_attr_lock.h) keep their type and value; the rest are rerolled into the gaps.
TItemTable const * pProto = GetProto();
const bool bAddon = pProto && pProto->sAddonType;
const unsigned lock = iAttributeCount ? PortAttrLockEffective(PortAttrLockGet(this), PortAttrFilled(this), bAddon) : 0;
TPlayerItemAttribute aLocked[MAX_NORM_ATTR_NUM];
memcpy(aLocked, m_aAttr, sizeof(aLocked));
ClearAttribute();
if (iAttributeCount == 0)
return;
TItemTable const * pProto = GetProto();
if (pProto && pProto->sAddonType)
if (bAddon && !(lock & kPortAttrLockAddonPair))
{
ApplyAddon(pProto->sAddonType);
}
for (int i = 0; i < MAX_NORM_ATTR_NUM; ++i)
if (lock >> i & 1)
m_aAttr[i] = aLocked[i];
int iFilled = 0;
for (int i = 0; i < MAX_NORM_ATTR_NUM; ++i)
if (m_aAttr[i].bType)
++iFilled;
static const int tmpChangeProb[ITEM_ATTRIBUTE_MAX_LEVEL] =
{
0, 10, 40, 35, 15,
};
for (int i = GetAttributeCount(); i < iAttributeCount; ++i)
// PutAttribute fills the first empty slot, so the gaps between locked slots fill in order.
for (int i = iFilled; i < iAttributeCount; ++i)
{
if (aiChangeProb == NULL)
{
@@ -333,6 +350,10 @@ void CItem::SetForceAttribute(int i, BYTE bType, short sValue)
void CItem::CopyAttributeTo(LPITEM pItem)
{
pItem->SetAttributes(m_aAttr);
// PORT: the lock follows the attributes to the refined / replaced item.
if (const unsigned lock = PortAttrLockGet(this))
PortAttrLockSet(GetOwner(), pItem, lock);
}
int CItem::GetRareAttrCount()
+4
View File
@@ -238,6 +238,7 @@ extern std::vector<TPlayerTable> g_vec_save;
unsigned int save_idx = 0;
void PortBossTick();
void PortAttrLockBoot();
void heartbeat(LPHEART ht, int pulse)
{
@@ -792,6 +793,9 @@ int start(int argc, char **argv)
config_init(st_localeServiceName);
// END_OF_LOCALE_SERVICE
if (!g_bAuthServer)
PortAttrLockBoot();
#ifdef __WIN32__
// In Windows dev mode, "verbose" option is [on] by default.
bVerbose = true;
+38
View File
@@ -0,0 +1,38 @@
#include "stdafx.h"
#include "utils.h"
#include "char.h"
#include "db.h"
#include "item.h"
#include "log.h"
#include "port_attr_lock.h"
void PortAttrLockBoot() {
std::unique_ptr<SQLMsg> msg(DBManager::instance().DirectQuery(
"CREATE TABLE IF NOT EXISTS mt_item_attr_lock (item_id INT UNSIGNED NOT NULL PRIMARY KEY,"
" mask TINYINT UNSIGNED NOT NULL) ENGINE=MyISAM"));
if(msg->uiSQLErrno)sys_err("PortAttrLockBoot: cannot create mt_item_attr_lock (errno %u)",msg->uiSQLErrno);
}
unsigned PortAttrLockGet(CItem* item) {
if(item->m_portAttrLockLoaded)return item->m_portAttrLock;
std::unique_ptr<SQLMsg> msg(DBManager::instance().DirectQuery("SELECT mask FROM mt_item_attr_lock WHERE item_id=%u",item->GetID()));
if(msg->uiSQLErrno){sys_err("PortAttrLockGet: item %u lookup failed",item->GetID());return 0;}
unsigned mask=0;
if(msg->Get()->uiNumRows) {
MYSQL_ROW row=mysql_fetch_row(msg->Get()->pSQLResult);
str_to_number(mask,row[0]);
}
item->m_portAttrLock=BYTE(mask);item->m_portAttrLockLoaded=true;
return mask;
}
bool PortAttrLockSet(CHARACTER* ch,CItem* item,unsigned mask) {
std::unique_ptr<SQLMsg> msg(mask?
DBManager::instance().DirectQuery("REPLACE INTO mt_item_attr_lock (item_id,mask) VALUES(%u,%u)",item->GetID(),mask):
DBManager::instance().DirectQuery("DELETE FROM mt_item_attr_lock WHERE item_id=%u",item->GetID()));
if(msg->uiSQLErrno){sys_err("PortAttrLockSet: item %u mask %u failed",item->GetID(),mask);return false;}
item->m_portAttrLock=BYTE(mask);item->m_portAttrLockLoaded=true;
char hint[16];snprintf(hint,sizeof(hint),"%u",mask);
if(ch)LogManager::instance().ItemLog(ch,item,"ATTR_LOCK",hint);
return true;
}
+51
View File
@@ -0,0 +1,51 @@
#ifndef METIN2_PORT_ATTR_LOCK_H
#define METIN2_PORT_ATTR_LOCK_H
// PORT: attribute lock (AVA2 ENABLE_LOCK_ATTR). Up to two of the five normal attribute slots keep their type and
// value through CItem::ChangeAttribute, so manual scrolls, the switchbot and GM rerolls all respect it.
// AVA2 keeps the lock indices in attribute slots 7/8; this server has no spare attribute or socket slot, so the
// mask lives in player.mt_item_attr_lock keyed by item ID (port_attr_lock.cpp) and no client packet changes.
// Bit i = normal slot i. On items with an addon type, slots 0 and 1 (skill / normal hit bonus) are one group.
static const unsigned kPortAttrLockSlots=5,kPortAttrLockGroups=2,kPortAttrLockAddonPair=3;
// Mask of the normal slots that hold an attribute.
template<class Item> unsigned PortAttrFilled(Item* item) {
unsigned filled=0;
for(unsigned i=0;i<kPortAttrLockSlots;++i)if(item->GetAttributeType(i))filled|=1u<<i;
return filled;
}
inline unsigned PortAttrLockGroupCount(unsigned mask,bool addon) {
unsigned groups=0;
for(unsigned i=0;i<kPortAttrLockSlots;++i)if(mask>>i&1)++groups;
if(addon && (mask&kPortAttrLockAddonPair)==kPortAttrLockAddonPair)--groups;
return groups;
}
// The stored mask as ChangeAttribute applies it: only filled slots, the addon pair kept whole.
inline unsigned PortAttrLockEffective(unsigned mask,unsigned filled,bool addon) {
mask&=(1u<<kPortAttrLockSlots)-1;
if(addon && (mask&kPortAttrLockAddonPair))mask|=kPortAttrLockAddonPair;
return mask&filled;
}
// Toggle the lock on SLOT. Returns NULL and sets OUT, or an MTSB1 error code:
// slot (out of range or empty), max (a third group, or every filled slot would be locked).
inline const char* PortAttrLockToggle(unsigned mask,unsigned slot,unsigned filled,bool addon,unsigned& out) {
if(slot>=kPortAttrLockSlots || !(filled>>slot&1))return "slot";
mask=PortAttrLockEffective(mask,filled,addon);
const unsigned bit=addon && slot<2?kPortAttrLockAddonPair&filled:1u<<slot;
if(mask&bit){out=mask&~bit;return 0;}
const unsigned next=mask|bit;
if(PortAttrLockGroupCount(next,addon)>kPortAttrLockGroups || next==filled)return "max";
out=next;return 0;
}
class CItem;
class CHARACTER;
void PortAttrLockBoot();
// Cached on the item after the first lookup. A failed lookup returns 0 and is retried next time.
unsigned PortAttrLockGet(CItem* item);
// Writes synchronously (a following warp loads the new value on the next core); false on SQL error.
bool PortAttrLockSet(CHARACTER* ch,CItem* item,unsigned mask);
#endif
+31 -1
View File
@@ -3,11 +3,13 @@
// PORT: AVA2-style automatic attribute change. Every roll goes through the original
// CHARACTER::UseItem change-attribute path, so its checks, probabilities, log and consumption apply unchanged.
// One bound item per character; not persisted; stops on logout, warp, busy windows or any rejected roll.
// The lock verb toggles the attribute lock (port_attr_lock.h) that ChangeAttribute applies to every reroll.
#include <map>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "port_attr_lock.h"
static const unsigned kPortSwitchAlternatives=2, kPortSwitchTargets=5, kPortSwitchLimit=1000;
static const unsigned kPortSwitchAddonSkillMax=30, kPortSwitchAddonNormalMax=65; // CItemAddonManager::ApplyAddonTo bounds.
@@ -141,6 +143,29 @@ static void PortSwitchStop(LPCHARACTER ch,const char* reason) {
g_portSwitchbots.erase(it);
}
static void PortSwitchLockLine(LPCHARACTER ch,LPITEM item) {
const bool addon=item->GetProto() && item->GetProto()->sAddonType;
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 lock %u %u %u",unsigned(item->GetCell()),unsigned(item->GetVnum()),
PortAttrLockEffective(PortAttrLockGet(item),PortAttrFilled(item),addon));
}
// lock CELL SLOT: toggle the lock on one normal slot; not while the bot rolls this item.
static const char* PortSwitchLock(LPCHARACTER ch,unsigned cell,unsigned slot) {
if(PortSwitchBusy(ch))return "busy";
LPITEM item=cell<INVENTORY_MAX_NUM?ch->GetItem(TItemPos(INVENTORY,cell)):NULL;
if(!item)return "item";
if(item->IsEquipped() || item->IsExchanging())return "equipped";
if(item->GetType()==ITEM_COSTUME || item->GetAttributeSetIndex()<0)return "no_attr";
auto it=g_portSwitchbots.find(ch->GetPlayerID());
if(it!=g_portSwitchbots.end() && it->second.item==item->GetID())return "running";
const bool addon=item->GetProto() && item->GetProto()->sAddonType;
unsigned mask=0;
if(const char* error=PortAttrLockToggle(PortAttrLockGet(item),slot,PortAttrFilled(item),addon,mask))return error;
if(!PortAttrLockSet(ch,item,mask))return "db";
PortSwitchLockLine(ch,item);
return NULL;
}
static void PortSwitchAttrs(LPCHARACTER ch,unsigned cell) {
LPITEM item=cell<INVENTORY_MAX_NUM?ch->GetItem(TItemPos(INVENTORY,cell)):NULL;
if(!item){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 error attrs item");return;}
@@ -150,6 +175,7 @@ static void PortSwitchAttrs(LPCHARACTER ch,unsigned cell) {
for(unsigned i=0;i<allowed.size();++i)
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 attr %u %u %d",i,allowed[i].first,allowed[i].second);
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 attrs_end %u %u",cell,unsigned(allowed.size()));
PortSwitchLockLine(ch,item);
}
// start CELL SCROLL LIMIT N1 (APPLY VALUE)*N1 [N2 (APPLY VALUE)*N2]
@@ -199,8 +225,12 @@ ACMD(do_port_switchbot) {
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 error %s rate",verb.c_str());return;
}
ch->m_portSwitchbotLastCommand=get_dword_time();
unsigned cell=0;
unsigned cell=0,slot=0;
if(verb=="attrs" && args.size()==3 && PortSwitchNumber(args[2],cell)) PortSwitchAttrs(ch,cell);
else if(verb=="lock" && args.size()==4 && PortSwitchNumber(args[2],cell) && PortSwitchNumber(args[3],slot)) {
const char* error=PortSwitchLock(ch,cell,slot);
if(error)ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 error lock %s",error);
}
else if(verb=="stop" && args.size()==2) PortSwitchStop(ch,"stopped");
else if(verb=="status" && args.size()==2) {
auto it=g_portSwitchbots.find(ch->GetPlayerID());
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""Attribute lock: compile the production CItem::ChangeAttribute body against a stub item and check the lock rules."""
from pathlib import Path
import re
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')
attribute=text('item_attribute.cpp');glue=text('port_attr_lock.cpp');main=text('main.cpp')
body=re.search(r'void CItem::ChangeAttribute\(const int\* aiChangeProb\)\n\{.*?\n\}\n',attribute,re.S).group(0)
copy=re.search(r'void CItem::CopyAttributeTo\(LPITEM pItem\)\n\{.*?\n\}\n',attribute,re.S).group(0)
assert 'PortAttrLockSet(GetOwner(), pItem, lock)' in copy # refine / replacement keeps the lock
assert 'port_attr_lock.cpp' in text('Makefile') and '#include "port_attr_lock.h"' in attribute
assert 'if (!g_bAuthServer)\n\t\tPortAttrLockBoot();' in main.split('config_init(st_localeServiceName);',1)[1][:120]
assert 'CREATE TABLE IF NOT EXISTS mt_item_attr_lock' in glue and 'item->m_portAttrLockLoaded=true' in glue
assert 'm_portAttrLockLoaded = false;' in text('item.cpp')
code=r'''
#include <cassert>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <vector>
typedef unsigned char BYTE;
enum {ITEM_ATTRIBUTE_MAX_LEVEL=5,ITEM_ATTRIBUTE_MAX_NUM=7,SKILL=71,NORMAL=72};
const int MAX_NORM_ATTR_NUM=5;
struct TPlayerItemAttribute{BYTE bType;short sValue;};
struct TItemTable{short sAddonType;};
class CHARACTER;
#include "port_attr_lock.h"
static unsigned g_lock=0;static int g_lookups=0;static BYTE g_next=10;
class CItem {
public:
TPlayerItemAttribute m_aAttr[ITEM_ATTRIBUTE_MAX_NUM];TItemTable proto;
CItem(){memset(m_aAttr,0,sizeof(m_aAttr));proto.sAddonType=0;}
BYTE GetAttributeType(int i){return m_aAttr[i].bType;}
int GetAttributeCount(){int i=0;while(i<MAX_NORM_ATTR_NUM && m_aAttr[i].bType)++i;return i;}
void ClearAttribute(){for(int i=0;i<MAX_NORM_ATTR_NUM;++i)m_aAttr[i].bType=0,m_aAttr[i].sValue=0;}
const TItemTable* GetProto(){return &proto;}
bool HasAttr(BYTE t){for(int i=0;i<MAX_NORM_ATTR_NUM;++i)if(m_aAttr[i].bType==t)return true;return false;}
// CItem::AddAttribute / AddAttr: write at GetAttributeCount(), the first empty slot.
void Put(BYTE t,short v){int i=GetAttributeCount();assert(i<MAX_NORM_ATTR_NUM && !HasAttr(t));m_aAttr[i].bType=t;m_aAttr[i].sValue=v;}
void ApplyAddon(int){Put(NORMAL,-5);Put(SKILL,3);}
void PutAttribute(const int*){while(HasAttr(g_next))++g_next;Put(g_next,g_next*10);++g_next;}
void ChangeAttribute(const int* aiChangeProb=NULL);
};
unsigned PortAttrLockGet(CItem*){++g_lookups;return g_lock;}
@BODY@
static CItem Item(const std::vector<BYTE>& types,bool addon){
CItem item;item.proto.sAddonType=addon;
for(size_t i=0;i<types.size();++i)item.m_aAttr[i].bType=types[i],item.m_aAttr[i].sValue=types[i]*10+1;
item.m_aAttr[5].bType=90;item.m_aAttr[5].sValue=9; // rare slot untouched
return item;
}
static void Check(CItem& item,unsigned keep,const CItem& before,int count){
assert(item.GetAttributeCount()==count); // contiguous, same count
for(int i=0;i<MAX_NORM_ATTR_NUM;++i){
if(keep>>i&1)assert(item.m_aAttr[i].bType==before.m_aAttr[i].bType && item.m_aAttr[i].sValue==before.m_aAttr[i].sValue);
for(int j=0;j<i;++j)assert(!item.m_aAttr[i].bType || item.m_aAttr[i].bType!=item.m_aAttr[j].bType);
}
assert(item.m_aAttr[5].bType==90 && item.m_aAttr[5].sValue==9);
}
int main(){
// No lock: identical to the original (addon first, then rerolls), all values change.
CItem a=Item({1,2,3,4,5},false),b=a;g_lock=0;a.ChangeAttribute();Check(a,0,b,5);
for(int i=0;i<5;++i)assert(a.m_aAttr[i].sValue!=b.m_aAttr[i].sValue);
// Slots 1 and 3 locked: kept in place, gaps refilled in order, no duplicate types.
a=Item({1,2,3,4,5},false);b=a;g_lock=10;a.ChangeAttribute();Check(a,10,b,5);
assert(a.m_aAttr[0].sValue!=b.m_aAttr[0].sValue && a.m_aAttr[4].sValue!=b.m_aAttr[4].sValue);
// Locked type is never rolled again (PutAttribute skips existing types).
g_next=2;a=Item({1,2,3},false);b=a;g_lock=2;a.ChangeAttribute();Check(a,2,b,3);assert(a.m_aAttr[0].bType!=2&&a.m_aAttr[2].bType!=2);
// Lock on an empty slot is ignored; count kept.
a=Item({1,2},false);b=a;g_lock=16;a.ChangeAttribute();Check(a,0,b,2);
// Addon item: lock on slot 1 keeps the whole pair and skips ApplyAddon; otherwise the addon is rerolled.
a=Item({NORMAL,SKILL,3,4},true);a.m_aAttr[0].sValue=-7;b=a;g_lock=2;a.ChangeAttribute();Check(a,3,b,4);
a=Item({NORMAL,SKILL,3,4},true);a.m_aAttr[0].sValue=-7;b=a;g_lock=8;a.ChangeAttribute();Check(a,8,b,4);
assert(a.m_aAttr[0].bType==NORMAL && a.m_aAttr[0].sValue==-5 && a.m_aAttr[1].bType==SKILL && a.m_aAttr[1].sValue==3);
// No attributes: cleared, no lookup.
g_lookups=0;a=Item({},false);a.ChangeAttribute();assert(a.GetAttributeCount()==0 && g_lookups==0);
// Toggle rules.
unsigned out=0;const unsigned five=31,three=7;
assert(!PortAttrLockToggle(0,4,five,false,out) && out==16);
assert(!PortAttrLockToggle(16,0,five,false,out) && out==17);
assert(!strcmp(PortAttrLockToggle(17,1,five,false,out),"max")); // third group
assert(!PortAttrLockToggle(17,4,five,false,out) && out==1); // unlock
assert(!strcmp(PortAttrLockToggle(0,3,three,false,out),"slot")); // empty slot
assert(!strcmp(PortAttrLockToggle(0,5,five,false,out),"slot"));
assert(!strcmp(PortAttrLockToggle(1,1,3,false,out),"max")); // would lock every filled slot
assert(!PortAttrLockToggle(0,0,five,true,out) && out==3); // addon pair = one group
assert(!PortAttrLockToggle(3,4,five,true,out) && out==19);
assert(!strcmp(PortAttrLockToggle(19,2,five,true,out),"max"));
assert(!PortAttrLockToggle(19,1,five,true,out) && out==16);
assert(!strcmp(PortAttrLockToggle(0,0,3,true,out),"max")); // pair is all there is
assert(PortAttrLockEffective(1,five,true)==3 && PortAttrLockEffective(0xff,three,false)==7 && PortAttrLockEffective(24,three,false)==0);
assert(PortAttrLockGroupCount(31,true)==4 && PortAttrLockGroupCount(5,true)==2);
puts("PASS: ChangeAttribute keeps locked slots (plain/addon/empty), no duplicates, rare untouched; toggle rules");
}
'''.replace('@BODY@',body)
with tempfile.TemporaryDirectory(prefix='mt-attrlock-') 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)
+35 -6
View File
@@ -41,13 +41,13 @@ void event_cancel(LPEVENT* e){if(*e)(*e)->cancelled=true;*e=nullptr;}
#define EVENTINFO(name) struct name : public event_info_data
#define PASSES_PER_SEC(s) ((s)*4)
static DWORD clockms=1000;DWORD get_dword_time(){return clockms;}
struct CHARACTER;
struct CItem {
class CHARACTER;
class CItem {public:
DWORD id,vnum;BYTE type,subtype;int set=0;unsigned cell;BYTE window=INVENTORY;bool equipped=false,exchanging=false;int count=1;
CHARACTER* owner=nullptr;TItemTable proto{};TPlayerItemAttribute attrs[7];
DWORD GetID(){return id;}DWORD GetVnum(){return vnum;}BYTE GetType(){return type;}BYTE GetSubType(){return subtype;}
int GetAttributeSetIndex(){return set;}const TItemTable* GetProto(){return &proto;}
const TPlayerItemAttribute& GetAttribute(int i){return attrs[i];}
const TPlayerItemAttribute& GetAttribute(int i){return attrs[i];}BYTE GetAttributeType(int i){return attrs[i].bType;}
int GetAttributeCount(){int n=0;for(int i=0;i<5;++i)n+=attrs[i].bType!=0;return n;}
CHARACTER* GetOwner(){return owner;}BYTE GetWindow(){return window;}unsigned GetCell(){return cell;}
bool IsEquipped(){return equipped;}bool IsExchanging(){return exchanging;}
@@ -58,7 +58,7 @@ struct ITEM_MANAGER{
static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;}
LPITEM Find(DWORD id){for(auto* i:items)if(i->id==id)return i;return nullptr;}
};
struct CHARACTER {
class CHARACTER {public:
DWORD m_portSwitchbotLastCommand=0;bool m_portQuietInfo=false;std::string m_portLastInfo;
DWORD pid=7;VID vid;bool desc=true,busy=false,dead=false,reject=false;int uses=0;
std::vector<std::string> messages,info;std::vector<CItem*> inventory;
@@ -92,6 +92,10 @@ struct CHARACTER_MANAGER{
};
#define ACMD(name) void name(LPCHARACTER ch,const char* argument)
#include "port_switchbot.h"
// Lock storage stub: the real one is a player.mt_item_attr_lock row (port_attr_lock.cpp).
static std::map<DWORD,unsigned> locks;static bool lockFail=false;
unsigned PortAttrLockGet(CItem* item){return locks[item->id];}
bool PortAttrLockSet(CHARACTER*,CItem* item,unsigned mask){if(lockFail)return false;locks[item->id]=mask;return true;}
static CHARACTER ch;
static void cmd(const char* text){clockms+=300;ch.messages.clear();do_port_switchbot(&ch,text);}
static long tick(){for(auto& e:events)if(!e->cancelled&&e->func){long r=e->func(e.get(),0);if(!r)e->func=nullptr;return r;}return -1;}
@@ -110,8 +114,9 @@ int main(){
// Allowed list: proto applies excluded, set filter, level cap picks lValues[level-1].
cmd("1 attrs 10");
assert(ch.messages.size()==4 && ch.messages[0]=="MTSB1 attrs 10 11209 2");
assert(ch.messages[1]=="MTSB1 attr 0 3 12" && ch.messages[2]=="MTSB1 attr 1 63 6" && last()=="MTSB1 attrs_end 10 2");
assert(ch.messages.size()==5 && ch.messages[0]=="MTSB1 attrs 10 11209 2");
assert(ch.messages[1]=="MTSB1 attr 0 3 12" && ch.messages[2]=="MTSB1 attr 1 63 6" && ch.messages[3]=="MTSB1 attrs_end 10 2");
assert(last()=="MTSB1 lock 10 11209 0");
armor.proto.sAddonType=1;cmd("1 attrs 10");assert(ch.messages[3]=="MTSB1 attr 2 71 30" && ch.messages[4]=="MTSB1 attr 3 72 65");armor.proto.sAddonType=0;
cmd("1 attrs 30");assert(last()=="MTSB1 error attrs no_attr");
cmd("1 attrs 99");assert(last()=="MTSB1 error attrs item");
@@ -161,6 +166,30 @@ int main(){
ch.vid.id=100;ch.messages.clear();assert(tick()==0 && ch.messages.empty() && g_portSwitchbots.empty());
assert(ch.uses==6);
// Lock toggle: filled slots only, at most 2 groups and never every filled slot, not on the rolling item.
armor.attrs[0]={APPLY_STR,2};armor.attrs[1]={APPLY_CRITICAL,1};armor.attrs[2]={APPLY_ATTBONUS_MONSTER,2};
cmd("1 lock 10 0");assert(last()=="MTSB1 lock 10 11209 1");
cmd("1 lock 10 2");assert(last()=="MTSB1 lock 10 11209 5");
cmd("1 lock 10 1");assert(last()=="MTSB1 error lock max");
cmd("1 lock 10 3");assert(last()=="MTSB1 error lock slot");
cmd("1 lock 10 5");assert(last()=="MTSB1 error lock slot");
cmd("1 lock 10 0");assert(last()=="MTSB1 lock 10 11209 4" && locks[1001]==4);
cmd("1 lock 10 1");assert(last()=="MTSB1 lock 10 11209 6");
cmd("1 attrs 10");assert(last()=="MTSB1 lock 10 11209 6");
cmd("1 lock 30 0");assert(last()=="MTSB1 error lock no_attr");
cmd("1 lock 99 0");assert(last()=="MTSB1 error lock item");
cmd("1 lock 10");assert(last()=="MTSB1 error lock invalid");
lockFail=true;cmd("1 lock 10 1");assert(last()=="MTSB1 error lock db" && locks[1001]==6);lockFail=false;
ch.rolls={{{APPLY_STR,2}}};cmd("1 start 10 71084 5 1 3 12");cmd("1 lock 10 1");assert(last()=="MTSB1 error lock running");
cmd("1 stop");
// Addon weapon: slots 0 and 1 lock together and count as one group.
armor.proto.sAddonType=1;locks[1001]=0;armor.attrs[3]={APPLY_MAX_HP,500};
cmd("1 lock 10 1");assert(last()=="MTSB1 lock 10 11209 3");
cmd("1 lock 10 3");assert(last()=="MTSB1 lock 10 11209 11");
cmd("1 lock 10 2");assert(last()=="MTSB1 error lock max");
cmd("1 lock 10 0");assert(last()=="MTSB1 lock 10 11209 8");
armor.proto.sAddonType=0;armor.attrs[2]=armor.attrs[3]=TPlayerItemAttribute{};locks.clear();
// Malformed or foreign input is ignored or rejected without side effects.
cmd("2 status");assert(ch.messages.empty());
cmd("1 explode");assert(last()=="MTSB1 error explode invalid");