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.

build(cmake): compile with /FS and register the python tool selfchecks

Olcay Seyganacadcd6059fc
diff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txt
index 7fae2fa29..c47a1d409 100644
--- a/GeneralsMD/Code/CMakeLists.txt
+++ b/GeneralsMD/Code/CMakeLists.txt
@@ -35,7 +35,12 @@ if(MSVC)
# dump is the only stack we get. StackDump.cpp walks the EBP chain by hand and
# /O2 implies /Oy (no frame pointer), which leaves that dump empty; /Zi + /DEBUG
# then give the frames names instead of bare addresses. Costs a PDB, buys Phase 5.
- add_compile_options(/Oy- /Zi)
+ # /FS goes with /Zi: MSBuild compiles a project's sources in parallel and they all write
+ # the one PDB. Without it the writes go through mspdbsrv.exe, and if that dies or is
+ # killed - which happens when a build is interrupted - every following compile fails with
+ # C1041, or worse, only some of them do and the library is left half-built against an old
+ # header. /FS serializes the writes in the compilers themselves instead.
+ add_compile_options(/Oy- /Zi /FS)
add_link_options(/DEBUG)
endif()
@@ -530,6 +535,19 @@ add_test(NAME dx8_smoke_d3d12 COMMAND dx8_smoke -d3d12)
# buffer pairing that DX8Wrapper::_Get_Non_MultiSampled_Depth_Buffer hands the screen filters.
add_test(NAME dx8_smoke_msaa COMMAND dx8_smoke -msaa 4)
+# Tools/bigfile.py reads and writes the game's BIG archives (that is how the shipped INIs
+# come out for editing). Its selfcheck round-trips synthetic files, so it needs no game
+# data - but it does need an interpreter, so it is only registered when one is present.
+find_package(Python3 COMPONENTS Interpreter QUIET)
+if(Python3_Interpreter_FOUND)
+ add_test(NAME bigfile_selfcheck
+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/Tools/bigfile.py selfcheck)
+ # Tools/vfx_tune.py rewrites those INIs in place; its selfcheck runs both rule sets over a
+ # synthetic one and checks the block parser did not eat an End or duplicate a key.
+ add_test(NAME vfx_tune_selfcheck
+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/Tools/vfx_tune.py selfcheck)
+endif()
+
if(RELEASE_DEBUG_LOGGING)
target_compile_definitions(gameengine PRIVATE RELEASE_DEBUG_LOGGING)
target_compile_definitions(gameenginedevice PRIVATE RELEASE_DEBUG_LOGGING)
diff --git a/GeneralsMD/Code/Tools/bigfile.py b/GeneralsMD/Code/Tools/bigfile.py
new file mode 100644
index 000000000..eb761d339
--- /dev/null
+++ b/GeneralsMD/Code/Tools/bigfile.py
@@ -0,0 +1,233 @@
+#!/usr/bin/env python3
+"""Read and write the game's BIG archives.
+
+Format, straight out of Win32BIGFileSystem::openArchiveFile:
+
+ 0x00 "BIGF"
+ 0x04 archive size, little endian (the game reads it and ignores it)
+ 0x08 file count, BIG endian
+ 0x0C offset of the first file's data, big endian (the game skips this and
+ seeks to 0x10 for the index, so it is only advisory)
+ 0x10 index: for each file, offset (BE), size (BE), NUL-terminated path
+ then the file data at the offsets the index gave
+
+File data is stored raw. Refpack-compressed members exist in some EA archives
+(they start with 0x10FB) and are reported, not decoded - nothing in this game's
+archives needs it.
+
+ python bigfile.py list <archive.big> [pattern]
+ python bigfile.py extract <archive.big> [pattern] [-o outdir]
+ python bigfile.py pack <archive.big> <indir>
+
+'pattern' is a case-insensitive fnmatch over the stored path, e.g. "*.ini" or
+"data/ini/particlesystem.ini". extract writes each member under outdir keeping
+its stored path (default: the archive name without its extension).
+
+pack rebuilds an archive from a directory laid out the way extract leaves one -
+enough to put an edited INI back into a copy of the .big, though loose files
+under Run/ override archives anyway and are the easier route for one file.
+"""
+
+import fnmatch
+import os
+import struct
+import sys
+
+
+def _read_index(f):
+ """Yield (path, offset, size) for every member, leaving f's position undefined."""
+ magic = f.read(4)
+ if magic != b"BIGF":
+ raise ValueError("not a BIG archive (magic is %r, expected b'BIGF')" % magic)
+ f.read(4) # archive size, unused
+ (count,) = struct.unpack(">I", f.read(4))
+ f.seek(0x10)
+ for _ in range(count):
+ offset, size = struct.unpack(">II", f.read(8))
+ name = bytearray()
+ while True:
+ ch = f.read(1)
+ if not ch:
+ raise ValueError("archive ends inside the index")
+ if ch == b"\0":
+ break
+ name += ch
+ yield name.decode("latin-1"), offset, size
+
+
+def _matches(path, pattern):
+ if not pattern:
+ return True
+ return fnmatch.fnmatch(path.lower().replace("\\", "/"),
+ pattern.lower().replace("\\", "/"))
+
+
+def cmd_list(archive, pattern=None):
+ with open(archive, "rb") as f:
+ entries = list(_read_index(f))
+ shown = 0
+ for path, offset, size in entries:
+ if not _matches(path, pattern):
+ continue
+ f.seek(offset)
+ note = " (refpack)" if f.read(2) == b"\x10\xfb" else ""
+ print("%10d %s%s" % (size, path, note))
+ shown += 1
+ print("%d of %d members" % (shown, len(entries)))
+
+
+def cmd_extract(archive, pattern=None, outdir=None):
+ if outdir is None:
+ outdir = os.path.splitext(os.path.basename(archive))[0]
+ written = 0
+ with open(archive, "rb") as f:
+ for path, offset, size in list(_read_index(f)):
+ if not _matches(path, pattern):
+ continue
+ dest = os.path.join(outdir, path.replace("\\", os.sep))
+ parent = os.path.dirname(dest)
+ if parent:
+ os.makedirs(parent, exist_ok=True)
+ f.seek(offset)
+ data = f.read(size)
+ if len(data) != size:
+ raise ValueError("%s: wanted %d bytes, archive had %d" % (path, size, len(data)))
+ with open(dest, "wb") as out:
+ out.write(data)
+ print(dest)
+ written += 1
+ print("%d file(s) written" % written)
+
+
+def cmd_pack(archive, indir):
+ members = []
+ for root, _dirs, files in os.walk(indir):
+ for name in sorted(files):
+ full = os.path.join(root, name)
+ stored = os.path.relpath(full, indir).replace(os.sep, "\\")
+ members.append((stored, full))
+ members.sort(key=lambda m: m[0].lower())
+
+ # index size first: the data offsets depend on it
+ index_size = 0x10 + sum(8 + len(s.encode("latin-1")) + 1 for s, _ in members)
+
+ offset = index_size
+ placed = []
+ for stored, full in members:
+ size = os.path.getsize(full)
+ placed.append((stored, full, offset, size))
+ offset += size
+ total = offset
+
+ with open(archive, "wb") as out:
+ out.write(b"BIGF")
+ out.write(struct.pack("<I", total))
+ out.write(struct.pack(">I", len(placed)))
+ out.write(struct.pack(">I", index_size))
+ for stored, _full, off, size in placed:
+ out.write(struct.pack(">II", off, size))
+ out.write(stored.encode("latin-1") + b"\0")
+ assert out.tell() == index_size, (out.tell(), index_size)
+ for _stored, full, _off, _size in placed:
+ with open(full, "rb") as src:
+ out.write(src.read())
+ print("%s: %d file(s), %d bytes" % (archive, len(placed), total))
+
+
+def cmd_selfcheck():
+ """Round-trip pack -> read -> extract on synthetic files, so the check needs no game data."""
+ import shutil
+ import tempfile
+
+ work = tempfile.mkdtemp(prefix="bigfile_selfcheck_")
+ try:
+ src = os.path.join(work, "src")
+ cases = {
+ "Data\\INI\\Alpha.ini": b"ParticleSystem Test\r\n Gravity = -1.0\r\nEnd\r\n",
+ "Data\\INI\\Sub\\Beta.ini": b"", # empty member
+ "Loose.txt": bytes(range(256)) * 40, # every byte value, > 8k
+ }
+ for stored, data in cases.items():
+ path = os.path.join(src, stored.replace("\\", os.sep))
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "wb") as f:
+ f.write(data)
+
+ archive = os.path.join(work, "test.big")
+ cmd_pack(archive, src)
+
+ with open(archive, "rb") as f:
+ index = {p: (o, s) for p, o, s in _read_index(f)}
+ assert set(index) == set(cases), (sorted(index), sorted(cases))
+ for stored, data in cases.items():
+ offset, size = index[stored]
+ assert size == len(data), (stored, size, len(data))
+ f.seek(offset)
+ assert f.read(size) == data, stored
+ # every member must start after the index and end inside the file
+ end = os.path.getsize(archive)
+ for stored, (offset, size) in index.items():
+ assert 0x10 <= offset and offset + size <= end, (stored, offset, size, end)
+
+ out = os.path.join(work, "out")
+ cmd_extract(archive, None, out)
+ for stored, data in cases.items():
+ with open(os.path.join(out, stored.replace("\\", os.sep)), "rb") as f:
+ assert f.read() == data, stored
+
+ # and a non-archive must be refused rather than read as garbage
+ junk = os.path.join(work, "junk.big")
+ with open(junk, "wb") as f:
+ f.write(b"NOPE" + b"\0" * 64)
+ try:
+ with open(junk, "rb") as f:
+ list(_read_index(f))
+ except ValueError:
+ pass
+ else:
+ raise AssertionError("a file without the BIGF magic was accepted")
+ finally:
+ shutil.rmtree(work, ignore_errors=True)
+
+ print("bigfile selfcheck OK")
+
+
+def main(argv):
+ if len(argv) == 2 and argv[1] == "selfcheck":
+ cmd_selfcheck()
+ return 0
+
+ if len(argv) < 3:
+ print(__doc__.strip())
+ return 2
+
+ cmd, archive = argv[1], argv[2]
+ rest = argv[3:]
+
+ outdir = None
+ if "-o" in rest:
+ i = rest.index("-o")
+ if i + 1 >= len(rest):
+ print("-o needs a directory")
+ return 2
+ outdir = rest[i + 1]
+ rest = rest[:i] + rest[i + 2:]
+ pattern = rest[0] if rest else None
+
+ if cmd == "list":
+ cmd_list(archive, pattern)
+ elif cmd == "extract":
+ cmd_extract(archive, pattern, outdir)
+ elif cmd == "pack":
+ if not pattern:
+ print("pack needs a source directory")
+ return 2
+ cmd_pack(archive, pattern)
+ else:
+ print(__doc__.strip())
+ return 2
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv))
diff --git a/GeneralsMD/Code/Tools/vfx_tune.py b/GeneralsMD/Code/Tools/vfx_tune.py
new file mode 100644
index 000000000..e957ecd1a
--- /dev/null
+++ b/GeneralsMD/Code/Tools/vfx_tune.py
@@ -0,0 +1,425 @@
+#!/usr/bin/env python3
+"""Apply the ground-collision / drift / flash pass to the loose game INIs.
+
+The shipped ParticleSystem.ini and FXList.ini live inside INIZH.big; pull them out as loose
+overrides first (loose files beat archives), then run this over them:
+
+ cd GeneralsMD/Run
+ python ../Code/Tools/bigfile.py extract INIZH.big "data/ini/particlesystem.ini" -o .
+ python ../Code/Tools/bigfile.py extract INIZH.big "data/ini/fxlist.ini" -o .
+ python ../Code/Tools/vfx_tune.py --dry-run # what it would touch
+ python ../Code/Tools/vfx_tune.py
+
+Re-running is safe: a block that already carries a key is left alone, so this is idempotent and
+composes with hand edits. To undo, extract the file again - that is the revert.
+
+The numbers below are the whole tuning surface; they are meant to be edited. Nothing here is
+derived from anything, it is all taste.
+"""
+
+import argparse
+import os
+import re
+import sys
+
+# ---------------------------------------------------------------- the knobs
+
+# Solids: chunks and sparks that should hit the ground and come off it again.
+SOLID_TEXTURES = ("exdirtdebris", "exspark", "exshell", "exfireembr", "exstarburst")
+SOLID = {"GroundCollision": "Yes", "GroundBounce": "0.35", "GroundFriction": "0.80"}
+# Friction is charged on every frame a particle is being pressed into the ground, not once per
+# landing, so it compounds: 0.80 skids for about a second before settling, 0.55 stops on the spot.
+
+# Soft: smoke, dust, dirt and flame that should pile up against the terrain and spread along it
+# instead of sinking into the hillside. Bounce 0 = no hop, high friction = it keeps sliding.
+SOFT_TEXTURES = ("exsmok", "excloud", "exdust", "exdrtexp", "expuddle", "exfire01", "exexplo")
+SOFT = {"GroundCollision": "Yes", "GroundBounce": "0.00", "GroundFriction": "0.94"}
+
+# Never collide these: the collision reads the terrain heightmap only, so anything living on the
+# water surface would be clamped to the seabed under it. Lens flares are screen-facing glows with
+# no business touching the ground at all.
+NO_COLLIDE_TEXTURES = ("exwater", "exwave", "exhydrant", "exsonic", "exlnzflar")
+
+# Weapon trails: let the smoke wander instead of hanging in a rigid tube. These angles are the
+# ones the artists used on the eight systems that already ship with WindMotion set.
+TRAIL_TEXTURES = ("exsmok", "excloud", "excontrail")
+TRAIL_WIND = {
+ "WindMotion": "PingPong",
+ "WindAngleChangeMin": "0.069813",
+ "WindAngleChangeMax": "0.139626",
+ "WindPingPongStartAngleMin": "0.000000",
+ "WindPingPongStartAngleMax": "0.261799",
+ "WindPingPongEndAngleMin": "5.497787",
+ "WindPingPongEndAngleMax": "6.283185",
+}
+# A trail whose puffs never grow reads as a solid tube; give the flat ones a little spread.
+TRAIL_SIZE_RATE = "0.05 0.12"
+
+# Every missile exhaust in the game is a STREAK - a ribbon drawn through its particles - so wind is
+# the wrong tool there (it shoves each particle independently and kinks the ribbon). DriftVelocity
+# moves them all the same way, which shears the ribbon smoothly instead. Nine STREAKs ship with it
+# at zero, and those are the trails that hang in the air perfectly still; the rest are artist-set
+# and left alone. Straight up, so it does not depend on which way the missile was flying.
+STREAK_DRIFT = "X:0.00 Y:0.00 Z:0.10"
+
+# Muzzle flash: a short warm flash on the ground under the gun. 65 of the 431 shipped FXLists
+# already carry a LightPulse and 141 a ViewShake, so both rules below only fill in the lists that
+# have neither - the hand-authored ones are left exactly as they are.
+MUZZLE_LIGHT = """ LightPulse
+ Color = R:255 G:214 B:150
+ Radius = 45
+ IncreaseTime = 0
+ DecreaseTime = 150
+ End
+"""
+
+# Impact: bigger, oranger, slower to fade.
+IMPACT_LIGHT = """ LightPulse
+ Color = R:255 G:170 B:90
+ Radius = 80
+ IncreaseTime = 0
+ DecreaseTime = 350
+ End
+"""
+
+# Camera shake accumulates across simultaneous hits and is clamped, so it is only worth spending on
+# rare, large events - a shell landing every second from thirty tanks would just pin it at the cap.
+DEATH_SHAKE = """ ViewShake
+ Type = SUBTLE
+ End
+"""
+
+MUZZLE_RE = re.compile(r"(MuzzleFlash|GunFire|CannonFire)", re.I)
+IMPACT_RE = re.compile(r"(Detonation|Explosion|Impact)", re.I)
+DEATH_RE = re.compile(r"(Die|DeathExplosion)", re.I)
+
+
+# ------------------------------------------------------------------ parsing
+
+def split_blocks(text, keyword):
+ """Split an INI into (prefix, [(header, body_lines)]) on top-level '<keyword> <name>' blocks.
+
+ A block runs to the next line that is exactly 'End' at column 0; nugget 'End's inside an
+ FXList are indented, which is what keeps them from closing the outer block early.
+ """
+ lines = text.split("\n")
+ prefix, blocks = [], []
+ i = 0
+ while i < len(lines):
+ if lines[i].startswith(keyword + " "):
+ header = lines[i]
+ body = []
+ i += 1
+ while i < len(lines) and lines[i].rstrip("\r") != "End":
+ body.append(lines[i])
+ i += 1
+ end = lines[i] if i < len(lines) else "End"
+ i += 1
+ blocks.append([header, body, end])
+ else:
+ if blocks:
+ blocks[-1].append(lines[i]) # trailing blank lines etc. ride with the last block
+ else:
+ prefix.append(lines[i])
+ i += 1
+ return prefix, blocks
+
+
+def field(body, name):
+ """Value of '<name> = ...' in a block body, or None."""
+ for line in body:
+ t = line.strip()
+ if t.startswith(name) and t[len(name):].lstrip().startswith("="):
+ return t.split("=", 1)[1].strip()
+ return None
+
+
+def has_field(body, name):
+ return field(body, name) is not None
+
+
+def is_zero_drift(value):
+ """True for a missing DriftVelocity or one that is X:0 Y:0 Z:0 however it is spelled."""
+ if value is None:
+ return True
+ nums = re.findall(r"[-+]?\d*\.?\d+", value)
+ return len(nums) == 3 and all(float(n) == 0.0 for n in nums)
+
+
+def texture_matches(tex, prefixes):
+ tex = (tex or "").lower()
+ return any(tex.startswith(p) for p in prefixes)
+
+
+# ------------------------------------------------- ParticleSystem.ini rules
+
+def tune_particles(text, report):
+ prefix, blocks = split_blocks(text, "ParticleSystem")
+ for block in blocks:
+ header, body = block[0], block[1]
+ name = header.split(None, 1)[1].strip() if " " in header else "?"
+ tex = field(body, "ParticleName")
+ priority = field(body, "Priority")
+ ptype = field(body, "Type")
+
+ add = {}
+
+ # collision: PARTICLE sprites only. STREAK segments and VOLUME_PARTICLE stacks are drawn
+ # from the position rather than at it, so clamping them to the ground looks wrong.
+ if (ptype == "PARTICLE"
+ and not has_field(body, "GroundCollision")
+ and not texture_matches(tex, NO_COLLIDE_TEXTURES)):
+ if texture_matches(tex, SOLID_TEXTURES):
+ add.update(SOLID)
+ report("solid bounces", name)
+ elif texture_matches(tex, SOFT_TEXTURES) or priority == "DUST_TRAIL":
+ add.update(SOFT)
+ report("soft settles", name)
+
+ # drift: weapon trails only, and only the smoke ones - a flamethrower jet must stay a jet.
+ # PARTICLE only again: a STREAK is a line drawn through its particles, and shoving those
+ # sideways one at a time turns the trail into a zigzag rather than bending it.
+ if (ptype == "PARTICLE"
+ and priority == "WEAPON_TRAIL"
+ and field(body, "WindMotion") in (None, "Unused")
+ and texture_matches(tex, TRAIL_TEXTURES)):
+ add.update(TRAIL_WIND)
+ if field(body, "SizeRate") in ("0.00 0.00", "0.0 0.0", "0 0"):
+ add["SizeRate"] = TRAIL_SIZE_RATE
+ report("trail spreads", name)
+ report("trail drifts", name)
+
+ # the ribbon trails: shear the whole thing upward rather than kinking it
+ if (ptype == "STREAK"
+ and priority == "WEAPON_TRAIL"
+ and is_zero_drift(field(body, "DriftVelocity"))):
+ add["DriftVelocity"] = STREAK_DRIFT
+ report("exhaust rises", name)
+
+ if add:
+ # replace in place where the key already exists (SizeRate), append the rest
+ for i, line in enumerate(body):
+ key = line.strip().split("=", 1)[0].strip()
+ if key in add:
+ indent = line[:len(line) - len(line.lstrip())] or " "
+ body[i] = "%s%s = %s" % (indent, key, add.pop(key))
+ body.extend(" %s = %s" % (k, v) for k, v in add.items())
+
+ out = list(prefix)
+ for block in blocks:
+ out.append(block[0])
+ out.extend(block[1])
+ out.append(block[2])
+ out.extend(block[3:])
+ return "\n".join(out)
+
+
+# -------------------------------------------------------- FXList.ini rules
+
+def tune_fxlists(text, report):
+ prefix, blocks = split_blocks(text, "FXList")
+ for block in blocks:
+ header, body = block[0], block[1]
+ name = header.split(None, 1)[1].strip() if " " in header else "?"
+ joined = "\n".join(body)
+
+ # only decorate lists that already do something visible at a place in the world
+ if "ParticleSystem" not in joined:
+ continue
+
+ additions = []
+ if "LightPulse" not in joined:
+ if MUZZLE_RE.search(name):
+ additions.append(MUZZLE_LIGHT)
+ report("muzzle light", name)
+ elif IMPACT_RE.search(name):
+ additions.append(IMPACT_LIGHT)
+ report("impact light", name)
+
+ # shake: rare and large only - something that scars the terrain when it dies
+ if ("ViewShake" not in joined and "TerrainScorch" in joined and DEATH_RE.search(name)):
+ additions.append(DEATH_SHAKE)
+ report("death shake", name)
+
+ for chunk in additions:
+ body.extend(chunk.rstrip("\n").split("\n"))
+
+ out = list(prefix)
+ for block in blocks:
+ out.append(block[0])
+ out.extend(block[1])
+ out.append(block[2])
+ out.extend(block[3:])
+ return "\n".join(out)
+
+
+# ------------------------------------------------------------------ driver
+
+def run(indir, dry_run, verbose):
+ counts = {}
+ examples = {}
+
+ def report(rule, name):
+ counts[rule] = counts.get(rule, 0) + 1
+ examples.setdefault(rule, []).append(name)
+
+ jobs = [("ParticleSystem.ini", tune_particles), ("FXList.ini", tune_fxlists)]
+ for filename, fn in jobs:
+ path = os.path.join(indir, filename)
+ if not os.path.exists(path):
+ print("missing: %s (extract it from INIZH.big first)" % path)
+ return 1
+ with open(path, "r", encoding="latin-1", newline=None) as f:
+ text = f.read()
+ tuned = fn(text, report)
+ if dry_run:
+ continue
+ with open(path, "w", encoding="latin-1", newline="\r\n") as f:
+ f.write(tuned)
+ print("wrote %s" % path)
+
+ if not counts:
+ print("nothing to do - already tuned, or the INIs are not where I looked")
+ for rule in sorted(counts):
+ print("%-16s %4d" % (rule, counts[rule]))
+ if verbose:
+ for n in examples[rule]:
+ print(" %s" % n)
+ continue
+ for n in examples[rule][:3]:
+ print(" e.g. %s" % n)
+ if dry_run:
+ print("(dry run - nothing written)")
+ return 0
+
+
+SELFCHECK_PARTICLES = """ParticleSystem TestDebris
+ Priority = DEATH_EXPLOSION
+ Type = PARTICLE
+ ParticleName = EXDirtDebris.tga
+ Gravity = -0.10
+End
+
+ParticleSystem TestStreak
+ Priority = WEAPON_TRAIL
+ Type = STREAK
+ ParticleName = EXSmokNew1.tga
+ SizeRate = 0.00 0.00
+End
+
+ParticleSystem TestSpray
+ Priority = WEAPON_EXPLOSION
+ Type = PARTICLE
+ ParticleName = EXWater04.tga
+End
+
+ParticleSystem TestTrail
+ Priority = WEAPON_TRAIL
+ Type = PARTICLE
+ ParticleName = EXSmokNew1.tga
+ SizeRate = 0.00 0.00
+End
+"""
+
+SELFCHECK_FXLISTS = """FXList WeaponFX_TestShellDetonation
+ Sound
+ Name = Boom
+ End
+ ParticleSystem
+ Name = Puff
+ End
+End
+
+FXList WeaponFX_TestQuiet
+ Sound
+ Name = Click
+ End
+End
+
+FXList FX_TestTankDieExplosion
+ ParticleSystem
+ Name = Fireball
+ End
+ TerrainScorch
+ Type = RANDOM
+ End
+End
+"""
+
+
+def cmd_selfcheck():
+ """Exercise the block parser and both rule sets on a synthetic INI - no game data needed."""
+ seen = []
+
+ def report(rule, name):
+ seen.append((rule, name))
+
+ # nugget "End"s are indented, the block's own "End" is not: the parser must not stop early
+ _prefix, blocks = split_blocks(SELFCHECK_FXLISTS, "FXList")
+ assert len(blocks) == 3, len(blocks)
+ assert "Sound" in "\n".join(blocks[0][1]), blocks[0][1]
+ assert "TerrainScorch" in "\n".join(blocks[2][1]), blocks[2][1]
+
+ tuned = tune_particles(SELFCHECK_PARTICLES, report)
+ rules = {r for r, _ in seen}
+ names = {n for _, n in seen}
+
+ assert ("solid bounces", "TestDebris") in seen, seen
+ assert "TestSpray" not in names, "a water particle must not be clamped to the seabed"
+ # and prove it block by block, not just by the report
+ for block_name, forbidden in (("TestStreak", "GroundCollision"),
+ ("TestSpray", "GroundCollision"),
+ ("TestStreak", "WindMotion")):
+ body = tuned.split("ParticleSystem " + block_name + "\n", 1)[1].split("\nEnd", 1)[0]
+ assert forbidden not in body, (block_name, forbidden, body)
+ assert ("trail drifts", "TestTrail") in seen, seen
+ assert ("trail spreads", "TestTrail") in seen, seen
+ assert ("exhaust rises", "TestStreak") in seen, seen
+ assert is_zero_drift(None) and is_zero_drift("X:0.00 Y:0.0 Z:0")
+ assert not is_zero_drift("X:0.00 Y:0.00 Z:-0.20")
+ assert "GroundBounce = 0.35" in tuned, tuned
+ assert "WindMotion = PingPong" in tuned, tuned
+ # SizeRate is replaced in place, not appended twice
+ assert tuned.count("SizeRate = ") == 2, tuned # one per WEAPON_TRAIL block
+ # every block still closes
+ assert tuned.count("\nEnd") == SELFCHECK_PARTICLES.count("\nEnd"), tuned
+
+ seen2 = []
+ again = tune_particles(tuned, lambda r, n: seen2.append((r, n)))
+ assert not seen2, "second pass should be a no-op, got %r" % (seen2,)
+ assert again == tuned
+
+ seen3 = []
+ fx = tune_fxlists(SELFCHECK_FXLISTS, lambda r, n: seen3.append((r, n)))
+ assert ("impact light", "WeaponFX_TestShellDetonation") in seen3, seen3
+ assert ("death shake", "FX_TestTankDieExplosion") in seen3, seen3
+ assert "WeaponFX_TestQuiet" not in {n for _, n in seen3}, "no ParticleSystem, nothing to light"
+ # block-closing "End"s sit at column 0 and must be unchanged; the three nuggets added
+ # (two lights and a shake) each bring an indented one
+ assert fx.count("\nEnd") == SELFCHECK_FXLISTS.count("\nEnd"), fx
+ assert fx.count("\n End") == SELFCHECK_FXLISTS.count("\n End") + 3, fx
+
+ seen4 = []
+ fx2 = tune_fxlists(fx, lambda r, n: seen4.append((r, n)))
+ assert not seen4, seen4
+ assert fx2 == fx
+
+ print("vfx_tune selfcheck OK (%d rules fired)" % len(rules))
+
+
+def main(argv):
+ if len(argv) == 2 and argv[1] == "selfcheck":
+ cmd_selfcheck()
+ return 0
+
+ p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
+ p.add_argument("--dir", default="Data/INI",
+ help="where the loose INIs are (default: Data/INI, i.e. run from GeneralsMD/Run)")
+ p.add_argument("--dry-run", action="store_true", help="report what would change, write nothing")
+ p.add_argument("-v", "--verbose", action="store_true", help="name every system, not just three")
+ args = p.parse_args(argv[1:])
+ return run(args.dir, args.dry_run, args.verbose)
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv))