Files

177 lines
9.0 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Build the Forever (70334) pfQuest + pfQuest-turtle add-ons from the unmodified forks.
build.py <pfQuest fork> <pfQuest-turtle fork> <out dir> (out dir gets pfQuest/ and pfQuest-turtle/)
* load order = the fork's .toc with its XML <Include>/<Script> files flattened; only enUS locale/database files
(the client is enUS only);
* every Lua file runs in pfQuestEnv: `setfenv(1, pfQuestEnv) ` is put in front of its first line (line numbers in
error messages stay the fork's);
* compat/forever.lua (the 70334 compat layer, plain global env) is loaded first, compat/forever-post.lua right after
the fork's compat/optional.lua;
* TOC: the client's interface number, SavedVariables unchanged, Dependencies kept.
"""
import re, shutil, subprocess, sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
LOCALES = ('deDE', 'esES', 'frFR', 'koKR', 'ptBR', 'ruRU', 'zhCN', 'zhTW')
INTERFACE = '16001' # same as the other ported add-ons (client_addons/OctoLazyPig)
PREFIX = 'setfenv(1, pfQuestEnv) '
# 1.12 Lua turns x/0 into inf; the 70334 Lua raises "Division by zero". Zones without minimap size data
# (Turtle zones, world map open) divide by 0. These source edits keep the 1.12 result (scale = inf,
# draw size = 0). Each old text must occur exactly once, or the build stops.
PATCHES = {
# Both scans use quest-log indices, which include section headers. The
# number of active quests alone cannot bound the index of the last row.
'quest.lua': [
(' local _, numQuests = GetNumQuestLogEntries()\n local found = 0\n',
' local numEntries = GetNumQuestLogEntries() or 0\n'),
(' for qlogid = 1, 40 do\n', ' for qlogid = 1, numEntries do\n'),
('\n found = found + 1\n if found >= numQuests then\n break\n end\n', '\n'),
],
'tracker.lua': [
(' if id > 25 then\n', ' if tracker.mode ~= "QUEST_TRACKING" and id > 25 then\n'),
(' for bid, button in pairs(tracker.buttons) do\n',
' for bid, button in ipairs(tracker.buttons) do\n'),
(' -- add tracked quests\n local _, numQuests = GetNumQuestLogEntries()\n local found = 0\n',
' if tracker.mode ~= "QUEST_TRACKING" then return end\n'
' local numEntries = GetNumQuestLogEntries() or 0\n'),
(' for qlogid = 1, 40 do\n', ' for qlogid = 1, numEntries do\n'),
(''' local watched = IsQuestWatched(qlogid)
-- "All Quests" must not depend on the client marking a quest as watched.
-- Turtle leaves some normal item/object quests (for example Hilary's
-- Necklace) unwatched, which previously made them disappear after the
-- tracker reset even though they were active in the quest log.
local trackingmethod = tonumber(pfQuest_config["trackingmethod"])
if trackingmethod ~= 5 and (watched or trackingmethod == 1) then
-- Objective rows can briefly be absent while the client reindexes the
-- quest log after a turn-in. Use the authoritative completion flag.
local img = complete
and pfQuestConfig.path .. "\\\\img\\\\complete_c"
or pfQuestConfig.path .. "\\\\img\\\\complete"
pfQuest.tracker.ButtonAdd(title, { dummy = true, addon = "PFQUEST", texture = img })
end
found = found + 1
if found >= numQuests then
break
end
''', ''' -- Map pins follow their tracking settings. This list follows the quest log.
local img = complete
and pfQuestConfig.path .. "\\\\img\\\\complete_c"
or pfQuestConfig.path .. "\\\\img\\\\complete"
pfQuest.tracker.ButtonAdd(title, { dummy = true, addon = "PFQUEST", texture = img })
'''),
],
# Owner 2026-11-27 (OCTO freeze, "database.lua:139: script ran too long" x19): the 70334 quest-log ID is the
# server's own quest ID (the Turtle ID pfQuest-turtle's database uses; the gateway does not remap it). The 1.12
# code trusted it only when the title matched its locale table, else it ran levenshtein against every quest
# title for every log entry, every update. Trust the ID; an ID not in the database is an unknown quest.
'database.lua': [
(' if linkedQuest and linkedTitleMatches then\n'
' return { [1] = id }\n'
' end\n',
' if linkedQuest then\n'
' return { [1] = id }\n'
' end\n'
' return { title }\n'),
],
'map.lua': [
(' local xScale = mapZoom / mapWidth\n local yScale = mapZoom / mapHeight\n',
' local xScale = mapWidth > 0 and mapZoom / mapWidth or math.huge\n'
' local yScale = mapHeight > 0 and mapZoom / mapHeight or math.huge\n'),
],
'route.lua': [
(' pfMap.queue_update = true\n', ' pfMap.queue_update = GetTime()\n'),
(' xdraw = pfMap.drawlayer:GetWidth() / (mapZoom / mapWidth) / 100\n'
' ydraw = pfMap.drawlayer:GetHeight() / (mapZoom / mapHeight) / 100\n'
' zoom = ((mapZoom / mapWidth) + (mapZoom / mapHeight)) * 3\n',
' xdraw = pfMap.drawlayer:GetWidth() * mapWidth / mapZoom / 100\n'
' ydraw = pfMap.drawlayer:GetHeight() * mapHeight / mapZoom / 100\n'
' zoom = (mapWidth > 0 and mapHeight > 0) and ((mapZoom / mapWidth) + (mapZoom / mapHeight)) * 3 or math.huge\n'),
],
}
def patch(rel, text):
for old, new in PATCHES.get(rel, []):
if text.count(old) != 1:
raise SystemExit(f'{rel}: patch text found {text.count(old)} times (expected 1)')
text = text.replace(old, new)
return text
def other_locale(path):
p = path.replace('\\', '/')
return any(f'/{l}/' in p or p.endswith(f'{l}.xml') or f'-{l}' in p or f'{l}-' in p for l in LOCALES) or \
'-tbc' in p or '-wotlk' in p
def flatten(root, rel, out):
path = root / rel.replace('\\', '/')
if rel.lower().endswith('.xml'):
text = path.read_text(encoding='utf-8', errors='replace')
if re.search(r'<(Frame|Button|Texture|FontString)\b', text):
raise SystemExit(f'{rel}: XML with widgets is not supported by this port')
for inc in re.findall(r'<(?:Include|Script)\s+file="([^"]+)"', text):
target = (Path(rel.replace('\\', '/')).parent / inc.replace('\\', '/'))
parts = []
for part in target.parts:
if part == '..': parts.pop()
elif part != '.': parts.append(part)
sub = '/'.join(parts)
if not other_locale(sub): flatten(root, sub, out)
else:
out.append(rel.replace('\\', '/'))
def build(src, dst, name, post_after=None):
toc = (src / f'{name}.toc').read_text(encoding='utf-8', errors='replace').splitlines()
head, files = [], []
for line in toc:
s = line.strip()
if not s: continue
if s.startswith('##'):
if s.startswith('## Interface:'): s = f'## Interface: {INTERFACE}'
head.append(s)
elif not s.startswith('#') and not other_locale(s):
flatten(src, s, files)
if dst.exists(): shutil.rmtree(dst)
dst.mkdir(parents=True)
# assets (textures, fonts) keep their paths
for f in src.rglob('*'):
if f.is_file() and f.suffix.lower() in ('.tga', '.blp', '.ttf', '.png'):
t = dst / f.relative_to(src); t.parent.mkdir(parents=True, exist_ok=True); shutil.copy2(f, t)
order = []
if name == 'pfQuest':
(dst / 'compat').mkdir(exist_ok=True)
shutil.copy2(HERE / 'forever_compat.lua', dst / 'compat/forever.lua')
order.append('compat/forever.lua')
for rel in files:
text = (src / rel).read_text(encoding='utf-8', errors='replace')
if text.startswith(''): text = text[1:]
if name == 'pfQuest': text = patch(rel, text)
t = dst / rel; t.parent.mkdir(parents=True, exist_ok=True)
t.write_text(PREFIX + text, encoding='utf-8')
order.append(rel)
if post_after and rel == post_after:
post = (HERE / 'forever_post.lua').read_text()
(dst / 'compat/forever-post.lua').write_text(PREFIX + post, encoding='utf-8')
order.append('compat/forever-post.lua')
head.insert(1, '## X-Port: OctoWoW Forever (70334) build of the pfQuest fork; ops/pfquest_port/build.py')
(dst / f'{name}.toc').write_text('\n'.join(head) + '\n\n' + '\n'.join(o.replace('/', '\\') for o in order) + '\n',
encoding='utf-8')
if name == 'pfQuest':
subprocess.run(['patch', '--batch', '--forward', '--fuzz=0', '-p1',
'--input', str(HERE / 'native_quest_log.patch')], cwd=dst, check=True)
subprocess.run(['patch', '--batch', '--forward', '--fuzz=0', '--no-backup-if-mismatch', '-p0',
'--input', str(HERE / f'{name}-map-scripts.patch')], cwd=dst, check=True)
return order
def main():
pf, turtle, out = map(Path, sys.argv[1:4])
a = build(pf, out / 'pfQuest', 'pfQuest', post_after='compat/optional.lua')
b = build(turtle, out / 'pfQuest-turtle', 'pfQuest-turtle')
print(f'pfQuest: {len(a)} files, pfQuest-turtle: {len(b)} files')
if __name__ == '__main__':
main()