#!/usr/bin/env python3 """Stage the AVA2 drop items that the 203 server lacks as ordinary 40250 items (server rows + client patch pack). Only types/subtypes/flags the 40250 server understands (plus the ported AVA2 systems: sash, mount, costume enchants, talismans, new rings) survive; items of the AVA2-only systems not ported yet (pets, weapon/sash-skin/effect costume enchants, new skill books) become plain ITEM_NONE items. Also writes mobs-server.tsv (MOUNT_MOBS) for install_items.py. Usage: see build_zh_locale.build_ava2_items and --help. """ import argparse,json,re,shutil,subprocess,tarfile from pathlib import Path HERE=Path(__file__).resolve().parent RANGES=((54001,54027,'时装强化石'),(54028,54078,'发型强化石'),(54079,54123,'武器外观强化石'), (54124,54174,'坐骑外观强化石'),(54175,54219,'披风外观强化石'),(54220,54267,'特效强化石')) # Dragon armor: +0..+9 per class (the refine chain needs every step). DRAGON={21210:'暗龙铠甲',21230:'风龙铠甲',21250:'魔龙铠甲',21270:'神龙铠甲'} # Talismans (P7, server port_pendant.cpp): +0..+200 per element, refine sets 440-499 (../pendant/refine.sql). PENDANT={9600:'火之护符',9830:'冰之护符',10060:'土之护符',10290:'暗之护符',10520:'风之护符',10750:'雷之护符'} PENDANT_STEPS=201 # New rings (P8, server port_rings.cpp): +0..+9 per family, 203's refine sets 46-54. RINGS={19500:'红宝石戒指',19520:'石榴石戒指',19540:'祖母绿戒指',19560:'蓝宝石戒指'} # Talisman attribute items: 71302 / 53996 reroll, 71301 / 53997 add (53996 / 53997 are generic on AVA2). PENDANT_SCROLLS={53996,53997,71301,71302} # AVA2 spirit stones: 20 complete grade chains, special stones and the broken-stone marker. STONE_FAMILIES={0:'屠杀石',4:'偏执石',8:'创伤石',12:'愚钝石',30:'鸡血石',31:'羊脂玉',32:'羚角石', 33:'虹河石',34:'青胆石',35:'精石',36:'鹰翼石',37:'木鱼石',38:'龙骨石',39:'青石', 40:'彩芒石',41:'鹿影石',42:'东海石',43:'帝王石',44:'破碑之石',45:'克首领之石', 46:'普攻强化石',47:'技能强化石',48:'普攻抵抗石',49:'技能抵抗石'} STONE_IDS={28000+100*grade+family for grade in range(6) for family in range(30,50)} | {28000,28100,28960} | {28000+100*grade+family for grade in range(1,6) for family in (4,8,12)} def stone_name(v): if v==28960:return '碎石片' grade=(v-28000)//100 # AVA2's special stones are not ordinary +0..+5 upgrade chains. Keep their visible grades. if v in (28100,28104,28304,28404,28504,28108,28308,28408):grade=0 return '%s+%d'%(STONE_FAMILIES[v%100],grade) def stone_lock_reason(cols, E): if cols[2] != 'ITEM_METIN': return '原始数据为占位物品,该灵石暂未开放。' if int(cols[0]) in STONE_IDS else None applies=[a for a,v in zip(cols[18:24:2],cols[19:24:2]) if a!='APPLY_NONE' and number(v)] if not applies and int(cols[0])!=28960:return '原始数据未配置属性,该灵石暂未开放。' if 'APPLY_ATTBONUS_WOLFMAN' in applies:return '狼人职业尚未开放,该灵石暂时无法使用。' missing=[a for a in applies if a not in E['apply']] if missing:raise ValueError('unsupported stone applies: '+','.join(missing)) return None # Models of the armor shapes the 40250 race msm lack (registered by the client's mt_shapes script): shape -> # model stem ('%s' = race); RACE_PATHS = the ShapeData PathName of each race msm. ARMOR_SHAPES={32:'%s_7_1'} SHOP_ARMOR_SHAPES={40062:'%s_salsa1',40063:'%s_springwear1'} SHOP_HAIRS={161:'hair/hair_16_1',191:'hair/hair_19_1'} RACE_PATHS={'warrior':('pc','pc2'),'assassin':('pc2','pc'),'sura':('pc','pc2'),'shaman':('pc2','pc')} # (male, female) # Kept with their 40250 meaning; everything else becomes ITEM_NONE (see module doc). KEEP_TYPES={'ITEM_MATERIAL','ITEM_QUEST','ITEM_GIFTBOX','ITEM_NONE','ITEM_TREASURE_BOX','ITEM_TREASURE_KEY','ITEM_NEW_RINGS'} KEEP_SUBTYPES={('ITEM_WEAPON',s) for s in ('WEAPON_SWORD','WEAPON_DAGGER','WEAPON_BOW','WEAPON_TWO_HANDED','WEAPON_BELL','WEAPON_FAN')}|{('ITEM_ARMOR','ARMOR_FOOTS'),('ITEM_ARMOR','ARMOR_BODY'),('ITEM_ARMOR','ARMOR_PENDANT'),('ITEM_METIN','METIN_NORMAL')}|{('ITEM_COSTUME',s) for s in ('COSTUME_SASH','COSTUME_MOUNT','COSTUME_MOUNT_SKIN')} DESC={'ITEM_METIN':'可镶嵌到武器的空孔中。','ITEM_MATERIAL':'制作与升级材料。','ITEM_QUEST':'任务物品。','ITEM_GIFTBOX':'打开后可获得物品。','ITEM_TREASURE_BOX':'需要对应的钥匙才能打开。','ITEM_TREASURE_KEY':'可以打开对应的宝箱。','ITEM_WEAPON':'','ITEM_ARMOR':'','ITEM_COSTUME':'披风。可在披风工匠处合成升级,或吸收武器、铠甲的部分属性。', 'ITEM_NEW_RINGS':'戒指。装备在两个戒指栏之一。可用钻头开孔(最多 3 孔)并镶嵌对应的宝石,可用转换道具重洗属性、用追加道具增加属性。'} # Sash system (metin2-server docs/FEATURE-AVA2-UNLOCK.md P4): effects registered by the client's mt_sash script # (files they reference are staged too), the window images, and item_scale.txt (model scale per job/sex; a row # covers vnum..vnum+4). SASH_EFFECTS=('d:/ymir work/effect/etc/buff/buff_item6.mse','d:/ymir work/effect/etc/buff/buff_item7.mse', 'd:/ymir work/pc/common/effect/armor/acc_01.mse') # Switchbot window (AVA2-PARITY-PLAN 阶段 1, client mt_switchbot = AVA2 uiswitchbot.py): its buttons and ui.ThinBoardCircle's frame. SWITCHBOT_UI=('d:/ymir work/ui/switchbot/','d:/ymir work/ui/pattern/thinboardcircle/') SASH_LOCALE={'locale/en/ui/acce/acce_combine.tga':'locale/zh/ui/acce/acce_combine.tga', 'locale/en/ui/acce/acce_absorb.tga':'locale/zh/ui/acce/acce_absorb.tga'} # Per-subtype descriptions (override DESC). # Costume enchants (P6, server port_costume_attr.cpp): only the body / hair / mount-skin ranges have a 40250 # target; AVA2 apply numbers in value0 equal 203's (P2 aligned 139/140). The rest stay locked. ENCHANT_KEEP=((54001,54078),(54124,54174)) DESC_SUB={('ITEM_USE','USE_CHANGE_ATTRIBUTE'):'拖到未穿戴的对应时装上,附加一条固定属性(每件时装最多 3 条,不能重复)。', ('ITEM_COSTUME','COSTUME_BODY'):'时装。装备后改变角色服装外观,附加属性在装备期间生效。', ('ITEM_COSTUME','COSTUME_HAIR'):'发型时装。装备后改变角色发型或头饰,附加属性在装备期间生效。', ('ITEM_COSTUME','COSTUME_MOUNT'):'坐骑时装。装备后召唤该坐骑(需要已拥有马匹),装备期间属性生效。', ('ITEM_COSTUME','COSTUME_MOUNT_SKIN'):'坐骑外观。需先装备坐骑时装,装备后改变坐骑外观。', ('ITEM_ARMOR','ARMOR_PENDANT'):'护符。装备在护符栏,对相应属性的怪物伤害提高(强化等级 +1 = +1%)。可用护符强化道具重洗属性,用护符加持道具追加属性(最多 5 条)。'} # Per-vnum descriptions (override DESC_SUB). DESC_VNUM={53998:'拖到未穿戴的时装上,移除最后一条普通属性,保留稀有属性。',53999:'拖到未穿戴的时装上,移除全部普通属性,保留稀有属性。', 100001:'拖到龙魂石上,补充总使用时间的50%,不超过时间上限。',100002:'拖到龙魂石上,补充24小时使用时间,不超过时间上限。',53996:'拖到未穿戴的护符上,重新随机全部属性。',71302:'拖到未穿戴的护符上,重新随机全部属性。', 53997:'拖到未穿戴的护符上,追加一条属性(最多 5 条)。',71301:'拖到未穿戴的护符上,追加一条属性(最多 5 条)。'} # Mount system (P5): races of the mount skins that 203 and the 40250 client lack -> (zh name, npc_mount folder). # Their AVA2 mob_proto rows go to mobs-server.tsv, the whole model folder into the pack; the client's mt_mount # script registers the race names (npclist.txt is read from the root pack only). MOUNT_MOBS={32012:('蓝色巴里','christmas_2017_sleddog'),32028:('白色冬日羊驼','christmas_2020_alpaca')} LOCKED='该物品所属的系统尚未开放,暂时无法使用。' def enums(proto_reader): src=proto_reader.read_text(encoding='latin1') def arr(name): m=re.search(r'(?:static\s+)?string\s+'+name+r'\[\]\s*=\s*\{(.*?)\};',src,re.S) return re.findall(r'"([^"]+)"',m.group(1)) types=arr('arType');m=re.search(r'arSubType\[\]\s*=\s*\{(.*?)\};',src,re.S) subs=[arr(t) if t!='0' else [] for t in re.findall(r'\b(0|arSub\d+)\b',re.sub(r'//[^\n]*','',m.group(1)))] assert len(subs)==len(types),(len(subs),len(types)) return dict(type=types,sub=subs,anti=arr('arAntiFlag'),flag=arr('arFlag'),wear=arr('arWearrFlag'), imm=arr('arImmune'),limit=arr('arLimitType'),apply=arr('arApplyType')) def tokens(text):return [t.strip() for t in text.split('|') if t.strip() and t.strip() not in ('NONE','0')] def number(text): try:return int(text) except ValueError:return 0 def names(): result={} for line in (HERE/'names_zh.tsv').read_text().splitlines(): if line and not line.startswith('#'): v,n=line.split('\t');result[int(v)]=n for lo,hi,n in RANGES: for v in range(lo,hi+1):result[v]=n for base,n in DRAGON.items(): for k in range(10):result[base+k]='%s+%d'%(n,k) for base,n in PENDANT.items(): for k in range(PENDANT_STEPS):result[base+k]='%s+%d'%(n,k) for base,n in RINGS.items(): for k in range(10):result[base+k]='%s+%d'%(n,k) # Combine consumes two sashes and advances to the next grade; import every step. for base,label in ((85001,'领主'),(85005,'大师'),(85011,'王朝'),(85015,'皇家')): for grade,suffix in enumerate(('普通','精致','高级','个人')): result[base+grade]=label+'披风('+suffix+')' result.update({41119:'萨尔萨礼服(男)',41120:'萨尔萨舞裙(女)', 41121:'绅士礼服(男)',41122:'鸡尾酒礼裙(女)', 45005:'莫西干发型(男)',45006:'刘海发型(女)', 45057:'博加特礼帽(男)',45058:'花饰发型(女)'}) for base,label in ((71500,'狮子'),(71503,'野猪'),(71506,'狼'),(71509,'老虎')): result[base]=label+'封印(7天)';result[base+1]=label+'封印(30天)' for v in sorted(STONE_IDS):result[v]=stone_name(v) result.update({50348:'属性锁定符',50349:'属性解锁符',70002:'第三只手'}) for month in range(1,13):result[25149+month]='%d月战令票'%month return result def convert(cols,E,imported): """AVA2 item_proto.txt row (str columns) -> (server row columns, client numeric fields, kept?).""" c=[x.strip() for x in cols[:33]] t,st=c[2],c[3] kept=t in KEEP_TYPES or (t,st) in KEEP_SUBTYPES or ((t,st)==('ITEM_USE','USE_CHANGE_ATTRIBUTE') and any(lo<=int(c[0])<=hi for lo,hi in ENCHANT_KEEP)) or ( (t,st) in (('ITEM_USE','USE_CHANGE_ATTRIBUTE'),('ITEM_USE','USE_ADD_ATTRIBUTE')) and int(c[0]) in PENDANT_SCROLLS) or ( int(c[0]) in (53998,53999) and (t,st)==('ITEM_USE','USE_CHANGE_ATTRIBUTE')) or ( int(c[0]) in (100001,100002) and t=='ITEM_USE' and st in ('USE_TIME_CHARGE_PER','USE_TIME_CHARGE_FIX')) or ( int(c[0]) in (50348,50349) and (t,st)==('ITEM_USE','USE_CHANGE_ATTRIBUTE')) or ( int(c[0]) in (70002,39063,39064) and (t,st)==('ITEM_USE','USE_SPECIAL')) if t=='ITEM_COSTUME' and st in ('COSTUME_BODY','COSTUME_HAIR') and int(c[0]) in (41119,41120,41121,41122,45005,45006,45057,45058):kept=True if stone_lock_reason(c,E):kept=False anti=tokens(c[5]);flags=tokens(c[6]) if 'ITEM_STACKABLE' in anti:anti.remove('ITEM_STACKABLE');flags.append('ITEM_STACKABLE') anti=[a for a in dict.fromkeys(anti) if a in E['anti']];flags=[f for f in dict.fromkeys(flags) if f in E['flag']] if not kept: t,st='ITEM_NONE','0';wear=imm=[];applies=[('APPLY_NONE','0')]*3;values=['0']*6 flags=[f for f in flags if f in ('ITEM_STACKABLE','LOG')] else: if t in ('ITEM_QUEST','ITEM_GIFTBOX','ITEM_NONE','ITEM_MATERIAL') and st not in E['sub'][E['type'].index(t)]:st='0' wear=[w for w in tokens(c[7]) if w in E['wear']] if t in ('ITEM_WEAPON','ITEM_ARMOR','ITEM_METIN') else [] imm=[i for i in tokens(c[8]) if i in E['imm']] applies=[(a,v) if a in E['apply'] else ('APPLY_NONE','0') for a,v in zip(c[18:24:2],c[19:24:2])] values=[str(number(v)) for v in c[24:30]] refine=(c[11],c[12]) if number(c[11]) in imported else ('0','0') limits=[(l if l in E['limit'] else 'LIMIT_NONE',str(number(v))) for l,v in zip(c[14:18:2],c[15:18:2])] j=lambda xs:' | '.join(xs) if xs else 'NONE' server=[c[0],c[1],t,st,c[4],j(anti),j(flags),j(wear),j(imm),c[9],c[10],refine[0],refine[1],c[13]] for l,v in limits:server+=[l,v] for a,v in applies:server+=[a,str(number(v))] server+=values+[str(number(c[30])),str(number(c[31])),str(number(c[32])) if len(c)>32 and c[32] else '0'] bits=lambda xs,k:sum(1< source file, from the AVA2 pack manifests.""" index={} for xml in sorted(pack_maker.glob('*_create.xml')): for archived,source in re.findall(r'ArchivedPath="([^"]+)">',xml.read_text(encoding='latin1')): index.setdefault(archived.lower().replace('\\','/'),pack_maker.parent/source) return index def pack_ui_subimages(assets,files): """Resolve original v1 subimage atlases under a private path; never replace the base UI atlas.""" root='d:/ymir work/ui/' for sub in list(assets.rglob('*.sub')): text=sub.read_bytes() match=re.search(rb'(?im)^image\s+"([^"\r\n]+)"',text) if not match:continue image=match[1].decode('latin1').lower().replace('\\','/') version=re.search(rb'(?im)^version\s+(\S+)',text) parent=sub.relative_to(assets).as_posix().rsplit('/',1)[0]+'/' source=image if image.startswith('d:/') else (parent if version and version[1]==b'2.0' else root)+image if image.startswith('ava2_native/') and (assets/source).is_file():continue # AVA2 v1 images resolve against the global UI search path. if source not in files: # Worldard subimages keep their atlas beside the parent directory. candidates=[q for q in (parent+image,parent.rstrip('/').rsplit('/',1)[0]+'/'+image) if q in files] if len(set(candidates))!=1:raise ValueError('missing or ambiguous UI subimage atlas %s for %s'%(source,sub)) source=candidates[0] alias='ava2_native/'+source[len(root):] if source.startswith(root) else 'ava2_native/'+source.rsplit('/',1)[-1] target=assets/(root+alias);target.parent.mkdir(parents=True,exist_ok=True) if not target.exists():shutil.copy2(files[source],target) # v1's image is relative to the global UI search path. updated=text[:match.start(1)]+alias.encode('ascii')+text[match.end(1):] updated=re.sub(rb'(?im)^version\s+\S+',b'version 1.0',updated) sub.write_bytes(updated) def copy_ui_literal_assets(text,assets,files): """Copy literal layout dependencies too, including placeholder icons used before runtime substitution.""" for name in re.findall(r"[\"']((?:icon/|d:/ymir work/ui/)[^\"']+\.(?:tga|dds|sub))[\"']",text,re.I): name=name.lower().replace('\\','/') if name not in files:raise ValueError('missing UI layout asset '+name) target=assets/name;target.parent.mkdir(parents=True,exist_ok=True) if not target.exists():shutil.copy2(files[name],target) def server_proto(ava,filename): path=ava/'2. Backup SF+SRC and SQL/home/srv1/db'/filename if path.is_file():return path.read_bytes() with tarfile.open(ava/'2. Backup SF+SRC and SQL/FILES+SRC.tgz','r:gz') as source: member=source.extractfile('home/srv1/db/'+filename) if member is None:raise ValueError('AVA2 archive has no '+filename) return member.read() def prepare(ava,proto_reader,locale,output,tool,packer,wrap=lambda text:text): """wrap: the locale's itemdesc line wrapping (build_zh_locale.wrap_description).""" E=enums(proto_reader);zh=names();wanted=set(zh) db=ava/'2. Backup SF+SRC and SQL/home/srv1/db';pack_maker=ava/'1. Client DEV/pack_maker' rows={} raw=server_proto(ava,'item_proto.txt') for line in raw.splitlines(): cols=line.split(b'\t') if cols[0].strip().isdigit() and int(cols[0]) in wanted:rows[int(cols[0])]=[x.decode('latin1') for x in cols] # The archived server DB omits lock materials and lower sash grades. # Fill missing requested rows from AVA2's original client definitions. if wanted-rows.keys(): dump=ava/'3. Source BIN/Tools/DumpProto/Release/item_proto.txt' if not dump.is_file():dump=ava.parent/'3. Source BIN/Tools/DumpProto/Release/item_proto.txt' for line in dump.read_bytes().splitlines(): cols=line.split(b'\t') if cols[0].strip().isdigit() and int(cols[0]) in wanted-rows.keys(): rows[int(cols[0])]=[x.decode('latin1') for x in cols] assert rows.keys()==wanted,sorted(wanted-rows.keys()) listrows={} for line in (pack_maker/'locale/locale/es/item_list.txt').read_bytes().splitlines(): c=[x.strip() for x in line.split(b'\t')] if c and c[0].isdigit() and int(c[0]) in wanted:listrows[int(c[0])]=[x.decode('latin1') for x in c if x] files=pack_index(pack_maker) for v in wanted-listrows.keys(): # 16 items have no AVA2 item_list row; their icons ship under the vnum listrows[v]=[str(v),'ETC','icon/item/%05d.tga'%v] output.mkdir(parents=True,exist_ok=True) assets=output/'assets' if assets.exists():shutil.rmtree(assets) server=[];client=[];report={'kept':[],'locked':[]} for v in sorted(wanted): s,n,kept=convert(rows[v],E,wanted) name=zh[v];s[1]=name server.append('\t'.join(s).encode('gbk')) client.append(('\t'.join(map(str,n))+'\t'+name).encode('gbk')) report['kept' if kept else 'locked'].append(v) copied=0 for v,row in listrows.items(): for path in row[2:4]: p=path.lower().replace('\\','/') sources=[p] if p.endswith('.gr2'):sources+=[s for s in MODEL_TEXTURES.get(p.rsplit('/',1)[1],())] for q in sources: if q not in files:raise SystemExit('missing AVA2 asset %s for %d'%(q,v)) target=assets/q;target.parent.mkdir(parents=True,exist_ok=True) if not target.exists():shutil.copy2(files[q],target);copied+=1 mount_files=[q for q in files for _,d in MOUNT_MOBS.values() if q.startswith('d:/ymir work/npc_mount/%s/'%d)] if len({q.split('/')[3] for q in mount_files})!=len(MOUNT_MOBS):raise SystemExit('missing AVA2 mount models') switchbot_files=[q for q in files if q.startswith(SWITCHBOT_UI)] if len(switchbot_files)