Files
WoW-Hybrid-gateway/ops/build_forever_create.py

552 lines
44 KiB
Python

#!/usr/bin/env python3
"""Build a read-only source-derived 70334 self-create serializer; never runs a server.
Generated Trinity code remains GPL-2.0-or-later. Build outputs stay under gateway/build; source-only archives may use runtime/codec-closures.
"""
import argparse
import ast
import hashlib
import json
from pathlib import Path
import re
import shlex
import subprocess
import time
from codec_build_cache import Cache,write_changed
import keyring_serializer
import classic_party_writer
from windows_codec_writer_closure import selected_function
ROOT=Path(__file__).resolve().parents[1]
def project_player_update(method):
# Scalar20 owns Inebriation. Removing only its payload leaves a live mask
# bit and corrupts the remainder of the native PlayerData stream.
allowed={0,3,12,14,16,19,20,21,25,50,53,229,256}
method=re.sub(r'if \(changesMask\[(\d+)\]\)',
lambda m:m[0] if int(m[1]) in allowed else 'if constexpr (false)',method)
return method.replace('WriteUpdate(ignoreNestedChangesMask, data, receiver, owner)',
'WriteUpdate(ignoreNestedChangesMask, data, nullptr, nullptr)')
def integer(expression, names):
node=ast.parse(expression,mode='eval').body
def visit(n):
if isinstance(n,ast.Constant) and isinstance(n.value,int): return n.value
if isinstance(n,ast.Name): return names[n.id]
if isinstance(n,ast.BinOp):
a,b=visit(n.left),visit(n.right)
if isinstance(n.op,ast.Add):return a+b
if isinstance(n.op,ast.Sub):return a-b
if isinstance(n.op,ast.LShift):return a<<b
if isinstance(n.op,ast.BitOr):return a|b
raise ValueError('Unsupported enum expression')
return visit(node)
def protocol_archive(path):
"""Select a regular ar archive without mutating installed build outputs."""
path=Path(path)
if path.is_symlink() or not path.is_file():
raise ValueError('Protocol library must be a regular archive file')
with path.open('rb') as stream:
if stream.read(8)!=b'!<arch>\n':
raise ValueError('Protocol library is not an ar archive')
resolved=path.resolve()
return resolved, {'path':str(resolved),'sha256':hashlib.sha256(resolved.read_bytes()).hexdigest(),'bytes':resolved.stat().st_size}
def packet_response_writer(forever, profile, output, packet, namespace, signatures):
packet_dir = forever / 'src/server/game/Server/Packets'
source = packet_dir / (packet + '.cpp')
for path in (source, packet_dir / (packet + '.h')):
if path.relative_to(forever).as_posix() not in profile['forever_sha256']:
raise RuntimeError('Unpinned packet writer input: ' + path.name)
text = source.read_text()
methods = [selected_function(text, signature) for signature in signatures]
write_changed(output, '// SPDX-License-Identifier: GPL-2.0-or-later\n'
f'#include "{packet}.h"\n#include "PacketOperators.h"\n'
f'namespace WorldPackets::{namespace} {{\n' + '\n\n'.join(methods) + '\n}\n')
return source
def main():
started=time.monotonic()
parser=argparse.ArgumentParser()
parser.add_argument('--forever-source',type=Path,default=Path.home()/'Projects/WoW-Hybrid/servers/trinity-forever')
parser.add_argument('--turtle-source',type=Path,default=Path.home()/'Servers/tortoise-wow')
parser.add_argument('--prepare-only',action='store_true',help='Generate and hash source inputs without invoking a compiler or linker')
parser.add_argument('--output-directory',type=Path,help='Separate build directory for background codec tests; never a client installation')
parser.add_argument('--protocol-library',type=Path,help='Explicit matching gateway_protocol archive for an isolated codec build')
parser.add_argument('--item-package',type=Path,help='Compile a staged compatibility package only with a separate output directory')
parser.add_argument('--item-package-sha256',help='Exact staged package SHA256; reuse the guarded package read for compilation')
parser.add_argument('--frozen-hotfix-header-sha256', help='Use the exact tracked header after verifying every row, page and lookup against the staged package')
parser.add_argument('--compact-metadata-data',action='store_true',help='Opt in to an escaped-byte registry blob for a staged --item-package; wire rows and public registry shape are unchanged')
parser.add_argument('--metadata-compiler',choices=('clang++','g++'),default='clang++',help='Compiler for only the compact staged metadata consumer; all other objects and links retain clang++')
parser.add_argument('--item-build-base-manifest',type=Path,help='Portable accepted item build manifest; default factory selection')
parser.add_argument('--item-build-base-root',type=Path,help='Portable source-input bundle for the accepted item build base')
parser.add_argument('--item-build-base-source-root',type=Path,help='Checkout containing the source files pinned by the accepted base manifest')
parser.add_argument('--render-profile-header',type=Path,help='Compile an isolated reviewed item-render header; requires a separate output and explicit matching protocol archive')
parser.add_argument('--login-profile-header',type=Path,help='Isolated source-proved creation-pair profile; requires --creation-profile-proof')
parser.add_argument('--creation-profile-proof',type=Path,help='Pinned all59 source eligibility receipt for the isolated login profile')
args=parser.parse_args();forever=args.forever_source.resolve();turtle=args.turtle_source.resolve()
default_output=ROOT/'build/forever-schema';output=args.output_directory.resolve()if args.output_directory else default_output
allowed_outputs=(ROOT/'build',ROOT/'runtime/vm-build-share')+((ROOT/'runtime/codec-closures',) if args.prepare_only else ())
if not any(output!=base and output.is_relative_to(base) for base in allowed_outputs) or output.is_symlink():parser.error('Codec output must be below build/VM share, or runtime/codec-closures for source-only preparation')
if args.prepare_only and output.exists():parser.error('Source-only preparation requires a fresh directory')
if args.frozen_hotfix_header_sha256 and not (args.item_package and args.item_package_sha256 and args.compact_metadata_data):
parser.error('The frozen native header requires an explicit pinned compact metadata package')
# Reject invalid creation overrides before resolving optional item inputs
# or staging any accepted package into the output directory.
from creation_login_profile import isolated_profile
login_profile=isolated_profile(args.login_profile_header,args.creation_profile_proof,
output,default_output,ROOT/'include/gateway/turtle_login_profile.hpp')
from isolated_item_render_profile import load_build_base,resolve_base_package
build_base=None
if not args.item_package and not args.render_profile_header:
build_base=load_build_base(args.item_build_base_manifest,args.item_build_base_root,source_root=args.item_build_base_source_root or ROOT)
if output==default_output:parser.error('Accepted base builds require a separate --output-directory and matching --protocol-library')
relocation=resolve_base_package(build_base,output)
args.item_package=Path(relocation['resolved_path']);args.item_package_sha256=relocation['resolved_sha256']
args.compact_metadata_data=True
args.render_profile_header=Path(build_base['inputs']['render_header']['path'])
elif args.item_build_base_manifest or args.item_build_base_root or args.item_build_base_source_root:
parser.error('Choose accepted base inputs or an explicit isolated header/package pair')
elif bool(args.item_package)!=bool(args.render_profile_header):
parser.error('Explicit isolated codec builds require both matching item package and render header')
if args.item_package and output==default_output:parser.error('Staged item packages require a separate --output-directory; preserve the running codec')
if args.compact_metadata_data and not args.item_package:parser.error('Compact metadata requires a staged --item-package and separate --output-directory')
if args.metadata_compiler!='clang++' and not args.compact_metadata_data:parser.error('Alternative metadata compiler requires compact staged metadata and a separate output directory')
if args.item_package_sha256 and (not args.item_package or not re.fullmatch(r'[0-9a-f]{64}',args.item_package_sha256)):
parser.error('An exact lowercase SHA256 requires --item-package')
if args.render_profile_header and not args.protocol_library:parser.error('Render overrides require an explicit matching --protocol-library')
from isolated_item_render_profile import stage_render_profile,compiler_flags
render_profile=stage_render_profile(args.render_profile_header,output,default_output)
output.mkdir(parents=True,exist_ok=True);compatibility_flags=[];package_sha=None
login_flags=[]
if login_profile is not None:
profile_bytes=Path(login_profile['header']['path']).read_bytes()
if hashlib.sha256(profile_bytes).hexdigest()!=login_profile['header']['sha256']:
raise ValueError('Creation profile changed after admission')
staged_profile=output/'staged-turtle-login-profile.hpp'
write_changed(staged_profile,profile_bytes.decode('utf-8'))
login_profile['compiled_header']={'path':str(staged_profile),'sha256':login_profile['header']['sha256']}
login_flags=['-DGW_TURTLE_LOGIN_PROFILE_HEADER='+json.dumps(str(staged_profile))]
from validate_warrior_cooldown_build import validate_current_package
cooldown_guard=None
if args.item_package:
from item_package_preflight import read_compatibility_package
from item_sparse_compat import _package_data,load_working_wire_baseline
if args.item_package_sha256:
package_sha=args.item_package_sha256
cooldown_guard,package=validate_current_package(args.item_package,package_sha,return_package=True)
else:
package,package_sha=read_compatibility_package(args.item_package)
if package.get('build')!='1.60.1.70334' or package.get('schema')!='wowstatic_camelot_1_60_1':raise ValueError('Staged item package build/schema mismatch')
wire_baseline=load_working_wire_baseline(package,required=True)
push,header,pages=_package_data(package['rows'],wire_baseline=wire_baseline,compact_payloads=args.compact_metadata_data)
if package.get('push_id')!=push:raise ValueError('Staged item package push identity differs')
if 'pushes'in package and package['pushes']!=pages:raise ValueError('Staged item package page ownership differs')
if args.frozen_hotfix_header_sha256:
from item_sparse_compat import verified_frozen_registry_header
header=verified_frozen_registry_header(ROOT/'include/gateway/item_sparse_compat.hpp',
args.frozen_hotfix_header_sha256,header,package['rows'])
include=output/'compatibility-include';(include/'gateway').mkdir(parents=True,exist_ok=True)
write_changed(include/'gateway/item_sparse_compat.hpp',header)
from item_random_property_compat import stage_header
random_header=stage_header(package)
if random_header is None:raise ValueError('Working codec build requires an explicit random-property profile')
if random_header is not None:write_changed(include/'gateway/item_random_property_profile.hpp',random_header)
compatibility_flags=['-I'+str(include)]
# A source cooldown bit may only target the complete, current native
# identity set proved by the generated Warrior mapping, including overlays.
guard_package=args.item_package or ROOT/'docs/evidence/data/item-sparse-compat/package.json'
guard_package_sha=package_sha if args.item_package else hashlib.sha256(guard_package.read_bytes()).hexdigest()
if cooldown_guard is None:cooldown_guard=validate_current_package(guard_package,guard_package_sha)
if not cooldown_guard['admissible']:raise ValueError('Warrior cooldown routes differ from current metadata identity sets')
if not args.item_package:
from item_package_preflight import read_compatibility_package
from item_sparse_compat import package_payloads,load_working_wire_baseline
current_package,_=read_compatibility_package(guard_package)
_,current_header=package_payloads(current_package['rows'],wire_baseline=load_working_wire_baseline(current_package,required=True))
if current_header.encode()!=(ROOT/'include/gateway/item_sparse_compat.hpp').read_bytes():
raise ValueError('Default compiled metadata differs from guarded canonical package')
from item_random_property_compat import stage_header
current_random=stage_header(current_package)
if current_random is None or current_random.encode()!=(ROOT/'include/gateway/item_random_property_profile.hpp').read_bytes():
raise ValueError('Default compiled random-property profile differs from guarded canonical package')
write_changed(output/'warrior-cooldown-guard.json',json.dumps(cooldown_guard,indent=2)+'\n')
source=forever/'src/server/game/Entities/Object/Updates/UpdateFields.cpp'
profile=json.loads((ROOT/'docs/FOREVER_SCHEMA_PROFILE.json').read_text())
for name,expected in profile.get('forever_db2_sha256',{}).items():
if hashlib.sha256((forever/'install/bin/dbc/enUS'/name).read_bytes()).hexdigest()!=expected:raise RuntimeError('Forever power table changed')
power_file=ROOT/'docs/evidence/gameplay/class-power-types-70334.json'
if hashlib.sha256(power_file.read_bytes()).hexdigest()!=profile['class_power_export_sha256']:raise RuntimeError('Audited power profile changed')
powers={}
for row in json.loads(power_file.read_text()):
cls,power=row['ClassID'],row['PowerType']
if not 1<=cls<12 or not 0<=power<32 or power in powers.setdefault(cls,[]):raise RuntimeError('Invalid class power profile')
powers[cls].append(power)
slots=[[-1]*4 for _ in range(12)]
for cls,types in powers.items():
for index,power in enumerate(sorted(types)):
if power<4:slots[cls][power]=index
# Native ComboPoints (PowerType 4) slot per class: the same sorted ChrClassesXPowerTypes order as above.
combo=[-1]*12
# Tortoise awards combo points only to Rogues (4) and Druids (11); other classes listing type 4 in
# ChrClassesXPowerTypes (Warrior, Mage) never receive them, and their PLAYER_FIELD_BYTES byte 1 is not points.
for cls,types in powers.items():
if cls in (4,11) and 4 in types:combo[cls]=sorted(types).index(4)
write_changed(output/'forever_power_profile.hpp','inline constexpr int ForeverClassPowerSlots[12][4] = {\n'+',\n'.join('{'+','.join(map(str,row))+'}' for row in slots)+'\n};\n'+
'inline constexpr int ForeverClassComboSlot[12] = {'+','.join(map(str,combo))+'};\n')
spec_file=ROOT/'docs/evidence/gameplay/class-specializations-70334.json'
if hashlib.sha256(spec_file.read_bytes()).hexdigest()!=profile['class_spec_export_sha256']:raise RuntimeError('Audited class specialization profile changed')
specs=[0]*12
for row in json.loads(spec_file.read_text()):
cls=row['ClassID']
if not cls:continue
if not 0<cls<12 or row['OrderIndex']!=0 or specs[cls]:raise RuntimeError('Default class specialization profile changed')
specs[cls]=row['ID']
write_changed(output/'forever_spec_profile.hpp','inline constexpr unsigned ForeverClassDefaultSpec[12] = {'+','.join(map(str,specs))+'};\n')
for relative,expected in profile['forever_sha256'].items():
if hashlib.sha256((forever/relative).read_bytes()).hexdigest()!=expected:
raise RuntimeError('Forever schema input changed: '+relative)
# New loot writers/enums must be explicitly reviewed and pinned in the
# same canonical profile before they enter the isolated source codec.
for relative in ('src/server/game/Server/Packets/LootPackets.cpp',
'src/server/game/Server/Packets/LootPackets.h',
'src/server/game/Loot/Loot.h','src/server/game/Loot/LootItemType.h'):
if relative not in profile['forever_sha256']:
raise RuntimeError('Unpinned loot source input: '+relative)
if hashlib.sha256((turtle/'src/game/Objects/UpdateFields.h').read_bytes()).hexdigest()!=profile['turtle_fields_sha256']:
raise RuntimeError('Turtle field indices changed; review schema profile')
text=source.read_text();methods=[]
for match in re.finditer(r'void (\w+)::WriteCreate\([^\n]+\) const\n\{',text):
brace=text.index('{',match.start());depth=1;end=brace+1
while depth:
depth+=(text[end]=='{')-(text[end]=='}');end+=1
method=text[match.start():end]
method=method.replace('std::string const surname = sCharacterCache->GetCharacterSurnameByGuid(owner->GetGUID());','std::string const surname;')
method=method.replace('ViewerDependentValue<StateWorldEffectIDsTag>::value_type','std::vector<uint32> const*')
method=re.sub(r'ViewerDependentValue<(\w+)Tag>::GetValue\(this, receiver, owner\)',
lambda m:'&*StateWorldEffectIDs' if m[1]=='StateWorldEffectIDs' else m[1],method)
method=method.replace('WriteCreate(data, receiver, owner)','WriteCreate(data, nullptr, nullptr)')
if match[1]=='ActivePlayerData':method=keyring_serializer.create(method)
methods.append(method)
if len(methods)!=126:raise RuntimeError('Source serializer profile changed; review before rebuilding')
# Retain the pinned Classic mask remapper and only audited explicit-mask unit writers.
update_methods=[]
for match in re.finditer(r'void (\w+)::WriteUpdate\([^\n]+\) const\n\{',text):
kind=match[1];signature=match[0]
if not ((kind in ('ObjectData','UnitData','ItemData','ContainerData','GameObjectData','DynamicObjectData') and 'Mask const&' in signature) or kind in ('VisibleItem','UnitAssistActionData','ItemEnchantment','ItemModList','SocketedGem','BitVector','BitVectors','QuestLog','RestInfo','StableInfo','StablePetInfo','ZonePlayerForcedReaction')):continue
brace=text.index('{',match.start());depth=1;end=brace+1
while depth:depth+=(text[end]=='{')-(text[end]=='}');end+=1
method=text[match.start():end].replace('ViewerDependentValue<StateWorldEffectIDsTag>::value_type','std::vector<uint32> const*')
method=re.sub(r'ViewerDependentValue<(\w+)Tag>::GetValue\(this, receiver, owner\)',lambda m:'&*StateWorldEffectIDs' if m[1]=='StateWorldEffectIDs' else m[1],method)
if kind=='DynamicObjectData':
# SpellCastVisual is a pure pair of integers. As in WriteCreate,
# the isolated writer has no live owner/player objects.
method=method.replace('WriteUpdate(ignoreNestedChangesMask, data, receiver, owner)',
'WriteUpdate(ignoreNestedChangesMask, data, nullptr, nullptr)')
if kind=='GameObjectData':
# Preserve the pinned original Classic28-bit mask remapper. Only
# Flags, State and ArtKit are admitted by --gameobject-values;
# unrelated nested fields must not instantiate unreviewed writers.
method=re.sub(r'if \(changesMask\[(\d+)\]\)',lambda m:m[0] if int(m[1]) in (0,12,16,19) else 'if constexpr (false)',method)
update_methods.append(method)
if len(update_methods)!=18:raise RuntimeError('Audited entity/item/exploration/game-object/quest/ground/rest update serializer method count changed')
# Preserve the pinned Classic player mask remapper and native visible-item
# framing. Only guild rank and this audited array are instantiated; unrelated player systems
# cannot gain accidental serialization support through this adapter.
player_helpers=text[text.index('static uint32 ClassicPlayerDataBit('):text.index('void PlayerData::WriteUpdate(Mask const&')]
start=text.index('void PlayerData::WriteUpdate(Mask const&');brace=text.index('{',start);depth=1;end=brace+1
while depth:depth+=(text[end]=='{')-(text[end]=='}');end+=1
# Keep the mask and payload for Customizations (3), and NativeSex (19).
# Group 50 writes the selected HOME byte in self PartyType values updates.
player_method=project_player_update(text[start:end])
update_methods.append(player_method)
# Keep native ActivePlayer framing/order, but instantiate only the audited
# scalar, skill and trait-config branches. SkillInfo's original nested
# update writer is required: mask63 alone would omit the skill payload.
active_start=text.index('static uint32 ClassicActivePlayerDataBit(')
active_end=text.index('void ActivePlayerData::WriteUpdate(Mask const&',active_start)
active_helpers=text[active_start:active_end]
# 374 is the native two-element ProfessionSkillLine group. Its children
# stay dynamically masked by the original writer (375 + slot).
# The owner self-resurrection list uses parent 0 and dynamic child 20.
allowed_active={0,20,32,58,60,61,63,64,70,72,73,75,77,78,79,91,101,102,105,107,108,109,110,124,132,133,134,147,148,155,163,272,311,374,401}
# Damage modifiers share group 275. The original writer selects each
# positive, negative and percentage school value by its own child bit.
allowed_active.add(275)
# 48 = CharacterBankTabSettings (group 32): a bank bag slot bought in the open bank adds a tab
# (Classic 4-bit count + byte padding are in the original writer); BankTabSettings writes each tab.
allowed_active.add(48)
# 56 = FarsightObject (group 32): Mind Vision / possess camera (Tortoise PLAYER_FARSIGHT); without its
# writer the mask bit ships with no GUID and 70334 reads past the update (crash, 2026-11-24).
allowed_active.add(56)
for kind in ('ActivePlayerData','TraitConfig','SkillInfo','BankTabSettings'):
needle='void '+kind+'::WriteUpdate('+('Mask const&' if kind=='ActivePlayerData' else 'bool ignoreChangesMask')
start=text.index(needle);brace=text.index('{',start);depth=1;end=brace+1
while depth:depth+=(text[end]=='{')-(text[end]=='}');end+=1
method=text[start:end]
if kind=='ActivePlayerData':
method=keyring_serializer.update(method)
method=re.sub(r'if \(changesMask\[(\d+)\]\)',lambda m:m[0] if int(m[1]) in allowed_active else 'if constexpr (false)',method)
update_methods.append(method)
mask_helpers=text[text.index('static uint32 ClassicUnitDataBit70009'):text.index('void UnitData::WriteUpdate(Mask const&')]
mask_helpers=keyring_serializer.mask_header(mask_helpers)
# Peer values use the original public visibility filter, not owner masks.
visibility_helpers=[]
already=mask_helpers+player_helpers+active_helpers+'\n'.join(update_methods)
for needle in ('static constexpr void UnitDataAppendAllowedFieldsMaskForFlag(',
'static constexpr void PlayerDataAppendAllowedFieldsMaskForFlag(',
'void UnitData::FilterDisallowedFieldsMaskForFlag(',
'void PlayerData::FilterDisallowedFieldsMaskForFlag('):
if needle in already:continue
start=text.index(needle);brace=text.index('{',start);depth=1;end=brace+1
while depth:depth+=(text[end]=='{')-(text[end]=='}');end+=1
visibility_helpers.append(text[start:end])
generated=output/'uf_create.cpp'
write_changed(generated,text[:text.index('#include')]+'''#include "UpdateFields.h"
#include "ByteBuffer.h"
#include "PacketOperators.h"
#include "UpdateFieldImpl.h"
#include "gateway/keyring_wire.hpp"
class ClassicOpcodes { public: static bool IsBuild70291OrLater() { return true; } };
namespace UF {
static uint32 ClassicCharacterSuperDistrictID() { return 2; }
static uint32 ClassicItemZoneFlags(uint32 flags) { return flags | 4 | ((flags & 1) ? 2 : 0); }
'''+ '\n\n'.join(methods)+'\n'+mask_helpers+'\n'+player_helpers+'\n'+active_helpers+'\n'+'\n\n'.join(visibility_helpers)+'\n'+'\n\n'.join(update_methods)+'\n}\n')
legacy=turtle/'src/game/Objects/UpdateFields.h'
enums=re.sub(r'/\*.*?\*/|//[^\n]*','',legacy.read_text(),flags=re.S);names={};lines=[]
for body in re.findall(r'enum \w+\s*\{(.*?)\}',enums,re.S):
current=-1
for entry in body.split(','):
entry=entry.strip()
if not entry:continue
if '=' in entry:
name,expression=entry.split('=',1);name=name.strip();current=integer(expression.strip(),names)
else:name=entry;current+=1
names[name]=current;lines.append(f'constexpr unsigned {name} = {current};')
write_changed(output/'turtle_fields.hpp','namespace Turtle {\n'+'\n'.join(lines)+'\n}\n')
query_source=forever/'src/server/game/Server/Packets/QueryPackets.cpp'
query_text=query_source.read_text();start=query_text.index('WorldPacket const* QueryCreatureResponse::Write()');brace=query_text.index('{',start);end=brace+1;depth=1
while depth:
depth+=(query_text[end]=='{')-(query_text[end]=='}');end+=1
query_generated=output/'query_create.cpp'
query_methods=[query_text[start:end]]
signature='WorldPacket const* CorpseLocation::Write()'
start=query_text.index(signature);brace=query_text.index('{',start);end=brace+1;depth=1
while depth:depth+=(query_text[end]=='{')-(query_text[end]=='}');end+=1
query_methods.append(query_text[start:end])
for signature in ('ByteBuffer& operator<<(ByteBuffer& data, PlayerGuidLookupData const&',
'ByteBuffer& operator<<(ByteBuffer& data, GuildGuidLookupData const&',
'ByteBuffer& operator<<(ByteBuffer& data, HouseLookupData const&',
'ByteBuffer& operator<<(ByteBuffer& data, NameCacheLookupResult const&',
'WorldPacket const* QueryPlayerNamesResponse::Write()',
'WorldPacket const* QueryPetNameResponse::Write()'):
start=query_text.index(signature);brace=query_text.index('{',start);end=brace+1;depth=1
while depth:depth+=(query_text[end]=='{')-(query_text[end]=='}');end+=1
query_methods.append(query_text[start:end])
write_changed(query_generated,'// SPDX-License-Identifier: GPL-2.0-or-later\n#include "QueryPackets.h"\n#include "PacketOperators.h"\nnamespace WorldPackets::Query {\n'+'\n'.join(query_methods)+'\n}\n')
# Export only response writers. The full request parsers also pull in live-world dependencies.
who_generated=output/'who_response.cpp'
who_source=packet_response_writer(forever,profile,who_generated,'WhoPackets','Who',(
'ByteBuffer& operator<<(ByteBuffer& data, WhoEntry const& entry)',
'ByteBuffer& operator<<(ByteBuffer& data, WhoResponse const& response)',
'WorldPacket const* WhoResponsePkt::Write()'))
pvp_generated=output/'pvp_statistics_response.cpp'
pvp_source=packet_response_writer(forever,profile,pvp_generated,'BattlegroundPackets','Battleground',(
'ByteBuffer& operator<<(ByteBuffer& data, PVPMatchStatistics::RatingData const& ratingData)',
'ByteBuffer& operator<<(ByteBuffer& data, PVPMatchStatistics::HonorData const& honorData)',
'ByteBuffer& operator<<(ByteBuffer& data, PVPMatchStatistics::PVPMatchPlayerPVPStat const& pvpStat)',
'ByteBuffer& operator<<(ByteBuffer& data, PVPMatchStatistics::PVPMatchPlayerStatistics const& playerData)',
'ByteBuffer& operator<<(ByteBuffer& data, PVPMatchStatistics const& pvpLogData)',
'WorldPacket const* PVPMatchStatisticsMessage::Write()'))
auction_generated=output/'auction_browse_response.cpp'
auction_source=packet_response_writer(forever,profile,auction_generated,'AuctionHousePackets','AuctionHouse',(
'ByteBuffer& operator<<(ByteBuffer& data, AuctionBucketKey const& itemKey)',
'ByteBuffer& operator<<(ByteBuffer& data, BucketInfo const& bucketInfo)',
'ByteBuffer& operator<<(ByteBuffer& data, AuctionItem const& auctionItem)',
'WorldPacket const* AuctionListBucketsResult::Write()',
'WorldPacket const* AuctionListItemsResult::Write()',
'WorldPacket const* AuctionListOwnedItemsResult::Write()',
'WorldPacket const* AuctionListBiddedItemsResult::Write()',
'WorldPacket const* AuctionGetCommodityQuoteResult::Write()'))
misc_source=forever/'src/server/game/Server/Packets/MiscPackets.cpp'
misc_relative=str(misc_source.relative_to(forever))
if misc_relative not in profile['forever_sha256']:
raise RuntimeError('Unpinned corpse writer source')
misc_text=misc_source.read_text();misc_methods=[]
for name in ('CorpseReclaimDelay','PreRessurect','DeathReleaseLoc','ExplorationExperience','RandomRoll'):
start=misc_text.index('WorldPacket const* '+name+'::Write()')
brace=misc_text.index('{',start);end=brace+1;depth=1
while depth:depth+=(misc_text[end]=='{')-(misc_text[end]=='}');end+=1
misc_methods.append(misc_text[start:end])
misc_generated=output/'corpse_delay.cpp'
write_changed(misc_generated,'// SPDX-License-Identifier: GPL-2.0-or-later\n#include "MiscPackets.h"\nnamespace WorldPackets::Misc {\n'+'\n'.join(misc_methods)+'\n}\n')
position_source=forever/'src/server/game/Entities/Object/Position.cpp'
position_text=position_source.read_text();position_methods=[]
for signature in ('ByteBuffer& operator<<(ByteBuffer& buf, Position::ConstStreamer<Position::PackedXYZ>',
'ByteBuffer& operator<<(ByteBuffer& buf, Position::ConstStreamer<Position::XYZO>',
'float Position::NormalizeOrientation(float o)'):
start=position_text.index(signature);brace=position_text.index('{',start);end=brace+1;depth=1
while depth:
depth+=(position_text[end]=='{')-(position_text[end]=='}');end+=1
position_methods.append(position_text[start:end])
position_generated=output/'packed_position.cpp'
write_changed(position_generated,'// SPDX-License-Identifier: GPL-2.0-or-later\n#include "Position.h"\n#include "ByteBuffer.h"\n'+'\n'.join(position_methods)+'\n')
auth_source=forever/'src/server/game/Server/Packets/AuthenticationPackets.cpp'
auth_text=auth_source.read_text();auth_methods=[]
for signature in ('ByteBuffer& operator<<(ByteBuffer& data, VirtualRealmNameInfo const&',
'ByteBuffer& operator<<(ByteBuffer& data, VirtualRealmInfo const&',
'ByteBuffer& operator<<(ByteBuffer& data, GameTime const&',
'ByteBuffer& operator<<(ByteBuffer& data, BaseBuildKey const&',
'ByteBuffer& operator<<(ByteBuffer& data, AuthSuccessInfo const&',
'ByteBuffer& operator<<(ByteBuffer& data, AuthWaitInfo const&',
'WorldPacket const* AuthResponse::Write()'):
start=auth_text.index(signature);brace=auth_text.index('{',start);end=brace+1;depth=1
while depth:depth+=(auth_text[end]=='{')-(auth_text[end]=='}');end+=1
auth_methods.append(auth_text[start:end])
auth_generated=output/'auth_init.cpp'
# Keep these source writers verbatim, excluding unrelated ConnectTo crypto
# singleton constructors/destructors and all server networking handlers.
write_changed(auth_generated,'// SPDX-License-Identifier: GPL-2.0-or-later\n#include "AuthenticationPackets.h"\n#include "CharacterTemplateDataStore.h"\n#include "ObjectMgr.h"\n#include "PacketOperators.h"\nnamespace WorldPackets::Auth {\n'+'\n\n'.join(auth_methods)+'\n}\n')
hotfix_source=forever/'src/server/game/Server/Packets/HotfixPackets.cpp'
hotfix_text=hotfix_source.read_text();hotfix_methods=[]
for signature in ('ByteBuffer& operator<<(ByteBuffer& data, DB2Manager::HotfixId const&',
'ByteBuffer& operator<<(ByteBuffer& data, DB2Manager::HotfixRecord const&',
'ByteBuffer& operator<<(ByteBuffer& data, HotfixConnect::HotfixData const&',
'WorldPacket const* HotfixConnect::Write()',
'WorldPacket const* AvailableHotfixes::Write()', 'WorldPacket const* DBReply::Write()'):
start=hotfix_text.index(signature);brace=hotfix_text.index('{',start);end=brace+1;depth=1
while depth:depth+=(hotfix_text[end]=='{')-(hotfix_text[end]=='}');end+=1
hotfix_methods.append(hotfix_text[start:end])
hotfix_generated=output/'hotfix_init.cpp'
write_changed(hotfix_generated,'// SPDX-License-Identifier: GPL-2.0-or-later\n#include "HotfixPackets.h"\n#include "PacketOperators.h"\nnamespace WorldPackets::Hotfix {\n'+'\n\n'.join(hotfix_methods)+'\n}\n')
config_source=forever/'src/server/game/Server/Packets/ClientConfigPackets.cpp'
config_text=config_source.read_text();config_methods=[]
for signature in ('WorldPacket const* AccountDataTimes::Write()',):
start=config_text.index(signature);brace=config_text.index('{',start);end=brace+1;depth=1
while depth:depth+=(config_text[end]=='{')-(config_text[end]=='}');end+=1
config_methods.append(config_text[start:end])
config_generated=output/'account_cache_init.cpp'
write_changed(config_generated,'// SPDX-License-Identifier: GPL-2.0-or-later\n#include "ClientConfigPackets.h"\nnamespace WorldPackets::ClientConfig {\n'+'\n\n'.join(config_methods)+'\n}\n')
merchant_source=forever/'src/server/game/Server/Packets/ItemPackets.cpp'
merchant_text=merchant_source.read_text();merchant_methods=[]
for name in ('SellResponse','BuySucceeded','BuyFailed','ItemCooldown'):
start=merchant_text.index('WorldPacket const* '+name+'::Write()');brace=merchant_text.index('{',start);end=brace+1;depth=1
while depth:depth+=(merchant_text[end]=='{')-(merchant_text[end]=='}');end+=1
merchant_methods.append(merchant_text[start:end])
merchant_generated=output/'merchant_response.cpp'
write_changed(merchant_generated,'// SPDX-License-Identifier: GPL-2.0-or-later\n#include "ItemPackets.h"\n#include "PacketOperators.h"\nnamespace WorldPackets::Item {\n'+'\n'.join(merchant_methods)+'\n}\n')
guild_source=forever/'src/server/game/Server/Packets/GuildPackets.cpp'
guild_text=guild_source.read_text();guild_methods=[]
for name in ('QueryGuildInfoResponse','GuildInvite','GuildCommandResult','GuildPermissionsQueryResults'):
start=guild_text.index('WorldPacket const* '+name+'::Write()');brace=guild_text.index('{',start);end=brace+1;depth=1
while depth:depth+=(guild_text[end]=='{')-(guild_text[end]=='}');end+=1
method=guild_text[start:end]
if name=='GuildInvite':
# Original70334 reader0x140a35380 adds a nine-bit surname after
# inviter6 (verified executable capture; see guild invite evidence).
# Legacy source has no surname. Keep the pinned reference unchanged.
anchor='_worldPacket << SizedString::BitsSize<6>(InviterName);'
if method.count(anchor)!=1:raise ValueError('GuildInvite reference writer changed')
method=method.replace(anchor,anchor+'\n _worldPacket.WriteBits(0, 9); //70334 empty surname')
guild_methods.append(method)
guild_generated=output/'guild_response.cpp'
write_changed(guild_generated,'// SPDX-License-Identifier: GPL-2.0-or-later\n#include "GuildPackets.h"\n#include "PacketOperators.h"\nnamespace WorldPackets::Guild {\n'+'\n'.join(guild_methods)+'\n}\n')
ninja=(forever/'build/build.ninja').read_text();start=ninja.index('build src/server/game/CMakeFiles/game.dir/Entities/Object/Updates/UpdateFields.cpp.o:')
block=ninja[start:ninja.index('\n\nbuild ',start)]
includes=shlex.split(re.search(r' INCLUDES = (.+)',block)[1])
common=['clang++','-std=c++20','-O1','-fPIC','-fvisibility=hidden','-fvisibility-inlines-hidden','-ffunction-sections','-fdata-sections','-DBOOST_BIND_NO_PLACEHOLDERS',
'-DBOOST_ASIO_NO_DEPRECATED','-DFMT_HEADER_ONLY','-DRAPIDJSON_HAS_STDSTRING',*includes]
party_sources,party_profile=classic_party_writer.prepare(forever,output)
packet_sources=forever/'src/server/game/Server/Packets'
sources=[(party_sources if name=='PartyPackets.cpp' else packet_sources)/name for name in
('MythicPlusPacketsCommon.cpp','ItemPacketsCommon.cpp','PerksProgramPacketsCommon.cpp','SystemPackets.cpp','MovementPackets.cpp','CombatLogPacketsCommon.cpp','NPCPackets.cpp','CombatPackets.cpp','CombatLogPackets.cpp','ReputationPackets.cpp','SpellPackets.cpp','CollectionPackets.cpp','LootPackets.cpp','PartyPackets.cpp','QuestPackets.cpp','SocialPackets.cpp','TradePackets.cpp','InstancePackets.cpp')]
prepared_sources=[generated,query_generated,who_generated,pvp_generated,auction_generated,misc_generated,position_generated,auth_generated,hotfix_generated,config_generated,merchant_generated,guild_generated,*sources,ROOT/'src/quest_packets_serializer.cpp',ROOT/'src/quest_log_serializer.cpp',ROOT/'src/social_packets_serializer.cpp',ROOT/'src/contact_names_serializer.cpp',ROOT/'src/who_serializer.cpp',ROOT/'src/pvp_statistics_serializer.cpp',ROOT/'src/auction_browse_serializer.cpp',ROOT/'src/forever_create.cpp',ROOT/'native/serializer.cpp']
if args.prepare_only:
party_compat=output/'party_writer_compat.hpp'
write_changed(party_compat,'struct SkillLineEntry;\n')
manifest={'kind':'source-only-codec-preparation','schema':1,'compiled':False,
'gateway_source':str(ROOT),'forever_source':str(forever),'turtle_source':str(turtle),
'sources':[str(p) for p in prepared_sources],
'source_sha256':{str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in prepared_sources},
'generated_sha256':{str(p.relative_to(output)):hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(output.rglob('*')) if p.is_file()},
'compiler_flags':common+compatibility_flags+login_flags+compiler_flags(render_profile)+['-I'+str(ROOT/'include'),'-I'+str(ROOT/'native'),'-I'+str(output)],
'item_package_sha256':package_sha,'party_profile':party_profile,
'warning':'Preparation is not a frozen dependency closure or a behavior differential; freeze with reviewed dependency inventory before building.'}
write_changed(output/'source-preparation.json',json.dumps(manifest,indent=2)+'\n')
print('Prepared',len(prepared_sources),'source units; no compiler or linker invoked.')
return
executable=output/'forever-create-codec'
cache=Cache(common[0]);flags=common+compatibility_flags+login_flags+compiler_flags(render_profile)+['-I'+str(ROOT/'include'),'-I'+str(ROOT/'native'),'-I'+str(output)]
metadata_cache=Cache(args.metadata_compiler)if args.metadata_compiler!=common[0]else cache
# The original PartyPackets TU includes Player.h, whose Classic extension
# declares IsClassicProfessionChildSkill(SkillLineEntry const*) without the
# server PCH's DB2Structure declaration. Only its nominal pointer type is
# required here; no skill layout/function/body is replaced or fabricated.
party_compat=output/'party-packet-forward-declarations.hpp'
write_changed(party_compat,'struct SkillLineEntry;\n')
def compile_source(p):
source_flags=flags+(['-include',str(party_compat)]if p.name=='PartyPackets.cpp'else [])
if p.name in ('PartyPackets.cpp','forever_create.cpp'):
source_flags=[source_flags[0],'-I'+str(party_sources),*source_flags[1:]]
source_cache=cache
if args.compact_metadata_data and p==ROOT/'src/forever_create.cpp':
source_cache=metadata_cache
source_flags=[args.metadata_compiler,*source_flags[1:]]
if args.metadata_compiler=='clang++':source_flags+=['-fconstexpr-steps=33554432']
return source_cache.compile(source_flags,p,output/(p.stem+'.o'))
objects=[compile_source(p)for p in prepared_sources]
library,protocol_provenance=protocol_archive(args.protocol_library or ROOT/'build/libgateway_protocol.a')
shared=output/'libforever_codec.so'
# Export only the bounded C ABI; no game/server symbols enter the host's
# global namespace. Both CLI oracle and native host use identical code.
exports=output/'codec.exports'
write_changed(exports,'{ global: gw_codec_abi; gw_codec_serialize; local: *; };\n')
shared_linked=cache.link([*flags,'-shared','-Wl,-soname,libforever_codec.so','-Wl,--gc-sections','-Wl,--no-undefined','-Wl,--version-script='+str(exports),*map(str,objects),str(library),'-lcrypto','-lz','-o',str(shared.with_suffix('.new'))],[*objects,library,exports],shared)
cli=cache.compile(flags,ROOT/'src/forever_codec_cli.cpp',output/'forever_codec_cli.o')
linked=cache.link([*flags,str(cli),str(shared),'-Wl,-rpath,$ORIGIN','-o',str(executable.with_suffix('.new'))],[cli,shared],executable)
provenance={'status':'experimental; not proof of actual world compatibility',
'item_package_sha256':package_sha,'separate_output':output!=default_output,
'metadata_payload_encoding':'escaped-byte-blob-v1'if args.compact_metadata_data else'per-record-byte-arrays-v1',
'staged_creation_profile':login_profile,'party_update_profile':party_profile,
'staged_render_profile':render_profile,
'warrior_cooldown_guard':cooldown_guard,
'protocol_library':protocol_provenance,
'forever_source':str(forever),'turtle_source':str(turtle),'serializer_methods':len(methods),
'sha256':{str(p.relative_to(forever) if p.is_relative_to(forever) else p):hashlib.sha256(p.read_bytes()).hexdigest()
for p in (source,legacy,query_source,who_source,pvp_source,auction_source,misc_source,position_source,auth_source,hotfix_source,config_source,merchant_source,*sources,forever/'src/server/game/Entities/Object/BaseEntity.cpp')}}
if build_base is not None:
provenance['accepted_item_build_base']=build_base
provenance['base_package_context_relocation']=relocation
if args.item_package:
provenance['working_registry_guard']={'baseline':package['working_wire_baseline'],
'delta':package['working_wire_delta'],'baseline_rows':len(wire_baseline.baseline),
'result_rows':len(wire_baseline.expected),'random_property_header_sha256':package['random_property_extension']['header_sha256']}
if args.compact_metadata_data:
provenance['per_tu_compiler']={'source':str(ROOT/'src/forever_create.cpp'),'compiler':args.metadata_compiler,
'version':metadata_cache.version.decode('utf-8',errors='replace').strip(),
'version_sha256':hashlib.sha256(metadata_cache.version).hexdigest()}
if args.compact_metadata_data and args.metadata_compiler=='clang++':
provenance['per_tu_constexpr_budget']={'source':str(ROOT/'src/forever_create.cpp'),'steps':33554432,
'option':'-fconstexpr-steps=33554432','reason':'compact registry constant initialization'}
provenance['sha256'][str(party_compat)]=hashlib.sha256(party_compat.read_bytes()).hexdigest()
provenance['sha256'].update(cooldown_guard['input_sha256'])
for guard_source in ['ops/validate_warrior_cooldown_build.py','ops/warrior_cooldown_modifier.py',
'include/gateway/race_slot_hide_profile.hpp','include/gateway/social.hpp','src/social.cpp','src/contact_names.cpp',
'src/social_packets_serializer.cpp','src/contact_names_serializer.cpp','include/gateway/who.hpp',
'src/who.cpp','src/who_serializer.cpp','include/gateway/pvp_statistics.hpp','src/pvp_statistics.cpp',
'src/pvp_statistics_serializer.cpp','include/gateway/auction_browse.hpp','src/auction_browse.cpp',
'src/auction_browse_serializer.cpp','native/serializer_modes.hpp',
'ops/isolated_item_render_profile.py','ops/creation_login_profile.py','ops/source_race_class_creation.py','ops/turtle_login_profile.py']:
guard_path=ROOT/guard_source;provenance['sha256'][str(guard_path)]=hashlib.sha256(guard_path.read_bytes()).hexdigest()
if render_profile is not None:
provenance['sha256'][render_profile['header']['path']]=render_profile['header']['sha256']
provenance['sha256'][render_profile['compiled_header']['path']]=render_profile['compiled_header']['sha256']
if login_profile is not None:
provenance['sha256'][login_profile['header']['path']]=login_profile['header']['sha256']
provenance['sha256'][login_profile['proof']['path']]=login_profile['proof']['sha256']
provenance['sha256'].update({str((ROOT/record['path']).resolve()):record['sha256'] for record in login_profile['input_pins']})
(output/'provenance.json').write_text(json.dumps(provenance,indent=2)+'\n')
compiled=cache.compiled+(metadata_cache.compiled if metadata_cache is not cache else 0)
print('Source-derived serializer:',executable,'compiled',compiled,'objects; linked',linked,'; native library linked',shared_linked,'; seconds',round(time.monotonic()-started,3))
if __name__=='__main__':main()