Port AVA2 native tracker and item-currency ticket shop

This commit is contained in:
shen
2026-10-18 10:41:51 -07:00
parent 83809631ed
commit 5decc93798
33 changed files with 1850 additions and 17 deletions
+35
View File
@@ -0,0 +1,35 @@
"""Run the shipped shop decoder against malformed and valid wire frames."""
import os,subprocess,tempfile,unittest
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
class WireTests(unittest.TestCase):
def test_complete_frame_and_no_partial_mutation(self):
code=r'''
#include "src/port/UserInterface/Ava2ShopWire.h"
#include <cassert>
#include <string>
#pragma pack(push,1)
struct Item { uint32_t vnum; char body[39]; };
struct Price { uint32_t vnum,count; };
struct Frame { uint32_t owner; Item items[40]; Price prices[40]; };
#pragma pack(pop)
static_assert(sizeof(Item)==43,"native baseline wire size");
static_assert(sizeof(Frame)==2044,"shop start payload size");
int main(){
Frame frame={};frame.items[0].vnum=25163;frame.prices[0]={90011,10};
Item items[40]={};Price prices[40]={};uint32_t owner=99;
const char* data=reinterpret_cast<const char*>(&frame);
assert(!DecodeAva2ShopStart(data,sizeof(frame)-1,owner,items,prices));assert(owner==99);
assert(!DecodeAva2ShopStart(data,sizeof(frame)+1,owner,items,prices));assert(owner==99);
assert(!DecodeAva2ShopStart(nullptr,sizeof(frame),owner,items,prices));
frame.prices[1]={90010,0};assert(!DecodeAva2ShopStart(data,sizeof(frame),owner,items,prices));assert(items[0].vnum==0);
frame.prices[1]={90010,20};assert(!DecodeAva2ShopStart(data,sizeof(frame),owner,items,prices));assert(owner==99);
frame.prices[1]={0,0};assert(DecodeAva2ShopStart(data,sizeof(frame),owner,items,prices));
assert(owner==0 && items[0].vnum==25163 && prices[0].vnum==90011 && prices[0].count==10);
}
'''
with tempfile.TemporaryDirectory() as d:
p=Path(d);(p/'test.cpp').write_text(code)
subprocess.run([os.environ.get('CXX','c++'),'-std=c++17','-I'+str(ROOT),str(p/'test.cpp'),'-o',str(p/'test')],check=True)
subprocess.run([str(p/'test')],check=True)
if __name__=='__main__':unittest.main()
+17
View File
@@ -16,18 +16,35 @@ class Button:
def __init__(self):self.ButtonText=None
def GetHeight(self):return 20
def SetText(self,text):self.ButtonText=Text();self.ButtonText.SetPosition(8,10);self.ButtonText.SetText(text)
class Window:
def SetPosition(self,x,y):self.position=(x,y)
def GetLocalPosition(self):return self.position
def GetHeight(self):return 20
class Image:
def __init__(self):self.eventDict={}
def SAFE_SetStringEvent(self,event,func):self.callback=func
class Loader:
def LoadElementText(self,*args):return True
def LoadElementButton(self,window,value,parent):window.SetText(value['text']);return True
class CompatTests(unittest.TestCase):
def setUp(self):
self.previous=sys.modules.get('ui');m=types.ModuleType('ui')
m.Button=type('Button',(Button,),{});m.TextLine=Text;m.PythonScriptLoader=type('Loader',(Loader,),{})
m.ToggleButton=type('Toggle',(),{'SetToggleUpEvent':lambda *a:None,'SetToggleDownEvent':lambda *a:None})
m.__mem_func__=lambda f:f
m.Window=type('Window',(Window,),{});m.ImageBox=type('Image',(Image,),{})
sys.modules['ui']=m;self.ui=m
source=(ROOT/'src/platform/ScriptLib/Ava2UICompatScript.inc').read_text().split('R"PY(',1)[1].rsplit(')PY";',1)[0]
exec(source,{})
def tearDown(self):
if self.previous is None:sys.modules.pop('ui',None)
else:sys.modules['ui']=self.previous
def test_tracker_scroll_origin_is_preserved(self):
w=self.ui.Window();w.SetPosition(5,100,True);w.SetPosition(5,20)
self.assertEqual(w.exPos,(5,100));self.assertEqual(w.GetBottom(),40)
def test_tracker_ticket_event_preserves_arguments(self):
called=[];image=self.ui.ImageBox();image.SAFE_SetStringEvent('MOUSE_OVER_IN',called.append,25163)
image.eventDict['MOUSE_OVER_IN']();self.assertEqual(called,[25163])
def test_checkbox_label_uses_original_ava2_offset(self):
button=self.ui.Button();self.assertTrue(self.ui.PythonScriptLoader().LoadElementButton(button,{'text':'灵石','text_x':20},None))
self.assertEqual(button.ButtonText.position,(20,10));self.assertEqual(button.ButtonText.align,'left')
+29
View File
@@ -0,0 +1,29 @@
"""Native tracker server replies must not advertise unavailable dungeons as ready."""
import pathlib, unittest, textwrap, types
SOURCE=(pathlib.Path(__file__).resolve().parents[2]/'src/platform/ScriptLib/NativeTrackScript.inc').read_text()
class NativeTrackTest(unittest.TestCase):
def test_unknown_then_ready_resets_state(self):
start=SOURCE.index('\tdef TrackDungeonInfo(');end=SOURCE.index('\n\tdef OpenShop(',start)
class Py2Dict(dict):
def has_key(self,key):return key in self
data={'bossVnum':2493,'status':True}
window=types.SimpleNamespace(_TrackWindow__dataDict=Py2Dict({0:[data]}))
scope={'app':types.SimpleNamespace(GetGlobalTimeStamp=lambda:10000)};exec('class TrackWindow:\n'+textwrap.indent(textwrap.dedent(SOURCE[start:end]),' '),scope)
method=scope['TrackWindow'].TrackDungeonInfo
method(window,'2493|-1|0#')
self.assertTrue(data['synced']);self.assertTrue(data['unavailable']);self.assertFalse(data['status'])
method(window,'2493|240|0#')
self.assertFalse(data['unavailable']);self.assertEqual(data['server_cooldown'],10240)
method(window,'2493|0|0#');self.assertEqual(data['server_cooldown'],10000)
def test_hidden_tab_does_not_notify_for_unknown(self):
start=SOURCE.index('class Tick(');end=SOURCE.index('\n_oldOpen=',start)
notices=[]
data={'synced':True,'unavailable':True,'status':False,'server_cooldown':9999,'name':'dragon'}
window=types.SimpleNamespace(_TrackWindow__dataDict={0:[data]},GetChild=lambda _:types.SimpleNamespace(GetItems=lambda:[]))
ns={'ui':types.SimpleNamespace(Window=object),'g_window':window,'app':types.SimpleNamespace(GetGlobalTimeStamp=lambda:10000),
'systemSetting':types.SimpleNamespace(GetDungeonTrack=lambda:True),'_game':types.SimpleNamespace(BINARY_OnRecvBulkWhisper=notices.append),
'localeInfo':types.SimpleNamespace(TRACK_DUNGEON_READY='%s ready')}
exec(SOURCE[start:end],ns)
ns['Tick'].OnUpdate(None);self.assertEqual(notices,[]);self.assertFalse(data['status'])
data['unavailable']=False;ns['Tick'].OnUpdate(None);self.assertEqual(notices,['dragon ready'])
ns['Tick'].OnUpdate(None);self.assertEqual(len(notices),1)
+77
View File
@@ -0,0 +1,77 @@
"""Exercise the native AVA2 currency confirmation and tooltip branches."""
import sys,types,unittest
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
def script(name):return (ROOT/'src/platform/ScriptLib'/name).read_text().split('R"PY(',1)[1].rsplit(')PY";',1)[0]
class Widget:
def __init__(self,*a):self.text='';self.shown=False
def __getattr__(self,n):return lambda *a:None
def SetText(self,t):self.text=t
def Show(self):self.shown=True
def Hide(self):self.shown=False
def GetHeight(self):return 32
class Question(Widget):
def SetAcceptEvent(self,f):self.accept=f
def SetCancelEvent(self,f):self.cancel=f
class Dialog:
def __init__(self):self.btnSell=Widget();self.old=[];self.answers=[]
def Open(self,vid):self.old.append(('open',vid))
def AskBuyItem(self,slot):self.old.append(('ask',slot))
def _ShopDialog__GetRealIndex(self,slot):return 40+slot
def AnswerBuyItem(self,yes):self.answers.append(yes)
class Tooltip:
def __init__(self):self.childrenList=[];self.toolTipWidth=240;self.toolTipHeight=100;self.old=[]
def SetShopItem(self,i):self.old.append(i)
def ClearToolTip(self):pass
def AddItemData(self,*args):self.item=args
def AppendSpace(self,n):self.toolTipHeight+=n
def AppendPrice(self,p):raise AssertionError('item currency must not be shown as gold')
def ResizeToolTip(self):pass
class Tests(unittest.TestCase):
def setUp(self):
self.previous={};self.mods={n:types.ModuleType(n) for n in ('constInfo','game','item','localeInfo','player','shop','uiCommon','uiShop','uiToolTip','ui','app')}
self.prices={41:(90011,10)};self.selected=0;self.questionStatus=[];self.opens=[]
m=self.mods;m['constInfo'].SET_ITEM_QUESTION_DIALOG_STATUS=self.questionStatus.append
m['item'].SelectItem=lambda v:setattr(self,'selected',v)
m['item'].GetItemName=lambda:{25163:'门票',90011:'原木'}[self.selected]
m['item'].GetIconImageFileName=lambda:'icon/item/90011.tga'
m['localeInfo'].SHOP_ERROR_DICT={};m['localeInfo'].DO_YOU_BUY_ITEM=lambda *a:'gold'
m['localeInfo'].NumberToMoneyString=lambda n:str(n)
m['player'].AutoHuntLocalize=lambda t:t;m['player'].METIN_SOCKET_MAX_NUM=3;m['player'].ATTRIBUTE_SLOT_MAX_NUM=7
m['shop'].GetVnumBuy=lambda i:self.prices.get(i,(0,0))[0]
m['shop'].GetCountBuy=lambda i:self.prices.get(i,(0,0))[1]
m['shop'].GetItemID=lambda i:25163;m['shop'].GetItemCount=lambda i:1;m['shop'].GetItemPrice=lambda i:0
m['shop'].GetItemMetinSocket=lambda *a:0;m['shop'].GetItemAttribute=lambda *a:(0,0)
m['shop'].Open=lambda *a:self.opens.append(a)
m['shop'].Close=lambda:self.opens.append(('close',))
m['game'].GameWindow=type('GameWindow',(),{'Close':lambda self:7})
m['ui'].ImageBox=m['ui'].TextLine=Widget;m['uiCommon'].QuestionDialog=Question
# Fresh classes prevent cross-test wrapper chaining.
m['uiShop'].ShopDialog=type('Dialog',(Dialog,),{})
m['uiToolTip'].ItemToolTip=type('Tooltip',(Tooltip,),{})
for n,mod in m.items():self.previous[n]=sys.modules.get(n);sys.modules[n]=mod
helper=types.ModuleType('extern_wa_shopitem');self.previous[helper.__name__]=sys.modules.get(helper.__name__);sys.modules[helper.__name__]=helper
exec(script('ShopItemCurrencyScript.inc'),helper.__dict__)
self.ns={'xrange':range};exec(script('TicketShopScript.inc'),self.ns)
def tearDown(self):
for n,v in self.previous.items():
if v is None:sys.modules.pop(n,None)
else:sys.modules[n]=v
def test_confirmation_uses_source_cost_and_global_slot(self):
d=self.mods['uiShop'].ShopDialog();d.AskBuyItem(1);q=d.itemBuyQuestionDialog
self.assertEqual(q.pos,41);self.assertIn('原木 ×10',q.text);self.assertIn('门票',q.text)
q.accept();q.cancel();self.assertEqual(d.answers,[True,False]);self.assertEqual(self.questionStatus,[1])
def test_regular_shop_retains_original_branch(self):
d=self.mods['uiShop'].ShopDialog();d.AskBuyItem(2);self.assertEqual(d.old,[('ask',2)])
t=self.mods['uiToolTip'].ItemToolTip();t.SetShopItem(2);self.assertEqual(t.old,[2])
def test_item_currency_tooltip_has_icon_and_quantity(self):
t=self.mods['uiToolTip'].ItemToolTip();t.SetShopItem(41)
self.assertEqual(t.item[0],25163);self.assertEqual(len(t.childrenList),3)
self.assertEqual(t.childrenList[1].text,'原木');self.assertEqual(t.childrenList[2].text,'数量:10')
def test_session_teardown_clears_shop_state_and_forwards(self):
self.assertEqual(self.mods['game'].GameWindow().Close(),7);self.assertEqual(self.opens,[('close',)])
def test_remote_currency_shop_is_npc_buy_mode(self):
self.prices[0]=(90011,10)
d=self.mods['uiShop'].ShopDialog();d.Open(0)
self.assertEqual(self.opens,[(False,False)])
if __name__=='__main__':unittest.main()
+40
View File
@@ -0,0 +1,40 @@
"""Round-trip tracker preferences through the actual classic config reader/writer."""
import pathlib, subprocess, tempfile, unittest, os
ROOT=pathlib.Path(__file__).resolve().parents[2]
class TrackConfigTest(unittest.TestCase):
def test_cold_restart_round_trip(self):
source=(ROOT/'src/port/UserInterface/PythonSystem.cpp').read_text()
header=(ROOT/'src/port/UserInterface/PythonSystem.h').read_text()
struct=header[header.index('typedef struct SConfig'):header.index('} TConfig;')+len('} TConfig;')]
def method(name):
a=source.index('bool CPythonSystem::'+name+'(');b=source.index('\n}',a)+2
return source[a:b]
code=r'''
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <cmath>
using DWORD=unsigned;using BYTE=unsigned char;using FLOAT=float;
#define stricmp strcasecmp
#define DEFAULT_VALUE_ALWAYS_SHOW_NAME false
const int SM_CXFULLSCREEN=0,SM_CYFULLSCREEN=1;
unsigned GetSystemMetrics(int){return 4096;}
int g_iLoadingDelayTime=20;
class CPythonSystem {public:
'''+struct+r'''
TConfig m_Config={},m_OldConfig={};bool LoadConfig();bool SaveConfig();
};
'''+method('LoadConfig')+method('SaveConfig')+r'''
int main(){
CPythonSystem first;strcpy(first.m_Config.SaveID,"0");first.m_Config.width=1280;
first.m_Config.dungeonTrack=true;first.m_Config.bossTrack=true;assert(first.SaveConfig());
CPythonSystem cold;assert(cold.LoadConfig());assert(cold.m_Config.dungeonTrack && cold.m_Config.bossTrack);assert(cold.m_Config.width==1280);
cold.m_Config.dungeonTrack=false;assert(cold.SaveConfig());
CPythonSystem again;assert(again.LoadConfig());assert(!again.m_Config.dungeonTrack && again.m_Config.bossTrack);
}
'''
with tempfile.TemporaryDirectory() as tmp:
p=pathlib.Path(tmp);(p/'test.cpp').write_text(code)
subprocess.run([os.environ.get('CXX','c++'),'-std=c++17',str(p/'test.cpp'),'-o',str(p/'test')],check=True)
subprocess.run([str(p/'test')],cwd=tmp,check=True)