Port the AVA2 switchbot (自动洗练) 1:1

AVA2 new_switchbot ported as port_switchbot.{h,cpp}: SWITCHBOT item window (7),
CG/GC 171 and GG 31 with AVA2 subheaders and field order, pack(1) structs pinned
by static_assert, 0.1 s roll, P2P hand-over on warp, boot ALTER of
player.item.window. Switchers come from the inventory; current checks and
ItemLog are kept. Clients sending "mt20261016" or newer as the version
timestamp get the switchbot; older clients are left alone.

The v1 /mt_switchbot chat command, its lock verb and query capability bit 64
are removed (cap mask 1023 -> 959).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-10-16 20:26:06 +09:00
co-authored by Claude Opus 5.5
parent c6813cd653
commit a28393b16b
39 changed files with 1485 additions and 555 deletions
+23
View File
@@ -474,6 +474,21 @@ enum EOnIdleEvents
ON_IDLE_MAX_NUM
};
// PORT: AVA2 ENABLE_SWITCHBOT (port_switchbot.cpp). Slot 5 is AVA2's hidden scroll cell; this port keeps
// the table width but never stores an item there.
enum SwitchbotValues
{
SWITCHBOT_SLOT_COUNT = 6,
SWITCHBOT_SLOT_COUNT_REAL = 5,
SWITCHBOT_ALTERNATIVE_COUNT = 2,
SWITCHBOT_NORM_ATTR_NUM = 5, // AVA2 MAX_NORM_ATTR_NUM
//1 = Switching Item
//2 = Yang
SWITCHBOT_PRICE_TYPE = 1,
//Amount Swtichting Items the Yang-Price
SWITCHBOT_PRICE_AMOUNT = 1,
};
enum EWindows
{
RESERVED_WINDOW,
@@ -483,6 +498,7 @@ enum EWindows
MALL,
DRAGON_SOUL_INVENTORY,
BELT_INVENTORY,
SWITCHBOT, // PORT: 7 = player.item.window enum 'SWITCHBOT' (appended after BELT_INVENTORY)
#ifdef __AUCTION__
AUCTION,
#endif
@@ -757,6 +773,8 @@ typedef struct SItemPos
return cell < INVENTORY_AND_EQUIP_SLOT_MAX;
case DRAGON_SOUL_INVENTORY:
return cell < (DRAGON_SOUL_INVENTORY_MAX_NUM);
case SWITCHBOT:
return cell < SWITCHBOT_SLOT_COUNT;
// 동적으로 크기가 정해지는 window는 valid 체크를 할 수가 없다.
case SAFEBOX:
case MALL:
@@ -796,6 +814,11 @@ typedef struct SItemPos
return INVENTORY == window_type && cell < INVENTORY_MAX_NUM;
}
bool IsSwitchbotPosition() const
{
return SWITCHBOT == window_type && cell < SWITCHBOT_SLOT_COUNT;
}
bool operator==(const struct SItemPos& rhs) const
{
return (window_type == rhs.window_type) && (cell == rhs.cell);
+46
View File
@@ -1484,5 +1484,51 @@ typedef struct SChannelStatus
BYTE bStatus;
} TChannelStatus;
// PORT: AVA2 ENABLE_SWITCHBOT tables (port_switchbot.cpp). TSwitchbotTable goes to the client as is
// (SUBHEADER_GC_SWITCHBOT_UPDATE) and between cores (HEADER_GG_SWITCHBOT): 220 bytes.
struct TSwitchbotAttributeAlternativeTable
{
TPlayerItemAttribute attributes[SWITCHBOT_NORM_ATTR_NUM];
bool IsConfigured() const
{
for (BYTE i = 0; i < SWITCHBOT_NORM_ATTR_NUM; ++i)
{
if (attributes[i].bType && attributes[i].sValue)
{
return true;
}
}
return false;
}
};
struct TSwitchbotTable
{
DWORD player_id;
bool active[SWITCHBOT_SLOT_COUNT];
bool finished[SWITCHBOT_SLOT_COUNT];
DWORD items[SWITCHBOT_SLOT_COUNT];
TSwitchbotAttributeAlternativeTable alternatives[SWITCHBOT_SLOT_COUNT][SWITCHBOT_ALTERNATIVE_COUNT];
TSwitchbotTable() : player_id(0)
{
memset(&items, 0, sizeof(items));
memset(&alternatives, 0, sizeof(alternatives));
memset(&active, false, sizeof(active));
memset(&finished, false, sizeof(finished));
}
};
// PORT: AVA2 declares max_value as long; int keeps the 4-byte wire width the client mirrors with LONG.
struct TSwitchbottAttributeTable
{
BYTE attribute_set;
int apply_num;
int max_value;
};
#pragma pack()
#endif
+5 -5
View File
@@ -322,8 +322,8 @@ void CClientManager::QUERY_PLAYER_LOAD(CPeer * peer, DWORD dwHandle, TPlayerLoad
{
snprintf(szQuery, sizeof(szQuery),
"SELECT id,window+0,pos,count,vnum,socket0,socket1,socket2,attrtype0,attrvalue0,attrtype1,attrvalue1,attrtype2,attrvalue2,attrtype3,attrvalue3,attrtype4,attrvalue4,attrtype5,attrvalue5,attrtype6,attrvalue6 "
"FROM item%s WHERE owner_id=%d AND (window < %d or window = %d)",
GetTablePostfix(), pTab->id, SAFEBOX, DRAGON_SOUL_INVENTORY);
"FROM item%s WHERE owner_id=%d AND (window < %d or window = %d or window = %d)",
GetTablePostfix(), pTab->id, SAFEBOX, DRAGON_SOUL_INVENTORY, SWITCHBOT);
CDBManager::instance().ReturnQuery(szQuery,
QID_ITEM,
@@ -379,8 +379,8 @@ void CClientManager::QUERY_PLAYER_LOAD(CPeer * peer, DWORD dwHandle, TPlayerLoad
//--------------------------------------------------------------
snprintf(queryStr, sizeof(queryStr),
"SELECT id,window+0,pos,count,vnum,socket0,socket1,socket2,attrtype0,attrvalue0,attrtype1,attrvalue1,attrtype2,attrvalue2,attrtype3,attrvalue3,attrtype4,attrvalue4,attrtype5,attrvalue5,attrtype6,attrvalue6 "
"FROM item%s WHERE owner_id=%d AND (window < %d or window = %d)",
GetTablePostfix(), packet->player_id, SAFEBOX, DRAGON_SOUL_INVENTORY);
"FROM item%s WHERE owner_id=%d AND (window < %d or window = %d or window = %d)",
GetTablePostfix(), packet->player_id, SAFEBOX, DRAGON_SOUL_INVENTORY, SWITCHBOT);
CDBManager::instance().ReturnQuery(queryStr, QID_ITEM, peer->GetHandle(), new ClientHandleInfo(dwHandle, packet->player_id));
//--------------------------------------------------------------
@@ -1132,7 +1132,7 @@ void CClientManager::__RESULT_PLAYER_DELETE(CPeer *peer, SQLMsg* msg)
snprintf(queryStr, sizeof(queryStr), "DELETE FROM player%s WHERE id=%d", GetTablePostfix(), pi->player_id);
delete CDBManager::instance().DirectQuery(queryStr);
snprintf(queryStr, sizeof(queryStr), "DELETE FROM item%s WHERE owner_id=%d AND (window < %d or window = %d)", GetTablePostfix(), pi->player_id, SAFEBOX, DRAGON_SOUL_INVENTORY);
snprintf(queryStr, sizeof(queryStr), "DELETE FROM item%s WHERE owner_id=%d AND (window < %d or window = %d or window = %d)", GetTablePostfix(), pi->player_id, SAFEBOX, DRAGON_SOUL_INVENTORY, SWITCHBOT);
delete CDBManager::instance().DirectQuery(queryStr);
snprintf(queryStr, sizeof(queryStr), "DELETE FROM quest%s WHERE dwPID=%d", GetTablePostfix(), pi->player_id);
+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 port_attr_lock.cpp port_sash.cpp port_mount.cpp port_costume_attr.cpp port_pendant.cpp port_rings.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 port_sash.cpp port_mount.cpp port_costume_attr.cpp port_pendant.cpp port_rings.cpp port_switchbot.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\
+7
View File
@@ -58,6 +58,7 @@
#include "skill_power.h"
#include "buff_on_attributes.h"
#include "port_battlepass_hooks.h"
#include "port_switchbot.h"
#ifdef __PET_SYSTEM__
#include "PetSystem.h"
@@ -5351,6 +5352,12 @@ bool CHARACTER::WarpSet(long x, long y, long lPrivateMapIndex)
p.wPort = wPort;
// PORT: AVA2 switchbot: the table follows the player to the target core (port_switchbot.cpp).
CSwitchbotManager::Instance().SetIsWarping(GetPlayerID(), true);
if (p.wPort != mother_port)
CSwitchbotManager::Instance().P2PSendSwitchbot(GetPlayerID(), p.wPort);
GetDesc()->Packet(&p, sizeof(TPacketGCWarp));
//if (!LC_IsNewCIBN())
+4 -3
View File
@@ -412,6 +412,8 @@ typedef struct character_point_instant
LPITEM pDSItems[DRAGON_SOUL_INVENTORY_MAX_NUM];
WORD wDSItemGrid[DRAGON_SOUL_INVENTORY_MAX_NUM];
LPITEM pSwitchbotItems[SWITCHBOT_SLOT_COUNT]; // PORT: AVA2 switchbot window (port_switchbot.cpp)
// by mhh
LPITEM pCubeItems[CUBE_MAX_NUM];
LPCHARACTER pCubeNpc;
@@ -526,9 +528,8 @@ class CHARACTER : public CEntity, public CFSM, public CHorseRider
public:
DWORD m_portFeatureLastQuery = 0; // PORT: read-only query throttle, not persisted.
DWORD m_portSwitchbotLastCommand = 0; // PORT: switchbot command throttle.
bool m_portQuietInfo = false; // PORT: switchbot rolls hold back per-roll INFO lines...
std::string m_portLastInfo; // ...keeping the last one to report a rejected roll.
bool m_portQuietInfo = false; // PORT: batch actions hold back per-item INFO lines...
std::string m_portLastInfo; // ...keeping the last one to report a rejected item.
DWORD m_portPickupLastCommand = 0; // PORT: batch pickup throttle.
LPCHARACTER FindCharacterInView(const char * name, bool bFindPCOnly);
+114
View File
@@ -44,6 +44,7 @@
#include "../../common/VnumHelper.h"
#include "DragonSoul.h"
#include "port_attr_lock.h"
#include "port_switchbot.h"
#include "buff_on_attributes.h"
#include "belt_inventory_helper.h"
@@ -263,6 +264,14 @@ LPITEM CHARACTER::GetItem(TItemPos Cell) const
return NULL;
}
return m_pointsInstant.pDSItems[wCell];
// PORT: AVA2 ENABLE_SWITCHBOT window (port_switchbot.cpp).
case SWITCHBOT:
if (wCell >= SWITCHBOT_SLOT_COUNT)
{
sys_err("CHARACTER::GetInventoryItem: invalid switchbot item cell %d", wCell);
return NULL;
}
return m_pointsInstant.pSwitchbotItems[wCell];
default:
return NULL;
@@ -399,6 +408,32 @@ void CHARACTER::SetItem(TItemPos Cell, LPITEM pItem)
m_pointsInstant.pDSItems[wCell] = pItem;
}
break;
case SWITCHBOT:
{
if (wCell >= SWITCHBOT_SLOT_COUNT)
{
sys_err("CHARACTER::SetItem: invalid switchbot item cell %d", wCell);
return;
}
LPITEM pOld = m_pointsInstant.pSwitchbotItems[wCell];
if (pItem && pOld)
{
return;
}
if (pItem)
{
CSwitchbotManager::Instance().RegisterItem(GetPlayerID(), pItem->GetID(), wCell);
}
else
{
CSwitchbotManager::Instance().UnregisterItem(GetPlayerID(), wCell);
}
m_pointsInstant.pSwitchbotItems[wCell] = pItem;
}
break;
default:
sys_err ("Invalid Inventory type %d", window_type);
return;
@@ -454,6 +489,9 @@ void CHARACTER::SetItem(TItemPos Cell, LPITEM pItem)
case DRAGON_SOUL_INVENTORY:
pItem->SetWindow(DRAGON_SOUL_INVENTORY);
break;
case SWITCHBOT:
pItem->SetWindow(SWITCHBOT);
break;
}
}
}
@@ -517,6 +555,17 @@ void CHARACTER::ClearItem()
item->SetSkipSave(true);
ITEM_MANAGER::instance().FlushDelayedSave(item);
item->RemoveFromCharacter();
M2_DESTROY_ITEM(item);
}
}
for (i = 0; i < SWITCHBOT_SLOT_COUNT; ++i)
{
if ((item = GetItem(TItemPos(SWITCHBOT, i))))
{
item->SetSkipSave(true);
ITEM_MANAGER::instance().FlushDelayedSave(item);
item->RemoveFromCharacter();
M2_DESTROY_ITEM(item);
}
@@ -681,6 +730,18 @@ bool CHARACTER::IsEmptyItemGrid(TItemPos Cell, BYTE bSize, int iExceptionCell) c
return true;
}
}
// PORT: AVA2 switchbot window; cell 5 (AVA2's hidden switcher cell) never takes an item here.
case SWITCHBOT:
{
WORD wCell = Cell.cell;
if (wCell >= SWITCHBOT_SLOT_COUNT_REAL)
return false;
if (m_pointsInstant.pSwitchbotItems[wCell])
return false;
return true;
}
}
}
@@ -5216,6 +5277,28 @@ bool CHARACTER::UseItem(TItemPos Cell, TItemPos DestCell)
if (item->IsExchanging())
return false;
// PORT: AVA2 switchbot: using an idle switchbot item takes it back to the inventory.
if (Cell.IsSwitchbotPosition())
{
if (CSwitchbotManager::Instance().IsActive(GetPlayerID(), Cell.cell))
return false;
int iEmptyCell = GetEmptyInventory(item->GetSize());
if (iEmptyCell == -1)
{
ChatPacket(CHAT_TYPE_INFO, LC_TEXT("소지하고 있는 아이템이 너무 많습니다."));
return false;
}
MoveItem(Cell, TItemPos(INVENTORY, iEmptyCell), item->GetCount());
return true;
}
// Switchbot items change only through the switchbot (CItem::UpdatePacket skips that window).
if (DestCell.IsSwitchbotPosition())
return false;
if (!item->CanUsedBy(this))
{
ChatPacket(CHAT_TYPE_INFO, LC_TEXT("군직이 맞지않아 이 아이템을 사용할 수 없습니다."));
@@ -5405,6 +5488,9 @@ bool CHARACTER::DropItem(TItemPos Cell, BYTE bCount)
if (IsDead())
return false;
if (Cell.IsSwitchbotPosition()) // PORT: switchbot items go back to the inventory first
return false;
if (!IsValidItemPosition(Cell) || !(item = GetItem(Cell)))
return false;
@@ -5613,6 +5699,28 @@ bool CHARACTER::MoveItem(TItemPos Cell, TItemPos DestCell, BYTE count)
return false;
}
// PORT: AVA2 switchbot: a running slot keeps its item; only switchbot items go in, and only between the
// switchbot window and the main inventory (cell 5 is refused by IsEmptyItemGrid).
if (Cell.IsSwitchbotPosition() || DestCell.IsSwitchbotPosition())
{
if (Cell.IsSwitchbotPosition() && CSwitchbotManager::Instance().IsActive(GetPlayerID(), Cell.cell))
{
ChatPacket(CHAT_TYPE_COMMAND, "switchbot_error active");
return false;
}
if (DestCell.IsSwitchbotPosition() && !SwitchbotHelper::IsValidItem(item))
{
ChatPacket(CHAT_TYPE_COMMAND, "switchbot_error invalid");
return false;
}
const TItemPos& other = Cell.IsSwitchbotPosition() ? DestCell : Cell;
if (!other.IsSwitchbotPosition() && !other.IsDefaultInventoryPosition())
return false;
}
// 이미 착용중인 아이템을 다른 곳으로 옮기는 경우, '장책 해제' 가능한 지 확인하고 옮김
if (Cell.IsEquipPosition() && !CanUnequipNow(item))
return false;
@@ -6727,6 +6835,9 @@ bool CHARACTER::GiveItem(LPCHARACTER victim, TItemPos Cell)
if (!CanHandleItem())
return false;
if (Cell.IsSwitchbotPosition()) // PORT: switchbot items go back to the inventory first
return false;
LPITEM item = GetItem(Cell);
if (item && !item->IsExchanging())
@@ -7472,6 +7583,9 @@ bool CHARACTER::IsValidItemPosition(TItemPos Pos) const
case DRAGON_SOUL_INVENTORY:
return cell < (DRAGON_SOUL_INVENTORY_MAX_NUM);
case SWITCHBOT:
return cell < SWITCHBOT_SLOT_COUNT;
case SAFEBOX:
if (NULL != m_pkSafebox)
return m_pkSafebox->IsValidPosition(cell);
-2
View File
@@ -10,7 +10,6 @@ ACMD(do_autohunt_pull);
ACMD(do_server_bonuses);
ACMD(do_port_biolog);
ACMD(do_port_features);
ACMD(do_port_switchbot);
ACMD(do_port_pickup);
ACMD(do_port_chest);
ACMD(do_port_vip);
@@ -604,7 +603,6 @@ struct command_info cmd_info[] =
// PORT: feature commands stay at the end: commands are prefix matched in table order, so an entry placed
// earlier would take over abbreviations of original commands (/m -> mob, /mt -> mto).
{ "mt_features", do_port_features, 0, POS_DEAD, GM_PLAYER },
{ "mt_switchbot", do_port_switchbot, 0, POS_DEAD, GM_PLAYER },
{ "mt_pickup", do_port_pickup, 0, POS_DEAD, GM_PLAYER },
{ "mt_chest", do_port_chest, 0, POS_DEAD, GM_PLAYER },
{ "mt_vip", do_port_vip, 0, POS_DEAD, GM_PLAYER },
-1
View File
@@ -44,7 +44,6 @@
#include "port_calendar_runtime.h"
#include "port_ava2_travel.h"
#include "port_features.h"
#include "port_switchbot.h"
#include "port_pickup.h"
#include "port_chest.h"
#include "port_premium.h"
+3
View File
@@ -147,6 +147,9 @@ bool CExchange::AddItem(TItemPos item_pos, BYTE display_pos)
if (item_pos.IsEquipPosition())
return false;
if (item_pos.IsSwitchbotPosition()) // PORT: switchbot items go back to the inventory first
return false;
LPITEM item;
if (!(item = m_pOwner->GetItem(item_pos)))
+2
View File
@@ -157,6 +157,7 @@ class CInputMain : public CInputProcessor
void Refine(LPCHARACTER ch, const char* c_pData);
void Sash(LPCHARACTER ch, const char* c_pData);
int Switchbot(LPCHARACTER ch, const char* data, size_t uiBytes); // AVA2 switchbot (port_switchbot.cpp)
void Roulette(LPCHARACTER ch, const char* c_pData);
};
@@ -354,6 +355,7 @@ class CInputP2P : public CInputProcessor
void BlockChat(const char * c_pData);
void PCBangUpdate(const char* c_pData);
void IamAwake(LPDESC d, const char * c_pData);
void Switchbot(LPDESC d, const char * c_pData); // AVA2 switchbot (port_switchbot.cpp)
protected:
CPacketInfoGG m_packetInfoGG;
+9
View File
@@ -47,6 +47,7 @@
// #include "HackShield.h"
#include "DragonSoul.h"
#include "port_switchbot.h"
#ifdef __AUCTION__
#include "auction_manager.h"
@@ -1578,6 +1579,14 @@ void CInputDB::ItemLoad(LPDESC d, const char * c_pData)
item->AddToCharacter(ch, TItemPos(p->window, p->pos));
break;
// PORT: AVA2 switchbot window; an item that cannot go back there is restored like the others.
case SWITCHBOT:
if (ch->IsEmptyItemGrid(TItemPos(SWITCHBOT, p->pos), item->GetSize()) && SwitchbotHelper::IsValidItem(item))
item->AddToCharacter(ch, TItemPos(SWITCHBOT, p->pos));
else
v.push_back(item);
break;
case EQUIPMENT:
if (item->CheckItemUseLevel(ch->GetLevel()) == true )
{
+2
View File
@@ -31,6 +31,7 @@
#include "db.h"
#include "item.h"
#include "port_premium.h"
#include "port_switchbot.h"
#include "horsename_manager.h"
#include "MarkManager.h"
// #include "HackShield.h"
@@ -649,6 +650,7 @@ void CInputLogin::Entergame(LPDESC d, const char * data)
}
// PORT: the db core keeps the login-time premium ends; a VIP card used since then is in the account table.
PortVipRefresh(ch, false);
CSwitchbotManager::Instance().EnterGame(ch); // PORT: AVA2 switchbot (port_switchbot.cpp)
if (LC_IsEurope())
{
+55
View File
@@ -41,6 +41,7 @@
// #include "HackShield.h"
// #include "XTrapManager.h"
#include "DragonSoul.h"
#include "port_switchbot.h"
extern void SendShout(const char * szText, BYTE bEmpire);
extern int g_nPortalLimitTime;
@@ -2065,6 +2066,9 @@ void CInputMain::SafeboxCheckin(LPCHARACTER ch, const char * c_pData)
if (!ch->CanHandleItem())
return;
if (p->ItemPos.IsSwitchbotPosition()) // PORT: switchbot items go back to the inventory first
return;
CSafebox * pkSafebox = ch->GetSafebox();
LPITEM pkItem = ch->GetItem(p->ItemPos);
@@ -2136,6 +2140,9 @@ void CInputMain::SafeboxCheckout(LPCHARACTER ch, const char * c_pData, bool bMal
if (!pkItem)
return;
if (p->ItemPos.IsSwitchbotPosition()) // PORT: only MoveItem fills the switchbot window
return;
if (!ch->IsEmptyItemGrid(p->ItemPos, pkItem->GetSize()))
return;
@@ -3043,6 +3050,49 @@ void CInputMain::Refine(LPCHARACTER ch, const char* c_pData)
ch->ClearRefineMode();
}
// AVA2 CInputMain::Switchbot: START carries SWITCHBOT_ALTERNATIVE_COUNT alternative tables, STOP nothing.
int CInputMain::Switchbot(LPCHARACTER ch, const char* data, size_t uiBytes)
{
const TPacketCGSwitchbot* p = reinterpret_cast<const TPacketCGSwitchbot*>(data);
if (uiBytes < sizeof(TPacketCGSwitchbot))
return -1;
const char* c_pData = data + sizeof(TPacketCGSwitchbot);
uiBytes -= sizeof(TPacketCGSwitchbot);
switch (p->subheader)
{
case SUBHEADER_CG_SWITCHBOT_START:
{
const size_t extraLen = sizeof(TSwitchbotAttributeAlternativeTable) * SWITCHBOT_ALTERNATIVE_COUNT;
if (uiBytes < extraLen)
return -1;
std::vector<TSwitchbotAttributeAlternativeTable> vec_alternatives;
for (BYTE alternative = 0; alternative < SWITCHBOT_ALTERNATIVE_COUNT; ++alternative)
{
TSwitchbotAttributeAlternativeTable attr;
memcpy(&attr, c_pData, sizeof(attr));
c_pData += sizeof(TSwitchbotAttributeAlternativeTable);
vec_alternatives.push_back(attr);
}
CSwitchbotManager::Instance().Start(ch->GetPlayerID(), p->slot, vec_alternatives);
return extraLen;
}
case SUBHEADER_CG_SWITCHBOT_STOP:
CSwitchbotManager::Instance().Stop(ch->GetPlayerID(), p->slot);
return 0;
}
return 0;
}
void CInputMain::Sash(LPCHARACTER ch, const char* c_pData)
{
quest::PC * pPC = quest::CQuestManager::instance().GetPCForce(ch->GetPlayerID());
@@ -3352,6 +3402,11 @@ int CInputMain::Analyze(LPDESC d, BYTE bHeader, const char * c_pData)
Sash(ch, c_pData);
break;
case HEADER_CG_SWITCHBOT:
if ((iExtraLen = Switchbot(ch, c_pData, m_iBufferLeft)) < 0)
return -1;
break;
case HEADER_CG_DRAGON_SOUL_REFINE:
{
TPacketCGDragonSoulRefine* p = reinterpret_cast <TPacketCGDragonSoulRefine*>((void*)c_pData);
+16
View File
@@ -21,6 +21,7 @@
#include "pcbang.h"
#include "skill.h"
#include "threeway_war.h"
#include "port_switchbot.h"
////////////////////////////////////////////////////////////////////////////////
@@ -416,6 +417,17 @@ void CInputP2P::IamAwake(LPDESC d, const char * c_pData)
sys_log(0, "P2P Awakeness check from %s. My P2P connection number is %d. and details...\n%s", d->GetHostName(), P2P_MANAGER::instance().GetDescCount(), hostNames.c_str());
}
// AVA2: every core gets the table; only the warp target keeps it.
void CInputP2P::Switchbot(LPDESC d, const char * c_pData)
{
const TPacketGGSwitchbot* p = reinterpret_cast<const TPacketGGSwitchbot*>(c_pData);
if (p->wPort != mother_port)
return;
CSwitchbotManager::Instance().P2PReceiveSwitchbot(p->table);
}
int CInputP2P::Analyze(LPDESC d, BYTE bHeader, const char * c_pData)
{
if (test_server)
@@ -536,6 +548,10 @@ int CInputP2P::Analyze(LPDESC d, BYTE bHeader, const char * c_pData)
case HEADER_GG_CHECK_AWAKENESS:
IamAwake(d, c_pData);
break;
case HEADER_GG_SWITCHBOT:
Switchbot(d, c_pData);
break;
}
return (iExtraLen);
+19
View File
@@ -209,6 +209,10 @@ void CItem::UpdatePacket()
if (!m_pOwner || !m_pOwner->GetDesc())
return;
// PORT: AVA2 switchbot: rolls in that window reach the client as SUBHEADER_GC_SWITCHBOT_UPDATE_ITEM.
if (m_bWindow == SWITCHBOT)
return;
TPacketGCItemUpdate pack;
pack.header = HEADER_GC_ITEM_UPDATE;
@@ -317,6 +321,13 @@ LPITEM CItem::RemoveFromCharacter()
else
pOwner->SetItem(TItemPos(m_bWindow, m_wCell), NULL);
}
else if (m_bWindow == SWITCHBOT) // PORT: AVA2 switchbot window
{
if (m_wCell >= SWITCHBOT_SLOT_COUNT)
sys_err("CItem::RemoveFromCharacter: pos >= SWITCHBOT_SLOT_COUNT");
else
pOwner->SetItem(TItemPos(SWITCHBOT, m_wCell), NULL);
}
else
{
TItemPos cell(INVENTORY, m_wCell);
@@ -362,6 +373,14 @@ bool CItem::AddToCharacter(LPCHARACTER ch, TItemPos Cell)
return false;
}
}
else if (SWITCHBOT == window_type) // PORT: AVA2 switchbot window
{
if (pos >= SWITCHBOT_SLOT_COUNT_REAL)
{
sys_err("CItem::AddToCharacter: switchbot cell overflow: %s to %s cell %d", m_pProto->szName, ch->GetName(), pos);
return false;
}
}
if (ch->GetDesc())
m_dwLastOwnerPID = ch->GetPlayerID();
+3
View File
@@ -241,6 +241,7 @@ class CItem : public CEntity
int GetPendantScrollKind();
bool IsNewRing(); // AVA2 new rings (port_rings.cpp)
void PutNewRingAttributeWithLevel(BYTE bLevel);
void PutPendantAttributeWithLevel(BYTE bLevel); // port_pendant.cpp
bool IsRamadanRing();
void ClearMountAttributeAndAffect();
@@ -339,5 +340,7 @@ EVENTINFO(item_vid_event_info)
};
DWORD GetNewRingJewelVnum(DWORD dwRingVnum); // port_rings.cpp, 0 = none
int GetNewRingAttrMaxValue(BYTE bApply); // port_rings.cpp, 0 = not in the ring pool
int GetPendantAttrMaxValue(BYTE bApply); // port_pendant.cpp, 0 = not in the talisman pool
#endif
+7
View File
@@ -124,6 +124,13 @@ void CItem::PutAttributeWithLevel(BYTE bLevel)
return;
}
// PORT: talismans reroll from their own pool (port_pendant.cpp), as the switchbot's 71302 rolls need.
if (IsTalisman())
{
PutPendantAttributeWithLevel(bLevel);
return;
}
int iAttributeSet = GetAttributeSetIndex();
if (iAttributeSet < 0)
+6
View File
@@ -63,6 +63,7 @@
#include "SpeedServer.h"
// #include "XTrapManager.h"
#include "DragonSoul.h"
#include "port_switchbot.h"
#include <boost/bind.hpp>
#ifndef __WIN32__
#include "limit_time.h"
@@ -239,6 +240,7 @@ unsigned int save_idx = 0;
void PortBossTick();
void PortAttrLockBoot();
void PortSwitchbotBoot();
void heartbeat(LPHEART ht, int pulse)
{
@@ -521,6 +523,7 @@ int main(int argc, char **argv)
CSpeedServerManager SSManager;
DSManager dsManager;
CSwitchbotManager switchbotManager; // PORT: AVA2 switchbot
#ifdef __AUCTION__
AuctionManager auctionManager;
@@ -794,7 +797,10 @@ int start(int argc, char **argv)
// END_OF_LOCALE_SERVICE
if (!g_bAuthServer)
{
PortAttrLockBoot();
PortSwitchbotBoot();
}
#ifdef __WIN32__
// In Windows dev mode, "verbose" option is [on] by default.
+55
View File
@@ -110,6 +110,7 @@ enum
HEADER_CG_DRAGON_SOUL_REFINE = 205,
HEADER_CG_STATE_CHECKER = 206,
HEADER_CG_SASH = 211, // AVA2 sash
HEADER_CG_SWITCHBOT = 171, // AVA2 switchbot (port_switchbot.cpp)
HEADER_CG_CLIENT_VERSION = 0xfd,
HEADER_CG_CLIENT_VERSION2 = 0xf1,
@@ -297,6 +298,7 @@ enum
HEADER_GC_DRAGON_SOUL_REFINE = 209,
HEADER_GC_RESPOND_CHANNELSTATUS = 210,
HEADER_GC_SASH = 215, // AVA2 sash
HEADER_GC_SWITCHBOT = 171, // AVA2 switchbot (port_switchbot.cpp)
/////////////////////////////////////////////////////////////////////////////
@@ -331,6 +333,7 @@ enum
HEADER_GG_PCBANG_UPDATE = 28,
HEADER_GG_CHECK_AWAKENESS = 29,
HEADER_GG_SWITCHBOT = 31, // AVA2 switchbot: table follows the player to another core
};
#pragma pack(1)
@@ -1174,6 +1177,58 @@ typedef struct SPacketSash
DWORD dwMaxAbs;
} TPacketSash;
// AVA2 switchbot (port_switchbot.cpp). CG/GC: header, size, subheader, slot, then the subheader's payload.
struct TPacketGGSwitchbot
{
BYTE bHeader;
WORD wPort;
TSwitchbotTable table;
TPacketGGSwitchbot() : bHeader(HEADER_GG_SWITCHBOT), wPort(0)
{
//table = {};
}
};
enum ECGSwitchbotSubheader
{
SUBHEADER_CG_SWITCHBOT_START, // + TSwitchbotAttributeAlternativeTable[SWITCHBOT_ALTERNATIVE_COUNT]
SUBHEADER_CG_SWITCHBOT_STOP,
};
struct TPacketCGSwitchbot
{
BYTE header;
int size;
BYTE subheader;
BYTE slot;
};
enum EGCSwitchbotSubheader
{
SUBHEADER_GC_SWITCHBOT_UPDATE, // + TSwitchbotTable
SUBHEADER_GC_SWITCHBOT_UPDATE_ITEM, // + TSwitchbotUpdateItem
SUBHEADER_GC_SWITCHBOT_SEND_ATTRIBUTE_INFORMATION, // + TSwitchbottAttributeTable[n]
};
struct TPacketGCSwitchbot
{
BYTE header;
int size;
BYTE subheader;
BYTE slot;
};
// Our item layout (3 sockets, 7 attributes), as in TPacketGCItemSet.
struct TSwitchbotUpdateItem
{
BYTE slot;
DWORD vnum;
WORD count;
long alSockets[ITEM_SOCKET_MAX_NUM];
TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_MAX_NUM];
};
typedef struct packet_item_del
{
BYTE header;
+2
View File
@@ -229,6 +229,7 @@ CPacketInfoCG::CPacketInfoCG()
Set(HEADER_CG_DRAGON_SOUL_REFINE, sizeof(TPacketCGDragonSoulRefine), "DragonSoulRefine", false);
Set(HEADER_CG_STATE_CHECKER, sizeof(BYTE), "ServerStateCheck", false);
Set(HEADER_CG_SASH, sizeof(TPacketSash), "Sash", true);
Set(HEADER_CG_SWITCHBOT, sizeof(TPacketCGSwitchbot), "Switchbot", true);
}
@@ -271,6 +272,7 @@ CPacketInfoGG::CPacketInfoGG()
Set(HEADER_GG_MONARCH_TRANSFER, sizeof(TPacketMonarchGGTransfer), "MonarchTransfer", false);
Set(HEADER_GG_PCBANG_UPDATE, sizeof(TPacketPCBangUpdate), "PCBangUpdate", false);
Set(HEADER_GG_CHECK_AWAKENESS, sizeof(TPacketGGCheckAwakeness), "CheckAwakeness", false);
Set(HEADER_GG_SWITCHBOT, sizeof(TPacketGGSwitchbot), "Switchbot", false);
}
CPacketInfoGG::~CPacketInfoGG()
+1 -1
View File
@@ -45,7 +45,7 @@ ACMD(do_port_features) {
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u rate",request);return;
}
ch->m_portFeatureLastQuery=get_dword_time();
if(kind=="cap" && args.size()==3) {ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 cap %u 1 1023 %lld",request,(long long)get_global_time());return;}
if(kind=="cap" && args.size()==3) {ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 cap %u 1 959 %lld",request,(long long)get_global_time());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) {
+48 -2
View File
@@ -3,8 +3,9 @@
// matching RACE_FLAG_ATT_* (battle.cpp).
// Its random attributes come from AVA2's item_attr "pendant" column. That column is not added to 203's item_attr
// table and ATTRIBUTE_SET_*, which would change the db -> game boot packet. Instead the pool lives here and
// GetAttributeSetIndex() stays -1, so the 40250 switchers, the switchbot and the attribute lock never touch a
// talisman, and drops carry no magic attributes.
// GetAttributeSetIndex() stays -1, so the 40250 switchers and the attribute lock never touch a talisman, and drops
// carry no magic attributes. The switchbot (port_switchbot.cpp) rerolls it with 71302 through ChangeAttribute,
// which PutAttributeWithLevel routes to PutPendantAttributeWithLevel.
// Only the talisman items change its attributes; AVA2 uses 71302 (reroll) and 71301 (add, up to 5). The
// imported 53996 / 53997 (AVA2 generic switcher / adder, which would be free 40250 gear rerolls) act as the same
// talisman reroll / add here, as their zh names say. Messages go to the client as "MTPENDANT <code>"
@@ -106,6 +107,51 @@ namespace
}
}
// Highest value of a talisman attribute, for the switchbot attribute list (port_switchbot.cpp).
int GetPendantAttrMaxValue(BYTE bApply)
{
for (size_t i = 0; i < sizeof(s_aPendantAttr) / sizeof(s_aPendantAttr[0]); ++i)
if (s_aPendantAttr[i].bApply == bApply)
return s_aPendantAttr[i].asValues[ITEM_ATTRIBUTE_MAX_LEVEL - 1];
return 0;
}
// CItem::PutAttributeWithLevel over the talisman pool (bLevel 1..5): CItem::ChangeAttribute, so the switchbot
// rerolls a talisman with 71302 like a 40250 item with a switcher.
void CItem::PutPendantAttributeWithLevel(BYTE bLevel)
{
if (bLevel < 1 || bLevel > ITEM_ATTRIBUTE_MAX_LEVEL)
return;
DWORD dwTotal = 0;
for (size_t i = 0; i < sizeof(s_aPendantAttr) / sizeof(s_aPendantAttr[0]); ++i)
if (!HasAttr(s_aPendantAttr[i].bApply))
dwTotal += s_aPendantAttr[i].dwProb;
if (!dwTotal)
return;
DWORD dwProb = number(1, dwTotal);
for (size_t i = 0; i < sizeof(s_aPendantAttr) / sizeof(s_aPendantAttr[0]); ++i)
{
const PendantAttr & r = s_aPendantAttr[i];
if (HasAttr(r.bApply))
continue;
if (dwProb <= r.dwProb)
{
AddAttribute(r.bApply, r.asValues[bLevel - 1]);
return;
}
dwProb -= r.dwProb;
}
}
bool CItem::IsTalisman()
{
return GetType() == ITEM_ARMOR && GetSubType() == ARMOR_PENDANT;
+11 -1
View File
@@ -4,7 +4,7 @@
// Their random attributes come from AVA2's item_attr_rings table. As with the talismans (port_pendant.cpp), that
// table is not added to 203's item_attr / ATTRIBUTE_SET_*, which would change the db -> game boot packet: the pool
// lives here, GetAttributeSetIndex() stays -1 and PutAttributeWithLevel() branches to it, and the 40250 switchers /
// adders accept rings (char_item.cpp). The switchbot and the rare (6th / 7th) attributes skip rings; AVA2's
// adders accept rings (char_item.cpp). The rare (6th / 7th) attributes skip rings; AVA2's
// item_attr_rare_rings is not ported. Rings drop without attributes (AlterToMagicItem only handles weapons / armor).
#include "stdafx.h"
#include "constants.h"
@@ -71,6 +71,16 @@ DWORD GetNewRingJewelVnum(DWORD dwRingVnum)
return 0;
}
// Highest value of a ring attribute, for the switchbot attribute list (port_switchbot.cpp).
int GetNewRingAttrMaxValue(BYTE bApply)
{
for (size_t i = 0; i < sizeof(s_aRingAttr) / sizeof(s_aRingAttr[0]); ++i)
if (s_aRingAttr[i].bApply == bApply)
return s_aRingAttr[i].asValues[ITEM_ATTRIBUTE_MAX_LEVEL - 1];
return 0;
}
// CItem::PutAttributeWithLevel over the ring pool (bLevel 1..5).
void CItem::PutNewRingAttributeWithLevel(BYTE bLevel)
{
+807
View File
@@ -0,0 +1,807 @@
// PORT: AVA2 ENABLE_SWITCHBOT, from AVA2 game/src/new_switchbot.cpp. Classes, API, packets, the 0.1 s roll
// speed and the CheckItem rule (one configured alternative fully matched within the first 5 attributes; no
// configured alternative counts as a match) are AVA2's. Deviations:
// - Cell 5 (AVA2's hidden 71084 cell) is never used; MoveItem rejects it. Switchers stay in the inventory and
// are taken one per roll, skipping stacks that are being exchanged, locked or sold in the player's shop.
// - Switcher choice follows the manual path (char_item.cpp USE_CHANGE_ATTRIBUTE): a talisman takes only 71302;
// a weapon or body armour without a level limit above 40 takes 71151 / 76023 first; everything else takes
// 71084, then 39028. AVA2 could pick 71151 / 76023 for high-level items and never consumed 39028.
// - A slot stops instead of rolling when its item has no attributes (the manual path refuses that too).
// - Every roll is in ItemLog as SWITCHBOT, with the item id as hint, like CHANGE_ATTRIBUTE.
// - The end / stop messages go to the client as server commands ("switchbot_end <slot>",
// "switchbot_stop <reason>") for localeInfo text, instead of AVA2's numeric locale ids 864 / 865.
// - Leaving the core deletes the table after it is sent (AVA2 leaked it), and a logout that unregisters the last
// active slot stops the roll event.
// - Version gate: EnterGame sends nothing unless the CG_CLIENT_VERSION timestamp is "mt<date>" with
// date >= PORT_SWITCHBOT_CLIENT_VERSION (older clients send __TIMESTAMP__ or "1215955205").
// - The attribute list has two pseudo sets after ATTRIBUTE_SET_MAX_NUM: 8 = rings (port_rings.cpp) and
// 9 = talismans (port_pendant.cpp), whose pools are not in item_attr.
#include "stdafx.h"
#include "constants.h"
#include "port_switchbot.h"
#include "desc.h"
#include "item.h"
#include "item_manager.h"
#include "char_manager.h"
#include "buffer_manager.h"
#include "char.h"
#include "config.h"
#include "p2p.h"
#include "packet.h"
#include "shop.h"
#include "log.h"
#include "db.h"
// Wire sizes the client (UserInterface/Packet.h) mirrors byte for byte.
static_assert(sizeof(TSwitchbotTable) == 220, "TSwitchbotTable");
static_assert(sizeof(TSwitchbotAttributeAlternativeTable) == 15, "TSwitchbotAttributeAlternativeTable");
static_assert(sizeof(TSwitchbottAttributeTable) == 9, "TSwitchbottAttributeTable");
static_assert(sizeof(TSwitchbotUpdateItem) == 40, "TSwitchbotUpdateItem");
static_assert(sizeof(TPacketCGSwitchbot) == 7 && sizeof(TPacketGCSwitchbot) == 7, "switchbot packet header");
static_assert(sizeof(TPacketGGSwitchbot) == 223, "TPacketGGSwitchbot");
namespace
{
const float c_fSpeed = 0.1f;
enum
{
SWITCHBOT_ATTRIBUTE_SET_NEW_RINGS = ATTRIBUTE_SET_MAX_NUM, // 8
SWITCHBOT_ATTRIBUTE_SET_PENDANT, // 9
};
bool ValidPosition(DWORD wCell)
{
return wCell < SWITCHBOT_SLOT_COUNT_REAL;
}
long SwitchbotPasses()
{
const long lPasses = long(PASSES_PER_SEC(c_fSpeed));
return lPasses > 0 ? lPasses : 1;
}
bool IsLowLevelSwitchTarget(LPITEM pkItem)
{
if (!(pkItem->GetType() == ITEM_WEAPON || (pkItem->GetType() == ITEM_ARMOR && pkItem->GetSubType() == ARMOR_BODY)))
return false;
for (int i = 0; i < ITEM_LIMIT_MAX_NUM; ++i)
if (pkItem->GetLimitType(i) == LIMIT_LEVEL && pkItem->GetLimitValue(i) > 40)
return false;
return true;
}
// CHARACTER::FindSpecifyItem over stacks the player can spend right now.
LPITEM FindUsableSwitcher(LPCHARACTER ch, DWORD dwVnum)
{
LPSHOP pkShop = ch->GetMyShop();
for (int i = 0; i < INVENTORY_MAX_NUM; ++i)
{
LPITEM item = ch->GetInventoryItem(i);
if (!item || item->GetVnum() != dwVnum || item->GetCount() < SWITCHBOT_PRICE_AMOUNT)
continue;
if (item->IsExchanging() || item->isLocked())
continue;
if (pkShop && pkShop->IsSellingItem(item->GetID()))
continue;
return item;
}
return NULL;
}
LPITEM SelectSwitcher(LPCHARACTER ch, LPITEM pkItem)
{
if (pkItem->IsTalisman())
return FindUsableSwitcher(ch, 71302);
static const DWORD s_adwLow[] = { 71151, 76023 };
static const DWORD s_adwNormal[] = { 71084, 39028 };
if (IsLowLevelSwitchTarget(pkItem))
for (size_t i = 0; i < sizeof(s_adwLow) / sizeof(s_adwLow[0]); ++i)
if (LPITEM scroll = FindUsableSwitcher(ch, s_adwLow[i]))
return scroll;
for (size_t i = 0; i < sizeof(s_adwNormal) / sizeof(s_adwNormal[0]); ++i)
if (LPITEM scroll = FindUsableSwitcher(ch, s_adwNormal[i]))
return scroll;
return NULL;
}
void WriteAttribute(TEMP_BUFFER& buf, BYTE bSet, int iApply, int iMax)
{
TSwitchbottAttributeTable table = {};
table.attribute_set = bSet;
table.apply_num = iApply;
table.max_value = iMax;
buf.write(&table, sizeof(table));
}
}
bool SwitchbotHelper::IsValidItem(LPITEM pkItem)
{
if (!pkItem)
return false;
switch (pkItem->GetType())
{
case ITEM_NEW_RINGS:
case ITEM_WEAPON:
return true;
case ITEM_ARMOR:
switch (pkItem->GetSubType())
{
case ARMOR_BODY:
case ARMOR_HEAD:
case ARMOR_SHIELD:
case ARMOR_WRIST:
case ARMOR_FOOTS:
case ARMOR_NECK:
case ARMOR_EAR:
case ARMOR_PENDANT:
return true;
}
return false;
default:
return false;
}
}
CSwitchbot::CSwitchbot() : m_pkSwitchEvent(NULL), m_isWarping(false)
{
}
CSwitchbot::~CSwitchbot()
{
if (m_pkSwitchEvent)
event_cancel(&m_pkSwitchEvent);
m_pkSwitchEvent = NULL;
}
void CSwitchbot::RegisterItem(WORD wCell, DWORD item_id)
{
if (!ValidPosition(wCell))
return;
m_table.items[wCell] = item_id;
}
void CSwitchbot::UnregisterItem(WORD wCell)
{
if (!ValidPosition(wCell))
return;
m_table.items[wCell] = 0;
m_table.active[wCell] = false;
m_table.finished[wCell] = false;
memset(&m_table.alternatives[wCell], 0, sizeof(m_table.alternatives[wCell]));
}
void CSwitchbot::SetAttributes(BYTE slot, const std::vector<TSwitchbotAttributeAlternativeTable>& vec_alternatives)
{
if (!ValidPosition(slot) || vec_alternatives.size() < SWITCHBOT_ALTERNATIVE_COUNT)
return;
for (BYTE alternative = 0; alternative < SWITCHBOT_ALTERNATIVE_COUNT; ++alternative)
{
for (BYTE attrIdx = 0; attrIdx < SWITCHBOT_NORM_ATTR_NUM; ++attrIdx)
{
m_table.alternatives[slot][alternative].attributes[attrIdx].bType = vec_alternatives[alternative].attributes[attrIdx].bType;
m_table.alternatives[slot][alternative].attributes[attrIdx].sValue = vec_alternatives[alternative].attributes[attrIdx].sValue;
}
}
}
void CSwitchbot::SetActive(BYTE slot, bool active)
{
if (!ValidPosition(slot))
return;
m_table.active[slot] = active;
m_table.finished[slot] = false;
}
EVENTINFO(TSwitchbotEventInfo)
{
CSwitchbot* pkSwitchbot;
TSwitchbotEventInfo() : pkSwitchbot(NULL)
{
}
};
EVENTFUNC(switchbot_event)
{
TSwitchbotEventInfo* info = dynamic_cast<TSwitchbotEventInfo*>(event->info);
if (info == NULL)
{
sys_err("switchbot_event> <Factor> Info Null pointer");
return 0;
}
if (!info->pkSwitchbot)
{
sys_err("switchbot_event> <Factor> Switchbot Null pointer");
return 0;
}
info->pkSwitchbot->SwitchItems();
return SwitchbotPasses();
}
void CSwitchbot::Start()
{
TSwitchbotEventInfo* info = AllocEventInfo<TSwitchbotEventInfo>();
info->pkSwitchbot = this;
m_pkSwitchEvent = event_create(switchbot_event, info, SwitchbotPasses());
CSwitchbotManager::Instance().SendSwitchbotUpdate(m_table.player_id);
}
void CSwitchbot::Stop()
{
if (m_pkSwitchEvent)
{
event_cancel(&m_pkSwitchEvent);
m_pkSwitchEvent = NULL;
}
memset(&m_table.active, 0, sizeof(m_table.active));
CSwitchbotManager::Instance().SendSwitchbotUpdate(m_table.player_id);
for (BYTE bSlot = 0; bSlot < SWITCHBOT_SLOT_COUNT_REAL; ++bSlot)
{
LPITEM pkItem = ITEM_MANAGER::Instance().Find(m_table.items[bSlot]);
if (!pkItem)
continue;
LPCHARACTER pkOwner = pkItem->GetOwner();
if (!pkOwner)
return;
SendItemUpdate(pkOwner, bSlot, pkItem);
}
}
void CSwitchbot::Pause()
{
if (m_pkSwitchEvent)
{
event_cancel(&m_pkSwitchEvent);
m_pkSwitchEvent = NULL;
}
for (BYTE bSlot = 0; bSlot < SWITCHBOT_SLOT_COUNT_REAL; ++bSlot)
{
LPITEM pkItem = ITEM_MANAGER::Instance().Find(m_table.items[bSlot]);
if (!pkItem)
continue;
LPCHARACTER pkOwner = pkItem->GetOwner();
if (!pkOwner)
return;
SendItemUpdate(pkOwner, bSlot, pkItem);
}
}
bool CSwitchbot::IsActive(BYTE slot)
{
if (!ValidPosition(slot))
return false;
return m_table.active[slot];
}
bool CSwitchbot::HasActiveSlots()
{
for (int i = 0; i < SWITCHBOT_SLOT_COUNT_REAL; ++i)
if (m_table.active[i])
return true;
return false;
}
bool CSwitchbot::IsSwitching()
{
return m_pkSwitchEvent != NULL;
}
// AVA2's success / out-of-switchers tail: deactivate the slot, stop when it was the last one, refresh the client.
void CSwitchbot::FinishSlot(LPCHARACTER ch, BYTE slot, LPITEM item, bool finished)
{
SetActive(slot, false);
m_table.finished[slot] = finished;
if (!HasActiveSlots())
Stop();
else
CSwitchbotManager::Instance().SendSwitchbotUpdate(m_table.player_id);
SendItemUpdate(ch, slot, item);
}
void CSwitchbot::SwitchItems()
{
for (BYTE bSlot = 0; bSlot < SWITCHBOT_SLOT_COUNT_REAL; ++bSlot)
{
if (!m_table.active[bSlot])
continue;
m_table.finished[bSlot] = false;
LPITEM pkItem = ITEM_MANAGER::Instance().Find(m_table.items[bSlot]);
if (!pkItem)
continue;
LPCHARACTER pkOwner = pkItem->GetOwner();
if (!pkOwner)
return;
if (pkOwner->GetPlayerID() != m_table.player_id || pkItem->GetWindow() != SWITCHBOT || pkItem->GetCell() != bSlot)
{
sys_err("switchbot: item %u is no longer in slot %d of player %u", m_table.items[bSlot], bSlot, m_table.player_id);
UnregisterItem(bSlot);
continue;
}
if (CheckItem(pkItem, bSlot))
{
pkOwner->ChatPacket(CHAT_TYPE_COMMAND, "switchbot_end %d", bSlot);
FinishSlot(pkOwner, bSlot, pkItem, true);
continue;
}
if (!pkItem->GetAttributeCount() || (pkItem->GetAttributeSetIndex() < 0 && !pkItem->IsNewRing() && !pkItem->IsTalisman()))
{
pkOwner->ChatPacket(CHAT_TYPE_COMMAND, "switchbot_stop noattr %d", bSlot);
FinishSlot(pkOwner, bSlot, pkItem, false);
continue;
}
LPITEM pkScroll = SelectSwitcher(pkOwner, pkItem);
if (!pkScroll)
{
pkOwner->ChatPacket(CHAT_TYPE_COMMAND, "switchbot_stop nochanger %d", bSlot);
FinishSlot(pkOwner, bSlot, pkItem, false);
return;
}
char szHint[21];
snprintf(szHint, sizeof(szHint), "%u", pkItem->GetID());
LogManager::instance().ItemLog(pkOwner, pkScroll, "SWITCHBOT", szHint);
pkScroll->SetCount(pkScroll->GetCount() - SWITCHBOT_PRICE_AMOUNT);
pkItem->ChangeAttribute();
}
}
bool CSwitchbot::CheckItem(LPITEM pkItem, BYTE slot)
{
if (!ValidPosition(slot) || !pkItem)
return false;
bool checked = false;
for (int i = 0; i < SWITCHBOT_ALTERNATIVE_COUNT; ++i)
{
const TSwitchbotAttributeAlternativeTable& alternative = m_table.alternatives[slot][i];
if (!alternative.IsConfigured())
continue;
BYTE configuredAttrCount = 0;
BYTE correctAttrCount = 0;
for (int j = 0; j < SWITCHBOT_NORM_ATTR_NUM; ++j)
{
const TPlayerItemAttribute& destAttr = alternative.attributes[j];
if (!destAttr.bType || !destAttr.sValue)
continue;
++configuredAttrCount;
for (BYTE attrIdx = 0; attrIdx < SWITCHBOT_NORM_ATTR_NUM; ++attrIdx)
{
const TPlayerItemAttribute& curAttr = pkItem->GetAttribute(attrIdx);
if (curAttr.bType != destAttr.bType || curAttr.sValue < destAttr.sValue)
continue;
++correctAttrCount;
break;
}
}
checked = true;
if (configuredAttrCount == correctAttrCount)
return true;
}
if (!checked)
return true;
return false;
}
void CSwitchbot::SendItemUpdate(LPCHARACTER ch, BYTE slot, LPITEM item)
{
LPDESC desc = ch->GetDesc();
if (!desc)
return;
TPacketGCSwitchbot pack;
pack.header = HEADER_GC_SWITCHBOT;
pack.subheader = SUBHEADER_GC_SWITCHBOT_UPDATE_ITEM;
pack.size = sizeof(TPacketGCSwitchbot) + sizeof(TSwitchbotUpdateItem);
pack.slot = slot;
TSwitchbotUpdateItem update = {};
update.slot = slot;
update.vnum = item->GetVnum();
update.count = item->GetCount();
thecore_memcpy(update.alSockets, item->GetSockets(), sizeof(update.alSockets));
thecore_memcpy(update.aAttr, item->GetAttributes(), sizeof(update.aAttr));
TEMP_BUFFER tmp_buf;
tmp_buf.write(&pack, sizeof(pack));
tmp_buf.write(&update, sizeof(update));
desc->Packet(tmp_buf.read_peek(), tmp_buf.size());
}
CSwitchbotManager::~CSwitchbotManager()
{
for (std::map<DWORD, CSwitchbot*>::iterator it = m_map_Switchbots.begin(); it != m_map_Switchbots.end(); ++it)
delete it->second;
m_map_Switchbots.clear();
}
void CSwitchbotManager::RegisterItem(DWORD player_id, DWORD item_id, WORD wCell)
{
if (!ValidPosition(wCell))
return;
CSwitchbot* pkSwitchbot = FindSwitchbot(player_id);
if (!pkSwitchbot)
{
pkSwitchbot = new CSwitchbot();
pkSwitchbot->SetPlayerId(player_id);
m_map_Switchbots.insert(std::make_pair(player_id, pkSwitchbot));
}
if (pkSwitchbot->IsWarping())
return;
pkSwitchbot->RegisterItem(wCell, item_id);
SendSwitchbotUpdate(player_id);
}
void CSwitchbotManager::UnregisterItem(DWORD player_id, WORD wCell)
{
if (!ValidPosition(wCell))
return;
CSwitchbot* pkSwitchbot = FindSwitchbot(player_id);
if (!pkSwitchbot)
return;
if (pkSwitchbot->IsWarping())
return;
pkSwitchbot->UnregisterItem(wCell);
if (!pkSwitchbot->HasActiveSlots() && pkSwitchbot->IsSwitching())
pkSwitchbot->Stop();
else
SendSwitchbotUpdate(player_id);
}
void CSwitchbotManager::Start(DWORD player_id, BYTE slot, const std::vector<TSwitchbotAttributeAlternativeTable>& vec_alternatives)
{
if (!ValidPosition(slot))
return;
CSwitchbot* pkSwitchbot = FindSwitchbot(player_id);
if (!pkSwitchbot)
{
sys_err("No Switchbot found for player_id %u slot %d", player_id, slot);
return;
}
if (pkSwitchbot->IsActive(slot))
{
sys_err("Switchbot slot %d already running for player_id %u", slot, player_id);
return;
}
if (!pkSwitchbot->GetTable().items[slot])
return;
pkSwitchbot->SetActive(slot, true);
pkSwitchbot->SetAttributes(slot, vec_alternatives);
if (pkSwitchbot->HasActiveSlots() && !pkSwitchbot->IsSwitching())
pkSwitchbot->Start();
else
SendSwitchbotUpdate(player_id);
}
void CSwitchbotManager::Stop(DWORD player_id, BYTE slot)
{
if (!ValidPosition(slot))
return;
CSwitchbot* pkSwitchbot = FindSwitchbot(player_id);
if (!pkSwitchbot)
{
sys_err("No Switchbot found for player_id %u slot %d", player_id, slot);
return;
}
if (!pkSwitchbot->IsActive(slot))
{
sys_err("Switchbot slot %d is not running for player_id %u", slot, player_id);
return;
}
pkSwitchbot->SetActive(slot, false);
if (!pkSwitchbot->HasActiveSlots() && pkSwitchbot->IsSwitching())
pkSwitchbot->Stop();
else
SendSwitchbotUpdate(player_id);
}
bool CSwitchbotManager::IsActive(DWORD player_id, BYTE slot)
{
if (!ValidPosition(slot))
return false;
CSwitchbot* pkSwitchbot = FindSwitchbot(player_id);
if (!pkSwitchbot)
return false;
return pkSwitchbot->IsActive(slot);
}
bool CSwitchbotManager::IsWarping(DWORD player_id)
{
CSwitchbot* pkSwitchbot = FindSwitchbot(player_id);
if (!pkSwitchbot)
return false;
return pkSwitchbot->IsWarping();
}
void CSwitchbotManager::SetIsWarping(DWORD player_id, bool warping)
{
CSwitchbot* pkSwitchbot = FindSwitchbot(player_id);
if (!pkSwitchbot)
return;
// PORT: the warp logout destroys the items; EnterGame starts the event again.
if (warping)
pkSwitchbot->Pause();
pkSwitchbot->SetIsWarping(warping);
}
CSwitchbot* CSwitchbotManager::FindSwitchbot(DWORD player_id)
{
std::map<DWORD, CSwitchbot*>::iterator it = m_map_Switchbots.find(player_id);
if (it == m_map_Switchbots.end())
return NULL;
return it->second;
}
void CSwitchbotManager::P2PSendSwitchbot(DWORD player_id, WORD wTargetPort)
{
CSwitchbot* pkSwitchbot = FindSwitchbot(player_id);
if (!pkSwitchbot)
return;
pkSwitchbot->Pause();
m_map_Switchbots.erase(player_id);
TPacketGGSwitchbot pack;
pack.wPort = wTargetPort;
pack.table = pkSwitchbot->GetTable();
P2P_MANAGER::Instance().Send(&pack, sizeof(pack));
delete pkSwitchbot;
}
void CSwitchbotManager::P2PReceiveSwitchbot(const TSwitchbotTable& table)
{
CSwitchbot* pkSwitchbot = FindSwitchbot(table.player_id);
if (!pkSwitchbot)
{
pkSwitchbot = new CSwitchbot();
m_map_Switchbots.insert(std::make_pair(table.player_id, pkSwitchbot));
}
pkSwitchbot->SetTable(table);
// The items arrive with the login before EnterGame clears this; RegisterItem keeps the received table.
pkSwitchbot->SetIsWarping(true);
}
void CSwitchbotManager::SendItemAttributeInformations(LPCHARACTER ch)
{
if (!ch)
return;
LPDESC desc = ch->GetDesc();
if (!desc)
return;
TPacketGCSwitchbot pack;
pack.header = HEADER_GC_SWITCHBOT;
pack.subheader = SUBHEADER_GC_SWITCHBOT_SEND_ATTRIBUTE_INFORMATION;
pack.size = sizeof(TPacketGCSwitchbot);
pack.slot = 0;
TEMP_BUFFER buf;
for (BYTE bAttributeSet = 0; bAttributeSet < ATTRIBUTE_SET_MAX_NUM; ++bAttributeSet)
{
for (int iApplyNum = 0; iApplyNum < MAX_APPLY_NUM; ++iApplyNum)
{
const TItemAttrTable& r = g_map_itemAttr[iApplyNum];
const BYTE max = r.bMaxLevelBySet[bAttributeSet];
if (max > 0)
WriteAttribute(buf, bAttributeSet, iApplyNum, r.lValues[MIN(max, ITEM_ATTRIBUTE_MAX_LEVEL) - 1]);
}
}
for (int iApplyNum = 0; iApplyNum < MAX_APPLY_NUM; ++iApplyNum)
if (const int iMax = GetNewRingAttrMaxValue(BYTE(iApplyNum)))
WriteAttribute(buf, SWITCHBOT_ATTRIBUTE_SET_NEW_RINGS, iApplyNum, iMax);
for (int iApplyNum = 0; iApplyNum < MAX_APPLY_NUM; ++iApplyNum)
if (const int iMax = GetPendantAttrMaxValue(BYTE(iApplyNum)))
WriteAttribute(buf, SWITCHBOT_ATTRIBUTE_SET_PENDANT, iApplyNum, iMax);
if (buf.size())
{
pack.size += buf.size();
desc->BufferedPacket(&pack, sizeof(pack));
desc->Packet(buf.read_peek(), buf.size());
}
else
desc->Packet(&pack, sizeof(pack));
}
void CSwitchbotManager::SendSwitchbotUpdate(DWORD player_id)
{
CSwitchbot* pkSwitchbot = FindSwitchbot(player_id);
if (!pkSwitchbot)
return;
LPCHARACTER ch = CHARACTER_MANAGER::Instance().FindByPID(player_id);
if (!ch)
return;
LPDESC d = ch->GetDesc();
if (!d)
return;
const TSwitchbotTable& table = pkSwitchbot->GetTable();
TPacketGCSwitchbot pack;
pack.header = HEADER_GC_SWITCHBOT;
pack.subheader = SUBHEADER_GC_SWITCHBOT_UPDATE;
pack.size = sizeof(TPacketGCSwitchbot) + sizeof(TSwitchbotTable);
pack.slot = 0;
d->BufferedPacket(&pack, sizeof(pack));
d->Packet(&table, sizeof(table));
}
bool SwitchbotHelper::IsClientSupported(LPCHARACTER ch)
{
LPDESC d = ch ? ch->GetDesc() : NULL;
const char* c_pszVersion = d ? d->GetClientVersion() : "";
return c_pszVersion[0] == 'm' && c_pszVersion[1] == 't' && atoi(c_pszVersion + 2) >= PORT_SWITCHBOT_CLIENT_VERSION;
}
void CSwitchbotManager::EnterGame(LPCHARACTER ch)
{
SetIsWarping(ch->GetPlayerID(), false);
// PORT: version gate. An older client has no GC_SWITCHBOT handler; it never fills the window either.
if (!SwitchbotHelper::IsClientSupported(ch))
return;
SendItemAttributeInformations(ch);
// A table kept over a warp (or received from another core) only keeps slots whose item is still there.
if (CSwitchbot* pkSwitchbot = FindSwitchbot(ch->GetPlayerID()))
{
for (BYTE bSlot = 0; bSlot < SWITCHBOT_SLOT_COUNT_REAL; ++bSlot)
{
LPITEM pkItem = ch->GetItem(TItemPos(SWITCHBOT, bSlot));
if (!pkItem)
pkSwitchbot->UnregisterItem(bSlot);
else if (pkSwitchbot->GetTable().items[bSlot] != pkItem->GetID())
{
pkSwitchbot->UnregisterItem(bSlot);
pkSwitchbot->RegisterItem(bSlot, pkItem->GetID());
}
}
}
SendSwitchbotUpdate(ch->GetPlayerID());
CSwitchbot* pkSwitchbot = FindSwitchbot(ch->GetPlayerID());
if (pkSwitchbot && pkSwitchbot->HasActiveSlots() && !pkSwitchbot->IsSwitching())
pkSwitchbot->Start();
}
void PortSwitchbotBoot()
{
std::unique_ptr<SQLMsg> msg(DBManager::instance().DirectQuery("SHOW COLUMNS FROM item LIKE 'window'"));
if (msg->uiSQLErrno || !msg->Get()->uiNumRows)
{
sys_err("PortSwitchbotBoot: cannot read item.window (errno %u)", msg->uiSQLErrno);
return;
}
MYSQL_ROW row = mysql_fetch_row(msg->Get()->pSQLResult);
if (row[1] && strstr(row[1], "'SWITCHBOT'"))
return;
std::unique_ptr<SQLMsg> alter(DBManager::instance().DirectQuery(
"ALTER TABLE item MODIFY window enum('INVENTORY','EQUIPMENT','SAFEBOX','MALL','DRAGON_SOUL_INVENTORY',"
"'BELT_INVENTORY','SWITCHBOT') NOT NULL DEFAULT 'INVENTORY'"));
if (alter->uiSQLErrno)
sys_err("PortSwitchbotBoot: cannot add SWITCHBOT to item.window (errno %u)", alter->uiSQLErrno);
else
sys_log(0, "PortSwitchbotBoot: added SWITCHBOT to item.window");
}
+69 -226
View File
@@ -1,248 +1,91 @@
#ifndef METIN2_PORT_SWITCHBOT_H
#define METIN2_PORT_SWITCHBOT_H
// 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"
// PORT: AVA2 ENABLE_SWITCHBOT (new_switchbot.{h,cpp}): items placed in the SWITCHBOT window (cells 0..4) are
// rerolled with switchers from the inventory until one configured alternative matches. Same classes, API,
// packets and speed as AVA2; the deviations are listed at the top of port_switchbot.cpp.
#include "../../common/tables.h"
static const unsigned kPortSwitchAlternatives=2, kPortSwitchTargets=5, kPortSwitchLimit=1000;
static const unsigned kPortSwitchAddonSkillMax=30, kPortSwitchAddonNormalMax=65; // CItemAddonManager::ApplyAddonTo bounds.
// PORT: clients from this protocol date on send "mt<date>" as their CG_CLIENT_VERSION timestamp
// (metin2-client PythonNetworkStreamPhaseGame.cpp SendClientVersionPacket).
enum { PORT_SWITCHBOT_CLIENT_VERSION = 20261016 };
struct PortSwitchTarget {unsigned apply;int value;};
struct PortSwitchbot {
DWORD pid=0,item=0,scroll=0;unsigned limit=0,rolls=0;VID vid;
std::vector<PortSwitchTarget> alternatives[kPortSwitchAlternatives];
LPEVENT event;
class SwitchbotHelper
{
public:
static bool IsValidItem(LPITEM pkItem);
static bool IsClientSupported(LPCHARACTER ch); // PORT: CG_CLIENT_VERSION timestamp gate
};
static std::map<DWORD,PortSwitchbot> g_portSwitchbots;
static bool PortSwitchNumber(const std::string& text,unsigned& value) {
if(text.empty() || text.size()>10)return false;
unsigned long long result=0;
for(char c:text){if(c<'0'||c>'9')return false;result=result*10+(c-'0');}
if(result>0xffffffffull)return false;
value=unsigned(result);return true;
}
class CSwitchbot
{
public:
CSwitchbot();
~CSwitchbot();
// Attribute types a reroll of this item can produce, with the highest value each can reach.
static std::vector<std::pair<unsigned,int> > PortSwitchAllowed(LPITEM item) {
std::vector<std::pair<unsigned,int> > allowed;
const int set=item->GetAttributeSetIndex();
if(set<0)return allowed;
const TItemTable* proto=item->GetProto();
for(unsigned apply=0;apply<MAX_APPLY_NUM;++apply) {
auto it=g_map_itemAttr.find(apply);
if(it==g_map_itemAttr.end())continue;
const unsigned level=it->second.bMaxLevelBySet[set];
if(!level)continue;
bool base=false;
for(int i=0;i<ITEM_APPLY_MAX_NUM;++i)base|=proto && proto->aApplies[i].bType==apply;
const long value=it->second.lValues[(level>5?5:level)-1];
if(!base && value>0)allowed.push_back(std::make_pair(apply,int(value)));
}
if(proto && proto->sAddonType) {
allowed.push_back(std::make_pair(unsigned(APPLY_SKILL_DAMAGE_BONUS),int(kPortSwitchAddonSkillMax)));
allowed.push_back(std::make_pair(unsigned(APPLY_NORMAL_HIT_DAMAGE_BONUS),int(kPortSwitchAddonNormalMax)));
}
return allowed;
}
void SetTable(const TSwitchbotTable& table) { m_table = table; }
const TSwitchbotTable& GetTable() const { return m_table; }
// AVA2 CheckItem semantics over the five normal slots: any one configured alternative fully satisfied.
static bool PortSwitchMatches(LPITEM item,const PortSwitchbot& bot) {
for(const auto& alternative:bot.alternatives) {
if(alternative.empty())continue;
bool all=true;
for(const auto& target:alternative) {
bool found=false;
for(int i=0;i<ITEM_MANAGER::MAX_NORM_ATTR_NUM && !found;++i) {
const TPlayerItemAttribute& attr=item->GetAttribute(i);
found=attr.bType==target.apply && attr.sValue>=target.value;
}
all&=found;
}
if(all)return true;
}
return false;
}
void SetPlayerId(DWORD player_id) { m_table.player_id = player_id; }
DWORD GetPlayerId() const { return m_table.player_id; }
static bool PortSwitchBusy(LPCHARACTER ch) {
return ch->IsDead() || ch->IsWarping() || !ch->CanHandleItem() || ch->GetExchange() || ch->GetMyShop() ||
ch->GetShopOwner() || ch->IsOpenSafebox() || ch->IsCubeOpen();
}
void RegisterItem(WORD wCell, DWORD item_id);
void UnregisterItem(WORD wCell);
void SetAttributes(BYTE slot, const std::vector<TSwitchbotAttributeAlternativeTable>& vec_alternatives);
static LPITEM PortSwitchItem(LPCHARACTER ch,const PortSwitchbot& bot) {
LPITEM item=ITEM_MANAGER::instance().Find(bot.item);
if(!item || item->GetOwner()!=ch || item->GetWindow()!=INVENTORY || item->GetCell()>=INVENTORY_MAX_NUM || item->IsEquipped())return NULL;
return item;
}
void SetActive(BYTE slot, bool active);
bool IsActive(BYTE slot);
bool HasActiveSlots();
bool IsSwitching();
bool IsWarping() { return m_isWarping; }
void SetIsWarping(bool warping) { m_isWarping = warping; }
static bool PortSwitchScroll(LPITEM scroll) {
return scroll && scroll->GetVnum()!=50348 && scroll->GetVnum()!=50349 &&
scroll->GetType()==ITEM_USE && scroll->GetSubType()==USE_CHANGE_ATTRIBUTE &&
!scroll->IsCostumeEnchant() && !scroll->GetPendantScrollKind();
}
void Start();
void Stop();
void Pause();
static void PortSwitchState(LPCHARACTER ch,const PortSwitchbot* bot,bool active,const char* reason) {
LPITEM item=bot?PortSwitchItem(ch,*bot):NULL;
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 state %u %u %u %u %u %u %d %s",unsigned(active),item?unsigned(item->GetCell()):0u,
item?unsigned(item->GetVnum()):0u,bot?bot->rolls:0u,bot?bot->limit:0u,bot?unsigned(bot->scroll):0u,
bot?ch->CountSpecifyItem(bot->scroll):0,reason);
}
void SwitchItems();
bool CheckItem(LPITEM pkItem, BYTE slot);
// One roll. Returns NULL to keep running, otherwise the stop reason.
static const char* PortSwitchStep(LPCHARACTER ch,PortSwitchbot& bot) {
if(PortSwitchBusy(ch))return "busy";
LPITEM item=PortSwitchItem(ch,bot);
if(!item)return "item_gone";
if(PortSwitchMatches(item,bot))return "matched";
if(bot.rolls>=bot.limit)return "limit";
LPITEM scroll=ch->FindSpecifyItem(bot.scroll);
if(!PortSwitchScroll(scroll))return "no_scroll";
const int before=ch->CountSpecifyItem(bot.scroll);
ch->m_portQuietInfo=true;ch->m_portLastInfo.clear();
ch->UseItem(TItemPos(INVENTORY,scroll->GetCell()),TItemPos(INVENTORY,item->GetCell()));
ch->m_portQuietInfo=false;
// Success is judged by the original path consuming exactly one scroll, not by its return value.
if(ch->CountSpecifyItem(bot.scroll)!=before-1) {
if(!ch->m_portLastInfo.empty())ch->ChatPacket(CHAT_TYPE_INFO,"%s",ch->m_portLastInfo.c_str());
return "rejected";
}
++bot.rolls;
item=PortSwitchItem(ch,bot);
if(!item)return "item_gone";
return PortSwitchMatches(item,bot)?"matched":bot.rolls>=bot.limit?"limit":NULL;
}
void SendItemUpdate(LPCHARACTER ch, BYTE slot, LPITEM item);
EVENTINFO(PortSwitchbotInfo){DWORD pid;PortSwitchbotInfo():pid(0){}};
protected:
void FinishSlot(LPCHARACTER ch, BYTE slot, LPITEM item, bool finished);
EVENTFUNC(port_switchbot_event) {
PortSwitchbotInfo* info=dynamic_cast<PortSwitchbotInfo*>(event->info);
if(!info)return 0;
auto it=g_portSwitchbots.find(info->pid);
if(it==g_portSwitchbots.end())return 0;
PortSwitchbot& bot=it->second;
LPCHARACTER ch=CHARACTER_MANAGER::instance().Find(bot.vid);
// A new instance after logout or warp carries a new VID; the bot does not follow it.
if(!ch || ch->GetPlayerID()!=bot.pid || !ch->GetDesc()) {bot.event=NULL;g_portSwitchbots.erase(it);return 0;}
const char* reason=PortSwitchStep(ch,bot);
if(!reason) {PortSwitchState(ch,&bot,true,"running");return PASSES_PER_SEC(1)/4;}
PortSwitchState(ch,&bot,false,reason);
bot.event=NULL;g_portSwitchbots.erase(it);
return 0;
}
TSwitchbotTable m_table;
LPEVENT m_pkSwitchEvent;
bool m_isWarping;
};
static void PortSwitchStop(LPCHARACTER ch,const char* reason) {
auto it=g_portSwitchbots.find(ch->GetPlayerID());
if(it==g_portSwitchbots.end()) {PortSwitchState(ch,NULL,false,"idle");return;}
if(it->second.event)event_cancel(&it->second.event);
PortSwitchState(ch,&it->second,false,reason);
g_portSwitchbots.erase(it);
}
class CSwitchbotManager : public singleton<CSwitchbotManager>
{
public:
CSwitchbotManager() { Initialize(); }
virtual ~CSwitchbotManager();
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));
}
void Initialize() { m_map_Switchbots.clear(); }
void RegisterItem(DWORD player_id, DWORD item_id, WORD wCell);
void UnregisterItem(DWORD player_id, WORD wCell);
void Start(DWORD player_id, BYTE slot, const std::vector<TSwitchbotAttributeAlternativeTable>& vec_alternatives);
void Stop(DWORD player_id, BYTE slot);
// 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;
const unsigned old=PortAttrLockEffective(PortAttrLockGet(item),PortAttrFilled(item),addon);
const bool removing=slot<5 && (old>>slot&1);
if(const char* error=PortAttrLockUse(ch,item,slot,ch->FindSpecifyItem(removing?50349:50348)))return error;
PortSwitchLockLine(ch,item);
return NULL;
}
bool IsActive(DWORD player_id, BYTE slot);
bool IsWarping(DWORD player_id);
void SetIsWarping(DWORD player_id, bool warping);
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;}
if(item->GetType()==ITEM_COSTUME || item->GetAttributeSetIndex()<0){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 error attrs no_attr");return;}
auto allowed=PortSwitchAllowed(item);
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 attrs %u %u %u",cell,unsigned(item->GetVnum()),unsigned(allowed.size()));
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);
}
CSwitchbot* FindSwitchbot(DWORD player_id);
// start CELL SCROLL LIMIT N1 (APPLY VALUE)*N1 [N2 (APPLY VALUE)*N2]
static const char* PortSwitchStart(LPCHARACTER ch,const std::vector<std::string>& args) {
unsigned cell=0,scrollVnum=0,limit=0;
if(args.size()<6 || !PortSwitchNumber(args[2],cell) || !PortSwitchNumber(args[3],scrollVnum) ||
!PortSwitchNumber(args[4],limit) || !limit || limit>kPortSwitchLimit)return "invalid";
if(g_portSwitchbots.count(ch->GetPlayerID()))return "running";
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 || !item->GetAttributeCount())return "no_attr";
if(!PortSwitchScroll(ch->FindSpecifyItem(scrollVnum)))return "scroll";
PortSwitchbot bot;bot.pid=ch->GetPlayerID();bot.vid=ch->GetVID();bot.item=item->GetID();bot.scroll=scrollVnum;bot.limit=limit;
const auto allowed=PortSwitchAllowed(item);
size_t at=5;
for(unsigned alt=0;alt<kPortSwitchAlternatives && at<args.size();++alt) {
unsigned count=0;
if(!PortSwitchNumber(args[at++],count) || !count || count>kPortSwitchTargets || at+count*2>args.size())return "invalid";
for(unsigned i=0;i<count;++i,at+=2) {
unsigned apply=0,value=0;
if(!PortSwitchNumber(args[at],apply) || !PortSwitchNumber(args[at+1],value) || !value)return "invalid";
int max=0;
for(const auto& a:allowed)if(a.first==apply)max=a.second;
if(!max || value>unsigned(max))return "target";
for(const auto& t:bot.alternatives[alt])if(t.apply==apply)return "target";
bot.alternatives[alt].push_back(PortSwitchTarget{apply,int(value)});
}
}
if(at!=args.size())return "invalid";
if(PortSwitchMatches(item,bot)) {PortSwitchState(ch,&bot,false,"matched");return NULL;}
PortSwitchbot& stored=g_portSwitchbots[bot.pid];stored=bot;
PortSwitchbotInfo* info=AllocEventInfo<PortSwitchbotInfo>();info->pid=bot.pid;
stored.event=event_create(port_switchbot_event,info,PASSES_PER_SEC(1)/4);
PortSwitchState(ch,&stored,true,"running");
return NULL;
}
void P2PSendSwitchbot(DWORD player_id, WORD wTargetPort);
void P2PReceiveSwitchbot(const TSwitchbotTable& table);
void SendItemAttributeInformations(LPCHARACTER ch);
void SendSwitchbotUpdate(DWORD player_id);
void EnterGame(LPCHARACTER ch);
protected:
std::map<DWORD, CSwitchbot*> m_map_Switchbots;
};
void PortSwitchbotBoot(); // adds 'SWITCHBOT' to player.item.window when it is missing
ACMD(do_port_switchbot) {
if(!ch || !ch->IsPC() || !ch->GetDesc())return;
std::istringstream input(argument);std::vector<std::string> args;std::string token;
while(input>>token){if(token.size()>10 || args.size()>=30)return;args.push_back(token);}
if(args.size()<2 || args[0]!="1")return;
const std::string& verb=args[1];
if(get_dword_time()-ch->m_portSwitchbotLastCommand<250 && ch->m_portSwitchbotLastCommand) {
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 error %s rate",verb.c_str());return;
}
ch->m_portSwitchbotLastCommand=get_dword_time();
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());
if(it==g_portSwitchbots.end())PortSwitchState(ch,NULL,false,"idle");
else PortSwitchState(ch,&it->second,true,"running");
}
else if(verb=="start") {
const char* error=PortSwitchStart(ch,args);
if(error)ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 error start %s",error);
}
else ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 error %s invalid",verb.size()<=10?verb.c_str():"unknown");
}
#endif