Blender tools: run an intent recipe in a background Blender; write a turntable recipe

run_intents.py sends a JSON list of intents through BrokkrBlenderTarget.run_intent in a
background Blender (the action table admits or denies each, host rows included) and writes
the receipts to a file. It refuses to start without private Blender user directories.
turntable_recipe.py writes such a recipe from Brokkr's own scene actions, so a before and
an after of one subject are framed identically.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-01 01:08:04 +01:00
commit 72258d9288
2 changed files with 181 additions and 0 deletions

View file

@ -0,0 +1,106 @@
"""Run a list of Brokkr intents in a background Blender, through the add-on's own agent turn.
blender --background --factory-startup --python surfaces/blender/tools/run_intents.py -- <recipe.json> [<receipts.json>]
For batch work on files (polishing a generated mesh, rendering a turntable) where no person has a Blender open.
Every intent goes through BrokkrBlenderTarget.run_intent: the action table admits or denies it, host add-on
rows are checked as in a live session, and each gets a receipt. No CultMesh node is opened: the receipts are
written to <receipts.json> (default: the recipe's name with .receipts.json) and nowhere else, so nothing here
shows in a person's Agents panel. This script is the human of its own Blender: it enables the host add-ons the
recipe names, reloads host actions once, and opens and saves the .blend. It refuses to start unless
BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are set, so it never reads or writes a
person's own Blender folders (docs/install.md).
The recipe:
{"requestedBy": "<mind>/<agent>",
"importDir": "<dir importGltf reads>", "outputDir": "<dir renderStill and exportGltf write>",
"hostAddons": ["brokkr_mesh_polish"], optional; modules found beside brokkr_bridge or in hostAddonDirs
"hostAddonDirs": ["<dir>"], optional; extra directories holding host add-on packages
"openBlend": "<path>", "saveBlend": "<path>", optional; without openBlend the scene starts empty; saveBlend
is written after the last intent
"keepGoing": false, optional; true runs the rest after a refusal
"intents": [{"action": "importGltf", "filepath": "ship.glb"}, ...]}
commandId defaults to <recipe stem>-<index>; requestedBy to the recipe's. Exit status: 0 when every intent was
accepted, 3 when one was not (the receipts file says which), 2 when the recipe could not be run at all.
"""
import importlib
import json
import os
import sys
import types
from pathlib import Path
import bpy
def fail(message: str) -> None:
print(f"run_intents: {message}", file=sys.stderr, flush=True)
sys.exit(2)
def main() -> int:
for name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"):
if not os.environ.get(name):
fail(f"{name} is not set: run in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories")
arguments = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
if not arguments:
fail("usage: blender --background --factory-startup --python run_intents.py -- <recipe.json> [<receipts.json>]")
recipe_path = Path(arguments[0]).resolve()
receipts_path = Path(arguments[1]).resolve() if len(arguments) > 1 else recipe_path.with_suffix(".receipts.json")
try:
recipe = json.loads(recipe_path.read_text(encoding="utf-8"))
except (OSError, ValueError) as error:
fail(f"cannot read {recipe_path}: {error}")
unknown = set(recipe) - {"requestedBy", "importDir", "outputDir", "hostAddons", "hostAddonDirs", "openBlend",
"saveBlend", "keepGoing", "intents"}
if unknown or not isinstance(recipe.get("intents"), list):
fail(f"recipe has unknown keys {sorted(unknown)} or no intents array")
surface = Path(__file__).resolve().parents[1]
package = types.ModuleType("brokkr_bridge") # the add-on's modules without registering its panel or timers
package.__path__ = [str(surface / "brokkr_bridge")]
sys.modules["brokkr_bridge"] = package
target_module = importlib.import_module("brokkr_bridge.blender_target")
if recipe.get("openBlend"):
bpy.ops.wm.open_mainfile(filepath=str(Path(recipe["openBlend"]).resolve()))
else:
bpy.ops.wm.read_factory_settings(use_empty=True) # no default cube, camera or light
import addon_utils
for directory in [str(surface)] + [str(Path(d).resolve()) for d in recipe.get("hostAddonDirs", [])]:
if directory not in sys.path:
sys.path.append(directory)
for module in recipe.get("hostAddons", []):
if addon_utils.enable(module, default_set=True) is None:
fail(f"host add-on {module!r} could not be enabled")
target = target_module.BrokkrBlenderTarget(bpy)
target.configure_action_dirs(recipe.get("importDir", ""), recipe.get("outputDir", ""))
target.reload_host_actions()
_, errors = target.host_actions()
if errors:
fail(f"host actions refused: {errors}")
receipts, status = [], 0
for index, intent in enumerate(recipe["intents"]):
command = dict(intent)
command.setdefault("commandId", f"{recipe_path.stem}-{index}")
command.setdefault("requestedBy", recipe.get("requestedBy", ""))
receipt = target.run_intent(bpy.context, command)
receipts.append(receipt)
print("RECEIPT", command["commandId"], command.get("action"), receipt["status"],
str(receipt.get("message", "")).replace("\n", " | ")[:300], flush=True)
if receipt["status"] != "accepted":
status = 3
if not recipe.get("keepGoing"):
break
receipts_path.write_text(json.dumps(receipts, indent=1, default=str), encoding="utf-8")
if recipe.get("saveBlend") and (status == 0 or recipe.get("keepGoing")):
bpy.ops.wm.save_as_mainfile(filepath=str(Path(recipe["saveBlend"]).resolve()))
return status
if __name__ == "__main__":
sys.exit(main())

