client: native AVA2 cube_renewal module (ENABLE_CUBE_RENEWAL_WORLDARD=1)

PythonCubeRenewal + PhaseGameCubeRenewal ported verbatim from AVA2: GC 221
fills the recipe list and calls BINARY_CUBE_RENEWAL_OPEN, the XXF
uicuberenewal window sends CG 216 make/close (its 3rd "improve" argument
is accepted and not sent). Replaces the read-only CubeRenewalScript.inc
preview shim. Version mt20261026 so the server picks the new window.
FakeLoginServer: CG 215/216 sizes and a /mt_test_cube_open fixture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-10-24 14:06:26 +09:00
co-authored by Claude Opus 5.5
parent d6617e01f7
commit 909fc8f851
15 changed files with 336 additions and 277 deletions
@@ -1,153 +0,0 @@
// PORT: server-backed modern Cube recipe preview, NOT a crafting backend.
static const char c_szCubeRenewalScript[] = R"PY(# -*- coding: utf-8 -*-
import game
import chat
import mt_feature_service
from mt_biolog import L
_dates=[]
_recipes=[]
_handler=None
_window=None
_epoch=0
_npc=0
_readonly=False
_last_preflight=None
_last_error=None
_check_serial=0
def CountDates():return len(_dates)
def GetDates(index):
if 0<=index<len(_dates):return _dates[index]
return (0,0,False,0,0,0,0,0,0,0,0,0,0,0,0,'None')
def SetCubeRenewalHandler(handler):
global _handler
_handler=handler
def _Tuple(row):
values=[row['reward'],row['count'],row['stackable']]
for v,n in row['materials']:values.extend((v,n))
values.extend([0,0]*(5-len(row['materials'])))
return tuple(values+[row['gold'],row['percent'],row['category']])
def CubeRenewalClose():
global _handler,_epoch,_npc,_readonly,_last_preflight
_epoch+=1;_npc=0;_readonly=False;_handler=None;_last_preflight=None
del _dates[:];del _recipes[:]
if _window:_window.Hide()
def LoadCatalogue(npc,callback=None):
global _epoch,_npc,_last_error,_readonly,_last_preflight
_epoch+=1;epoch=_epoch;_npc=npc;_last_error=None;_readonly=False;_last_preflight=None
if _window:_window.Hide()
del _dates[:];del _recipes[:]
service=mt_feature_service.g_service
if not service:
_last_error='offline'
if callback:callback(None,'offline')
return 0
pending=[];state={'total':None,'revision':None}
def fail(error):
global _last_error
_last_error=error
if callback:callback(None,error)
def receive(result,error):
if epoch!=_epoch:return
if error:fail(error);return
if state['total'] is None:state['total']=result['total']
if result['total']!=state['total'] or result['offset']!=len(pending):fail('stale_catalogue');return
ids=set(r['id'] for r in pending)
for row in result['rows']:
if state['revision'] is None:state['revision']=row['catalogue']
if row['catalogue']!=state['revision'] or row['id'] in ids:fail('stale_catalogue');return
ids.add(row['id']);pending.append(row)
if len(pending)<state['total']:
service.Request('cube',npc,len(pending),receive);return
_recipes[:]=pending;_dates[:]=[_Tuple(row) for row in pending]
if callback:callback(list(_recipes),None)
return service.Request('cube',npc,0,receive)
def CheckBatch(index,attempts,callback=None):
global _last_error,_last_preflight,_check_serial
_last_preflight=None;_last_error=None;_check_serial+=1;serial=_check_serial
if not isinstance(index,int) or not isinstance(attempts,int) or not 0<=index<len(_recipes) or not 1<=attempts<=100:
_last_error='invalid'
if callback:callback(None,'invalid')
return 0
service=mt_feature_service.g_service
if not service:
_last_error='offline'
if callback:callback(None,'offline')
return 0
epoch=_epoch;recipe=_recipes[index]
def receive(result,error):
global _last_error,_last_preflight
if epoch!=_epoch or serial!=_check_serial:return
_last_error=error
if error:pass
else:
values=dict(result['rows']);version='%08x%08x'%(values['revision_hi'],values['revision_lo'])
if version!=recipe['revision']:_last_error='stale_recipe'
elif values['gold_required']!=recipe['gold']*attempts or values['reward_maximum']!=recipe['count']*attempts or bool(values['copy_required'])!=recipe['copy']:_last_error='bad_preflight'
else:
for i,(v,n) in enumerate(recipe['materials'],1):
if values.get('material%d'%i)!=v or values.get('needed%d'%i)!=n*attempts or values.get('available%d'%i,-1)<0:
_last_error='bad_preflight';break
keys=set(('revision_hi','revision_lo','attempts','gold_required','gold_available','materials_ok','gold_ok','mutation_enabled','reward_maximum','capacity_reserved','copy_required'))
for i in range(1,len(recipe['materials'])+1):keys.update(('material%d'%i,'needed%d'%i,'available%d'%i))
material_ok=all(values.get('available%d'%i,-1)>=n*attempts for i,(v,n) in enumerate(recipe['materials'],1))
if set(values)!=keys or values['gold_available']>2000000000000000 or bool(values['gold_ok'])!=(values['gold_available']>=values['gold_required']) or bool(values['materials_ok'])!=material_ok:_last_error='bad_preflight'
if not _last_error:_last_preflight=values
if callback:callback(_last_preflight,_last_error)
return service.Request('cubecheck',recipe['id'],attempts,receive)
def CubeRenewalMakeItem(index_craft,count_item,index_improve=0):
# Original UI name; only our labeled preview can use it, for a read-only check.
if not _readonly:raise RuntimeError('Cube Renewal requires an implemented durable server crafting contract')
if index_improve not in (0,-1):
chat.AppendChat(chat.CHAT_TYPE_INFO,L('预检暂不支持成功率道具;未扣除材料。'));return 0
def checked(result,error):
if error:chat.AppendChat(chat.CHAT_TYPE_INFO,L('配方预检失败,未扣料、未制作:')+str(error));return
chat.AppendChat(chat.CHAT_TYPE_INFO,L('只读预检:尝试 %d 次,需金币 %d;材料%s,金币%s。未预留背包、未扣料、未制作。')%
(result['attempts'],result['gold_required'],L('充足' if result['materials_ok'] else '不足'),L('充足' if result['gold_ok'] else '不足')))
return CheckBatch(index_craft,count_item,checked)
def OpenPreview(npc):
def loaded(rows,error):
global _window,_readonly,_last_error
if error:
if error!='unsupported':chat.AppendChat(chat.CHAT_TYPE_INFO,L('制作配方预览不可用:')+str(error))
return
try:
if _window is None:
import uiCubeRenewal
_window=uiCubeRenewal.CubeRenewalWindows()
SetCubeRenewalHandler(_window)
_window.BINARY_CUBE_RENEWAL_LOADING()
_window.button_ok.SetText(L('批量预检'))
_window.slot_improve.Hide();_window.imporve_slot.Hide()
_window.SetCenterPosition();_window.Show();_readonly=True
except Exception:
_readonly=False;_last_error='cube_ui_unavailable';SetCubeRenewalHandler(None)
if _window:_window.Hide()
_window=None
chat.AppendChat(chat.CHAT_TYPE_INFO,L('现代制作界面资源不可用,保留原制作窗口;未扣料、未制作。'))
return
chat.AppendChat(chat.CHAT_TYPE_INFO,L('现代制作只读预览:当前不扣料、不发奖;原制作窗口保持不变。'))
return LoadCatalogue(npc,loaded)
_open=game.GameWindow.BINARY_Cube_Open
_close=game.GameWindow.BINARY_Cube_Close
_game_close=game.GameWindow.Close
def Open(self,npc):
_open(self,npc);OpenPreview(npc)
def Close(self):
CubeRenewalClose();return _close(self)
def GameClose(self):
CubeRenewalClose();return _game_close(self)
game.GameWindow.BINARY_Cube_Open=Open
game.GameWindow.BINARY_Cube_Close=Close
game.GameWindow.Close=GameClose
)PY";
+3 -2
View File
@@ -39,6 +39,7 @@
#include "UserInterface/PythonMessenger.h"
#include "UserInterface/PythonSafeBox.h"
#include "UserInterface/PythonSash.h"
#include "UserInterface/PythonCubeRenewal.h"
#include "UserInterface/PythonSwitchbot.h"
#include "UserInterface/PythonGuild.h"
#include "UserInterface/MarkManager.h"
@@ -160,6 +161,7 @@ struct GameSingletons
CPythonMessenger pyManager;
CPythonSafeBox pySafeBox;
CPythonSash pySash; // PORT: AVA2 sash
CPythonCubeRenewal pyCubeRenewal; // PORT: AVA2 cuberenewal
CPythonSwitchbot pySwitchbot; // PORT: AVA2 switchbot
#ifdef ENABLE_SHOP_SEARCH_SYSTEM
CPythonPrivateShopSearch pyPrivateShopSearch; // PORT: AVA2 shop search
@@ -948,6 +950,7 @@ bool run_main_script_body(const char* lpCmdLine, std::string* error)
initMessenger();
initsafebox();
initSash();
initCubeRenewal();
initSwitchbot();
initguild();
initServerStateChecker();
@@ -1046,7 +1049,6 @@ namespace PythonBoot
#include "WikiEntryScript.inc"
#include "TargetElementScript.inc"
#include "MinimapButtonsScript.inc"
#include "CubeRenewalScript.inc"
#include "RankScript.inc"
#include "WonScript.inc"
#include "Ava2UICompatScript.inc"
@@ -1172,7 +1174,6 @@ bool RunMainScript(const char* lpCmdLine, std::string* error)
install_script_module("mt_wiki_entries", c_szWikiEntryScript);
install_script_module("mt_target_element", c_szTargetElementScript);
install_script_module("mt_minimap_buttons", c_szMinimapButtonsScript);
install_script_module("cube_renewal", c_szCubeRenewalScript);
install_script_module("mt_rank", c_szRankScript);
install_script_module("mt_won", c_szWonScript);
install_script_module("mt_switchbot", c_szSwitchbotScript);
+43
View File
@@ -165,6 +165,7 @@ enum
HEADER_CG_DRAGON_SOUL_REFINE = 205,
HEADER_CG_STATE_CHECKER = 206,
HEADER_CG_SASH = 211, // PORT: AVA2 sash (metin2-server FEATURE-AVA2-UNLOCK P4)
HEADER_CG_CUBE_RENEWAL = 216, // PORT: AVA2 cuberenewal (ENABLE_CUBE_RENEWAL_WORLDARD)
#if defined(ENABLE_ATTR_6TH_7TH)
HEADER_CG_67_ATTR = 208,
HEADER_CG_CLOSE_67_ATTR = 209,
@@ -388,6 +389,7 @@ enum
HEADER_GC_CHESTDROP = 66, // PORT: AVA2, DWORD dynamic length
HEADER_GC_AVA2_EVENTS = 214,
HEADER_GC_AVA2_DROP = 220,
HEADER_GC_CUBE_RENEWAL = 221, // PORT: AVA2 cuberenewal (ENABLE_CUBE_RENEWAL_WORLDARD)
HEADER_GC_SWITCHBOT = 171, // PORT: AVA2 switchbot, DYNAMIC_SIZE_PACKET
HEADER_GC_EXTENDED_POINTS = 218, // PORT: AVA2 64-bit gold and extended points
HEADER_GC_PORT_QUIVER = 219, // PORT: sent only after quiver capability subscription.
@@ -3176,4 +3178,45 @@ struct TPacketGCExtendedPointGold
int64_t gold;
};
static_assert(sizeof(TPacketGCExtendedPointGold) == 10, "TPacketGCExtendedPointGold size mismatch");
// PORT: AVA2 cuberenewal (ENABLE_CUBE_RENEWAL_WORLDARD), byte-identical to the AVA2 packets.
enum ECubeRenewalSubHeader
{
CUBE_RENEWAL_SUB_HEADER_OPEN_RECEIVE,
CUBE_RENEWAL_SUB_HEADER_CLEAR_DATES_RECEIVE,
CUBE_RENEWAL_SUB_HEADER_DATES_RECEIVE,
CUBE_RENEWAL_SUB_HEADER_DATES_LOADING,
CUBE_RENEWAL_SUB_HEADER_MAKE_ITEM,
CUBE_RENEWAL_SUB_HEADER_CLOSE,
};
struct TPacketCGCubeRenewalSend
{
uint8_t header;
uint8_t subheader;
uint32_t index_item;
uint32_t count_item;
};
struct TInfoDateCubeRenewal
{
uint32_t npc_vnum;
uint32_t index;
uint32_t vnum_reward;
int32_t count_reward;
bool item_reward_stackable;
uint32_t vnum_material_1; int32_t count_material_1;
uint32_t vnum_material_2; int32_t count_material_2;
uint32_t vnum_material_3; int32_t count_material_3;
uint32_t vnum_material_4; int32_t count_material_4;
uint32_t vnum_material_5; int32_t count_material_5;
int32_t gold;
int32_t percent;
char category[100];
};
struct TPacketGCCubeRenewalReceive
{
uint8_t header;
uint8_t subheader;
TInfoDateCubeRenewal date_cube_renewal;
};
static_assert(sizeof(TPacketCGCubeRenewalSend)==10,"AVA2 CG216 size");
static_assert(sizeof(TPacketGCCubeRenewalReceive)==167,"AVA2 GC221 size");
#pragma pack(pop)
@@ -1677,7 +1677,7 @@ void initapp()
// Archived AVA2 formula exists, but its source switch was disabled.
PyModule_AddIntConstant(poModule, "ENABLE_MAGIC_REDUCTION_SYSTEM", 0);
PyModule_AddIntConstant(poModule, "ENABLE_DS_CHANGE_ATTR", 0);
PyModule_AddIntConstant(poModule, "ENABLE_CUBE_RENEWAL_WORLDARD", 0);
PyModule_AddIntConstant(poModule, "ENABLE_CUBE_RENEWAL_WORLDARD", 1);
PyModule_AddIntConstant(poModule, "ENABLE_CHEQUE_SYSTEM", 0);
PyModule_AddIntConstant(poModule, "ENABLE_RANKING_SYSTEM", 1);
PyModule_AddIntConstant(poModule, "ENABLE_PLAYER_PER_ACCOUNT5", 0);
@@ -0,0 +1,133 @@
#include "StdAfx.h"
// PORT: AVA2 PythonCubeRenewal.cpp (ENABLE_CUBE_RENEWAL_WORLDARD) verbatim; xxf uicuberenewal.py drives it.
#include "PythonCubeRenewal.h"
#include "PythonNetworkStream.h"
#include "Packet.h"
CPythonCubeRenewal::CPythonCubeRenewal()
: m_CubeRenewalHandler(NULL)
{
ClearList();
}
CPythonCubeRenewal::~CPythonCubeRenewal()
{
ClearList();
}
void CPythonCubeRenewal::LoadingList()
{
if (m_CubeRenewalHandler)
PyCallClassMemberFunc(m_CubeRenewalHandler, "BINARY_CUBE_RENEWAL_LOADING", Py_BuildValue("()"));
}
void CPythonCubeRenewal::ClearList()
{
cube_renewal_list.clear();
}
void CPythonCubeRenewal::ReceiveList(const TInfoDateCubeRenewal & TInfoCR)
{
cube_renewal_list.push_back(TInfoCR);
}
int CPythonCubeRenewal::GetCountList()
{
return cube_renewal_list.size();
}
const CPythonCubeRenewal::TInfoStrucCubeRenewal & CPythonCubeRenewal::GetList()
{
return cube_renewal_list;
}
PyObject * GetCountCubeRenewalList(PyObject * poSelf, PyObject * poArgs)
{
return Py_BuildValue("i", CPythonCubeRenewal::Instance().GetCountList());
}
PyObject * GetCubeRenewalDates(PyObject * poSelf, PyObject * poArgs)
{
int index;
if (!PyTuple_GetInteger(poArgs, 0, &index))
return Py_BuildException();
const CPythonCubeRenewal::TInfoStrucCubeRenewal & CRItemVector = CPythonCubeRenewal::Instance().GetList();
if (DWORD(index) >= CRItemVector.size())
return Py_BuildValue("iibiiiiiiiiiiiis",0,0,false,0,0,0,0,0,0,0,0,0,0,0,0,"None");
const TInfoDateCubeRenewal & CRenewalItemVector = CRItemVector[index];
char category[sizeof(CRenewalItemVector.category) + 1] = {};
memcpy(category, CRenewalItemVector.category, sizeof(CRenewalItemVector.category)); // PORT: never trust the wire NUL
return Py_BuildValue("iibiiiiiiiiiiiis",
CRenewalItemVector.vnum_reward,
CRenewalItemVector.count_reward,
CRenewalItemVector.item_reward_stackable,
CRenewalItemVector.vnum_material_1,
CRenewalItemVector.count_material_1,
CRenewalItemVector.vnum_material_2,
CRenewalItemVector.count_material_2,
CRenewalItemVector.vnum_material_3,
CRenewalItemVector.count_material_3,
CRenewalItemVector.vnum_material_4,
CRenewalItemVector.count_material_4,
CRenewalItemVector.vnum_material_5,
CRenewalItemVector.count_material_5,
CRenewalItemVector.gold,
CRenewalItemVector.percent,
category
);
}
PyObject * SetCubeRenewalHandler(PyObject* poSelf, PyObject* poArgs)
{
PyObject * poEventHandler;
if (!PyTuple_GetObject(poArgs, 0, &poEventHandler))
return Py_BuildException();
CPythonCubeRenewal::Instance().SetCubeRenewalHandler(poEventHandler);
return Py_BuildNone();
}
PyObject * CubeRenewalMakeItem(PyObject* poSelf, PyObject* poArgs)
{
int index_craft;
if (!PyTuple_GetInteger(poArgs, 0, &index_craft))
return Py_BuildException();
int count_item;
if (!PyTuple_GetInteger(poArgs, 1, &count_item))
return Py_BuildException();
// PORT: xxf uicuberenewal.py passes a third "improve" slot (79605); the AVA2 packet has no
// field for it and the window clears it for 100% recipes, so it is accepted and not sent.
CPythonNetworkStream& rkNetStream=CPythonNetworkStream::Instance();
rkNetStream.CubeRenewalMakeItem(index_craft,count_item);
return Py_BuildNone();
}
PyObject * CubeRenewalClose(PyObject* poSelf, PyObject* poArgs)
{
CPythonNetworkStream& rkNetStream=CPythonNetworkStream::Instance();
rkNetStream.CubeRenewalClose();
return Py_BuildNone();
}
void initCubeRenewal()
{
static PyMethodDef s_methods[] =
{
{ "CountDates", GetCountCubeRenewalList, METH_VARARGS },
{ "GetDates", GetCubeRenewalDates, METH_VARARGS },
{ "SetCubeRenewalHandler", SetCubeRenewalHandler, METH_VARARGS },
{ "CubeRenewalMakeItem", CubeRenewalMakeItem, METH_VARARGS },
{ "CubeRenewalClose", CubeRenewalClose, METH_VARARGS },
{ NULL, NULL, NULL },
};
Py_InitModule("cube_renewal", s_methods);
}
@@ -0,0 +1,27 @@
#pragma once
#include "Packet.h"
// PORT: AVA2 PythonCubeRenewal.h (ENABLE_CUBE_RENEWAL_WORLDARD), fed by HEADER_GC_CUBE_RENEWAL.
class CPythonCubeRenewal : public CSingleton<CPythonCubeRenewal>
{
public:
typedef std::vector<TInfoDateCubeRenewal> TInfoStrucCubeRenewal;
public:
CPythonCubeRenewal();
virtual ~CPythonCubeRenewal();
void LoadingList();
void ClearList();
void ReceiveList(const TInfoDateCubeRenewal & TInfoCR);
int GetCountList();
const TInfoStrucCubeRenewal & GetList();
void SetCubeRenewalHandler(PyObject* _CubeRenewalHandler){m_CubeRenewalHandler = _CubeRenewalHandler == Py_None ? NULL : _CubeRenewalHandler;}
private:
TInfoStrucCubeRenewal cube_renewal_list;
PyObject* m_CubeRenewalHandler;
};
@@ -190,6 +190,7 @@ class CMainPacketHeaderMap : public CNetworkPacketHeaderMap
Set(HEADER_GC_PORT_QUIVER, CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCQuiverState), STATIC_SIZE_PACKET));
Set(HEADER_GC_CHESTDROP, CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCChestDrop), DYNAMIC_SIZE_PACKET));
Set(HEADER_GC_AVA2_DROP,CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCAva2Drop),STATIC_SIZE_PACKET));
Set(HEADER_GC_CUBE_RENEWAL, CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCCubeRenewalReceive), STATIC_SIZE_PACKET)); // PORT: AVA2 cuberenewal
Set(93,CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCAva2Events),DYNAMIC_SIZE_PACKET));
Set(HEADER_GC_AVA2_EVENTS,CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCAva2Events),DYNAMIC_SIZE_PACKET));
Set(HEADER_GC_SWITCHBOT, CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCSwitchbot), DYNAMIC_SIZE_PACKET)); // PORT: AVA2 switchbot
@@ -301,6 +301,8 @@ class CPythonNetworkStream : public CNetworkStream, public CSingleton<CPythonNet
bool SendSashAddPacket(TItemPos tPos, BYTE bPos);
bool SendSashRemovePacket(BYTE bPos);
bool SendSashRefinePacket();
bool CubeRenewalMakeItem(int index_item, int count_item); // PORT: AVA2 cuberenewal
bool CubeRenewalClose();
// PORT: AVA2 switchbot
bool SendSwitchbotStartPacket(BYTE slot, std::vector<CPythonSwitchbot::TSwitchbotAttributeAlternativeTable> alternatives);
@@ -598,6 +600,7 @@ class CPythonNetworkStream : public CNetworkStream, public CSingleton<CPythonNet
// 용혼석 관련
bool RecvDragonSoulRefine();
bool RecvSashPacket(bool bReturn = false); // PORT: AVA2 sash
bool RecvCubeRenewalPacket(); // PORT: AVA2 cuberenewal
bool RecvQuiverState();
bool RecvAva2DropQuery();
bool RecvAva2Events();
@@ -638,6 +638,9 @@ void CPythonNetworkStream::GamePhase()
case HEADER_GC_SASH: // PORT: AVA2 sash
ret = RecvSashPacket();
break;
case HEADER_GC_CUBE_RENEWAL: // PORT: AVA2 cuberenewal
ret = RecvCubeRenewalPacket();
break;
case HEADER_GC_PORT_QUIVER:
ret = RecvQuiverState();
break;
@@ -4530,7 +4533,7 @@ bool CPythonNetworkStream::SendClientVersionPacket()
kVersionPacket.header = HEADER_CG_CLIENT_VERSION2;
strncpy(kVersionPacket.filename, filename.c_str(), sizeof(kVersionPacket.filename)-1);
// PORT: revision mt20261024 adds 64-bit shop prices, fixed offline records and 64-bit exchange/guild money; preserve the numeric prefix for atoi version checks.
strncpy(kVersionPacket.timestamp, "1215955205 mt20261025", sizeof(kVersionPacket.timestamp)-1); // PORT: revision25 adds full-count and Cube presentation companions.
strncpy(kVersionPacket.timestamp, "1215955205 mt20261026", sizeof(kVersionPacket.timestamp)-1); // PORT: revision26 adds the AVA2 Cube Renewal packets (CG216/GC221).
//strncpy(kVersionPacket.timestamp, __TIMESTAMP__, sizeof(kVersionPacket.timestamp)-1); // old_string_ver
//strncpy(kVersionPacket.timestamp, "1218055205", sizeof(kVersionPacket.timestamp)-1); // new_future
//strncpy(kVersionPacket.timestamp, "1214055205", sizeof(kVersionPacket.timestamp)-1); // old_past
@@ -4544,7 +4547,7 @@ bool CPythonNetworkStream::SendClientVersionPacket()
kVersionPacket.header = HEADER_CG_CLIENT_VERSION;
strncpy(kVersionPacket.filename, filename.c_str(), sizeof(kVersionPacket.filename)-1);
// PORT: 64-bit money protocol requires mt20261024; older AVA2 services retain their own revision gates.
strncpy(kVersionPacket.timestamp, "mt20261025", sizeof(kVersionPacket.timestamp)-1); // PORT: revision25 is backward-compatible with revision24 money.
strncpy(kVersionPacket.timestamp, "mt20261026", sizeof(kVersionPacket.timestamp)-1); // PORT: revision26 is backward-compatible with revision24 money.
if (!Send(sizeof(kVersionPacket), &kVersionPacket))
Tracef("SendClientReportPacket Error");
@@ -0,0 +1,84 @@
#include "StdAfx.h"
#include "PythonNetworkStream.h"
#include "PythonCubeRenewal.h"
#include "Packet.h"
// PORT: AVA2 PythonNetworkStreamPhaseGame.cpp cuberenewal packets (ENABLE_CUBE_RENEWAL_WORLDARD) verbatim.
bool CPythonNetworkStream::CubeRenewalMakeItem(int index_item, int count_item)
{
if (!__CanActMainInstance())
return true;
TPacketCGCubeRenewalSend packet;
packet.header = HEADER_CG_CUBE_RENEWAL;
packet.subheader = CUBE_RENEWAL_SUB_HEADER_MAKE_ITEM;
packet.index_item = index_item;
packet.count_item = count_item;
if (!Send(sizeof(TPacketCGCubeRenewalSend), &packet))
{
Tracef("CPythonNetworkStream::CubeRenewalMakeItem Error\n");
return false;
}
return SendSequence();
}
bool CPythonNetworkStream::CubeRenewalClose()
{
if (!__CanActMainInstance())
return true;
TPacketCGCubeRenewalSend packet;
packet.header = HEADER_CG_CUBE_RENEWAL;
packet.subheader = CUBE_RENEWAL_SUB_HEADER_CLOSE;
packet.index_item = 0;
packet.count_item = 0;
if (!Send(sizeof(TPacketCGCubeRenewalSend), &packet))
{
Tracef("CPythonNetworkStream::CubeRenewalClose Error\n");
return false;
}
return SendSequence();
}
bool CPythonNetworkStream::RecvCubeRenewalPacket()
{
TPacketGCCubeRenewalReceive CubeRenewalPacket;
if (!Recv(sizeof(CubeRenewalPacket), &CubeRenewalPacket))
return false;
switch (CubeRenewalPacket.subheader)
{
case CUBE_RENEWAL_SUB_HEADER_OPEN_RECEIVE:
{
PyCallClassMemberFunc(m_apoPhaseWnd[PHASE_WINDOW_GAME], "BINARY_CUBE_RENEWAL_OPEN", Py_BuildValue("()"));
}
break;
case CUBE_RENEWAL_SUB_HEADER_DATES_RECEIVE:
{
CPythonCubeRenewal::Instance().ReceiveList(CubeRenewalPacket.date_cube_renewal);
}
break;
case CUBE_RENEWAL_SUB_HEADER_DATES_LOADING:
{
CPythonCubeRenewal::Instance().LoadingList();
}
break;
case CUBE_RENEWAL_SUB_HEADER_CLEAR_DATES_RECEIVE:
{
CPythonCubeRenewal::Instance().ClearList();
}
break;
}
return true;
}
+1
View File
@@ -69,6 +69,7 @@ void initBackground();
void initMessenger();
void initsafebox();
void initSash(); // PORT: AVA2 sash
void initCubeRenewal(); // PORT: AVA2 cuberenewal
void initSwitchbot(); // PORT: AVA2 switchbot
void initguild();
void initServerStateChecker();
+4
View File
@@ -219,6 +219,8 @@ enum : uint8_t {
HDR_CG_XTRAP_ACK = 204,
HDR_CG_DRAGON_SOUL_REFINE = 205,
HDR_CG_STATE_CHECKER = 206,
HDR_CG_AVA2_DROP = 215, // AVA2 drop query, 1+1+4
HDR_CG_CUBE_RENEWAL = 216, // AVA2 cuberenewal, 1+1+4+4
};
// GC (server -> client). Server packet.h (wire authority).
@@ -1427,6 +1429,8 @@ constexpr int packet_size_cg(uint8_t h) {
case HDR_CG_SAFEBOX_CHECKOUT: return sizeof(CGSafeboxCheckout);
case HDR_CG_SAFEBOX_ITEM_MOVE: return sizeof(CGItemMove);
case HDR_CG_STATE_CHECKER: return 1;
case HDR_CG_AVA2_DROP: return 6;
case HDR_CG_CUBE_RENEWAL: return 10;
default: return 0;
}
}
+21 -15
View File
@@ -903,6 +903,13 @@ bool FakeLoginServer::ServeGame(Connection& c, int index)
if (!ok)
return Fail(name + ": send GC_EXCHANGE");
}
if (header == HDR_CG_CUBE_RENEWAL)
{
std::uint32_t index = 0, count = 0;
std::memcpy(&index, packet + 2, 4);
std::memcpy(&count, packet + 6, 4);
Event(name + ":cube_renewal " + std::to_string(packet[1]) + " " + std::to_string(index) + " " + std::to_string(count));
}
// CInputMain::Chat (input_main.cpp): the line comes back to the speaker (PacketAround includes them)
// as a CHAT_TYPE_TALKING GC_CHAT "<name> : <text>" carrying their vid and empire.
if (header == HDR_CG_CHAT)
@@ -941,6 +948,19 @@ bool FakeLoginServer::ServeGame(Connection& c, int index)
if (!c.Send(chat) || !c.Send(cmd.c_str(), cmd.size() + 1)) return Fail(name + ": biolog reply");
}
}
else if (text == "/mt_test_cube_open" && std::getenv("MT_TEST_CUBE")) {
// cube.cpp CubeRenewal_Open: CLEAR, one DATES per recipe, LOADING, OPEN (GC 221, 167 bytes).
auto cube=[&](std::uint8_t sub,bool row) {
std::uint8_t pkt[167]={};pkt[0]=221;pkt[1]=sub;
if(row) {
const std::uint32_t head[4]={20383,0,19,1};std::memcpy(pkt+2,head,sizeof(head));
const std::int32_t tail[12]={30006,1,0,0,0,0,0,0,0,0,100,50};std::memcpy(pkt+19,tail,sizeof(tail));
std::memcpy(pkt+67,"WORLDARD",8);
}
return c.Send(pkt,sizeof(pkt));
};
if(!cube(1,false)||!cube(2,true)||!cube(3,false)||!cube(0,false))return Fail(name+": cube renewal open");
}
else if (text.rfind("/mt_features ",0)==0) {
std::istringstream in(text);std::string command,kind;unsigned version=0,request=0,subject=0,offset=0;
in>>command>>version>>request>>kind>>subject>>offset;
@@ -949,21 +969,7 @@ bool FakeLoginServer::ServeGame(Connection& c, int index)
return c.Send(chat)&&c.Send(cmd.c_str(),cmd.size()+1);
};
const std::string r=std::to_string(request);
if(kind=="cap") {if(!reply("MTF1 cap "+r+" 1 "+(std::getenv("MT_TEST_CUBE")?"4159":std::getenv("MT_TEST_QUIVER")?"2111":"63")+" 1700000000"))return Fail(name+": feature cap");}
else if(kind=="cube" && std::getenv("MT_TEST_CUBE")) {
if(!reply("MTF1 begin "+r+" cube 20383 0 1 0 1700000000")||
!reply("MTF1 recipe "+r+" 0 1 1111111111111111 2222222222222222 19 1 0 100 50 0 574f524c44415244 1 30006 1")||
!reply("MTF1 end "+r+" 1"))return Fail(name+": cube catalogue");
}
else if(kind=="cubecheck" && std::getenv("MT_TEST_CUBE")) {
std::vector<std::pair<std::string,int64_t>> rows={{"revision_hi",0x22222222},{"revision_lo",0x22222222},
{"attempts",offset},{"gold_required",int64_t(offset)*100},{"gold_available",1000},{"materials_ok",1},
{"gold_ok",1},{"mutation_enabled",0},{"reward_maximum",offset},{"capacity_reserved",0},{"copy_required",0},
{"material1",30006},{"needed1",offset},{"available1",offset}};
if(!reply("MTF1 begin "+r+" cubecheck "+std::to_string(subject)+" "+std::to_string(offset)+" "+std::to_string(rows.size())+" 0 1700000000"))return Fail(name+": cube preflight begin");
for(unsigned i=0;i<rows.size();++i)if(!reply("MTF1 stat "+r+" "+std::to_string(i)+" "+rows[i].first+" "+std::to_string(rows[i].second)))return Fail(name+": cube preflight row");
if(!reply("MTF1 end "+r+" "+std::to_string(rows.size())))return Fail(name+": cube preflight end");
}
if(kind=="cap") {if(!reply("MTF1 cap "+r+" 1 "+(std::getenv("MT_TEST_QUIVER")?"2111":"63")+" 1700000000"))return Fail(name+": feature cap");}
else if(kind=="quiver" && std::getenv("MT_TEST_QUIVER")) {
if(!reply("MTF1 begin "+r+" quiver 0 0 0 0 1700000000") || !reply("MTF1 end "+r+" 0"))return Fail(name+": quiver ack");
std::uint8_t state[6]={219,0,0,0,0,9};std::uint32_t vid=kMainVID;
+10 -11
View File
@@ -553,18 +553,17 @@ int main(int argc, char** argv)
" item.SelectItem(_pack_vnum)\n"
" assert item.GetItemType()==_pack_type and item.GetItemSubType()==0, (_pack_vnum,item.GetItemType(),item.GetItemSubType())\n"));
}
CHECK(py("import cube_renewal, app, player\nassert not app.ENABLE_CUBE_RENEWAL_WORLDARD\n_cube_gold=player.GetElk()\n_cube_materials=player.GetItemCountByVnum(30006)\ncube_renewal.LoadCatalogue(20383)"));
// AVA2 cuberenewal: GC 221 fills the list and opens the window, CG 216 carries make/close.
CHECK(py("import cube_renewal, app\nassert app.ENABLE_CUBE_RENEWAL_WORLDARD\nimport net\nnet.SendChatPacket('/mt_test_cube_open')"));
CHECK(pump_until(8,[] {return py_true("cube_renewal.CountDates()==1");}));
CHECK(py("assert cube_renewal.GetDates(0)==(19,1,False,30006,1,0,0,0,0,0,0,0,0,100,50,'WORLDARD')"));
if(std::getenv("MT_TEST_CUBE_LAYOUT")) {
CHECK(py("_stream.curPhaseWindow.BINARY_Cube_Open(20383)"));
CHECK(pump_until(8,[] {return py_true("cube_renewal._window is not None and cube_renewal._window.IsShow() and cube_renewal._readonly");}));
CHECK(py("cube_renewal.CubeRenewalMakeItem(0,3)"));
} else CHECK(py("cube_renewal.CheckBatch(0,3)"));
CHECK(pump_until(8,[] {return py_true("cube_renewal._last_preflight is not None");}));
CHECK(py("assert cube_renewal._last_error is None\nassert cube_renewal._last_preflight['gold_required']==300\nassert cube_renewal._last_preflight['mutation_enabled']==0\nassert player.GetElk()==_cube_gold\nassert player.GetItemCountByVnum(30006)==_cube_materials\nassert cube_renewal.CheckBatch(0,101)==0\ncube_renewal.CubeRenewalClose()\nassert cube_renewal.CountDates()==0\napp.Exit()"));
CHECK(py("assert cube_renewal.GetDates(0)==(19,1,False,30006,1,0,0,0,0,0,0,0,0,100,50,'WORLDARD'), cube_renewal.GetDates(0)\nassert cube_renewal.GetDates(1)[0]==0"));
if(std::getenv("MT_TEST_CUBE_LAYOUT"))
CHECK(pump_until(8,[] {return py_true("_stream.curPhaseWindow.interface.wndCubeRenewal.IsShow()");}));
CHECK(py("cube_renewal.CubeRenewalMakeItem(0,3,-1)\ncube_renewal.CubeRenewalClose()"));
CHECK(pump_until(8,[&server] {bool make=false,close=false;for(const auto& e:server->Events()){make|=e.find(":cube_renewal 4 0 3")!=std::string::npos;close|=e.find(":cube_renewal 5 0 0")!=std::string::npos;}return make&&close;}));
CHECK(py("app.Exit()"));
pump_until(2,[] {return !PythonBoot::IsAppLooping();});PythonBoot::Stop();
std::printf("cube read-only catalogue/preflight fixture: %s\n",g_failures?"FAILED":"PASS");return g_failures?1:0;
std::printf("cube renewal packet fixture: %s\n",g_failures?"FAILED":"PASS");return g_failures?1:0;
}
if (server && std::getenv("MT_TEST_AUTOHUNT_BATCH")) {
CHECK(CPythonPlayer::Instance().NEW_GetMainActorPtr());
@@ -1922,7 +1921,7 @@ int main(int argc, char** argv)
CHECK(py("import cube_renewal"));
CHECK(py_true("cube_renewal.CountDates() == 0"));
CHECK(py_true("cube_renewal.GetDates(0)[0] == 0"));
CHECK(py("try:\n cube_renewal.CubeRenewalMakeItem(0, 1)\nexcept RuntimeError:\n pass\nelse:\n raise AssertionError('unsupported craft silently succeeded')\n"));
CHECK(py_true("app.ENABLE_CUBE_RENEWAL_WORLDARD == 1"));
// F24: Full server ranking system (uirank)
CHECK(py_true("app.ENABLE_RANKING_SYSTEM == 1"));
-93
View File
@@ -1,93 +0,0 @@
"""Run the real modern Cube controller with explicit transport/UI substitutes."""
from pathlib import Path
import sys
import types
import unittest
from unittest.mock import patch
ROOT=Path(__file__).resolve().parents[2]
class CubeCatalogueTests(unittest.TestCase):
def setUp(self):
self.requests=[];self.replies=[]
mods={n:types.ModuleType(n) for n in ('game','chat','mt_feature_service','mt_biolog')}
mods['game'].GameWindow=type('GameWindow',(),dict(BINARY_Cube_Open=lambda s,n:None,BINARY_Cube_Close=lambda s:None,Close=lambda s:None))
mods['chat'].CHAT_TYPE_INFO=1;mods['chat'].AppendChat=lambda *a:None
mods['mt_biolog'].L=lambda text:text
class Service:
def Request(service,*args):self.requests.append(args);return len(self.requests)
mods['mt_feature_service'].g_service=Service()
raw=(ROOT/'src/platform/ScriptLib/CubeRenewalScript.inc').read_text()
self.ns={}
with patch.dict(sys.modules,mods):exec(raw.split('R"PY(',1)[1].rsplit(')PY";',1)[0],self.ns)
def row(self,i=1,revision='2222222222222222',catalogue='1111111111111111'):
return dict(id=i,catalogue=catalogue,revision=revision,reward=19,count=1,stackable=False,
gold=100,percent=50,copy=False,category='WORLDARD',materials=[(30006,2)])
def page(self,rows,total=None,offset=0):
self.requests[-1][3](dict(rows=rows,total=len(rows) if total is None else total,offset=offset),None)
def load(self):
self.ns['LoadCatalogue'](20383,lambda d,e:self.replies.append((d,e)))
self.page([self.row()])
def result(self,**changes):
values=dict(revision_hi=0x22222222,revision_lo=0x22222222,attempts=3,gold_required=300,
gold_available=1000,materials_ok=1,gold_ok=1,mutation_enabled=0,capacity_reserved=0,
reward_maximum=3,copy_required=0,material1=30006,needed1=6,available1=6)
values.update(changes);return dict(rows=list(values.items()))
def test_no_partial_catalogue_and_exact_original_tuple(self):
self.ns['LoadCatalogue'](20383)
self.page([self.row(i) for i in range(1,9)],9)
self.assertEqual(self.ns['CountDates'](),0)
self.page([self.row(9)],9,8)
self.assertEqual(self.ns['CountDates'](),9)
self.assertEqual(self.ns['GetDates'](0),(19,1,False,30006,2,0,0,0,0,0,0,0,0,100,50,'WORLDARD'))
def test_mixed_pages_and_stale_callback_never_commit(self):
self.ns['LoadCatalogue'](20383)
self.page([self.row(i) for i in range(1,9)],9)
self.page([self.row(9,catalogue='aaaaaaaaaaaaaaaa')],9,8)
self.assertEqual(self.ns['CountDates'](),0)
self.ns['LoadCatalogue'](20383);callback=self.requests[-1][3]
self.ns['CubeRenewalClose']();callback(dict(rows=[self.row()],total=1,offset=0),None)
self.assertEqual(self.ns['CountDates'](),0)
def test_missing_ui_preserves_classic_without_enabling_crafting(self):
self.ns['OpenPreview'](20383)
with patch.dict(sys.modules,{'uiCubeRenewal':None}):self.page([self.row()])
self.assertEqual(self.ns['_last_error'],'cube_ui_unavailable')
self.assertFalse(self.ns['_readonly'])
self.assertIsNone(self.ns['_handler'])
self.assertIsNone(self.ns['_window'])
def test_preflight_is_read_only_and_revision_bound(self):
self.load();self.ns['CheckBatch'](0,3,lambda d,e:self.replies.append((d,e)))
self.assertEqual(self.requests[-1][:3],('cubecheck',1,3))
self.requests[-1][3](self.result(),None);self.assertIsNone(self.replies[-1][1])
for update in (dict(revision_lo=1),dict(gold_required=301),dict(materials_ok=0),dict(available1=5),dict(extra=1)):
self.ns['CheckBatch'](0,3,lambda d,e:self.replies.append((d,e)))
self.requests[-1][3](self.result(**update),None)
self.assertIsNone(self.replies[-1][0]);self.assertIsNotNone(self.replies[-1][1])
with self.assertRaises(RuntimeError):self.ns['CubeRenewalMakeItem'](0,3)
self.ns['_readonly']=True;self.ns['CubeRenewalMakeItem'](0,3)
self.assertTrue(all(r[0] in ('cube','cubecheck') for r in self.requests))
def test_newer_check_or_closed_window_discards_old_reply(self):
self.load();self.ns['CheckBatch'](0,3);old=self.requests[-1][3]
self.ns['CheckBatch'](0,4);old(self.result(),None)
self.assertIsNone(self.ns['_last_preflight'])
latest=self.requests[-1][3];self.ns['CubeRenewalClose']();latest(self.result(attempts=4),None)
self.assertIsNone(self.ns['_last_preflight'])
self.load();self.ns['CheckBatch'](0,3);self.requests[-1][3](self.result(),None)
self.assertIsNotNone(self.ns['_last_preflight'])
self.ns['LoadCatalogue'](20384)
self.assertIsNone(self.ns['_last_preflight'])
self.assertEqual(self.ns['CheckBatch'](0,3),0)
self.assertEqual(self.ns['_last_error'],'invalid')
if __name__=='__main__':unittest.main()