Skip to content

Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.

feat(gameengine): open hard usa like a player, skip unbuildable urgent builds

Olcay Seygan283da26196e3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 65ee05bdb..b1ce7d0b4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -33,6 +33,8 @@ found and fixed — EA's own, not port damage.**
- The AI checks ten seconds of supply-line damage, not a third of one.
- One AI decision read leftover memory, so identical matches played out differently.
- Difficulty and AI money change build pace again; every order was pinned at three seconds.
+- An urgent building it could not put up yet no longer stops the whole base. The computer always builds its most urgent request first, and when that request needed something it did not have, it built nothing else either: a Hard China that asked for a bunker before its barracks stood sat on 35,000 until well into the match. It now skips to the first urgent request it can actually build.
+- Hard USA opens the way a player does. It used to start on a barracks and hold its first power plant until a second dozer existed, so its first harvest came in at the 74 second mark. It now puts down the power plant and the supply centre straight away and the barracks after them. Over 20 Hard USA against Hard China matches on Tournament Desert, seats swapped both ways, USA won 15 where it won 10. The same opening was tried on China and lost it 17 matches instead of 10, and on GLA it decided too few matches to say anything, so both keep the opening they shipped with.
- The computer no longer shoots at what it cannot see. Its units, and its base defences, used to auto-target through the fog of war - a hard exemption written into the code for computer players only. Stealth works against it now, and so does anything it has not scouted.
- It scouts. There was no such thing as scouting in the computer opponent - it never needed to look, because it could already see everything. One cheap unit now tours the enemy start positions and keeps going round for the rest of the match, replaced out of spare change when it dies. Every difficulty scouts; an opponent that never looks reads as broken, not as easy. And it tours on purpose rather than in a circle: it goes to whichever base it has gone longest without seeing, nearest first, and it does not walk across the map to look again at something it looked at a minute ago - it stays and watches instead. Two scouts never trail each other round the same lap.
- It takes the oil derricks instead of blowing them up. An oil derrick pays whoever owns it and costs one infantryman to walk in - and the computer used to march past the neutral ones and shell yours, which is the one thing you can do with a derrick that earns nobody anything. It now keeps a cheap infantryman doing the rounds of every derrick, refinery and hospital it has found, takes them, and when there is nothing left to take it leaves him standing on the last one instead of walking him home. And it no longer picks a capturable building as a target of its own accord: it can still be ordered to level one, and one that shoots back is still shot back at.
diff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txt
index f298760b0..7a0ca7161 100644
--- a/GeneralsMD/Code/CMakeLists.txt
+++ b/GeneralsMD/Code/CMakeLists.txt
@@ -632,6 +632,11 @@ add_custom_command(TARGET generals POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${CMAKE_CURRENT_SOURCE_DIR}/Data/Patch.str
${CMAKE_CURRENT_SOURCE_DIR}/../Run/Data/
+ # The skirmish AI's scripts with the USA Hard opening rewritten by Tools/ScbTool/opening.py. The
+ # file is in the multiplayer checksum (GlobalData.cpp), so it ships with the exe like the INIs.
+ COMMAND ${CMAKE_COMMAND} -E copy_directory
+ ${CMAKE_CURRENT_SOURCE_DIR}/Data/Scripts
+ ${CMAKE_CURRENT_SOURCE_DIR}/../Run/Data/Scripts
# The translations the Language option lays over the English strings, one directory per
# language. Strings are not in the multiplayer INI checksum: two players can read one match in
# two languages.
diff --git a/GeneralsMD/Code/Data/Scripts/SkirmishScripts.scb b/GeneralsMD/Code/Data/Scripts/SkirmishScripts.scb
new file mode 100644
index 000000000..a47dd9590
Binary files /dev/null and b/GeneralsMD/Code/Data/Scripts/SkirmishScripts.scb differ
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
index 48ffb5c05..fb0023440 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
@@ -388,6 +388,9 @@ AIPlayer::~AIPlayer()
// ------------------------------------------------------------------------------------------------
void AIPlayer::onStructureProduced( Object *factory, Object *bldg )
{
+ // the opening build order is read from these: which building came up on which frame
+ DEBUG_LOG(("AI BUILT frame %d player %d '%s', %d in the bank\n", TheGameLogic->getFrame(),
+ m_player->getPlayerIndex(), bldg->getTemplate()->getName().str(), m_player->getMoney()->countMoney()));
m_teamDelay = 0; // Cause the update queues & selection to happen immediately.
m_buildDelay = 0; // Cause
/* Find the info building this. */
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp
index d95f9ae75..2f2f97224 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp
@@ -202,7 +202,10 @@ void AISkirmishPlayer::processBaseBuilding( void )
// The safety check below is a range query over everything near the spot, most of a
// millisecond each late in a 4v4, and it ran for every unbuilt entry on every pass (36 of
// them, 28ms, in one frame). An entry that cannot change what this pass picks skips it.
- const Bool couldBePriority = info->isPriorityBuild() && !isPriority;
+ // A priority entry whose prerequisite is not standing yet was taken all the same, and
+ // buildObjectNow refused it on every pass, so nothing queued behind it went up either: a
+ // China AI asked for a bunker before its barracks and sat on 35,000 until frame 8116.
+ const Bool couldBePriority = info->isPriorityBuild() && !isPriority && m_player->canBuild(curPlan);
const Bool couldBePower = powerPlan==NULL && curPlan->isKindOf(KINDOF_FS_POWER) &&
!curPlan->isKindOf(KINDOF_CASH_GENERATOR) && (isUnderPowered || info->isAutomaticBuild());
const Bool couldBeBuilt = bldgPlan==NULL && info->isAutomaticBuild() && info->isBuildable();
@@ -216,13 +219,11 @@ void AISkirmishPlayer::processBaseBuilding( void )
if (!locationSafe) {
continue;
}
- if (info->isPriorityBuild()) {
+ if (couldBePriority) {
// Always take priority build, unless we already have priority build.
- if (!isPriority) {
- bldgPlan = curPlan;
- bldgInfo = info;
- isPriority = true;
- }
+ bldgPlan = curPlan;
+ bldgInfo = info;
+ isPriority = true;
}
if (curPlan->isKindOf(KINDOF_FS_POWER)) {
if (powerPlan==NULL && !curPlan->isKindOf(KINDOF_CASH_GENERATOR)) {
diff --git a/Tools/ScbTool/opening.py b/Tools/ScbTool/opening.py
new file mode 100644
index 000000000..c402b0f4e
--- /dev/null
+++ b/Tools/ScbTool/opening.py
@@ -0,0 +1,111 @@
+"""Rewrite the skirmish AI's opening build order in SkirmishScripts.scb.
+
+EA's Hard scripts open every USA and China side on a barracks, hold the first power plant until a
+second dozer exists, and queue the supply centre only once that power plant stands; China then puts
+a gattling cannon by its supply dock ahead of the war factory. On Tournament Desert that brought
+USA's first income at frame 2227 and China's war factory at 6785. The opening this writes is the
+one a player uses: power plant, supply centre (the GLA stash), then the war factory (the arms dealer)
+and the barracks together, and the dock defence after the war factory.
+
+The build queue takes the newest request first (Player::addToPriorityBuildList puts it at the head),
+and since AISkirmishPlayer::processBaseBuilding skips a request whose prerequisite is not standing,
+the supply centre can be asked for on the first frame and still go up right after the power plant.
+
+usage: opening.py <in.scb> <out.scb> <rungs> [<side index> ...]
+ rungs is any of E N H, e.g. NH; no side index means every side.
+"""
+import copy
+import sys
+
+import scbtool
+
+SIDE = 11
+OBJECT_TYPE = 15
+THIS_PLAYER = "<This Player>"
+
+
+def scripts_by_name(script_list, rung):
+ suffix = f" - {rung}"
+ return {script.fields[0][:-len(suffix)]: script for _, script in scbtool.walk_scripts(script_list.children)
+ if script.fields[0].endswith(suffix)}
+
+
+def action_object(script):
+ for child in script.children:
+ if child.name == "ScriptAction":
+ for parameter in child.fields[2]:
+ if parameter[0] == OBJECT_TYPE:
+ return parameter[3]
+ raise ValueError(f"{script.fields[0]} names no object type")
+
+
+def set_condition(script, condition_chunk):
+ script.children = [condition_chunk] + [child for child in script.children if child.name != "OrCondition"]
+
+
+def single_condition(chunks, condition_name):
+ """The first AND group in the file made of one condition of that name, to copy from."""
+ for _, script in scbtool.walk_scripts(chunks):
+ for condition in (child for child in script.children if child.name == "OrCondition"):
+ if len(condition.children) == 1 and condition.children[0].fields[1] == condition_name:
+ return condition
+ raise ValueError(f"no lone {condition_name} condition in the file to copy")
+
+
+def built_condition(built_template, object_type):
+ condition = copy.deepcopy(built_template)
+ for parameter in condition.children[0].fields[2]:
+ if parameter[0] == OBJECT_TYPE:
+ parameter[3] = object_type
+ elif parameter[0] == SIDE:
+ parameter[3] = THIS_PLAYER
+ return condition
+
+
+def rewrite_side(scripts, family, true_condition, built_template):
+ """Returns the names of the scripts it changed."""
+ supply = scripts[f"{family} Supply Center"]
+ supply_type = action_object(supply)
+ changed = [supply]
+ set_condition(supply, true_condition)
+ if family == "GLA":
+ factory = scripts["GLA Arms Dealer"]
+ else:
+ factory = scripts[f"{family} War Factory"]
+ power = scripts[f"{family} 1st Power Plant"]
+ set_condition(power, true_condition)
+ changed.append(power)
+ barracks = scripts[f"{family} Barracks"]
+ set_condition(barracks, built_condition(built_template, supply_type))
+ changed.append(barracks)
+ dock_defence = scripts.get("China Supply Gat") if family == "China" else None
+ if dock_defence:
+ set_condition(dock_defence, built_condition(built_template, action_object(factory)))
+ changed.append(dock_defence)
+ return [script.fields[0] for script in changed]
+
+
+def main():
+ source, target, rungs = sys.argv[1], sys.argv[2], sys.argv[3].upper()
+ sides = {int(side) for side in sys.argv[4:]}
+ table, chunks = scbtool.load(source)
+ true_condition = single_condition(chunks, "CONDITION_TRUE")
+ built_template = single_condition(chunks, "BUILT_BY_PLAYER")
+ changed = []
+ for list_chunk in (chunk for chunk in chunks if chunk.name == "PlayerScriptsList"):
+ for index, script_list in enumerate(list_chunk.children):
+ if sides and index not in sides:
+ continue
+ for rung in rungs:
+ scripts = scripts_by_name(script_list, rung)
+ family = next((f for f in ("USA", "China", "GLA") if f"{f} Supply Center" in scripts), None)
+ if family:
+ changed += [f"[{index}] {name}" for name in rewrite_side(scripts, family, true_condition, built_template)]
+ if not changed:
+ raise SystemExit("no side matched")
+ scbtool.save(target, table, chunks)
+ print("\n".join(changed))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Tools/ScbTool/scbtool.py b/Tools/ScbTool/scbtool.py
new file mode 100644
index 000000000..d240eab79
--- /dev/null
+++ b/Tools/ScbTool/scbtool.py
@@ -0,0 +1,305 @@
+"""Read, dump and rewrite the skirmish AI's script file, Data/Scripts/SkirmishScripts.scb.
+
+The file is EA's chunk format (DataChunk.cpp): a "CkMp" table of names, then nested chunks of
+id, version and size. Script actions and conditions name their template through that table, so a
+dump reads without the engine. WorldBuilder is the only other writer and it is not built here.
+
+usage: scbtool.py dump <file.scb> [<substring>] every script, its conditions and actions
+ scbtool.py check <file.scb> decode and encode again, compare byte for byte
+
+Editing is done from Python: load(), change the tree, save(). A patch script imports this module.
+"""
+import struct
+import sys
+
+MAGIC = b"CkMp"
+CHUNK_HEADER = struct.Struct("<IHi")
+COORD3D = 16
+DICT_BOOL, DICT_INT, DICT_REAL, DICT_ASCII, DICT_UNICODE = range(5)
+CONTAINERS = {"PlayerScriptsList", "ScriptList", "OrCondition"}
+PARAMETER_TYPE_NAMES = [
+ "INT", "REAL", "SCRIPT", "TEAM", "COUNTER", "FLAG", "COMPARISON", "WAYPOINT", "BOOLEAN",
+ "TRIGGER_AREA", "TEXT_STRING", "SIDE", "SOUND", "SCRIPT_SUBROUTINE", "UNIT", "OBJECT_TYPE",
+ "COORD3D", "ANGLE", "TEAM_STATE", "RELATION", "AI_MOOD", "DIALOG", "MUSIC", "MOVIE",
+ "WAYPOINT_PATH", "LOCALIZED_TEXT", "BRIDGE", "KIND_OF_PARAM", "ATTACK_PRIORITY_SET",
+ "RADAR_EVENT_TYPE", "SPECIAL_POWER", "SCIENCE", "UPGRADE", "COMMANDBUTTON_ABILITY", "BOUNDARY",
+ "BUILDABLE", "SURFACES_ALLOWED", "SHAKE_INTENSITY", "COMMAND_BUTTON", "FONT_NAME",
+ "OBJECT_STATUS", "COMMANDBUTTON_ALL_ABILITIES", "SKIRMISH_WAYPOINT_PATH", "COLOR", "EMOTICON",
+ "OBJECT_PANEL_FLAG", "FACTION_NAME", "OBJECT_TYPE_LIST", "REVEALNAME", "SCIENCE_AVAILABILITY",
+ "LEFT_OR_RIGHT", "PERCENT",
+]
+
+
+class Chunk:
+ def __init__(self, name, version, fields, children):
+ self.name = name
+ self.version = version
+ self.fields = fields
+ self.children = children
+
+
+class Reader:
+ def __init__(self, data, names):
+ self.data = data
+ self.position = 0
+ self.names = names
+
+ def take(self, fmt):
+ values = struct.unpack_from(fmt, self.data, self.position)
+ self.position += struct.calcsize(fmt)
+ return values[0]
+
+ def string(self):
+ length = self.take("<H")
+ text = self.data[self.position:self.position + length].decode("latin-1")
+ self.position += length
+ return text
+
+ def unicode(self):
+ length = self.take("<H")
+ text = self.data[self.position:self.position + 2 * length].decode("utf-16-le")
+ self.position += 2 * length
+ return text
+
+ def name_key(self):
+ return self.names[self.take("<i") >> 8]
+
+ def dict(self):
+ entries = []
+ for _ in range(self.take("<H")):
+ key_and_type = self.take("<i")
+ kind, key = key_and_type & 0xFF, self.names[key_and_type >> 8]
+ readers = {DICT_BOOL: lambda: self.take("<B"), DICT_INT: lambda: self.take("<i"),
+ DICT_REAL: lambda: self.take("<f"), DICT_ASCII: self.string, DICT_UNICODE: self.unicode}
+ entries.append([key, kind, readers[kind]()])
+ return entries
+
+ def parameter(self):
+ kind = self.take("<i")
+ if kind == COORD3D:
+ return [kind, (self.take("<f"), self.take("<f"), self.take("<f"))]
+ return [kind, self.take("<i"), self.take("<f"), self.string()]
+
+ def chunk(self):
+ chunk_id, version, size = CHUNK_HEADER.unpack_from(self.data, self.position)
+ self.position += CHUNK_HEADER.size
+ end = self.position + size
+ name = self.names[chunk_id]
+ fields = []
+ if name == "ScriptGroup":
+ fields = [self.string(), self.take("<B")] + ([self.take("<B")] if version >= 2 else [])
+ elif name == "Script":
+ fields = [self.string() for _ in range(4)] + [self.take("<B") for _ in range(6)]
+ fields += [self.take("<i")] if version >= 2 else []
+ elif name == "Condition":
+ fields = [self.take("<i"), self.name_key() if version >= 4 else None]
+ fields.append([self.parameter() for _ in range(self.take("<i"))])
+ elif name in ("ScriptAction", "ScriptActionFalse"):
+ fields = [self.take("<i"), self.name_key() if version >= 2 else None]
+ fields.append([self.parameter() for _ in range(self.take("<i"))])
+ elif name == "ScriptsPlayers":
+ has_dicts = self.take("<i") if version >= 2 else 0
+ count = self.take("<i")
+ fields = [has_dicts, [[self.string(), self.dict() if has_dicts else None] for _ in range(count)]]
+ elif name == "ScriptTeams":
+ while self.position < end:
+ fields.append(self.dict())
+ elif name not in CONTAINERS:
+ fields = [self.data[self.position:end]]
+ self.position = end
+ children = []
+ while self.position < end:
+ children.append(self.chunk())
+ if self.position != end:
+ raise ValueError(f"{name} chunk read {self.position - end} bytes past its end")
+ return Chunk(name, version, fields, children)
+
+
+class Writer:
+ def __init__(self, table):
+ self.table = list(table)
+ self.ids = dict(table)
+ self.parts = []
+
+ def name_index(self, name):
+ # DataChunkOutput writes the newest name first with the next id up, so a name the file did
+ # not have goes to the front.
+ if name not in self.ids:
+ self.ids[name] = max(self.ids.values(), default=0) + 1
+ self.table.insert(0, (name, self.ids[name]))
+ return self.ids[name]
+
+ def put(self, fmt, value):
+ self.parts.append(struct.pack(fmt, value))
+
+ def string(self, text):
+ encoded = text.encode("latin-1")
+ self.put("<H", len(encoded))
+ self.parts.append(encoded)
+
+ def unicode(self, text):
+ self.put("<H", len(text))
+ self.parts.append(text.encode("utf-16-le"))
+
+ def name_key(self, name):
+ self.put("<i", (self.name_index(name) << 8) | DICT_ASCII)
+
+ def dict(self, entries):
+ self.put("<H", len(entries))
+ for key, kind, value in entries:
+ self.put("<i", (self.name_index(key) << 8) | kind)
+ writers = {DICT_BOOL: lambda v: self.put("<B", v), DICT_INT: lambda v: self.put("<i", v),
+ DICT_REAL: lambda v: self.put("<f", v), DICT_ASCII: self.string, DICT_UNICODE: self.unicode}
+ writers[kind](value)
+
+ def parameter(self, parameter):
+ self.put("<i", parameter[0])
+ if parameter[0] == COORD3D:
+ for coordinate in parameter[1]:
+ self.put("<f", coordinate)
+ return
+ self.put("<i", parameter[1])
+ self.put("<f", parameter[2])
+ self.string(parameter[3])
+
+ def chunk(self, chunk):
+ outer_parts, self.parts = self.parts, []
+ fields = chunk.fields
+ if chunk.name == "ScriptGroup":
+ self.string(fields[0])
+ for flag in fields[1:]:
+ self.put("<B", flag)
+ elif chunk.name == "Script":
+ for text in fields[:4]:
+ self.string(text)
+ for flag in fields[4:10]:
+ self.put("<B", flag)
+ if chunk.version >= 2:
+ self.put("<i", fields[10])
+ elif chunk.name in ("Condition", "ScriptAction", "ScriptActionFalse"):
+ self.put("<i", fields[0])
+ if fields[1] is not None:
+ self.name_key(fields[1])
+ self.put("<i", len(fields[2]))
+ for parameter in fields[2]:
+ self.parameter(parameter)
+ elif chunk.name == "ScriptsPlayers":
+ if chunk.version >= 2:
+ self.put("<i", fields[0])
+ self.put("<i", len(fields[1]))
+ for player_name, side_dict in fields[1]:
+ self.string(player_name)
+ if fields[0]:
+ self.dict(side_dict)
+ elif chunk.name == "ScriptTeams":
+ for team in fields:
+ self.dict(team)
+ elif chunk.name not in CONTAINERS:
+ self.parts.append(fields[0])
+ for child in chunk.children:
+ self.chunk(child)
+ body = b"".join(self.parts)
+ self.parts = outer_parts
+ self.parts += [CHUNK_HEADER.pack(self.name_index(chunk.name), chunk.version, len(body)), body]
+
+
+def load(path):
+ with open(path, "rb") as file:
+ data = file.read()
+ if data[:4] != MAGIC:
+ raise ValueError(f"{path} does not start with {MAGIC!r}")
+ count = struct.unpack_from("<i", data, 4)[0]
+ position = 8
+ table = []
+ for _ in range(count):
+ length = data[position]
+ name = data[position + 1:position + 1 + length].decode("latin-1")
+ position += 1 + length
+ table.append((name, struct.unpack_from("<I", data, position)[0]))
+ position += 4
+ reader = Reader(data, {name_id: name for name, name_id in table})
+ reader.position = position
+ chunks = []
+ while reader.position < len(data):
+ chunks.append(reader.chunk())
+ return table, chunks
+
+
+def encode(table, chunks):
+ writer = Writer(table)
+ for chunk in chunks:
+ writer.chunk(chunk)
+ header = [MAGIC, struct.pack("<i", len(writer.table))]
+ for name, name_id in writer.table:
+ encoded = name.encode("latin-1")
+ header += [bytes([len(encoded)]), encoded, struct.pack("<I", name_id)]
+ return b"".join(header + writer.parts)
+
+
+def save(path, table, chunks):
+ with open(path, "wb") as file:
+ file.write(encode(table, chunks))
+
+
+def walk_scripts(chunks, group=""):
+ for chunk in chunks:
+ if chunk.name == "Script":
+ yield group, chunk
+ else:
+ yield from walk_scripts(chunk.children, chunk.fields[0] if chunk.name == "ScriptGroup" else group)
+
+
+def describe_parameter(parameter):
+ kind = PARAMETER_TYPE_NAMES[parameter[0]]
+ if parameter[0] == COORD3D:
+ return f"{kind}{parameter[1]}"
+ value = parameter[3] if parameter[3] else (parameter[2] if parameter[0] in (1, 17, 51) else parameter[1])
+ return f"{kind}={value}"
+
+
+def describe_call(chunk):
+ arguments = ", ".join(describe_parameter(parameter) for parameter in chunk.fields[2])
+ return f"{chunk.fields[1]}({arguments})"
+
+
+def dump(chunks, needle):
+ for chunk in chunks:
+ if chunk.name == "ScriptsPlayers":
+ print("players:", [player for player, _ in chunk.fields[1]])
+ player_lists = [chunk for chunk in chunks if chunk.name == "PlayerScriptsList"]
+ for list_chunk in player_lists:
+ for index, script_list in enumerate(list_chunk.children):
+ for group, script in walk_scripts(script_list.children):
+ name, flags = script.fields[0], script.fields[4:10]
+ text = [describe_call(child) for child in script.children if child.name != "OrCondition"]
+ conditions = [" AND ".join(describe_call(c) for c in orc.children)
+ for orc in script.children if orc.name == "OrCondition"]
+ block = f"[{index}] {group} / {name} active={flags[0]} once={flags[1]} " \
+ f"e/n/h={flags[2]}{flags[3]}{flags[4]} sub={flags[5]} delay={script.fields[10] if len(script.fields) > 10 else 0}"
+ body = [f" IF {' OR '.join(conditions) or 'true'}"]
+ body += [f" {'ELSE' if child.name == 'ScriptActionFalse' else 'DO'} {call}"
+ for child, call in zip([c for c in script.children if c.name != "OrCondition"], text)]
+ full = "\n".join([block] + body)
+ if needle is None or needle.lower() in full.lower():
+ print(full)
+
+
+def main():
+ command, path = sys.argv[1], sys.argv[2]
+ table, chunks = load(path)
+ if command == "dump":
+ dump(chunks, sys.argv[3] if len(sys.argv) > 3 else None)
+ elif command == "check":
+ with open(path, "rb") as file:
+ original = file.read()
+ rewritten = encode(table, chunks)
+ if rewritten != original:
+ first = next(i for i, (a, b) in enumerate(zip(original, rewritten)) if a != b)
+ raise SystemExit(f"round trip differs at byte {first} ({len(original)} -> {len(rewritten)} bytes)")
+ print(f"round trip identical, {len(original)} bytes")
+ else:
+ raise SystemExit(f"unknown command {command!r}; expected dump or check")
+
+
+if __name__ == "__main__":
+ main()