diff --git a/tests/Aetheria.Shared.Tests/PackageMountCensusTests.cs b/tests/Aetheria.Shared.Tests/PackageMountCensusTests.cs index 76d847adc..8e1512378 100644 --- a/tests/Aetheria.Shared.Tests/PackageMountCensusTests.cs +++ b/tests/Aetheria.Shared.Tests/PackageMountCensusTests.cs @@ -13,13 +13,25 @@ using Xunit; // (ruling census-tests-read-the-owners). public sealed class PackageMountCensusTests { - private static CultCache Catalog() + private static CultCache Open(string catalog) { var cache = new CultCache(TestCatalog.Registry()); - cache.AddBackingStore(new SingleFileMessagePackBackingStore(TestCatalog.Repo, true), AetheriaStores.CatalogTypes); + cache.AddBackingStore(new SingleFileMessagePackBackingStore(catalog, true), AetheriaStores.CatalogTypes); return cache; } + // Every package hull of a composed catalog, named by ship id. The key format is ShipModCatalog's: a hull record with a mod + // key is a package's, and the id is what follows the prefix HullKey puts on it. + private static (string Package, HullData Hull)[] Packages(CultCache cache) + { + var prefix = ShipModCatalog.HullKey("").Value; + return cache.GetAll() + .Select(hull => (Key: cache.RefOf(hull).Key, Hull: hull)) + .Where(entry => ShipModCatalog.IsModKey(entry.Key)) + .Select(entry => (entry.Key.Value.Substring(prefix.Length), entry.Hull)) + .ToArray(); + } + // One line per hardpoint no catalog item of its type fits, naming package, row and type. private static string[] Unfilled(IEnumerable<(string Package, HullData Hull)> packages, IReadOnlyCollection items) => packages.SelectMany(package => package.Hull.Hardpoints @@ -30,35 +42,54 @@ public sealed class PackageMountCensusTests [Fact] public void EveryPackageMountTakesSomeGear() { - using var cache = Catalog(); - var packages = cache.GetAll() - .Select(hull => (Key: cache.RefOf(hull).Key, Hull: hull)) - .Where(entry => entry.Key.Value.StartsWith("mod-hull:", StringComparison.Ordinal)) - .Select(entry => (entry.Key.Value.Substring("mod-hull:".Length), entry.Hull)) - .ToArray(); + using var cache = Open(TestCatalog.Repo); + var packages = Packages(cache); Assert.NotEmpty(packages); Assert.Empty(Unfilled(packages, cache.GetAll().ToArray())); } - // The census cannot pass vacuously. The starter package passes; the same package with one row's Shape cut to a single cell - // fails naming that row. (Widening a mount only lets it take more gear under Takes, so the pin narrows.) + private static HullData StarterHull(string root, string id, HullData like) => + ShipModCatalog.ReadPackage(ShipStarterCommand.Write(Path.Combine(root, "GameData", "Mods"), id, "Probe " + id, like)).Hull; + + private static HullData Like() => new HullData { Name = "Like", HullType = HullType.Ship, Mass = 1234, Behaviors = { new VelocityLimitData() } }; + + // The census cannot pass vacuously. The starter package passes; the same package with any one row's Shape cut to a single + // cell, that row first or last in the list, fails naming that row and no other. (Widening a mount only lets it take more + // gear under Takes, so the pin narrows.) Every row the pin can narrow is tried, so a census that skips a row fails here. [Fact] public void TheCensusNamesAMountNothingFits() { - using var cache = Catalog(); + using var cache = Open(TestCatalog.Repo); var items = cache.GetAll().ToArray(); using var work = new TempDirectory(); - var like = new HullData { Name = "Like", HullType = HullType.Ship, Mass = 1234, Behaviors = { new VelocityLimitData() } }; - var path = ShipStarterCommand.Write(Path.Combine(work.Path, "GameData", "Mods"), "probe.census", "Probe Census", like); - - var hull = ShipModCatalog.ReadPackage(path).Hull; + var hull = StarterHull(work.Path, "probe.census", Like()); Assert.Empty(Unfilled(new[] { ("probe.census", hull) }, items)); - var control = hull.Hardpoints.Single(row => row.Transform == "internal.control"); - Assert.False(items.Where(item => item.HardpointType == control.Type).All(item => item.Shape.Coordinates.Length == 1), - "the pin needs a control module larger than one cell"); - control.Shape = new Shape(1, 1); - var failures = Unfilled(new[] { ("probe.census", hull) }, items); - Assert.Equal(new[] { "probe.census: row internal.control (ControlModule) takes no catalog item" }, failures); + var original = hull.Hardpoints.ToList(); + var narrowable = original.Where(row => items.Any(item => item.HardpointType == row.Type && item.Shape.Coordinates.Length > 1)).ToArray(); + Assert.True(narrowable.Length >= 2, "the pin needs at least two rows that a one-cell shape starves"); + foreach (var row in narrowable) + foreach (var first in new[] { true, false }) + { + var shape = row.Shape; + row.Shape = new Shape(1, 1); + var others = original.Where(other => other != row); + hull.Hardpoints = first ? new[] { row }.Concat(others).ToList() : others.Append(row).ToList(); + Assert.Equal(new[] { $"probe.census: row {row.Transform} ({row.Type}) takes no catalog item" }, Unfilled(new[] { ("probe.census", hull) }, items)); + row.Shape = shape; + } + } + + // Enumeration reads every package of the composed catalog, not the first: two packages compose, and both are censused. + [Fact] + public void TheCensusEnumeratesEveryPackage() + { + using var work = new TempDirectory(); + var mods = Path.Combine(work.Path, "GameData", "Mods"); + foreach (var id in new[] { "probe.alpha", "probe.omega" }) + ShipStarterCommand.Write(mods, id, "Probe " + id, Like()); + var catalog = TestCatalog.Resolve(Path.Combine(RunStartTests.FindRepoRoot(), "GameData", "Aetheria.cc"), mods, work.Path); + using var cache = Open(catalog); + Assert.Equal(new[] { "probe.alpha", "probe.omega" }, Packages(cache).Select(package => package.Package).OrderBy(id => id, StringComparer.Ordinal).ToArray()); } } diff --git a/tools/blender/hull_packager/build_aetherdb.ps1 b/tools/blender/hull_packager/build_aetherdb.ps1 new file mode 100644 index 000000000..0f2f2c566 --- /dev/null +++ b/tools/blender/hull_packager/build_aetherdb.ps1 @@ -0,0 +1,15 @@ +# build_aetherdb.ps1 -Game -CultLibRoot -CultMathRoot [-Repo ] +# Publishes tools/AetherDb into \ModTools, the AetherDb.exe package_hull.py runs. also needs GameData\Aetheria.cc +# (the shipped catalog's content, not its LFS pointer). CultLibRoot and CultMathRoot are CultLib worktrees at the revisions +# Directory.Build.props names for this repo revision (git worktree add --detach ). +# ErrorOnDuplicatePublishOutputFiles=false is the NETSDK1152 workaround: Aetheria.Shared and CultLib publish the same files. +param( + [Parameter(Mandatory)] [string]$Game, + [Parameter(Mandatory)] [string]$CultLibRoot, + [Parameter(Mandatory)] [string]$CultMathRoot, + [string]$Repo = (Resolve-Path "$PSScriptRoot\..\..\..").Path +) +$ErrorActionPreference = "Stop" +& dotnet publish "$Repo\tools\AetherDb" -c Release -o "$Game\ModTools" "-p:CultLibRoot=$CultLibRoot" "-p:CultMathRoot=$CultMathRoot" "-p:ErrorOnDuplicatePublishOutputFiles=false" +if ($LASTEXITCODE -ne 0) { throw "dotnet publish exited $LASTEXITCODE" } +if (-not (Test-Path "$Game\ModTools\AetherDb.exe")) { throw "no AetherDb.exe in $Game\ModTools" } diff --git a/tools/blender/hull_packager/compare.py b/tools/blender/hull_packager/compare.py new file mode 100644 index 000000000..6a7367806 --- /dev/null +++ b/tools/blender/hull_packager/compare.py @@ -0,0 +1,38 @@ +"""compare.py : exit 0 and COMPARE_EQUAL when the two packages hold the same shape, rows (id, +type, cell, footprint, rotation, armour, arc), stats, price and product (maker, name, description, offered), both read through +aetheria_ships/ship_cc.py. GLB bytes are not compared. Needs CULTLIB_PACKAGES.""" +import importlib.util +import os +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +spec = importlib.util.spec_from_file_location("ship_cc", HERE.parent / "aetheria_ships" / "ship_cc.py") +sc = importlib.util.module_from_spec(spec) +spec.loader.exec_module(sc) +P = os.environ["CULTLIB_PACKAGES"] +sys.path.insert(0, str(Path(P) / "cultcache-py" / "src")) +import msgpack + + +def view(path): + f = sc.read(path, P) + shape, rows, _ = sc.read_layout(path, P) + b = f.hull.body + limit = [p for u, p in b[11] if u == 11][0][1] + prods = [msgpack.unpackb(e.payload, raw=False) for e in f.store.pull_all() if e.type == sc.PRODUCT_SCHEMA] + return {"shape": shape, "rows": [sc.decode_hardpoint(r) for r in rows], "name": b[1], "mass": b[4], "price": b[8], + "durability": b[12], "armor": b[27], "drag": b[28], "top": (limit[0], limit[1]), "makers": sc.product_makers(path, P), + "products": [(p[1], p[2], p[8]) for p in prods]} + + +a, b = view(sys.argv[1]), view(sys.argv[2]) +bad = [k for k in a if a[k] != b[k]] +for k in bad: + print("DIFF", k, *([] if k == "rows" else [a[k], b[k]])) +if "rows" in bad: + for x, y in zip(a["rows"], b["rows"]): + if x != y: + print("DIFF row", x, y) +print("COMPARE_EQUAL" if not bad else "COMPARE_DIFFERENT", len(a["rows"]), "rows") +sys.exit(1 if bad else 0) diff --git a/tools/blender/hull_packager/gen_manifest.py b/tools/blender/hull_packager/gen_manifest.py new file mode 100644 index 000000000..59697f687 --- /dev/null +++ b/tools/blender/hull_packager/gen_manifest.py @@ -0,0 +1,63 @@ +"""gen_manifest.py --like --extent X Y Z --maker [--length N] + +A packager manifest (see ../package_hull.md) from an existing package's ship.cc, read through aetheria_ships/ship_cc.py: rows, +stats, price and product come from the .cc; the arguments are what a .cc does not record (the hull to copy, the model extent in +metres, the maker, the schematic length in cells). The id is the package folder's name. The hull.scad is copied beside the +manifest. Needs CULTLIB_PACKAGES. +""" +import argparse +import importlib.util +import json +import os +import shutil +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +spec = importlib.util.spec_from_file_location("ship_cc", HERE.parent / "aetheria_ships" / "ship_cc.py") +sc = importlib.util.module_from_spec(spec) +spec.loader.exec_module(sc) + + +def footprint(raw): + w, h, cells = raw[0] + return "/".join("".join("#" if cells[x * h + y] else "." for x in range(w)) for y in range(h - 1, -1, -1)) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("ship_cc") + parser.add_argument("hull_scad") + parser.add_argument("out") + parser.add_argument("--like", required=True) + parser.add_argument("--extent", required=True, nargs=3, type=float) + parser.add_argument("--maker", required=True) + parser.add_argument("--length", type=int, default=30) + args = parser.parse_args() + packages = os.environ["CULTLIB_PACKAGES"] + sys.path.insert(0, str(Path(packages) / "cultcache-py" / "src")) + import msgpack + f = sc.read(args.ship_cc, packages) + _, rows, _ = sc.read_layout(args.ship_cc, packages) + body = f.hull.body + limit = [p for u, p in body[11] if u == 11][0][1] + assert limit[0] == limit[1], "the manifest holds one top speed" + product = [msgpack.unpackb(e.payload, raw=False) for e in f.store.pull_all() if e.type == sc.PRODUCT_SCHEMA][0] + manifest = { + "id": Path(args.ship_cc).resolve().parent.name, + "name": body[1], "like": args.like, "length": args.length, "extent": args.extent, + "hull": Path(args.hull_scad).name, "maker": args.maker, "description": product[2], "offered": not product[8], + "price": body[8], + "stats": {"mass": body[4], "durability": body[12], "armor": body[27], "drag": round(body[28], 6), "top_speed": limit[0]}, + "rows": [{"id": d["Transform"], "kind": sc.HARDPOINT_TYPE_NAMES[d["Type"]], "cell": list(d["Position"]), + "footprint": footprint(d["Shape"]), "rotation": d["Rotation"], "armor": d["Armor"], "arc": d["FiringArc"]} + for d in map(sc.decode_hardpoint, rows)], + } + out = Path(args.out) + out.write_text(json.dumps(manifest, indent=1), encoding="utf-8") + shutil.copy(args.hull_scad, out.parent / Path(args.hull_scad).name) + print("manifest", out, len(manifest["rows"]), "rows") + + +if __name__ == "__main__": + main() diff --git a/tools/blender/hull_packager/job.ps1 b/tools/blender/hull_packager/job.ps1 new file mode 100644 index 000000000..234cfa76a --- /dev/null +++ b/tools/blender/hull_packager/job.ps1 @@ -0,0 +1,82 @@ +# job.ps1 -Scratch -Game [-Blender ] [-OpenScad ] [-Packages ] [-Lock ] +# The packager's regression job: package_hull.py on the fixture manifest; on a manifest generated from the committed +# aetheria.nakovalnya package, compared (compare.py) with that package; a second run without --replace (must refuse and leave +# the package byte-identical); a --replace that fails (must leave it byte-identical); and AetherDb compose over the result. +# Launch detached. It logs to \job.log and writes \job.status (pid, state, time): +# Start-Process powershell -ArgumentList '-NoProfile','-File','tools\blender\hull_packager\job.ps1','-Scratch','','-Game','\game' +# holds GameData\Aetheria.cc and ModTools\AetherDb.exe (build_aetherdb.ps1); its GameData\Mods is emptied first. +param( + [Parameter(Mandatory)] [string]$Scratch, + [Parameter(Mandatory)] [string]$Game, + [string]$Blender = "C:\Program Files (x86)\Steam\steamapps\common\Blender\blender.exe", + [string]$OpenScad = "C:\Tools\OpenSCAD-2026.09.23-x86-64\openscad.com", + [string]$Packages = "F:\Projects\CultLib\packages", + [string]$Lock = "F:\Projects\eureka-handoff-aux-2026-10-19\starfire_lock.py" +) +$ErrorActionPreference = "Stop" +$Repo = (Resolve-Path "$PSScriptRoot\..\..\..").Path +$Log = "$Scratch\job.log" +$Status = "$Scratch\job.status" +$Packager = "$Repo\tools\blender\package_hull.py" +function Say($text) { Add-Content -Path $Log -Value "$(Get-Date -Format s) $text" -Encoding utf8 } +function State($text) { Set-Content -Path $Status -Value "pid $PID`n$text`n$(Get-Date -Format s)" -Encoding utf8 } +function Native($label, [scriptblock]$block, [int]$want = 0) { + Say "BEGIN $label" + & $block 2>&1 | ForEach-Object { Add-Content -Path $Log -Value " $_" -Encoding utf8 } + $code = $LASTEXITCODE + Say "END $label exit $code" + if ($code -ne $want) { throw "$label exited $code, wanted $want" } +} +function Digest($dir) { (Get-ChildItem $dir -Recurse -File | Sort-Object FullName | ForEach-Object { "$($_.Name) $((Get-FileHash $_.FullName).Hash)" }) -join "`n" } +function Pack($manifest, $flags = @()) { & $Blender --background --factory-startup --python-use-system-env --python $Packager -- $manifest @flags } + +New-Item -ItemType Directory -Force $Scratch | Out-Null +Set-Content -Path $Log -Value "" -Encoding utf8 +State "waiting for the Starfire lock" +if (Test-Path $Lock) { & py -3 $Lock acquire hull-packager 2>&1 | ForEach-Object { Say $_ } } +try { + $env:GAME_FOLDER = $Game + $env:CULTLIB_PACKAGES = $Packages + $env:OPENSCAD = $OpenScad + # Blender's Python needs msgpack: point it at the newest Blender user site that has it, unless PYTHONPATH is already set. + if (-not $env:PYTHONPATH) { $env:PYTHONPATH = (Get-ChildItem "$env:APPDATA\Blender Foundation\Blender" -Directory | Sort-Object Name | Select-Object -Last 1).FullName + "\scripts\modules" } + $Fixture = "$Repo\tools\blender\tests\fixtures\hulls\zh-ammo-tender\package.json" + $Committed = "$Repo\GameData\Mods\aetheria.nakovalnya" + $Mods = "$Game\GameData\Mods" + $Nak = "$Scratch\nakovalnya.json" + Set-Location $Game + Remove-Item -Recurse -Force $Mods -ErrorAction SilentlyContinue + New-Item -ItemType Directory -Force $Mods | Out-Null + + State "running: fixture" + Native "packager on the fixture manifest" { Pack $Fixture } + Native "validate fixture" { & "$Game\ModTools\AetherDb.exe" ship-authoring validate "$Mods\smoke.package.tender\ship.cc" } + + State "running: nakovalnya" + Native "manifest from the committed package" { & py -3 "$PSScriptRoot\gen_manifest.py" "$Committed\ship.cc" "$Committed\hull.scad" $Nak --like Djinni --extent 37.6 58.4 14.9 --maker Zhestokost } + Native "packager on the Nakovalnya manifest" { Pack $Nak } + Native "validate nakovalnya" { & "$Game\ModTools\AetherDb.exe" ship-authoring validate "$Mods\aetheria.nakovalnya\ship.cc" } + Native "compare to the committed package" { & py -3 "$PSScriptRoot\compare.py" "$Committed\ship.cc" "$Mods\aetheria.nakovalnya\ship.cc" } + + State "running: refusal, failed replace, compose" + $before = Digest "$Mods\aetheria.nakovalnya" + Native "second run without --replace refuses" { Pack $Nak } 1 + if ($before -ne (Digest "$Mods\aetheria.nakovalnya")) { throw "the refused run changed the package" } + Say "REFUSAL LEFT THE PACKAGE BYTE-IDENTICAL" + # A manifest that fails after the build has started: its first row sits far off the raster (hull.scad is beside it already). + $bad = Get-Content $Nak -Raw | ConvertFrom-Json + $bad.rows[0].cell = @(500, 500) + $bad | ConvertTo-Json -Depth 8 | Set-Content "$Scratch\bad.json" -Encoding utf8 + Native "failed --replace" { Pack "$Scratch\bad.json" @("--replace") } 1 + if ($before -ne (Digest "$Mods\aetheria.nakovalnya")) { throw "the failed --replace changed the package" } + Say "FAILED REPLACE LEFT THE PACKAGE BYTE-IDENTICAL" + Remove-Item "$Scratch\derived.cc" -ErrorAction SilentlyContinue + Native "compose" { & "$Game\ModTools\AetherDb.exe" ship-authoring compose "$Game\GameData\Aetheria.cc" "$Scratch\derived.cc" $Mods } + Say "JOB OK" + State "done: OK" +} catch { + Say "JOB FAILED: $_" + State "done: FAILED $_" +} finally { + if (Test-Path $Lock) { & py -3 $Lock release hull-packager 2>&1 | ForEach-Object { Say $_ } } +} diff --git a/tools/blender/package_hull.md b/tools/blender/package_hull.md new file mode 100644 index 000000000..08bf896e9 --- /dev/null +++ b/tools/blender/package_hull.md @@ -0,0 +1,62 @@ +# package_hull.py: the hull packager + +One bench hull plus one manifest becomes one ship package (`GameData/Mods//ship.cc`, `ship.glb`, `hull.scad`) that the +validator accepts, with no Unity and no clicking. The header of `package_hull.py` gives the command line, the environment +(`GAME_FOLDER`, `CULTLIB_PACKAGES`, `OPENSCAD`) and the order of steps. This file is the manifest schema and the way to check the +packager still matches the committed first-party package. + +## Contract + +- The manifest is creation input only. Once `GameData/Mods/` exists, its `ship.cc` owns rows, stats and product; the manifest + is never read again. Without `--replace` an existing package is refused untouched. With `--replace` it is re-derived and edits + made since are discarded, but only on success: the old package is moved aside during the run, and any failure removes what the + run built and puts the old one back exactly as it was. +- The last output line is `PACKAGE_OK` (exit 0) or `PACKAGE_FAILED` (exit 1, with the reason). There is no third state: a row whose + cell is off the raster, outside the hull shape or overlapping an earlier row fails the run; nothing is moved for you. +- A manifest is checked before Blender or the game folder is touched: bad JSON, an unknown or missing key, an unknown `kind`, a + malformed footprint, a duplicate row id and a missing hull file are each refused by name. + +## Manifest (JSON; no key may be missing or unknown) + +| key | meaning | +| --- | --- | +| `id` | the stable ship id and the folder name under `GameData/Mods`; `ship_cc.valid_ship_id` decides what is valid | +| `name` | the hull's display name | +| `like` | the name of a shipped catalog hull of type Ship whose stats and top speed the new hull starts from (AetherDb `--like`) | +| `length` | whole cells, at least 1: the New Ship length field of the add-on | +| `extent` | `[x, y, z]` metres of the stand-in box the model is made from; with the add-on's `CELL_SIZE` of 2 m (`aetheria_ships/hull_grid.py`) this fixes the raster, so rows written for one extent do not carry to another | +| `hull` | a file beside the manifest, copied to the package as `hull.scad` (OpenSCAD source with the kit's faction modules) | +| `maker` | the name of a faction the shipped catalog holds; the product record is made for it | +| `description` | the product's description | +| `offered` | `true` or `false`: whether the maker sells it | +| `price` | at least 0 (AetherDb `price`) | +| `stats` | `mass`, `durability`, `armor`, `drag`, each at least 0, and optionally `top_speed` (a hull without it keeps `like`'s) | +| `rows` | a non-empty list of hardpoint rows, below | + +A row has all of `id`, `kind`, `cell`, `footprint`, `rotation`, `armor`, `arc`: + +- `id` is the mount id the model's anchor binds to (`aetheria.id`); unique in the manifest. +- `kind` is one of `ship_cc.HARDPOINT_TYPE_NAMES` (Hull, Tool, Thermal, Thruster, WarpDrive, Reactor, Radiator, Shield, Sensors, + Energy, Ballistic, Launcher, ControlModule). The packager keeps no list of its own. +- `cell` is `[x, y]`, whole numbers of at least 0: the footprint's lowest-x, lowest-y cell on the raster. `x` runs across, `y` from + the stern (0) toward the bow, as the layout panel shows it. Cells are in schematic space, not model space. +- `footprint` is rows of `#` (the mount's cells) and `.` separated by `/`, all one width, at least one `#`. The first row is the top + (highest y); the last row is `y` itself. `##/#.` is a 2x2 box missing its lower-right cell. +- `rotation` is `0` None, `1` CounterClockwise, `2` Reversed, `3` Clockwise (`ship_cc.ROTATION_NAMES`). +- `armor` is at least 0; `arc` is the firing arc in degrees, 0 to 360. + +The committed example is `tests/fixtures/hulls/zh-ammo-tender/package.json`; its rows fit the raster that its `hull.scad` and +`extent` produce. + +## Reproducers (`hull_packager/`) + +- `build_aetherdb.ps1` publishes `tools/AetherDb` into `/ModTools`: it needs CultLib and CultMath worktrees at the revisions + `Directory.Build.props` names and passes `ErrorOnDuplicatePublishOutputFiles=false` (the NETSDK1152 workaround). +- `gen_manifest.py --like ... --extent X Y Z --maker ...` turns an existing package into a manifest. +- `compare.py ` prints `COMPARE_EQUAL` when shape, rows, stats, price and product match. +- `job.ps1` runs the regression on a workstation with Blender and OpenSCAD: the fixture manifest; the committed + `aetheria.nakovalnya` regenerated from its own manifest and compared; a refused second run and a failed `--replace`, each + required to leave the package byte-identical; then compose. Launch it detached; its header gives the log and status files. + +`python -m unittest discover -s tools/blender/tests -p test_package_hull.py` runs the Blender-free tests (manifest refusals, row +placement, the all-or-nothing swap). diff --git a/tools/blender/package_hull.py b/tools/blender/package_hull.py index 540b9c607..ab1e356c2 100644 --- a/tools/blender/package_hull.py +++ b/tools/blender/package_hull.py @@ -5,11 +5,13 @@ Environment: GAME_FOLDER (holds GameData/Aetheria.cc and ModTools/AetherDb.exe), CULTLIB_PACKAGES, OPENSCAD. The repo (and so the add-on) is found from this file. The manifest is creation input only: once GameData/Mods/ exists, ship.cc owns rows, stats and product, and a manifest is never read again; --replace re-derives the package and discards edits made since. Without --replace an -existing package is refused untouched. +existing package is refused untouched. A run is all or nothing: --replace moves the existing package aside, builds, and deletes the old one +only when the new one is complete; any failure removes what the run built and puts the old package back as it was. Order, one owner per step: New Ship --like, the first Save Layout creates ship.cc, AetherDb stats/price/product (the one writer of each), hull.scad copied in, Load Layout, Build From Hull Source, Rasterise Hull, the rows through place(), Save Layout, Package Ship. -The last line is PACKAGE_OK or PACKAGE_FAILED. Everything outside package() is pure Python (test_package_hull.py). +The last line is PACKAGE_OK (exit 0) or PACKAGE_FAILED (exit 1); a row that does not fit its cell is a failure, never a move. +Manifest schema and the reproducers: package_hull.md. Everything outside package() is pure Python (test_package_hull.py). """ import importlib.util @@ -19,6 +21,7 @@ import shutil import subprocess import sys import traceback +from contextlib import contextmanager from pathlib import Path HERE = Path(__file__).resolve().parent @@ -28,8 +31,6 @@ STATS_KEYS = ("mass", "durability", "armor", "drag") STATS_OPTIONAL = ("top_speed",) ROW_KEYS = ("id", "kind", "cell", "footprint", "rotation", "armor", "arc") -created = [] # package folders this run made; removed on failure, so a refused run leaves an existing package alone - class Refused(Exception): pass @@ -135,32 +136,52 @@ def cells_of(x, y, footprint): def place(rows, width, height, occupied): - """Each row at its cell, or at the nearest cell where its whole footprint is inside the shape and clear of earlier rows.""" + """Each row at its cell, or Refused naming the row: the manifest's cells are authored against the raster, so a cell off the + raster, outside the shape or overlapping an earlier row is a fault in the manifest, not something to move.""" taken, placed = set(), [] for mount_id, kind, (x, y), footprint, rotation, armor, arc in rows: - def fits(px, py): - return all(0 <= cx < width and 0 <= cy < height and occupied(cx, cy) and (cx, cy) not in taken - for cx, cy in cells_of(px, py, footprint)) - if fits(x, y): - at = (x, y) - else: - candidates = sorted(((px - x) ** 2 + (py - y) ** 2, px, py) for px in range(width) for py in range(height) if fits(px, py)) - if not candidates: - raise Refused(f"No cell fits row {mount_id or kind}") - at = candidates[0][1:] - print(f"DEVIATION row {mount_id or 'kind ' + kind} moved from {(x, y)} to {at}: outside the shape or overlapping", flush=True) - taken.update(cells_of(*at, footprint)) - placed.append((mount_id, kind, at, footprint, rotation, armor, arc)) + for cx, cy in cells_of(x, y, footprint): + if not (0 <= cx < width and 0 <= cy < height): + raise Refused(f"row {mount_id or kind} cell ({cx}, {cy}) is off the {width}x{height} raster") + if not occupied(cx, cy): + raise Refused(f"row {mount_id or kind} cell ({cx}, {cy}) is outside the hull shape") + if (cx, cy) in taken: + raise Refused(f"row {mount_id or kind} cell ({cx}, {cy}) overlaps an earlier row") + taken.update(cells_of(x, y, footprint)) + placed.append((mount_id, kind, (x, y), footprint, rotation, armor, arc)) return placed +@contextmanager +def swap(package_dir, backup, replace): + """The all-or-nothing run. An existing package is refused untouched, or with replace moved to backup (same volume, a rename) + before the build. On any failure what the run built is removed and the old package moved back; on success the backup goes.""" + existed = package_dir.exists() + if existed and not replace: + raise Refused(f"{package_dir} exists; pass --replace to re-derive it (this discards edits made since)") + if backup.exists(): + raise Refused(f"{backup} is left from an interrupted run; restore or delete it first") + if existed: + backup.parent.mkdir(parents=True, exist_ok=True) + shutil.move(str(package_dir), str(backup)) + try: + yield + except BaseException: + shutil.rmtree(package_dir, ignore_errors=True) + if existed: + shutil.move(str(backup), str(package_dir)) + raise + if existed: + shutil.rmtree(backup) + + def rows_of(manifest): return [(row["id"], row["kind"], tuple(row["cell"]), row["footprint"], row["rotation"], row["armor"], row["arc"]) for row in manifest["rows"]] -def package(manifest, manifest_dir, game, packages, openscad, replace): - """The Blender half. Leaves GameData/Mods/ in place; raises Refused with a message on any failure.""" +def package(manifest, manifest_dir, game, packages, openscad): + """The Blender half, run inside swap(). Builds GameData/Mods/; raises Refused with a message on any failure.""" import addon_utils import bmesh import bpy @@ -170,12 +191,7 @@ def package(manifest, manifest_dir, game, packages, openscad, replace): package_dir = game / "GameData" / "Mods" / ship_id ship_cc_path = package_dir / "ship.cc" aetherdb = game / "ModTools" / "AetherDb.exe" - if package_dir.exists() and not replace: - raise Refused(f"{package_dir} exists; pass --replace to re-derive it (this discards edits made since)") print(f"STEP Blender {bpy.app.version_string}", flush=True) - if package_dir.exists(): - shutil.rmtree(package_dir) - created.append(package_dir) def require(condition, message): if not condition: @@ -307,24 +323,27 @@ def main(argv): env[key] = os.environ[key] manifest_path = Path(paths[0]).resolve() manifest = load_manifest(manifest_path) - package(manifest, manifest_path.parent, Path(env["GAME_FOLDER"]), env["CULTLIB_PACKAGES"], env["OPENSCAD"], replace) + game = Path(env["GAME_FOLDER"]) + with swap(game / "GameData" / "Mods" / manifest["id"], game / f".hull-packager-backup-{manifest['id']}", replace): + package(manifest, manifest_path.parent, game, env["CULTLIB_PACKAGES"], env["OPENSCAD"]) -if __name__ == "__main__": +def entry(argv): + """The exit status: 0 and PACKAGE_OK, or 1 and PACKAGE_FAILED. swap() has already put the game folder back.""" try: - main(sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []) + main(argv) except Refused as stop: print(f"PACKAGE_FAILED: {stop}", flush=True) - code = 1 + return 1 except Exception: traceback.print_exc() print("PACKAGE_FAILED", flush=True) - code = 1 - else: - print("PACKAGE_OK", flush=True) - code = 0 - if code: - for folder in created: - shutil.rmtree(folder, ignore_errors=True) + return 1 + print("PACKAGE_OK", flush=True) + return 0 + + +if __name__ == "__main__": + code = entry(sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []) sys.stdout.flush() os._exit(code) diff --git a/tools/blender/tests/test_package_hull.py b/tools/blender/tests/test_package_hull.py index 5463c77d6..6511ebb3a 100644 --- a/tools/blender/tests/test_package_hull.py +++ b/tools/blender/tests/test_package_hull.py @@ -8,10 +8,12 @@ package_hull is loaded by path; its bpy imports are inside package(), and its dr import importlib.util import json +import os import sys import tempfile import unittest from pathlib import Path +from unittest import mock _spec = importlib.util.spec_from_file_location( "package_hull", Path(__file__).resolve().parents[1] / "package_hull.py") @@ -75,26 +77,121 @@ class PlaceTests(unittest.TestCase): placed = ph.place([self.ROW], 6, 6, lambda x, y: True) self.assertEqual(placed[0][2], (2, 2)) - def test_a_row_outside_the_shape_moves_with_a_deviation(self): - import io - from contextlib import redirect_stdout - with redirect_stdout(io.StringIO()) as captured: - placed = ph.place([self.ROW], 6, 6, lambda x, y: x < 2) - self.assertEqual(placed[0][2], (0, 2)) - self.assertIn("DEVIATION row Gun.D moved from (2, 2) to (0, 2)", captured.getvalue()) + def refused(self, rows, width, height, occupied, *words): + with self.assertRaises(ph.Refused) as caught: + ph.place(rows, width, height, occupied) + for word in words: + self.assertIn(word, str(caught.exception)) - def test_a_row_overlapping_an_earlier_one_moves(self): - import io - from contextlib import redirect_stdout - second = ("Gun.E", "Ballistic", (2, 2), "#", 0, 20, 90) - with redirect_stdout(io.StringIO()) as captured: - placed = ph.place([self.ROW, second], 6, 6, lambda x, y: True) - self.assertNotIn(placed[1][2], ph.cells_of(2, 2, "##/##")) - self.assertIn("DEVIATION row Gun.E", captured.getvalue()) + def test_a_row_off_the_raster_is_refused_not_moved(self): + self.refused([("Gun.D", "Ballistic", (50, 50), "#", 0, 20, 90)], 6, 6, lambda x, y: True, "Gun.D", "off the 6x6 raster") + self.refused([("Gun.D", "Ballistic", (5, 5), "##/##", 0, 20, 90)], 6, 6, lambda x, y: True, "Gun.D", "off the 6x6 raster") - def test_a_row_no_cell_fits_is_refused(self): - with self.assertRaises(ph.Refused): - ph.place([self.ROW], 6, 6, lambda x, y: False) + def test_a_row_outside_the_shape_is_refused_not_moved(self): + self.refused([self.ROW], 6, 6, lambda x, y: x < 2, "Gun.D", "outside the hull shape") + + def test_a_row_overlapping_an_earlier_one_is_refused_not_moved(self): + second = ("Gun.E", "Ballistic", (3, 3), "#", 0, 20, 90) + self.refused([self.ROW, second], 6, 6, lambda x, y: True, "Gun.E", "overlaps") + + +class SwapTests(unittest.TestCase): + """The all-or-nothing run, through main() with the Blender half replaced by one that writes into the package and then fails + or finishes. The existing package must be exactly as it was after any failure.""" + + def setUp(self): + self.work = tempfile.TemporaryDirectory() + self.addCleanup(self.work.cleanup) + root = Path(self.work.name) + self.game = root / "game" + self.manifest = root / "package.json" + data = json.loads(FIXTURE.read_text(encoding="utf-8")) + self.id = data["id"] + self.manifest.write_text(json.dumps(data), encoding="utf-8") + (root / data["hull"]).write_text("// hull" + chr(10), encoding="utf-8") + self.package_dir = self.game / "GameData" / "Mods" / self.id + old = mock.patch.dict(os.environ, {"GAME_FOLDER": str(self.game), "CULTLIB_PACKAGES": "x", "OPENSCAD": "x"}) + old.start() + self.addCleanup(old.stop) + self.real = ph.package + self.addCleanup(setattr, ph, "package", self.real) + + def existing(self): + self.package_dir.mkdir(parents=True) + (self.package_dir / "ship.cc").write_bytes(b"studio edits") + (self.package_dir / "ship.glb").write_bytes(b"model") + + def digest(self): + files = sorted(self.game.rglob("*")) if self.game.exists() else [] + return [(str(p.relative_to(self.game)), p.read_bytes() if p.is_file() else None) for p in files] + + def builder(self, then): + def package(manifest, manifest_dir, game, packages, openscad): + self.package_dir.mkdir(parents=True, exist_ok=True) + (self.package_dir / "ship.cc").write_bytes(b"derived") + (self.package_dir / "hull.scad").write_bytes(b"half built") + then() + ph.package = package + + def run_entry(self, *flags): + import io + from contextlib import redirect_stderr, redirect_stdout + with redirect_stdout(io.StringIO()) as out, redirect_stderr(io.StringIO()): + code = ph.entry([str(self.manifest), *flags]) + return code, out.getvalue() + + def fail(self): + raise ph.Refused("No cell fits") + + def test_a_failed_replace_leaves_the_package_exactly_as_it_was(self): + self.existing() + before = self.digest() + self.builder(self.fail) + code, out = self.run_entry("--replace") + self.assertEqual(code, 1) + self.assertIn("PACKAGE_FAILED: No cell fits", out) + self.assertEqual(self.digest(), before) + + def test_a_crash_in_a_replace_leaves_the_package_exactly_as_it_was(self): + self.existing() + before = self.digest() + self.builder(lambda: 1 / 0) + code, out = self.run_entry("--replace") + self.assertEqual(code, 1) + self.assertTrue(out.rstrip().endswith("PACKAGE_FAILED")) + self.assertEqual(self.digest(), before) + + def test_a_successful_replace_swaps_and_leaves_no_backup(self): + self.existing() + self.builder(lambda: None) + code, out = self.run_entry("--replace") + self.assertEqual((code, out.rstrip().endswith("PACKAGE_OK")), (0, True)) + self.assertEqual((self.package_dir / "ship.cc").read_bytes(), b"derived") + self.assertEqual(sorted(p.name for p in self.game.iterdir()), ["GameData"]) + + def test_an_existing_package_without_replace_is_refused_untouched(self): + self.existing() + before = self.digest() + self.builder(lambda: self.fail()) + code, out = self.run_entry() + self.assertEqual(code, 1) + self.assertIn("--replace", out) + self.assertEqual(self.digest(), before) + + def test_a_failed_first_run_leaves_no_package(self): + self.builder(self.fail) + code, _ = self.run_entry() + self.assertEqual(code, 1) + self.assertFalse(self.package_dir.exists()) + + def test_a_manifest_off_the_raster_exits_1(self): + def rows(): + ph.place([("Gun.D", "Ballistic", (50, 50), "#", 0, 20, 90)], 6, 6, lambda x, y: True) + self.builder(rows) + code, out = self.run_entry() + self.assertEqual(code, 1) + self.assertIn("PACKAGE_FAILED: row Gun.D", out) + self.assertFalse(self.package_dir.exists()) if __name__ == "__main__":