View file

@ -0,0 +1,75 @@
"""Write a run_intents recipe that renders a turntable of a .blend with Brokkr's own scene actions.
python surfaces/blender/tools/turntable_recipe.py --blend ship.blend --output-dir renders --prefix ship_before \
--radius 0.75 --requested-by nibu/hands > turntable.json
The subject is assumed centred on the origin (brokkr_mesh_polish.orient leaves it there); --radius is half the
length the frame must hold. Each view is an orthographic still from a camera on a circle at --elevation degrees,
so two recipes with the same numbers frame two files identically: a before and an after can be compared view
by view. --look lit adds a sun over a dim grey world; --look flat lights with a uniform white world alone, which
shows a base colour texture as it is stored, baked shadows included. renderStill never overwrites, so a
recipe runs once per prefix.
"""
from __future__ import annotations
import argparse
import json
import math
import sys
def camera_pose(azimuth_deg: float, elevation_deg: float, distance: float) -> tuple[list[float], list[float]]:
"""(location, XYZ Euler radians) of a camera on the circle that looks at the origin with +Z up. Azimuth 0
looks along +Y from behind the subject's -Y end; it grows counter-clockwise seen from above."""
azimuth, elevation = math.radians(azimuth_deg), math.radians(elevation_deg)
x = distance * math.cos(elevation) * math.sin(azimuth)
y = -distance * math.cos(elevation) * math.cos(azimuth)
z = distance * math.sin(elevation)
return [x, y, z], [math.pi / 2 - elevation, 0.0, azimuth]
def recipe(blend: str, output_dir: str, prefix: str, radius: float, views: int, elevation: float, size: int,
engine: str, look: str, requested_by: str) -> dict:
distance = radius * 6
intents: list[dict] = [
{"action": "setWorld", "color": [1, 1, 1] if look == "flat" else [0.5, 0.5, 0.5], "strength": 1.0 if look == "flat" else 0.4},
{"action": "createObject", "objectType": "CAMERA", "name": "TurntableCamera"},
{"action": "setCamera", "targetObjectName": "TurntableCamera", "cameraType": "ORTHO", "orthoScale": radius * 2.1,
"clipStart": radius * 0.01, "clipEnd": radius * 20, "active": True},
]
if look == "lit":
intents += [
{"action": "createObject", "objectType": "LIGHT", "lightType": "SUN", "name": "TurntableSun"},
{"action": "setLight", "targetObjectName": "TurntableSun", "energy": 3.0, "color": [1, 1, 1]},
{"action": "setObjectTransform", "targetObjectName": "TurntableSun", "rotationEuler": [math.radians(40), 0.0, math.radians(35)]},
]
poses = [(360.0 * i / views, elevation) for i in range(views)] + [(0.0, 90.0), (0.0, -90.0)]
names = [f"{round(a):03d}" for a, _ in poses[:views]] + ["top", "bottom"]
for name, (azimuth, tilt) in zip(names, poses):
location, rotation = camera_pose(azimuth, tilt, distance)
intents.append({"action": "setObjectTransform", "targetObjectName": "TurntableCamera", "location": location, "rotationEuler": rotation})
intents.append({"action": "renderStill", "outputPath": f"{prefix}_{look}_{name}.png", "engine": engine,
"resolutionX": size, "resolutionY": size, "cameraName": "TurntableCamera"})
return {"requestedBy": requested_by, "outputDir": output_dir, "openBlend": blend, "intents": intents}
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--blend", required=True)
parser.add_argument("--output-dir", required=True)
parser.add_argument("--prefix", required=True)
parser.add_argument("--radius", type=float, required=True)
parser.add_argument("--views", type=int, default=8)
parser.add_argument("--elevation", type=float, default=25.0)
parser.add_argument("--size", type=int, default=1024)
parser.add_argument("--engine", default="BLENDER_EEVEE")
parser.add_argument("--look", choices=("lit", "flat"), default="lit")
parser.add_argument("--requested-by", required=True)
a = parser.parse_args(argv)
json.dump(recipe(a.blend, a.output_dir, a.prefix, a.radius, a.views, a.elevation, a.size, a.engine, a.look,
a.requested_by), sys.stdout, indent=1)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))