Blender add-on: one action table (actions.json) decides every intent's fields and undo class

run_intent admits through action_table.validate: unknown field, wrong type, enum miss, bound miss,
missing required field are 'denied' (admission: nothing ran, no undo step). The entry's changesScene
and editModeSafe replace READ_ACTIONS, MUTATING_ACTIONS, NO_SCENE_CHANGE_ACTIONS and
EDIT_MODE_SAFE_ACTIONS; the handler is '_' + the action's name, so _dispatch's if-chain, the scene
field helpers (number, integer, choice, color), node_actions' text/tree_key/check_idname and the
cross-aliases (objectName on scene actions, targetObjectName on node actions, parentName) are gone.
New bounds only where nothing was checked: createObject size, lightType/emptyDisplayType enums,
resolution minimum 4 (Blender clamps 1..3 silently), the probed panoramaType items, node label 63.
Handlers keep scene-dependent refusals (ActionRefused, 'failed').

Parity fixture surfaces/blender/tests/action_cases.json is for brokkr-ctl's validator, which follows.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-28 02:47:07 +01:00
commit 7c6092bc0a
14 changed files with 956 additions and 387 deletions

View file

@ -0,0 +1,213 @@
"""The action table: which Blender intents exist, what fields each may carry, and each action's undo class.
actions.json (schema brokkr.blender.actions.v0) is the one owner. run_intent admits every intent through
validate(); brokkr-ctl embeds the same file for `send --help` and early refusal, with the same rules and
message text (surfaces/blender/tests/action_cases.json pins the two). Stdlib only, no bpy.
Vocabulary: null means absent; a required field absent is refused; a field neither declared nor in the
envelope is refused; enums match exactly; number and integer are never bool and always within the declared
minimum and maximum, integer is whole; string may declare minLength, maxLength, chars (a named charset),
prefixes (starts with one and has at least one more character) and forbid (substrings); array declares
items, minItems, maxItems; object with properties is closed and recursive, without is a free map; any is
any non-null value; only {field, in} refuses a field present unless the sibling's value is in the list;
defaults fill absent top-level fields after validation. Scene-dependent rules stay in the handlers.
"""
from __future__ import annotations
import functools
import json
import math
from pathlib import Path
from typing import Any
TABLE_PATH = Path(__file__).with_name("actions.json")
SCHEMA = "brokkr.blender.actions.v0"
TYPES = ("string", "number", "integer", "boolean", "array", "object", "any")
TYPE_WORDS = {"string": "a string", "number": "a finite number", "integer": "a whole number",
"boolean": "true or false", "array": "an array", "object": "an object"}
class IntentInvalid(ValueError):
"""The intent breaks a rule of the table; the message names the field path and the rule."""
class TableInvalid(ValueError):
"""actions.json itself is malformed."""
def number_text(value: float) -> str:
"""A bound as it is printed in messages: whole values without a fraction, others as the shortest digits."""
return str(int(value)) if value == int(value) else repr(float(value))
def _list(items: list) -> str:
return ", ".join(items)
@functools.lru_cache(maxsize=1)
def _raw() -> dict[str, Any]:
return json.loads(TABLE_PATH.read_text(encoding="utf-8"))
@functools.lru_cache(maxsize=1)
def table() -> dict[str, Any]:
"""actions.json, loaded and checked once."""
document = _raw()
check_table(document)
return document
def entry(action: Any) -> dict[str, Any] | None:
"""The table row for an action name, or None."""
return _by_name().get(action) if isinstance(action, str) else None
@functools.lru_cache(maxsize=1)
def _by_name() -> dict[str, dict[str, Any]]:
return {a["name"]: a for a in table()["actions"]}
def check_table(document: dict[str, Any]) -> None:
"""Refuse a table with an unbounded number field, an 'only' naming a missing field, an unknown charset,
a default that breaks its own field's rules, or a bound that prints differently in Python and Rust."""
if document.get("schema") != SCHEMA:
raise TableInvalid(f"table schema must be {SCHEMA}")
charsets = document.get("charsets", {})
names = set()
for action in document["actions"]:
if action["name"] in names:
raise TableInvalid(f"action {action['name']} is listed twice")
names.add(action["name"])
fields = {f["name"]: f for f in action["fields"]}
if len(fields) != len(action["fields"]):
raise TableInvalid(f"{action['name']} repeats a field")
for field in action["fields"]:
_check_spec(field, f"{action['name']}.{field['name']}", charsets, fields, top=True)
if "default" in field:
try:
_value(field, field["default"], field["name"])
except IntentInvalid as error:
raise TableInvalid(f"{action['name']}.{field['name']} default: {error}") from None
def _check_spec(spec: dict[str, Any], where: str, charsets: dict, siblings: dict, top: bool) -> None:
kind = spec.get("type")
if kind not in TYPES:
raise TableInvalid(f"{where}: unknown type {kind!r}")
if kind in ("number", "integer"):
for bound in ("minimum", "maximum"):
value = spec.get(bound)
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise TableInvalid(f"{where}: a {kind} field declares {bound}")
if "e" in number_text(value):
raise TableInvalid(f"{where}: {bound} {value} does not print as plain digits")
if "chars" in spec and spec["chars"] not in charsets:
raise TableInvalid(f"{where}: charset {spec['chars']!r} is not defined")
if "only" in spec:
if not top or spec["only"]["field"] not in siblings:
raise TableInvalid(f"{where}: 'only' must name a field of the same action")
if "default" in spec and not top:
raise TableInvalid(f"{where}: only top-level fields have defaults")
if kind == "array":
_check_spec(spec["items"], where + "[]", charsets, siblings, top=False)
if kind == "object" and "properties" in spec:
inner = {p["name"]: p for p in spec["properties"]}
for prop in spec["properties"]:
_check_spec(prop, f"{where}.{prop['name']}", charsets, inner, top=False)
def validate(command: dict[str, Any]) -> dict[str, Any]:
"""The normalized copy of an intent (nulls dropped, defaults filled), or IntentInvalid naming the rule."""
action = command.get("action", "")
row = entry(action)
if row is None:
raise IntentInvalid(f"Unsupported Blender command action: {action}")
present = {k: v for k, v in command.items() if v is not None}
_fields(row["fields"], present, None, action, set(table()["envelope"]))
result = dict(present)
for field in row["fields"]:
if field["name"] not in result and "default" in field:
result[field["name"]] = field["default"]
return result
def _fields(specs: list[dict[str, Any]], values: dict[str, Any], parent: str | None, where: str, skip: set) -> None:
"""The fields of an action (parent None) or of a closed object: unknown names first, sorted, then each
declared field in table order."""
declared = [s["name"] for s in specs]
for key in sorted(k for k in values if k not in skip and k not in declared):
raise IntentInvalid(f"{where} has no field '{key}'; its fields: {_list(declared) or 'none'}.")
for spec in specs:
path = spec["name"] if parent is None else f"{parent}.{spec['name']}"
value = values.get(spec["name"])
if value is None:
if spec.get("required"):
raise IntentInvalid(f"{path} is required.")
continue
only = spec.get("only")
if only is not None and values.get(only["field"]) not in only["in"]:
raise IntentInvalid(f"{path} applies only when {only['field']} is one of {_list(only['in'])}.")
_value(spec, value, path)
def _value(spec: dict[str, Any], value: Any, path: str) -> None:
kind = spec["type"]
if kind == "any":
return
if kind in ("number", "integer"):
_number(spec, value, path)
elif kind == "string":
if not isinstance(value, str):
raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.")
if "enum" in spec:
if value not in spec["enum"]:
raise IntentInvalid(f"{path} must be one of {_list(spec['enum'])}.")
else:
_string(spec, value, path)
elif kind == "boolean":
if not isinstance(value, bool):
raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.")
elif kind == "array":
if not isinstance(value, list):
raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.")
if "minItems" in spec and len(value) < spec["minItems"]:
raise IntentInvalid(f"{path} must have at least {spec['minItems']} items.")
if "maxItems" in spec and len(value) > spec["maxItems"]:
raise IntentInvalid(f"{path} must have at most {spec['maxItems']} items.")
for index, item in enumerate(value):
if item is None:
raise IntentInvalid(f"{path}[{index}] must be {TYPE_WORDS.get(spec['items']['type'], 'a value')}.")
_value(spec["items"], item, f"{path}[{index}]")
elif kind == "object":
if not isinstance(value, dict):
raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.")
if "properties" in spec:
_fields(spec["properties"], {k: v for k, v in value.items() if v is not None}, path, path, frozenset())
def _string(spec: dict[str, Any], value: str, path: str) -> None:
if "minLength" in spec and len(value) < spec["minLength"]:
raise IntentInvalid(f"{path} must have at least {spec['minLength']} characters.")
if "maxLength" in spec and len(value) > spec["maxLength"]:
raise IntentInvalid(f"{path} must have at most {spec['maxLength']} characters.")
if "chars" in spec:
charset = _raw()["charsets"][spec["chars"]]
if any(c not in charset["allowed"] for c in value):
raise IntentInvalid(f"{path} may contain only {charset['text']}.")
if "prefixes" in spec and not any(value.startswith(p) and len(value) > len(p) for p in spec["prefixes"]):
raise IntentInvalid(f"{path} must start with one of {_list(spec['prefixes'])} and have at least one more character.")
for part in spec.get("forbid", ()):
if part in value:
raise IntentInvalid(f"{path} may not contain '{part}'.")
def _number(spec: dict[str, Any], value: Any, path: str) -> None:
kind = spec["type"]
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.")
if isinstance(value, float) and not math.isfinite(value):
raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.")
if kind == "integer" and isinstance(value, float) and value != int(value):
raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.")
if not spec["minimum"] <= value <= spec["maximum"]:
raise IntentInvalid(f"{path} must be between {number_text(spec['minimum'])} and {number_text(spec['maximum'])}.")

View file

@ -0,0 +1,144 @@
{
"schema": "brokkr.blender.actions.v0",
"envelope": ["schema", "commandId", "action", "requestedBy", "note"],
"charsets": {
"id": {"allowed": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-", "text": "letters, digits, '.', '_' or '-'"},
"key": {"allowed": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ._-", "text": "letters, digits, space, '.', '_' or '-'"},
"alnum": {"allowed": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "text": "letters and digits"}
},
"actions": [
{"name": "createObject", "doc": "Add an object at a location; a MESH is a cube.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "objectType", "type": "string", "enum": ["MESH", "LIGHT", "CAMERA", "EMPTY"], "default": "EMPTY"},
{"name": "name", "type": "string"},
{"name": "location", "type": "array", "items": {"type": "number", "minimum": -1000000000, "maximum": 1000000000}, "minItems": 3, "maxItems": 3, "doc": "[x,y,z]"},
{"name": "size", "type": "number", "minimum": 0.001, "maximum": 1000000, "default": 1, "doc": "cube size, used by MESH"},
{"name": "meshType", "type": "string", "enum": ["CUBE"], "only": {"field": "objectType", "in": ["MESH"]}},
{"name": "lightType", "type": "string", "enum": ["POINT", "SUN", "SPOT", "AREA"], "default": "POINT", "only": {"field": "objectType", "in": ["LIGHT"]}},
{"name": "emptyDisplayType", "type": "string", "enum": ["PLAIN_AXES", "ARROWS", "SINGLE_ARROW", "CIRCLE", "CUBE", "SPHERE", "CONE", "IMAGE"], "default": "PLAIN_AXES", "only": {"field": "objectType", "in": ["EMPTY"]}}
]},
{"name": "deleteObject", "doc": "Delete an object.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}
]},
{"name": "setObjectTransform", "doc": "Set any of an object's location, rotation and scale.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"},
{"name": "location", "type": "array", "items": {"type": "number", "minimum": -1000000000, "maximum": 1000000000}, "minItems": 3, "maxItems": 3, "doc": "[x,y,z]"},
{"name": "rotationEuler", "type": "array", "items": {"type": "number", "minimum": -1000000000, "maximum": 1000000000}, "minItems": 3, "maxItems": 3, "doc": "[x,y,z] radians"},
{"name": "scale", "type": "array", "items": {"type": "number", "minimum": -1000000000, "maximum": 1000000000}, "minItems": 3, "maxItems": 3, "doc": "[x,y,z]"}
]},
{"name": "setObjectVisibility", "doc": "Show or hide an object in the viewport and in renders.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"},
{"name": "visible", "type": "boolean", "default": true}
]},
{"name": "setObjectParent", "doc": "Parent an object to another.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"},
{"name": "parentObjectName", "type": "string", "doc": "empty or absent clears the parent"}
]},
{"name": "setObjectCustomProperty", "doc": "Set one custom property on an object.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"},
{"name": "propertyName", "type": "string", "default": "brokkrValue"},
{"name": "value", "type": "any", "required": true, "doc": "any JSON value Blender accepts as a property"}
]},
{"name": "selectObject", "doc": "Select an object and make it active.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"},
{"name": "clearSelection", "type": "boolean", "default": true}
]},
{"name": "assignMaterial", "doc": "Assign a material (created when new) to an object's slots.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"},
{"name": "materialName", "type": "string", "default": "Brokkr Material"},
{"name": "color", "type": "array", "items": {"type": "number", "minimum": 0, "maximum": 1}, "minItems": 3, "maxItems": 4, "doc": "[r,g,b] or [r,g,b,a], linear; alpha defaults to 1"}
]},
{"name": "importGltf", "doc": "Import a .gltf or .glb from the add-on's import directory.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "filepath", "type": "string", "required": true, "doc": "relative to the add-on's import directory"}
]},
{"name": "exportGltf", "doc": "Write the scene, or the named objects, as .glb or .gltf into the output directory.", "changesScene": false, "editModeSafe": false, "fields": [
{"name": "filepath", "type": "string", "required": true, "doc": ".glb or .gltf relative to the add-on's output directory"},
{"name": "extras", "type": "boolean", "default": true},
{"name": "yUp", "type": "boolean", "default": true},
{"name": "applyModifiers", "type": "boolean", "default": true},
{"name": "selection", "type": "array", "items": {"type": "string", "minLength": 1}, "minItems": 1, "doc": "object names; the whole scene when absent"}
]},
{"name": "setCamera", "doc": "Change a camera's lens, projection and clipping.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"},
{"name": "lens", "type": "number", "minimum": 1, "maximum": 5000, "doc": "mm"},
{"name": "cameraType", "type": "string", "enum": ["PERSP", "ORTHO", "PANO"]},
{"name": "orthoScale", "type": "number", "minimum": 0.001, "maximum": 100000},
{"name": "clipStart", "type": "number", "minimum": 0.0001, "maximum": 1000000},
{"name": "clipEnd", "type": "number", "minimum": 0.001, "maximum": 10000000},
{"name": "panoramaType", "type": "string", "enum": ["EQUIRECTANGULAR", "EQUIANGULAR_CUBEMAP_FACE", "MIRRORBALL", "FISHEYE_EQUIDISTANT", "FISHEYE_EQUISOLID", "FISHEYE_LENS_POLYNOMIAL", "CENTRAL_CYLINDRICAL"]},
{"name": "active", "type": "boolean", "doc": "true makes it the scene camera"}
]},
{"name": "setLight", "doc": "Change a light's energy, colour and type.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"},
{"name": "energy", "type": "number", "minimum": 0, "maximum": 10000000},
{"name": "color", "type": "array", "items": {"type": "number", "minimum": 0, "maximum": 1}, "minItems": 3, "maxItems": 3, "doc": "[r,g,b] linear"},
{"name": "lightType", "type": "string", "enum": ["POINT", "SUN", "SPOT", "AREA"]}
]},
{"name": "setWorld", "doc": "Edit the world's Background node; a world is created when there is none.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "worldName", "type": "string", "doc": "default: the scene's world"},
{"name": "color", "type": "array", "items": {"type": "number", "minimum": 0, "maximum": 1}, "minItems": 3, "maxItems": 3, "doc": "[r,g,b] linear"},
{"name": "strength", "type": "number", "minimum": 0, "maximum": 1000000}
]},
{"name": "renderStill", "doc": "Render the scene to a still in the output directory; settings are restored afterwards.", "changesScene": false, "editModeSafe": true, "fields": [
{"name": "outputPath", "type": "string", "required": true, "doc": ".png, .jpg or .exr relative to the add-on's output directory"},
{"name": "engine", "type": "string", "minLength": 1, "doc": "a render engine identifier of the running Blender"},
{"name": "resolutionX", "type": "integer", "minimum": 4, "maximum": 16384},
{"name": "resolutionY", "type": "integer", "minimum": 4, "maximum": 16384},
{"name": "cameraName", "type": "string"}
]},
{"name": "look", "doc": "Capture the 3D view she is looking at; the receipt carries lookPath.", "changesScene": false, "editModeSafe": true, "fields": [
]},
{"name": "createNodeGroup", "doc": "Create a geometry node group with an interface.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"},
{"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"},
{"name": "interface", "type": "array", "required": true, "minItems": 1, "maxItems": 64, "items": {"type": "object", "properties": [{"name": "inOut", "type": "string", "required": true, "enum": ["INPUT", "OUTPUT"]}, {"name": "name", "type": "string", "required": true, "minLength": 1, "maxLength": 63}, {"name": "type", "type": "string", "required": true, "enum": ["Geometry", "Float", "Int", "Bool", "Vector"]}, {"name": "default", "type": "any", "doc": "a value of the socket's type"}]}, "doc": "sockets: {inOut, name, type, default?}"}
]},
{"name": "addNode", "doc": "Add a node to a geometry node group.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"},
{"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"},
{"name": "id", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "required": true, "doc": "brokkr's key for the node"},
{"name": "blIdname", "type": "string", "required": true, "chars": "alnum", "prefixes": ["GeometryNode", "FunctionNode", "ShaderNode"], "forbid": ["Import", "Export", "Script", "Bake", "Group", "Simulation", "Repeat", "Foreach", "Viewer", "TexImage", "TexEnvironment", "ImageTexture", "InputImage", "TexIES"], "doc": "Blender's node type; file, script, cache, group and image nodes are refused"},
{"name": "location", "type": "array", "items": {"type": "number", "minimum": -1000000000, "maximum": 1000000000}, "minItems": 2, "maxItems": 2, "default": [0, 0], "doc": "[x,y]"},
{"name": "label", "type": "string", "maxLength": 63},
{"name": "properties", "type": "object", "doc": "enum, bool, int or float node settings"},
{"name": "inputs", "type": "object", "doc": "unlinked input defaults"}
]},
{"name": "removeNode", "doc": "Remove a node and its links.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"},
{"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"},
{"name": "id", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "required": true}
]},
{"name": "linkSockets", "doc": "Link one node's output socket to another's input.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"},
{"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"},
{"name": "fromNode", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "required": true},
{"name": "fromSocket", "type": "string", "required": true, "doc": "identifier or unique name"},
{"name": "toNode", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "required": true},
{"name": "toSocket", "type": "string", "required": true, "doc": "identifier or unique name"}
]},
{"name": "unlinkSockets", "doc": "Remove the links into an input socket, or only the one from a named output.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"},
{"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"},
{"name": "toNode", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "required": true},
{"name": "toSocket", "type": "string", "required": true},
{"name": "fromNode", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "doc": "with fromSocket: remove only that link"},
{"name": "fromSocket", "type": "string"}
]},
{"name": "addModifier", "doc": "Add or retarget a Geometry Nodes modifier on an object.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "objectName", "type": "string", "required": true, "doc": "the object's name"},
{"name": "modifierType", "type": "string", "enum": ["NODES"], "default": "NODES"},
{"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"},
{"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"},
{"name": "modifierName", "type": "string", "chars": "key", "minLength": 1, "maxLength": 63, "default": "Brokkr GeoNodes"}
]},
{"name": "removeModifier", "doc": "Remove a Geometry Nodes modifier from an object.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "objectName", "type": "string", "required": true, "doc": "the object's name"},
{"name": "modifierName", "type": "string", "minLength": 1, "maxLength": 255, "forbid": ["\u0000"], "default": "Brokkr GeoNodes"}
]},
{"name": "setModifierInput", "doc": "Set one exposed input of a Geometry Nodes modifier.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "objectName", "type": "string", "required": true, "doc": "the object's name"},
{"name": "modifierName", "type": "string", "default": "Brokkr GeoNodes"},
{"name": "socket", "type": "string", "required": true, "doc": "identifier or unique interface name"},
{"name": "value", "type": "any", "required": true, "doc": "Float, Int, Bool or Vector"}
]}
]
}

View file

@ -25,6 +25,7 @@ if os.name == "nt":
else:
import fcntl
from . import action_table as at
from . import node_actions as na
from . import scene_actions as sa
from .server_guard import BindRefused, SessionGuard, check_bind, guarded_server_class, is_loopback_host, stop_pending
@ -49,8 +50,6 @@ SYNC_VAR_SCHEMA = "brokkr.sync.var.v0"
SYNC_TIMELINE_BINDING_SCHEMA = "brokkr.sync.timeline_binding.v0"
SYNC_RECEIPT_SCHEMA = "brokkr.sync.receipt.v0"
CREATABLE_OBJECT_TYPES = ("MESH", "LIGHT", "CAMERA", "EMPTY")
# Engines that draw through the GL stack. A headless Blender with no usable GL device aborts the whole
# process inside bpy.ops.render.render for these (no receipt); CYCLES renders on the CPU. Whether it
# will is found by rendering one pixel in a child Blender (gl_render_failure), not by guessing at libraries.
@ -60,20 +59,6 @@ EXPORT_STAGE_PREFIX = ".brokkr-export-"
STAGE_LOCK = ".brokkr-lock"
STAGE_JOURNAL = ".brokkr-journal"
# Actions that only read the scene and so push no undo step.
READ_ACTIONS = ("look",)
MUTATING_ACTIONS = (
"createObject", "deleteObject", "setObjectTransform", "setObjectVisibility", "setObjectParent",
"setObjectCustomProperty", "selectObject", "assignMaterial", "importGltf", "exportGltf",
"setCamera", "setLight", "setWorld", "renderStill",
)
# Actions that change no scene state: they push no undo step (exportGltf restores its selection;
# renderStill restores its settings).
NO_SCENE_CHANGE_ACTIONS = ("exportGltf", "renderStill")
# While an object is in Edit Mode, undo steps are edit-mesh steps, so a scene write is not reverted by
# one undo, and some operators leave Edit Mode (brokkr-live:ruling:object-intents-refused-in-edit-mode).
# Anything that writes scene state or changes her mode is refused; renderStill and look do neither.
EDIT_MODE_SAFE_ACTIONS = ("renderStill", "look")
LOOK_DIR = "look" # under the output directory: scratch captures named by command id (brush-tree:ruling:look-files-are-scratch)
LOOK_KEPT = 20 # the newest captures that stay after each look
EDIT_SELECTION_CAP = 4096 # indices listed per element kind and object; the total stays true beside the list
@ -636,29 +621,40 @@ class BrokkrBlenderTarget:
}
def run_intent(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
"""The one agent turn: admit, run with operator undo off, push one labelled undo step, receipt."""
"""The one agent turn: admit, run with operator undo off, push one labelled undo step, receipt.
Admission order: commandId shape, id unused, requestedBy, then the action table (action known, fields
valid), then Edit Mode. While an object is in Edit Mode undo steps are edit-mesh steps, so a scene write
is not reverted by one undo and some operators leave Edit Mode
(brokkr-live:ruling:object-intents-refused-in-edit-mode); the table's editModeSafe actions write nothing
and change no mode. A refusal at admission is 'denied': nothing ran, no undo step."""
command_id = command.get("commandId")
requested_by = command.get("requestedBy")
action = command.get("action", "")
denial = ""
row = None
if not _valid_command_id(command_id):
denial = "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'."
elif command_id in self._receipted:
denial = f"commandId {command_id!r} was already receipted; ids are single-use."
elif not isinstance(requested_by, str) or not REQUESTED_BY_SHAPE.fullmatch(requested_by):
denial = "Intent has no requestedBy of the form '<mind>/<agent>'."
elif action not in MUTATING_ACTIONS and action not in READ_ACTIONS and action not in na.NodeActions.ACTIONS:
denial = f"Unsupported Blender command action: {action}"
elif action not in EDIT_MODE_SAFE_ACTIONS and self._edit_mode_object() is not None:
denial = (f"Object {self._edit_mode_object()!r} is in Edit Mode: object-level intents are refused "
"until she leaves it; nothing was changed.")
else:
try:
command = at.validate(command)
row = at.entry(action)
except at.IntentInvalid as error:
denial = str(error)
if not denial and not row["editModeSafe"] and self._edit_mode_object() is not None:
denial = (f"Object {self._edit_mode_object()!r} is in Edit Mode: object-level intents are refused "
"until she leaves it; nothing was changed.")
if denial:
if _valid_command_id(command_id):
self._receipted.add(command_id)
return self._receipt(command, "denied", denial, "")
label = f"Brokkr {requested_by}: {action} {command_id[-8:]}" # the tail: uuid v7 ids lead with a timestamp, one value per minute
push = action not in READ_ACTIONS and action not in NO_SCENE_CHANGE_ACTIONS
push = row["changesScene"]
self.agent_turn = True
self._wrote = True
try:
@ -700,108 +696,70 @@ class BrokkrBlenderTarget:
self.bpy.ops.ed.undo_push(message=label)
def _dispatch(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
"""The action table. Only run_intent calls it; it owns refusal, failure and the undo step."""
action = command.get("action", "")
if action == "createObject":
return self._create_object(context, command)
if action == "deleteObject":
return self._delete_object(context, command)
if action == "setObjectTransform":
return self._set_object_transform(context, command)
if action == "setObjectVisibility":
return self._set_object_visibility(context, command)
if action == "setObjectParent":
return self._set_object_parent(context, command)
if action == "setObjectCustomProperty":
return self._set_object_custom_property(context, command)
if action == "selectObject":
return self._select_object(context, command)
if action == "assignMaterial":
return self._assign_material(context, command)
if action == "importGltf":
return self._import_gltf(context, command)
if action == "exportGltf":
return self._export_gltf(context, command)
if action == "setCamera":
return self._set_camera(context, command)
if action == "setLight":
return self._set_light(context, command)
if action == "setWorld":
return self._set_world(context, command)
if action == "renderStill":
return self._render_still(context, command)
if action == "look":
return self._look(context, command)
if action in na.NodeActions.ACTIONS:
"""Only run_intent calls it, with an intent the table admitted: the handler is '_' + the action's name,
on NodeActions for the node actions and on this target for the rest. It owns refusal, failure and the undo step."""
action = command["action"]
if hasattr(self.nodes, "_" + action):
message, name = self.nodes.execute(action, command)
self._wrote = self.nodes.changed
return self._receipt(command, "accepted", message, name)
return self._receipt(command, "failed", f"Unsupported Blender command action: {action}", "")
return getattr(self, "_" + action)(context, command)
def _create_object(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
object_type = command.get("objectType", "EMPTY")
if not isinstance(object_type, str) or object_type not in CREATABLE_OBJECT_TYPES:
shown = object_type if isinstance(object_type, str) else repr(object_type)
raise sa.ActionRefused(
f"objectType {shown!r} cannot be created; allowed: {', '.join(CREATABLE_OBJECT_TYPES)}.")
mesh_type = command.get("meshType")
if mesh_type is not None and object_type != "MESH":
raise sa.ActionRefused(f"meshType applies only to objectType MESH, not {object_type}.")
if mesh_type is not None and (not isinstance(mesh_type, str) or mesh_type.upper() != "CUBE"):
raise sa.ActionRefused(f"meshType {mesh_type!r} is not available; a MESH is a CUBE.")
def _createObject(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
object_type = command["objectType"]
name = command.get("name") or f"Brokkr {object_type.title()}"
location = _vector(command.get("location"), 3, (0.0, 0.0, 0.0))
location = tuple(command.get("location") or (0.0, 0.0, 0.0))
if object_type == "MESH":
self.bpy.ops.mesh.primitive_cube_add("EXEC_DEFAULT", False, size=float(command.get("size", 1.0)), location=location)
self.bpy.ops.mesh.primitive_cube_add("EXEC_DEFAULT", False, size=float(command["size"]), location=location)
elif object_type == "LIGHT":
self.bpy.ops.object.light_add("EXEC_DEFAULT", False, type=command.get("lightType", "POINT"), location=location)
self.bpy.ops.object.light_add("EXEC_DEFAULT", False, type=command["lightType"], location=location)
elif object_type == "CAMERA":
self.bpy.ops.object.camera_add("EXEC_DEFAULT", False, location=location)
else: # EMPTY
self.bpy.ops.object.empty_add("EXEC_DEFAULT", False, type=command.get("emptyDisplayType", "PLAIN_AXES"), location=location)
self.bpy.ops.object.empty_add("EXEC_DEFAULT", False, type=command["emptyDisplayType"], location=location)
obj = context.object
obj.name = name
return self._receipt(command, "accepted", "Blender object created.", obj.name)
def _delete_object(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
def _deleteObject(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
obj = self._resolve_object(command)
if obj is None:
return self._receipt(command, "failed", "Target Blender object was not found.", "")
self.bpy.data.objects.remove(obj, do_unlink=True)
return self._receipt(command, "accepted", "Blender object deleted.", command.get("targetObjectName", ""))
def _set_object_transform(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
def _setObjectTransform(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
obj = self._resolve_object(command)
if obj is None:
return self._receipt(command, "failed", "Target Blender object was not found.", "")
if "location" in command:
obj.location = _vector(command["location"], 3, obj.location)
obj.location = tuple(command["location"])
if "rotationEuler" in command:
obj.rotation_euler = _vector(command["rotationEuler"], 3, obj.rotation_euler)
obj.rotation_euler = tuple(command["rotationEuler"])
if "scale" in command:
obj.scale = _vector(command["scale"], 3, obj.scale)
obj.scale = tuple(command["scale"])
return self._receipt(command, "accepted", "Blender object transform updated.", obj.name)
def _set_object_visibility(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
def _setObjectVisibility(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
obj = self._resolve_object(command)
if obj is None:
return self._receipt(command, "failed", "Target Blender object was not found.", "")
visible = bool(command.get("visible", True))
visible = command["visible"]
obj.hide_viewport = not visible
obj.hide_render = not visible
return self._receipt(command, "accepted", "Blender object visibility updated.", obj.name)
def _set_object_parent(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
def _setObjectParent(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
obj = self._resolve_object(command)
if obj is None:
return self._receipt(command, "failed", "Target Blender object was not found.", "")
parent_name = command.get("parentObjectName") or command.get("parentName") or ""
parent_name = command.get("parentObjectName") or ""
parent = self.bpy.data.objects.get(parent_name) if parent_name else None
if parent_name and parent is None:
return self._receipt(command, "failed", f"Parent Blender object was not found: {parent_name}", obj.name)
@ -809,42 +767,43 @@ class BrokkrBlenderTarget:
obj.parent = parent
return self._receipt(command, "accepted", "Blender object parent updated.", obj.name)
def _set_object_custom_property(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
def _setObjectCustomProperty(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
obj = self._resolve_object(command)
if obj is None:
return self._receipt(command, "failed", "Target Blender object was not found.", "")
property_name = command.get("propertyName") or "brokkrValue"
property_name = command["propertyName"]
if property_name.startswith("customProperties."):
property_name = property_name[len("customProperties."):]
modifier_name = na.drives_modifier_input(obj, property_name)
if modifier_name:
return self._receipt(command, "failed", f"{property_name!r} is an input of Geometry Nodes modifier {modifier_name!r}; "
"a custom property does not drive it, use setModifierInput.", obj.name)
obj[property_name] = command.get("value")
obj[property_name] = command["value"]
return self._receipt(command, "accepted", "Blender custom property updated.", obj.name)
def _select_object(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
def _selectObject(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
obj = self._resolve_object(command)
if obj is None:
return self._receipt(command, "failed", "Target Blender object was not found.", "")
if command.get("clearSelection", True):
if command["clearSelection"]:
for existing in context.selected_objects:
existing.select_set(False)
obj.select_set(True)
context.view_layer.objects.active = obj
return self._receipt(command, "accepted", "Blender object selected.", obj.name)
def _assign_material(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
def _assignMaterial(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
obj = self._resolve_object(command)
if obj is None:
return self._receipt(command, "failed", "Target Blender object was not found.", "")
if not (obj.data and hasattr(obj.data, "materials")):
return self._receipt(command, "failed", "Target object cannot receive materials.", obj.name)
rgba = sa.color_rgba(command) # refused before anything is created or changed
material_name = command.get("materialName") or "Brokkr Material"
color = command.get("color")
rgba = (*color, 1.0)[:4] if color is not None else None # the table admits [r,g,b] or [r,g,b,a]
material_name = command["materialName"]
material = self.bpy.data.materials.get(material_name) or self.bpy.data.materials.new(material_name)
if rgba is not None:
if not material.use_nodes or material.node_tree is None:
@ -858,8 +817,8 @@ class BrokkrBlenderTarget:
obj.data.materials.append(material)
return self._receipt(command, "accepted", "Blender material assigned.", obj.name)
def _import_gltf(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
name = str(command.get("filepath") or "")
def _importGltf(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
name = command["filepath"]
path = sa.resolve_inside(self.import_dir, name, "import")
sa.require_gltf(path)
stamped = sa.fingerprint([path]) # before the parse, so a swap during it shows
@ -877,28 +836,19 @@ class BrokkrBlenderTarget:
added = sorted(set(self.bpy.data.objects.keys()) - before)
return self._receipt(command, "accepted", f"Imported {len(added)} object(s) from {path.name}.", added[0] if added else "")
def _export_gltf(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
def _exportGltf(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
"""Write the scene (or the named objects) as .glb or .gltf under the output directory."""
name = command.get("filepath")
if not isinstance(name, str):
raise sa.ActionRefused("filepath must be a string.")
name = command["filepath"]
if self.output_dir:
_sweep_stale_stages(Path(self.output_dir).resolve())
path = sa.resolve_inside(self.output_dir, name, "output", new_file=True)
suffix = path.suffix.lower()
if suffix not in sa.GLTF_EXTENSIONS:
raise sa.ActionRefused(f"Export path must end in {' or '.join(sa.GLTF_EXTENSIONS)}.")
options = {}
for field, key in (("extras", "export_extras"), ("yUp", "export_yup"), ("applyModifiers", "export_apply")):
value = command.get(field, True)
if not isinstance(value, bool):
raise sa.ActionRefused(f"{field} must be true or false.")
options[key] = value
options = {"export_extras": command["extras"], "export_yup": command["yUp"], "export_apply": command["applyModifiers"]}
names = command.get("selection")
chosen = []
if names is not None:
if not isinstance(names, list) or not names or not all(isinstance(n, str) and n for n in names):
raise sa.ActionRefused("selection must be a non-empty list of object names.")
missing = [n for n in names if n not in self.bpy.data.objects]
if missing:
raise sa.ActionRefused(f"Selection object was not found: {missing[0]}")
@ -1002,58 +952,40 @@ class BrokkrBlenderTarget:
raise sa.ActionRefused(f"Target Blender object is not a {object_type}.")
return obj
def _set_camera(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
def _setCamera(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
obj = self._resolve_typed(command, "CAMERA")
camera = obj.data
# Validate everything before changing anything, so a refused intent leaves the camera alone.
lens = sa.number(command, "lens", 1.0, sa.MAX_LENS_MM)
camera_type = sa.choice(command, "cameraType", sa.CAMERA_TYPES)
ortho_scale = sa.number(command, "orthoScale", 0.001, 100000.0)
clip_start = sa.number(command, "clipStart", 0.0001, 1.0e6)
clip_end = sa.number(command, "clipEnd", 0.001, 1.0e7)
panorama_type = sa.choice(command, "panoramaType", self._panorama_types(camera))
if lens is not None:
camera.lens = lens
if camera_type is not None:
camera.type = camera_type
if ortho_scale is not None:
camera.ortho_scale = ortho_scale
if clip_start is not None:
camera.clip_start = clip_start
if clip_end is not None:
camera.clip_end = clip_end
if panorama_type is not None:
# Blender 4.2 moved panorama_type from camera.cycles to the camera itself.
holder = camera if hasattr(camera, "panorama_type") else camera.cycles
holder.panorama_type = panorama_type
# Nothing below can be refused: the table checked every value, so a camera is never half set.
if "lens" in command:
camera.lens = command["lens"]
if "cameraType" in command:
camera.type = command["cameraType"]
if "orthoScale" in command:
camera.ortho_scale = command["orthoScale"]
if "clipStart" in command:
camera.clip_start = command["clipStart"]
if "clipEnd" in command:
camera.clip_end = command["clipEnd"]
if "panoramaType" in command:
camera.panorama_type = command["panoramaType"] # on the camera since Blender 4.2
if command.get("active"):
context.scene.camera = obj
return self._receipt(command, "accepted", "Blender camera updated.", obj.name)
def _panorama_types(self, camera: Any) -> tuple[str, ...]:
holder = camera if hasattr(camera, "panorama_type") else getattr(camera, "cycles", camera)
try:
return tuple(item.identifier for item in holder.bl_rna.properties["panorama_type"].enum_items)
except (KeyError, AttributeError):
return ("EQUIRECTANGULAR", "EQUIDISTANT", "FISHEYE_EQUISOLID", "MIRRORBALL")
def _set_light(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
def _setLight(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
obj = self._resolve_typed(command, "LIGHT")
energy = sa.number(command, "energy", 0.0, 1.0e7)
light_color = sa.color(command)
light_type = sa.choice(command, "lightType", sa.LIGHT_TYPES)
if energy is not None:
obj.data.energy = energy
if light_color is not None:
obj.data.color = light_color
if light_type is not None:
obj.data.type = light_type
if "energy" in command:
obj.data.energy = command["energy"]
if "color" in command:
obj.data.color = tuple(command["color"])
if "lightType" in command:
obj.data.type = command["lightType"]
return self._receipt(command, "accepted", "Blender light updated.", obj.name)
def _set_world(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
world_color = sa.color(command)
strength = sa.number(command, "strength", 0.0, 1.0e6)
name = str(command.get("worldName") or "")
def _setWorld(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
world_color = command.get("color")
strength = command.get("strength")
name = command.get("worldName") or ""
scene = context.scene
world = self.bpy.data.worlds.get(name) if name else scene.world
if world is None:
@ -1069,22 +1001,19 @@ class BrokkrBlenderTarget:
background.inputs["Strength"].default_value = strength
return self._receipt(command, "accepted", "Blender world updated.", world.name)
def _render_still(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
def _renderStill(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
scene = context.scene
render = scene.render
name = str(command.get("outputPath") or "")
name = command["outputPath"]
path = sa.resolve_inside(self.output_dir, name, "output", new_file=True)
file_format = sa.still_format(path)
# The engine enum is dynamic (Cycles and add-on engines register at runtime), and RNA's
# enum_items on a dynamic enum lists only its static defaults, so the running Blender is
# asked by assignment below and a TypeError there is the refusal.
engine = command.get("engine")
if engine is not None and (not isinstance(engine, str) or not engine.strip()):
raise sa.ActionRefused("engine must be a render engine identifier.")
engine = engine.strip().upper() if engine else None
width = sa.integer(command, "resolutionX", 1, sa.MAX_RESOLUTION)
height = sa.integer(command, "resolutionY", 1, sa.MAX_RESOLUTION)
camera_name = str(command.get("cameraName") or "")
engine = command.get("engine") # an identifier, exactly as given: a name Blender does not have is a TypeError below
width = command.get("resolutionX")
height = command.get("resolutionY")
camera_name = command.get("cameraName") or ""
camera = None
if camera_name:
camera = self.bpy.data.objects.get(camera_name)
@ -1301,7 +1230,7 @@ class BrokkrBlenderTarget:
os.unlink(old)
def _resolve_object(self, command: dict[str, Any]) -> Any:
name = command.get("targetObjectName") or command.get("objectName")
name = command.get("targetObjectName")
return self.bpy.data.objects.get(name) if name else None
def _scene_snapshot(self, scene: Any) -> dict[str, Any]:
@ -1742,15 +1671,6 @@ def _valid_command_id(value: Any) -> bool:
return isinstance(value, str) and COMMAND_ID_SHAPE.fullmatch(value) is not None
def _vector(value: Any, size: int, fallback: Any) -> tuple[float, ...]:
if value is None:
return tuple(float(item) for item in fallback)
result = [float(item) for item in value[:size]]
while len(result) < size:
result.append(0.0)
return tuple(result)
def _jsonable(value: Any) -> Any:
if value is None or isinstance(value, (str, int, float, bool)):
if isinstance(value, float) and not math.isfinite(value):

View file

@ -1,33 +1,23 @@
"""Geometry node graph command actions: createNodeGroup, addNode, linkSockets, addModifier, setModifierInput.
Owner of how an intent becomes a node group, a node, a link or a modifier input on Blender 5.2.
Validation is plain Python and runs before bpy is touched; apply steps that can still fail after
Field shape is action_table's and arrives validated; apply steps that can still fail after
Blender has been asked (an unknown node type, an enum that is not offered) undo what they made, so a
refused intent leaves the tree as it was. Docs: docs/node-actions.md. The design is PR #3 (branch libby/blender-node-graphs-design).
"""
from __future__ import annotations
import math
import re
from typing import Any
from .scene_actions import ActionRefused
ID_PATTERN = re.compile(r"[A-Za-z0-9._-]{1,63}")
KEY_PATTERN = re.compile(r"[A-Za-z0-9 ._-]{1,63}")
# A geometry tree may hold geometry, function and shader math nodes. Nodes that read or write files,
# run code, write caches, nest groups or sample images are not part of this cut.
NODE_IDNAME = re.compile(r"(GeometryNode|FunctionNode|ShaderNode)[A-Za-z0-9]+")
NODE_DENIED = ("Import", "Export", "Script", "Bake", "Group", "Simulation", "Repeat", "Foreach", "Viewer", "TexImage", "TexEnvironment",
"ImageTexture", "InputImage", "TexIES")
MAX_NODES = 500
MAX_INTERFACE = 64
MAX_MODIFIERS = 8
MAX_VALUE = 1.0e9
MAX_INT = 4096 # counts, levels and sizes multiply: a 4096 x 4096 grid is the ceiling
SOCKET_TYPES = {"Geometry": "NodeSocketGeometry", "Float": "NodeSocketFloat", "Int": "NodeSocketInt",
"Bool": "NodeSocketBool", "Vector": "NodeSocketVector"}
IN_OUT = {"INPUT", "OUTPUT"}
# Node properties that are not node settings, or that make a node reach outside the tree.
NODE_PROPERTY_DENIED = frozenset({"name", "label", "location", "width", "height", "parent", "node_tree", "select",
"mute", "hide", "show_options", "show_preview", "show_texture", "use_custom_color",
@ -37,24 +27,6 @@ NODE_PROPERTY_DENIED = frozenset({"name", "label", "location", "width", "height"
SETTABLE_PROPERTY_TYPES = ("ENUM", "BOOLEAN", "INT", "FLOAT")
def text(command: dict[str, Any], key: str, pattern: re.Pattern, label: str, *, required: bool = True) -> str:
value = command.get(key)
if value is None or value == "":
if required:
raise ActionRefused(f"{label} is required.")
return ""
if not isinstance(value, str) or not pattern.fullmatch(value):
raise ActionRefused(f"{label} must be 1..63 characters of letters, digits, space, '.', '_' or '-'.")
return value
def tree_key(command: dict[str, Any]) -> str:
kind = command.get("treeKind", "geometry")
if kind != "geometry":
raise ActionRefused(f"treeKind {kind!r} is not supported; only 'geometry'.")
return text(command, "treeKey", KEY_PATTERN, "treeKey")
def finite(value: Any, label: str) -> float:
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or abs(value) > MAX_VALUE:
raise ActionRefused(f"{label} must be a finite number within +-{MAX_VALUE:g}.")
@ -82,34 +54,19 @@ def typed_value(value: Any, kind: str, label: str) -> Any:
raise ActionRefused(f"{label}: socket type {kind} cannot be set by an intent.")
def check_idname(idname: Any) -> str:
if not isinstance(idname, str) or not NODE_IDNAME.fullmatch(idname):
raise ActionRefused("blIdname must be a GeometryNode*, FunctionNode* or ShaderNode* type.")
for denied in NODE_DENIED:
if denied in idname:
raise ActionRefused(f"node type {idname} is not allowed in this cut ({denied}).")
return idname
def check_interface(items: Any) -> list[dict[str, str]]:
if not isinstance(items, list) or not items or len(items) > MAX_INTERFACE:
raise ActionRefused(f"interface must be a list of 1..{MAX_INTERFACE} sockets.")
def check_interface(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""The interface as the table admitted it, minus what only a typed read can judge: a repeated (inOut, name)
and a default that does not fit its socket type."""
seen: set[tuple[str, str]] = set()
result = []
for i, item in enumerate(items):
if not isinstance(item, dict):
raise ActionRefused(f"interface[{i}] must be an object.")
in_out = str(item.get("inOut", "")).upper()
name = item.get("name")
socket_type = item.get("type")
if in_out not in IN_OUT or not isinstance(name, str) or not name or len(name) > 63 or socket_type not in SOCKET_TYPES:
raise ActionRefused(f"interface[{i}] needs inOut INPUT|OUTPUT, a name and a type of {sorted(SOCKET_TYPES)}.")
if (in_out, name) in seen:
raise ActionRefused(f"interface[{i}] repeats {in_out} socket {name!r}.")
seen.add((in_out, name))
entry = {"inOut": in_out, "name": name, "type": socket_type}
key = (item["inOut"], item["name"])
if key in seen:
raise ActionRefused(f"interface[{i}] repeats {key[0]} socket {key[1]!r}.")
seen.add(key)
entry = dict(item)
if "default" in item:
entry["default"] = typed_value(item["default"], socket_type, f"interface[{i}].default")
entry["default"] = typed_value(item["default"], item["type"], f"interface[{i}].default")
result.append(entry)
return result
@ -117,8 +74,6 @@ def check_interface(items: Any) -> list[dict[str, str]]:
class NodeActions:
"""Applies the node-graph actions to a bpy module. Stateless: every lookup goes to bpy.data."""
ACTIONS = ("createNodeGroup", "addNode", "removeNode", "linkSockets", "unlinkSockets", "addModifier", "removeModifier", "setModifierInput")
def __init__(self, bpy_module: Any):
self.bpy = bpy_module
self.changed = False # whether the last execute wrote anything: an absent-target removal does not
@ -159,8 +114,8 @@ class NodeActions:
# actions
def _createNodeGroup(self, command: dict[str, Any]) -> tuple[str, str]:
key = tree_key(command)
interface = check_interface(command.get("interface"))
key = command["treeKey"]
interface = check_interface(command["interface"])
existing = self.bpy.data.node_groups.get(key)
if existing is not None:
raise ActionRefused(f"Node group {key!r} already exists.")
@ -181,17 +136,12 @@ class NodeActions:
return "Created node group; interface identifiers: " + ", ".join(made), tree.name
def _addNode(self, command: dict[str, Any]) -> tuple[str, str]:
tree = self._tree(tree_key(command))
node_id = text(command, "id", ID_PATTERN, "id")
idname = check_idname(command.get("blIdname"))
location = command.get("location", [0, 0])
if not isinstance(location, (list, tuple)) or len(location) != 2:
raise ActionRefused("location must be two numbers.")
location = [finite(part, "location") for part in location]
properties = command.get("properties") or {}
inputs = command.get("inputs") or {}
if not isinstance(properties, dict) or not isinstance(inputs, dict):
raise ActionRefused("properties and inputs must be objects.")
tree = self._tree(command["treeKey"])
node_id = command["id"]
idname = command["blIdname"]
location = list(command["location"])
properties = command.get("properties", {})
inputs = command.get("inputs", {})
if any(n.get("brokkr_id") == node_id for n in tree.nodes):
raise ActionRefused(f"Node id {node_id!r} already exists in {tree.name!r}.")
if len(tree.nodes) >= MAX_NODES:
@ -204,7 +154,7 @@ class NodeActions:
node["brokkr_id"] = node_id
node.location = location
if command.get("label"):
node.label = str(command["label"])[:63]
node.label = command["label"]
for name, value in properties.items(): # node settings first: they decide which sockets exist
self._set_property(node, name, value)
for name, value in inputs.items():
@ -232,8 +182,8 @@ class NodeActions:
raise ActionRefused(f"property {name!r} cannot be {value!r}: {error}") from None
def _removeNode(self, command: dict[str, Any]) -> tuple[str, str]:
tree = self._tree(tree_key(command))
node_id = text(command, "id", ID_PATTERN, "id")
tree = self._tree(command["treeKey"])
node_id = command["id"]
if node_id in ("gin", "gout"):
raise ActionRefused(f"{node_id!r} is the group's own input/output node and stays.")
node = next((n for n in tree.nodes if n.get("brokkr_id") == node_id), None)
@ -244,13 +194,15 @@ class NodeActions:
return "Node removed.", node_id
def _unlinkSockets(self, command: dict[str, Any]) -> tuple[str, str]:
tree = self._tree(tree_key(command))
target = self._node(tree, text(command, "toNode", ID_PATTERN, "toNode"))
into = self._socket(target.inputs, str(command.get("toSocket", "")), "toSocket")
tree = self._tree(command["treeKey"])
target = self._node(tree, command["toNode"])
into = self._socket(target.inputs, command["toSocket"], "toSocket")
source = out = None
if command.get("fromNode") or command.get("fromSocket"):
source = self._node(tree, text(command, "fromNode", ID_PATTERN, "fromNode"))
out = self._socket(source.outputs, str(command.get("fromSocket", "")), "fromSocket")
if ("fromNode" in command) != ("fromSocket" in command):
raise ActionRefused("fromNode and fromSocket are given together or not at all.")
if "fromNode" in command:
source = self._node(tree, command["fromNode"])
out = self._socket(source.outputs, command["fromSocket"], "fromSocket")
doomed = [l for l in tree.links if l.to_socket == into and (out is None or l.from_socket == out)]
for link in doomed:
tree.links.remove(link)
@ -258,11 +210,11 @@ class NodeActions:
return f"Removed {len(doomed)} link(s).", tree.name
def _linkSockets(self, command: dict[str, Any]) -> tuple[str, str]:
tree = self._tree(tree_key(command))
source = self._node(tree, text(command, "fromNode", ID_PATTERN, "fromNode"))
target = self._node(tree, text(command, "toNode", ID_PATTERN, "toNode"))
out = self._socket(source.outputs, str(command.get("fromSocket", "")), "fromSocket")
into = self._socket(target.inputs, str(command.get("toSocket", "")), "toSocket")
tree = self._tree(command["treeKey"])
source = self._node(tree, command["fromNode"])
target = self._node(tree, command["toNode"])
out = self._socket(source.outputs, command["fromSocket"], "fromSocket")
into = self._socket(target.inputs, command["toSocket"], "toSocket")
if reaches(tree, target, source): # includes a self link
raise ActionRefused(f"Link {source.get('brokkr_id')} -> {target.get('brokkr_id')} would make a cycle.")
displaced = [(l.from_socket, l.is_muted) for l in tree.links if l.to_socket == into] if not getattr(into, "is_multi_input", False) else []
@ -275,7 +227,7 @@ class NodeActions:
return f"Linked {source.get('brokkr_id')}.{out.identifier} -> {target.get('brokkr_id')}.{into.identifier}.", tree.name
def _object(self, command: dict[str, Any]) -> Any:
name = command.get("objectName") or command.get("targetObjectName")
name = command["objectName"]
obj = self.bpy.data.objects.get(name) if name else None
if obj is None:
raise ActionRefused(f"Object {name!r} was not found.")
@ -283,11 +235,8 @@ class NodeActions:
def _addModifier(self, command: dict[str, Any]) -> tuple[str, str]:
obj = self._object(command)
kind = command.get("modifierType", "NODES")
if kind != "NODES":
raise ActionRefused("modifierType must be NODES; other modifiers are not part of this cut.")
tree = self._tree(tree_key(command))
name = text(command, "modifierName", KEY_PATTERN, "modifierName", required=False) or "Brokkr GeoNodes"
tree = self._tree(command["treeKey"])
name = command["modifierName"]
modifier = obj.modifiers.get(name)
if modifier is not None and modifier.type != "NODES":
raise ActionRefused(f"{obj.name!r} already has a non-Geometry-Nodes modifier named {name!r}.")
@ -304,9 +253,7 @@ class NodeActions:
def _removeModifier(self, command: dict[str, Any]) -> tuple[str, str]:
obj = self._object(command)
# A lookup, not a creation: a modifier made by hand may have any name Blender allows.
name = command.get("modifierName") or "Brokkr GeoNodes"
if not isinstance(name, str) or len(name) > 255 or "\0" in name:
raise ActionRefused("modifierName must be a string of at most 255 characters.")
name = command["modifierName"]
modifier = obj.modifiers.get(name)
if modifier is None:
self.changed = False
@ -319,11 +266,11 @@ class NodeActions:
def _setModifierInput(self, command: dict[str, Any]) -> tuple[str, str]:
obj = self._object(command)
modifier = obj.modifiers.get(str(command.get("modifierName") or "Brokkr GeoNodes"))
modifier = obj.modifiers.get(command["modifierName"])
if modifier is None or modifier.type != "NODES" or modifier.node_group is None:
raise ActionRefused(f"{obj.name!r} has no Geometry Nodes modifier with a node group of that name.")
item = modifier_input(modifier.node_group, str(command.get("socket", "")))
value = typed_value(command.get("value"), item.socket_type.replace("NodeSocket", ""), f"input {item.name!r}")
item = modifier_input(modifier.node_group, command["socket"])
value = typed_value(command["value"], item.socket_type.replace("NodeSocket", ""), f"input {item.name!r}")
# modifier.properties.inputs[id] is a raw IDPropertyGroup on 5.2.3; attribute access reaches the struct.
getattr(modifier.properties.inputs, item.identifier).value = value
obj.update_tag() # without it a headless re-evaluation returned the previous result

View file

@ -1,13 +1,12 @@
"""Validation for the Blender scene command actions. Stdlib only, no bpy.
"""Path and file safety for the Blender scene command actions. Stdlib only, no bpy.
Everything an intent can say is checked here before bpy is touched, so the rules
are testable without Blender. Failures raise ActionRefused; the target turns the
message into a failed receipt.
What an intent's fields may hold (names, types, enums, bounds) is action_table's. What a path or a glTF
may reach is checked here before bpy is touched, so the rules are testable without Blender. Failures raise
ActionRefused; the target turns the message into a failed receipt.
"""
from __future__ import annotations
import json
import math
import os
import struct
from pathlib import Path
@ -16,10 +15,6 @@ from urllib.parse import unquote
GLTF_EXTENSIONS = (".gltf", ".glb")
STILL_FORMATS = {".png": "PNG", ".jpg": "JPEG", ".jpeg": "JPEG", ".exr": "OPEN_EXR"}
CAMERA_TYPES = ("PERSP", "ORTHO", "PANO")
LIGHT_TYPES = ("POINT", "SUN", "SPOT", "AREA")
MAX_RESOLUTION = 16384
MAX_LENS_MM = 5000.0
class ActionRefused(ValueError):
@ -166,72 +161,6 @@ def _glb_json_chunk(path: Path) -> bytes:
return data
def number(command: dict[str, Any], key: str, low: float, high: float) -> float | None:
"""A finite number in [low, high], or None when the key is absent."""
if key not in command or command[key] is None:
return None
value = command[key]
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
raise ActionRefused(f"{key} must be a finite number.")
if not low <= value <= high:
raise ActionRefused(f"{key} must be between {low} and {high}.")
return float(value)
def integer(command: dict[str, Any], key: str, low: int, high: int) -> int | None:
value = number(command, key, low, high)
if value is None:
return None
if value != int(value):
raise ActionRefused(f"{key} must be a whole number.")
return int(value)
def unit_component(key: str, item: Any) -> float:
"""One colour component: a number in [0, 1]. The range test comes first: it also refuses nan and inf,
and a huge int (10**400) never reaches math.isfinite, which would raise OverflowError instead of
naming the field."""
if isinstance(item, bool) or not isinstance(item, (int, float)) or not 0.0 <= item <= 1.0:
raise ActionRefused(f"{key} components must be numbers between 0 and 1.")
return float(item)
def color(command: dict[str, Any], key: str = "color") -> tuple[float, float, float] | None:
"""Linear RGB, three finite numbers in [0, 1], or None when absent."""
if key not in command or command[key] is None:
return None
value = command[key]
if not isinstance(value, (list, tuple)) or len(value) != 3:
raise ActionRefused(f"{key} must be three numbers [r, g, b].")
parts = []
for item in value:
parts.append(unit_component(key, item))
return (parts[0], parts[1], parts[2])
def color_rgba(command: dict[str, Any], key: str = "color") -> tuple[float, float, float, float] | None:
"""Linear RGB or RGBA, finite numbers in [0, 1] (RGB gets alpha 1), or None when absent."""
if key not in command or command[key] is None:
return None
value = command[key]
if not isinstance(value, (list, tuple)) or len(value) not in (3, 4):
raise ActionRefused(f"{key} must be [r, g, b] or [r, g, b, a].")
parts = []
for item in value:
parts.append(unit_component(key, item))
return (parts[0], parts[1], parts[2], parts[3] if len(parts) == 4 else 1.0)
def choice(command: dict[str, Any], key: str, allowed: Iterable[str]) -> str | None:
if key not in command or command[key] is None:
return None
allowed = tuple(allowed)
value = command[key]
if not isinstance(value, str) or value.upper() not in allowed:
raise ActionRefused(f"{key} must be one of {', '.join(allowed)}.")
return value.upper()
def still_format(path: Path) -> str:
try:
return STILL_FORMATS[path.suffix.lower()]

View file

@ -0,0 +1,233 @@
[
{"action": "createObject", "fields": {}, "expect": "ok"},
{"action": "createObject", "fields": {"objectType": "MESH", "name": "N", "location": [0, 0, 1], "size": 2, "meshType": "CUBE"}, "expect": "ok"},
{"action": "createObject", "fields": {"objectType": null, "name": null, "location": null}, "expect": "ok"},
{"action": "createObject", "fields": {"note": "n", "requestedBy": "a/b", "commandId": "x", "schema": "s"}, "expect": "ok"},
{"action": "look", "fields": {}, "expect": "ok"},
{"action": "deleteObject", "fields": {"targetObjectName": "Cube"}, "expect": "ok"},
{"action": "deleteObject", "fields": {}, "expect": "targetObjectName is required."},
{"action": "deleteObject", "fields": {"targetObjectName": null}, "expect": "targetObjectName is required."},
{"action": "createObject", "fields": {"bogus": 1}, "expect": "createObject has no field 'bogus'; its fields: objectType, name, location, size, meshType, lightType, emptyDisplayType."},
{"action": "createObject", "fields": {"zeta": 1, "alpha": 2}, "expect": "createObject has no field 'alpha'; its fields: objectType, name, location, size, meshType, lightType, emptyDisplayType."},
{"action": "setObjectTransform", "fields": {"objectName": "x"}, "expect": "setObjectTransform has no field 'objectName'; its fields: targetObjectName, location, rotationEuler, scale."},
{"action": "addModifier", "fields": {"targetObjectName": "x"}, "expect": "addModifier has no field 'targetObjectName'; its fields: objectName, modifierType, treeKind, treeKey, modifierName."},
{"action": "setObjectParent", "fields": {"targetObjectName": "x", "parentName": "p"}, "expect": "setObjectParent has no field 'parentName'; its fields: targetObjectName, parentObjectName."},
{"action": "look", "fields": {"x": 1}, "expect": "look has no field 'x'; its fields: none."},
{"action": "runPython", "fields": {}, "expect": "Unsupported Blender command action: runPython"},
{"action": "createobject", "fields": {}, "expect": "Unsupported Blender command action: createobject"},
{"action": "createObject", "fields": {"name": 5}, "expect": "name must be a string."},
{"action": "createObject", "fields": {"size": "x"}, "expect": "size must be a finite number."},
{"action": "createObject", "fields": {"size": true}, "expect": "size must be a finite number."},
{"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 1.5}, "expect": "resolutionX must be a whole number."},
{"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": true}, "expect": "resolutionX must be a whole number."},
{"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": "64"}, "expect": "resolutionX must be a whole number."},
{"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 640.0}, "expect": "ok"},
{"action": "setObjectVisibility", "fields": {"targetObjectName": "c", "visible": 1}, "expect": "visible must be true or false."},
{"action": "setObjectVisibility", "fields": {"targetObjectName": "c", "visible": false}, "expect": "ok"},
{"action": "createObject", "fields": {"location": "x"}, "expect": "location must be an array."},
{"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "properties": []}, "expect": "properties must be an object."},
{"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "properties": {"x": null, "y": 1}, "inputs": {"a": [1, 2]}}, "expect": "ok"},
{"action": "setObjectCustomProperty", "fields": {"targetObjectName": "c", "value": null}, "expect": "value is required."},
{"action": "setObjectCustomProperty", "fields": {"targetObjectName": "c", "value": {"a": [1]}}, "expect": "ok"},
{"action": "setObjectCustomProperty", "fields": {"targetObjectName": "c", "value": false}, "expect": "ok"},
{"action": "createObject", "fields": {"objectType": "mesh"}, "expect": "objectType must be one of MESH, LIGHT, CAMERA, EMPTY."},
{"action": "createObject", "fields": {"objectType": " MESH"}, "expect": "objectType must be one of MESH, LIGHT, CAMERA, EMPTY."},
{"action": "createObject", "fields": {"objectType": 3}, "expect": "objectType must be a string."},
{"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "CUSTOM"}, "expect": "cameraType must be one of PERSP, ORTHO, PANO."},
{"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "ortho"}, "expect": "cameraType must be one of PERSP, ORTHO, PANO."},
{"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "EQUIDISTANT"}, "expect": "panoramaType must be one of EQUIRECTANGULAR, EQUIANGULAR_CUBEMAP_FACE, MIRRORBALL, FISHEYE_EQUIDISTANT, FISHEYE_EQUISOLID, FISHEYE_LENS_POLYNOMIAL, CENTRAL_CYLINDRICAL."},
{"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "CENTRAL_CYLINDRICAL", "cameraType": "PANO", "active": true}, "expect": "ok"},
{"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G", "modifierType": "SUBSURF"}, "expect": "modifierType must be one of NODES."},
{"action": "addNode", "fields": {"treeKind": "shader", "treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath"}, "expect": "treeKind must be one of geometry."},
{"action": "createObject", "fields": {"objectType": "MESH", "lightType": "POINT"}, "expect": "lightType applies only when objectType is one of LIGHT."},
{"action": "createObject", "fields": {"lightType": "POINT"}, "expect": "lightType applies only when objectType is one of LIGHT."},
{"action": "createObject", "fields": {"objectType": "LIGHT", "emptyDisplayType": "CUBE"}, "expect": "emptyDisplayType applies only when objectType is one of EMPTY."},
{"action": "createObject", "fields": {"objectType": "LIGHT", "meshType": "CUBE"}, "expect": "meshType applies only when objectType is one of MESH."},
{"action": "createObject", "fields": {"objectType": "LIGHT", "lightType": "SPOT"}, "expect": "ok"},
{"action": "createObject", "fields": {"objectType": "EMPTY", "emptyDisplayType": "IMAGE"}, "expect": "ok"},
{"action": "createObject", "fields": {"objectType": "LIGHT", "lightType": "LASER"}, "expect": "lightType must be one of POINT, SUN, SPOT, AREA."},
{"action": "createObject", "fields": {"objectType": "EMPTY", "emptyDisplayType": "BOX"}, "expect": "emptyDisplayType must be one of PLAIN_AXES, ARROWS, SINGLE_ARROW, CIRCLE, CUBE, SPHERE, CONE, IMAGE."},
{"action": "createNodeGroup", "fields": {"treeKey": "", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "treeKey must have at least 1 characters."},
{"action": "createNodeGroup", "fields": {"treeKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "treeKey must have at most 63 characters."},
{"action": "createNodeGroup", "fields": {"treeKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "ok"},
{"action": "createNodeGroup", "fields": {"treeKey": "my group.1-x_y", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "ok"},
{"action": "createNodeGroup", "fields": {"treeKey": "a/b", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "treeKey may contain only letters, digits, space, '.', '_' or '-'."},
{"action": "removeNode", "fields": {"treeKey": "G", "id": "a b"}, "expect": "id may contain only letters, digits, '.', '_' or '-'."},
{"action": "removeNode", "fields": {"treeKey": "G", "id": "a\n"}, "expect": "id may contain only letters, digits, '.', '_' or '-'."},
{"action": "removeNode", "fields": {"treeKey": "G", "id": "\u00e9"}, "expect": "id may contain only letters, digits, '.', '_' or '-'."},
{"action": "removeNode", "fields": {"treeKey": "G", "id": "gin"}, "expect": "ok"},
{"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "Math"}, "expect": "blIdname must start with one of GeometryNode, FunctionNode, ShaderNode and have at least one more character."},
{"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "GeometryNode"}, "expect": "blIdname must start with one of GeometryNode, FunctionNode, ShaderNode and have at least one more character."},
{"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "Geometry Node"}, "expect": "blIdname may contain only letters and digits."},
{"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "GeometryNodeGroup"}, "expect": "blIdname may not contain 'Group'."},
{"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeTexImage"}, "expect": "blIdname may not contain 'TexImage'."},
{"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "FunctionNodeCompare"}, "expect": "ok"},
{"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "label": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "expect": "label must have at most 63 characters."},
{"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "label": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "expect": "ok"},
{"action": "removeModifier", "fields": {"objectName": "o", "modifierName": "a\u0000b"}, "expect": "modifierName may not contain '\u0000'."},
{"action": "removeModifier", "fields": {"objectName": "o", "modifierName": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "expect": "modifierName must have at most 255 characters."},
{"action": "removeModifier", "fields": {"objectName": "o", "modifierName": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "expect": "ok"},
{"action": "removeModifier", "fields": {"objectName": "o", "modifierName": ""}, "expect": "modifierName must have at least 1 characters."},
{"action": "removeModifier", "fields": {"objectName": "o", "modifierName": "G\u00e9 x/y"}, "expect": "ok"},
{"action": "renderStill", "fields": {"outputPath": "a.png", "engine": ""}, "expect": "engine must have at least 1 characters."},
{"action": "renderStill", "fields": {"outputPath": "a.png", "engine": "CYCLES"}, "expect": "ok"},
{"action": "exportGltf", "fields": {"filepath": "a.glb", "selection": []}, "expect": "selection must have at least 1 items."},
{"action": "exportGltf", "fields": {"filepath": "a.glb", "selection": [3]}, "expect": "selection[0] must be a string."},
{"action": "exportGltf", "fields": {"filepath": "a.glb", "selection": ["a", ""]}, "expect": "selection[1] must have at least 1 characters."},
{"action": "exportGltf", "fields": {"filepath": "a.glb", "selection": ["a", null]}, "expect": "selection[1] must be a string."},
{"action": "exportGltf", "fields": {"filepath": "a.glb", "selection": ["a"], "extras": "yes"}, "expect": "extras must be true or false."},
{"action": "createObject", "fields": {"location": [1, 2]}, "expect": "location must have at least 3 items."},
{"action": "createObject", "fields": {"location": [1, 2, 3, 4]}, "expect": "location must have at most 3 items."},
{"action": "createObject", "fields": {"location": [1, "x", 3]}, "expect": "location[1] must be a finite number."},
{"action": "createObject", "fields": {"location": [1, null, 3]}, "expect": "location[1] must be a finite number."},
{"action": "createObject", "fields": {"location": [1, 2, true]}, "expect": "location[2] must be a finite number."},
{"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [1, 0]}, "expect": "color must have at least 3 items."},
{"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [1, 0, 0, 0, 0]}, "expect": "color must have at most 4 items."},
{"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [1, 0, 0, 0.5]}, "expect": "ok"},
{"action": "setLight", "fields": {"targetObjectName": "c", "color": [1, 0, 0, 1]}, "expect": "color must have at most 3 items."},
{"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "location": [1]}, "expect": "location must have at least 2 items."},
{"action": "createNodeGroup", "fields": {"treeKey": "G"}, "expect": "interface is required."},
{"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": []}, "expect": "interface must have at least 1 items."},
{"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "interface must have at most 64 items."},
{"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "ok"},
{"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [1]}, "expect": "interface[0] must be an object."},
{"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "type": "Int"}]}, "expect": "interface[0].name is required."},
{"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": null, "type": "Int"}]}, "expect": "interface[1].name is required."},
{"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "input", "name": "a", "type": "Int"}]}, "expect": "interface[0].inOut must be one of INPUT, OUTPUT."},
{"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Mat"}]}, "expect": "interface[0].type must be one of Geometry, Float, Int, Bool, Vector."},
{"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "", "type": "Int"}]}, "expect": "interface[0].name must have at least 1 characters."},
{"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "type": "Int"}]}, "expect": "interface[0].name must have at most 63 characters."},
{"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int", "extra": 1}]}, "expect": "interface[0] has no field 'extra'; its fields: inOut, name, type, default."},
{"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int", "default": "anything"}]}, "expect": "ok"},
{"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int", "default": null}]}, "expect": "ok"},
{"action": "linkSockets", "fields": {"treeKey": "G", "fromNode": "a", "fromSocket": "o", "toNode": "b"}, "expect": "toSocket is required."},
{"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i"}, "expect": "ok"},
{"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i", "fromNode": "a"}, "expect": "ok"},
{"action": "createObject", "fields": {"location": [-1000000000, -1000000000, -1000000000]}, "expect": "ok"},
{"action": "createObject", "fields": {"location": [1000000000, 1000000000, 1000000000]}, "expect": "ok"},
{"action": "createObject", "fields": {"location": [-1000000000, -1000000000, 1000000001]}, "expect": "location[2] must be between -1000000000 and 1000000000."},
{"action": "createObject", "fields": {"location": [-1000000001, -1000000000, -1000000000]}, "expect": "location[0] must be between -1000000000 and 1000000000."},
{"action": "createObject", "fields": {"size": 0.001}, "expect": "ok"},
{"action": "createObject", "fields": {"size": 1000000}, "expect": "ok"},
{"action": "createObject", "fields": {"size": 1000001}, "expect": "size must be between 0.001 and 1000000."},
{"action": "createObject", "fields": {"size": -0.999}, "expect": "size must be between 0.001 and 1000000."},
{"action": "setObjectTransform", "fields": {"targetObjectName": "c", "location": [-1000000000, -1000000000, -1000000000]}, "expect": "ok"},
{"action": "setObjectTransform", "fields": {"targetObjectName": "c", "location": [1000000000, 1000000000, 1000000000]}, "expect": "ok"},
{"action": "setObjectTransform", "fields": {"targetObjectName": "c", "location": [-1000000000, -1000000000, 1000000001]}, "expect": "location[2] must be between -1000000000 and 1000000000."},
{"action": "setObjectTransform", "fields": {"targetObjectName": "c", "location": [-1000000001, -1000000000, -1000000000]}, "expect": "location[0] must be between -1000000000 and 1000000000."},
{"action": "setObjectTransform", "fields": {"targetObjectName": "c", "rotationEuler": [-1000000000, -1000000000, -1000000000]}, "expect": "ok"},
{"action": "setObjectTransform", "fields": {"targetObjectName": "c", "rotationEuler": [1000000000, 1000000000, 1000000000]}, "expect": "ok"},
{"action": "setObjectTransform", "fields": {"targetObjectName": "c", "rotationEuler": [-1000000000, -1000000000, 1000000001]}, "expect": "rotationEuler[2] must be between -1000000000 and 1000000000."},
{"action": "setObjectTransform", "fields": {"targetObjectName": "c", "rotationEuler": [-1000000001, -1000000000, -1000000000]}, "expect": "rotationEuler[0] must be between -1000000000 and 1000000000."},
{"action": "setObjectTransform", "fields": {"targetObjectName": "c", "scale": [-1000000000, -1000000000, -1000000000]}, "expect": "ok"},
{"action": "setObjectTransform", "fields": {"targetObjectName": "c", "scale": [1000000000, 1000000000, 1000000000]}, "expect": "ok"},
{"action": "setObjectTransform", "fields": {"targetObjectName": "c", "scale": [-1000000000, -1000000000, 1000000001]}, "expect": "scale[2] must be between -1000000000 and 1000000000."},
{"action": "setObjectTransform", "fields": {"targetObjectName": "c", "scale": [-1000000001, -1000000000, -1000000000]}, "expect": "scale[0] must be between -1000000000 and 1000000000."},
{"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [0, 0, 0]}, "expect": "ok"},
{"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [1, 1, 1]}, "expect": "ok"},
{"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [0, 0, 2]}, "expect": "color[2] must be between 0 and 1."},
{"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [-1, 0, 0]}, "expect": "color[0] must be between 0 and 1."},
{"action": "setCamera", "fields": {"targetObjectName": "c", "lens": 1}, "expect": "ok"},
{"action": "setCamera", "fields": {"targetObjectName": "c", "lens": 5000}, "expect": "ok"},
{"action": "setCamera", "fields": {"targetObjectName": "c", "lens": 5001}, "expect": "lens must be between 1 and 5000."},
{"action": "setCamera", "fields": {"targetObjectName": "c", "lens": 0}, "expect": "lens must be between 1 and 5000."},
{"action": "setCamera", "fields": {"targetObjectName": "c", "orthoScale": 0.001}, "expect": "ok"},
{"action": "setCamera", "fields": {"targetObjectName": "c", "orthoScale": 100000}, "expect": "ok"},
{"action": "setCamera", "fields": {"targetObjectName": "c", "orthoScale": 100001}, "expect": "orthoScale must be between 0.001 and 100000."},
{"action": "setCamera", "fields": {"targetObjectName": "c", "orthoScale": -0.999}, "expect": "orthoScale must be between 0.001 and 100000."},
{"action": "setCamera", "fields": {"targetObjectName": "c", "clipStart": 0.0001}, "expect": "ok"},
{"action": "setCamera", "fields": {"targetObjectName": "c", "clipStart": 1000000}, "expect": "ok"},
{"action": "setCamera", "fields": {"targetObjectName": "c", "clipStart": 1000001}, "expect": "clipStart must be between 0.0001 and 1000000."},
{"action": "setCamera", "fields": {"targetObjectName": "c", "clipStart": -0.9999}, "expect": "clipStart must be between 0.0001 and 1000000."},
{"action": "setCamera", "fields": {"targetObjectName": "c", "clipEnd": 0.001}, "expect": "ok"},
{"action": "setCamera", "fields": {"targetObjectName": "c", "clipEnd": 10000000}, "expect": "ok"},
{"action": "setCamera", "fields": {"targetObjectName": "c", "clipEnd": 10000001}, "expect": "clipEnd must be between 0.001 and 10000000."},
{"action": "setCamera", "fields": {"targetObjectName": "c", "clipEnd": -0.999}, "expect": "clipEnd must be between 0.001 and 10000000."},
{"action": "setLight", "fields": {"targetObjectName": "c", "energy": 0}, "expect": "ok"},
{"action": "setLight", "fields": {"targetObjectName": "c", "energy": 10000000}, "expect": "ok"},
{"action": "setLight", "fields": {"targetObjectName": "c", "energy": 10000001}, "expect": "energy must be between 0 and 10000000."},
{"action": "setLight", "fields": {"targetObjectName": "c", "energy": -1}, "expect": "energy must be between 0 and 10000000."},
{"action": "setLight", "fields": {"targetObjectName": "c", "color": [0, 0, 0]}, "expect": "ok"},
{"action": "setLight", "fields": {"targetObjectName": "c", "color": [1, 1, 1]}, "expect": "ok"},
{"action": "setLight", "fields": {"targetObjectName": "c", "color": [0, 0, 2]}, "expect": "color[2] must be between 0 and 1."},
{"action": "setLight", "fields": {"targetObjectName": "c", "color": [-1, 0, 0]}, "expect": "color[0] must be between 0 and 1."},
{"action": "setWorld", "fields": {"color": [0, 0, 0]}, "expect": "ok"},
{"action": "setWorld", "fields": {"color": [1, 1, 1]}, "expect": "ok"},
{"action": "setWorld", "fields": {"color": [0, 0, 2]}, "expect": "color[2] must be between 0 and 1."},
{"action": "setWorld", "fields": {"color": [-1, 0, 0]}, "expect": "color[0] must be between 0 and 1."},
{"action": "setWorld", "fields": {"strength": 0}, "expect": "ok"},
{"action": "setWorld", "fields": {"strength": 1000000}, "expect": "ok"},
{"action": "setWorld", "fields": {"strength": 1000001}, "expect": "strength must be between 0 and 1000000."},
{"action": "setWorld", "fields": {"strength": -1}, "expect": "strength must be between 0 and 1000000."},
{"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 4}, "expect": "ok"},
{"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 16384}, "expect": "ok"},
{"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 16385}, "expect": "resolutionX must be between 4 and 16384."},
{"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 3}, "expect": "resolutionX must be between 4 and 16384."},
{"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 4}, "expect": "ok"},
{"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 16384}, "expect": "ok"},
{"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 16385}, "expect": "resolutionY must be between 4 and 16384."},
{"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 3}, "expect": "resolutionY must be between 4 and 16384."},
{"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "location": [-1000000000, -1000000000]}, "expect": "ok"},
{"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "location": [1000000000, 1000000000]}, "expect": "ok"},
{"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "location": [-1000000000, 1000000001]}, "expect": "location[1] must be between -1000000000 and 1000000000."},
{"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "location": [-1000000001, -1000000000]}, "expect": "location[0] must be between -1000000000 and 1000000000."},
{"action": "createObject", "fields": {"objectType": "MESH"}, "expect": "ok"},
{"action": "createObject", "fields": {"objectType": "LIGHT"}, "expect": "ok"},
{"action": "createObject", "fields": {"objectType": "CAMERA"}, "expect": "ok"},
{"action": "createObject", "fields": {"objectType": "EMPTY"}, "expect": "ok"},
{"action": "createObject", "fields": {"objectType": "mesh_"}, "expect": "objectType must be one of MESH, LIGHT, CAMERA, EMPTY."},
{"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "PERSP"}, "expect": "ok"},
{"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "ORTHO"}, "expect": "ok"},
{"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "PANO"}, "expect": "ok"},
{"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "persp_"}, "expect": "cameraType must be one of PERSP, ORTHO, PANO."},
{"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "EQUIRECTANGULAR"}, "expect": "ok"},
{"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "EQUIANGULAR_CUBEMAP_FACE"}, "expect": "ok"},
{"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "MIRRORBALL"}, "expect": "ok"},
{"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "FISHEYE_EQUIDISTANT"}, "expect": "ok"},
{"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "FISHEYE_EQUISOLID"}, "expect": "ok"},
{"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "FISHEYE_LENS_POLYNOMIAL"}, "expect": "ok"},
{"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "CENTRAL_CYLINDRICAL"}, "expect": "ok"},
{"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "equirectangular_"}, "expect": "panoramaType must be one of EQUIRECTANGULAR, EQUIANGULAR_CUBEMAP_FACE, MIRRORBALL, FISHEYE_EQUIDISTANT, FISHEYE_EQUISOLID, FISHEYE_LENS_POLYNOMIAL, CENTRAL_CYLINDRICAL."},
{"action": "setLight", "fields": {"targetObjectName": "c", "lightType": "POINT"}, "expect": "ok"},
{"action": "setLight", "fields": {"targetObjectName": "c", "lightType": "SUN"}, "expect": "ok"},
{"action": "setLight", "fields": {"targetObjectName": "c", "lightType": "SPOT"}, "expect": "ok"},
{"action": "setLight", "fields": {"targetObjectName": "c", "lightType": "AREA"}, "expect": "ok"},
{"action": "setLight", "fields": {"targetObjectName": "c", "lightType": "point_"}, "expect": "lightType must be one of POINT, SUN, SPOT, AREA."},
{"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}], "treeKind": "geometry"}, "expect": "ok"},
{"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}], "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."},
{"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "treeKind": "geometry"}, "expect": "ok"},
{"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."},
{"action": "removeNode", "fields": {"treeKey": "G", "id": "a", "treeKind": "geometry"}, "expect": "ok"},
{"action": "removeNode", "fields": {"treeKey": "G", "id": "a", "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."},
{"action": "linkSockets", "fields": {"treeKey": "G", "fromNode": "a", "fromSocket": "o", "toNode": "b", "toSocket": "i", "treeKind": "geometry"}, "expect": "ok"},
{"action": "linkSockets", "fields": {"treeKey": "G", "fromNode": "a", "fromSocket": "o", "toNode": "b", "toSocket": "i", "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."},
{"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i", "treeKind": "geometry"}, "expect": "ok"},
{"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i", "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."},
{"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G", "modifierType": "NODES"}, "expect": "ok"},
{"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G", "modifierType": "nodes_"}, "expect": "modifierType must be one of NODES."},
{"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G", "treeKind": "geometry"}, "expect": "ok"},
{"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G", "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."},
{"action": "createObject", "fields": {}, "expect": "ok"},
{"action": "deleteObject", "fields": {"targetObjectName": "c"}, "expect": "ok"},
{"action": "setObjectTransform", "fields": {"targetObjectName": "c"}, "expect": "ok"},
{"action": "setObjectVisibility", "fields": {"targetObjectName": "c"}, "expect": "ok"},
{"action": "setObjectParent", "fields": {"targetObjectName": "c"}, "expect": "ok"},
{"action": "setObjectCustomProperty", "fields": {"targetObjectName": "c", "value": 1}, "expect": "ok"},
{"action": "selectObject", "fields": {"targetObjectName": "c"}, "expect": "ok"},
{"action": "assignMaterial", "fields": {"targetObjectName": "c"}, "expect": "ok"},
{"action": "importGltf", "fields": {"filepath": "a.glb"}, "expect": "ok"},
{"action": "exportGltf", "fields": {"filepath": "a.glb"}, "expect": "ok"},
{"action": "setCamera", "fields": {"targetObjectName": "c"}, "expect": "ok"},
{"action": "setLight", "fields": {"targetObjectName": "c"}, "expect": "ok"},
{"action": "setWorld", "fields": {}, "expect": "ok"},
{"action": "renderStill", "fields": {"outputPath": "a.png"}, "expect": "ok"},
{"action": "look", "fields": {}, "expect": "ok"},
{"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "ok"},
{"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath"}, "expect": "ok"},
{"action": "removeNode", "fields": {"treeKey": "G", "id": "a"}, "expect": "ok"},
{"action": "linkSockets", "fields": {"treeKey": "G", "fromNode": "a", "fromSocket": "o", "toNode": "b", "toSocket": "i"}, "expect": "ok"},
{"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i"}, "expect": "ok"},
{"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G"}, "expect": "ok"},
{"action": "removeModifier", "fields": {"objectName": "o"}, "expect": "ok"},
{"action": "setModifierInput", "fields": {"objectName": "o", "socket": "s", "value": 1}, "expect": "ok"}
]

View file

@ -202,7 +202,7 @@ def q5_edit():
push("driver edit baseline")
queue("aaaaaaaa-0006", action="setWorld", color=[1, 0, 0], requestedBy="nibu/hands")
queue("aaaaaaaa-0007", action="exportGltf", filepath="edit.glb", requestedBy="nibu/hands")
queue("aaaaaaaa-0008", action="setObjectTransform", objectName="Cube", location=[0, 0, 9], requestedBy="nibu/hands")
queue("aaaaaaaa-0008", action="setObjectTransform", targetObjectName="Cube", location=[0, 0, 9], requestedBy="nibu/hands")
def q5_check():

View file

@ -88,7 +88,7 @@ def s_create():
def s_transform():
intent(action="setObjectTransform", objectName="AgentCube", location=[3, 2, 0])
intent(action="setObjectTransform", targetObjectName="AgentCube", location=[3, 2, 0])
check("transform applied", loc("AgentCube") == [3.0, 2.0, 0.0], loc("AgentCube"))
@ -131,7 +131,7 @@ def s_edit_enter():
def s_edit_agent():
r = intent(action="setObjectTransform", objectName="Cube", location=[0, 0, 5])
r = intent(action="setObjectTransform", targetObjectName="Cube", location=[0, 0, 5])
R["editMode"].update(mode_after_intent=bpy.context.mode, loc_after_intent=loc("Cube"), receipt=r["status"],
message=r["message"], undoLabel=r["undoLabel"])
check("edit mode: object-level intent refused, scene and her mode unchanged",

View file

@ -0,0 +1,181 @@
"""The action table: the parity fixture, handler coverage, and the table's own load checks. No Blender."""
from __future__ import annotations
import copy
import json
import re
import unittest
from pathlib import Path
from unittest import mock
import test_scene_actions as ts
at = ts.at
bt = ts.bt
na = ts.bt.na
CASES = json.loads((Path(__file__).with_name("action_cases.json")).read_text(encoding="utf-8"))
def validate(action, fields):
try:
at.validate({"action": action, **fields})
except at.IntentInvalid as error:
return str(error)
return "ok"
class ParityFixtureTests(unittest.TestCase):
"""action_cases.json is also run by brokkr-ctl's actions.rs: one table, two interpreters, one set of messages."""
def test_every_case_yields_exactly_its_expected_message_or_ok(self):
wrong = [(c["action"], c["fields"], c["expect"], validate(c["action"], c["fields"]))
for c in CASES if validate(c["action"], c["fields"]) != c["expect"]]
self.assertEqual(wrong, [])
def test_the_fixture_covers_every_rule_kind_and_every_number_field(self):
text = json.dumps(CASES)
for needle in ("is required.", "has no field", "must be one of", "must be between", "must have at least", "must have at most",
"may contain only", "must start with one of", "may not contain", "applies only when", "Unsupported Blender"):
self.assertIn(needle, text)
for action in at.table()["actions"]:
for field in action["fields"]:
if field["type"] in ("number", "integer") or field.get("items", {}).get("type") == "number":
pins = [c for c in CASES if c["action"] == action["name"] and field["name"] in c["fields"]
and c["expect"].startswith(f"{field['name']}") and "must be between" in c["expect"]]
self.assertGreaterEqual(len(pins), 2, f"{action['name']}.{field['name']}: both bounds")
self.assertTrue(any(c["action"] == action["name"] and c["expect"] == "ok" for c in CASES), action["name"])
def test_validate_normalizes_null_to_absent_and_fills_defaults(self):
normal = at.validate({"action": "createObject", "objectType": None, "location": None, "note": "n"})
self.assertEqual(normal["objectType"], "EMPTY")
self.assertEqual((normal["size"], normal["lightType"], normal["emptyDisplayType"]), (1, "POINT", "PLAIN_AXES"))
self.assertNotIn("location", normal)
self.assertEqual(normal["note"], "n")
self.assertEqual(at.validate({"action": "setLight", "targetObjectName": "L"}).get("lightType"), None) # no default: absent stays absent
def test_a_mutant_validator_fails_the_fixture(self):
"""The fixture pins the rules: casefolding enums, widening a bound or letting bool pass as a number each break cases."""
original = at._value
def casefolded(spec, value, path):
if "enum" in spec and isinstance(value, str):
value = next((e for e in spec["enum"] if e.lower() == value.lower()), value)
return original(spec, value, path)
for mutant in (casefolded,):
with mock.patch.object(at, "_value", mutant):
self.assertNotEqual([c for c in CASES if validate(c["action"], c["fields"]) != c["expect"]], [])
number = at._number
def widened(spec, value, path):
return number({**spec, "maximum": spec["maximum"] * 10 + 10}, value, path)
def boolish(spec, value, path):
return number(spec, int(value) if isinstance(value, bool) else value, path)
for mutant in (widened, boolish):
with mock.patch.object(at, "_number", mutant):
self.assertNotEqual([c for c in CASES if validate(c["action"], c["fields"]) != c["expect"]], [], mutant.__name__)
class HandlerCoverageTests(unittest.TestCase):
def test_each_table_action_resolves_to_exactly_one_handler_and_each_handler_has_an_entry(self):
names = [a["name"] for a in at.table()["actions"]]
self.assertEqual(len(names), len(set(names)))
target = bt.BrokkrBlenderTarget
for name in names:
owners = [owner for owner in (target, na.NodeActions) if hasattr(owner, "_" + name)]
self.assertEqual(len(owners), 1, f"{name}: handlers {owners}")
camel = re.compile(r"_[a-z]+[A-Z][A-Za-z0-9]*") # every other private name of both classes is snake_case
handlers = {n[1:] for owner in (target, na.NodeActions) for n in vars(owner) if camel.fullmatch(n)} | {"look"}
self.assertEqual(sorted(handlers - set(names)), [], "a handler without a table entry")
self.assertEqual(sorted(set(names) - handlers), [], "a table entry without a handler")
def test_node_socket_types_are_the_tables(self):
spec = next(a for a in at.table()["actions"] if a["name"] == "createNodeGroup")
interface = next(f for f in spec["fields"] if f["name"] == "interface")
kinds = next(p for p in interface["items"]["properties"] if p["name"] == "type")["enum"]
self.assertEqual(sorted(kinds), sorted(na.SOCKET_TYPES))
def test_removing_an_entry_makes_the_action_unsupported(self):
trimmed = copy.deepcopy(at.table())
trimmed["actions"] = [a for a in trimmed["actions"] if a["name"] != "deleteObject"]
with mock.patch.object(at, "table", return_value=trimmed), mock.patch.object(at, "_by_name", return_value={a["name"]: a for a in trimmed["actions"]}):
self.assertEqual(validate("deleteObject", {"targetObjectName": "c"}), "Unsupported Blender command action: deleteObject")
def test_undo_and_edit_mode_classes_are_the_tables(self):
rows = {a["name"]: a for a in at.table()["actions"]}
self.assertEqual(sorted(n for n, a in rows.items() if not a["changesScene"]), ["exportGltf", "look", "renderStill"])
self.assertEqual(sorted(n for n, a in rows.items() if a["editModeSafe"]), ["look", "renderStill"])
class TableCheckTests(unittest.TestCase):
def table(self):
return copy.deepcopy(at.table())
def test_an_unbounded_number_field_is_refused_at_load(self):
broken = self.table()
del next(f for a in broken["actions"] for f in a["fields"] if f["name"] == "lens")["maximum"]
with self.assertRaisesRegex(at.TableInvalid, "lens.*maximum"):
at.check_table(broken)
broken = self.table()
del next(f for a in broken["actions"] if a["name"] == "createObject" for f in a["fields"] if f["name"] == "location")["items"]["minimum"]
with self.assertRaisesRegex(at.TableInvalid, "minimum"):
at.check_table(broken)
def test_an_only_naming_a_missing_field_is_refused(self):
broken = self.table()
next(f for a in broken["actions"] for f in a["fields"] if f["name"] == "lightType" and "only" in f)["only"]["field"] = "nope"
with self.assertRaisesRegex(at.TableInvalid, "only"):
at.check_table(broken)
def test_an_unknown_charset_is_refused(self):
broken = self.table()
next(f for a in broken["actions"] for f in a["fields"] if f.get("chars") == "key")["chars"] = "nope"
with self.assertRaisesRegex(at.TableInvalid, "charset"):
at.check_table(broken)
def test_a_default_that_breaks_its_own_field_is_refused(self):
broken = self.table()
next(f for a in broken["actions"] for f in a["fields"] if f["name"] == "objectType")["default"] = "TEXT"
with self.assertRaisesRegex(at.TableInvalid, "default"):
at.check_table(broken)
def test_a_bound_that_prints_differently_in_python_and_rust_is_refused(self):
broken = self.table()
next(f for a in broken["actions"] for f in a["fields"] if f["name"] == "clipStart")["minimum"] = 1e-7
with self.assertRaisesRegex(at.TableInvalid, "plain digits"):
at.check_table(broken)
class AdmissionTests(unittest.TestCase):
setUp = ts.ActionTests.setUp
run_action = ts.ActionTests.run_action
def test_a_table_refusal_is_denied_pushes_no_undo_step_and_calls_no_operator(self):
for fields in ({"action": "createObject", "bogus": 1}, {"action": "createObject", "objectType": "mesh"},
{"action": "renderStill", "outputPath": "a.png", "resolutionX": 2},
{"action": "setObjectTransform", "objectName": "Cube", "location": [0, 0, 1]}):
receipt = self.run_action(**fields)
self.assertEqual(receipt["status"], "denied", fields)
self.assertEqual(receipt["undoLabel"], "")
self.assertEqual((self.bpy.created, self.bpy.undo.pushes, self.bpy.rendered), ([], [], []))
self.assertEqual(self.bpy.mesh.__dict__.get("location"), None)
def test_the_unknown_action_message_and_the_order_of_admission(self):
self.assertEqual(self.run_action(action="runPython")["message"], "Unsupported Blender command action: runPython")
self.bpy.mesh.mode = "EDIT"
receipt = self.run_action(action="createObject", objectType="mesh") # invalid fields are named before the mode
self.assertNotIn("Edit Mode", receipt["message"])
receipt = self.run_action(action="createObject", objectType="EMPTY")
self.assertIn("Edit Mode", receipt["message"])
def test_defaults_reach_the_handler(self):
self.assertEqual(self.run_action(action="createObject", objectType="MESH")["status"], "accepted")
self.assertEqual(self.bpy.created[-1][1]["size"], 1.0)
self.assertEqual(self.run_action(action="createObject", objectType="LIGHT")["status"], "accepted")
self.assertEqual(self.bpy.created[-1][1]["type"], "POINT")
if __name__ == "__main__":
unittest.main()

View file

@ -11,6 +11,7 @@ from pathlib import Path
import test_scene_actions as ts
bt = ts.bt
at = ts.at
SOURCE = Path(bt.__file__)
@ -30,7 +31,7 @@ class AgentTurnTests(unittest.TestCase):
def test_object_intent_is_refused_while_an_object_is_in_edit_mode(self):
self.bpy.mesh.mode = "EDIT"
receipt = self.run_action(action="setObjectTransform", objectName="Cube", location=[0, 0, 5])
receipt = self.run_action(action="setObjectTransform", targetObjectName="Cube", location=[0, 0, 5])
self.assertEqual(receipt["status"], "denied")
self.assertIn("Edit Mode", receipt["message"])
self.assertEqual(receipt["undoLabel"], "")
@ -76,13 +77,15 @@ class AgentTurnTests(unittest.TestCase):
def test_refusal_pushes_nothing(self):
receipt = self.run_action(action="createObject", objectType="BOGUS")
self.assertEqual(receipt["status"], "failed")
self.assertEqual(receipt["status"], "denied")
self.assertEqual(receipt["undoLabel"], "")
self.assertEqual(self.bpy.undo.pushes, [])
receipt = self.run_action(action="deleteObject", targetObjectName="Nope") # a scene refusal: ran, failed, no step
self.assertEqual(receipt["status"], "failed")
self.assertEqual(self.bpy.undo.pushes, [])
def test_read_action_pushes_nothing(self):
with unittest.mock.patch.object(bt, "READ_ACTIONS", ("createObject",)):
self.run_action(action="createObject", objectType="EMPTY")
self.assertNotEqual(self.run_action(action="look")["status"], "denied") # admitted; the fake has no 3D view to capture
self.assertEqual(self.bpy.undo.pushes, [])
def test_raise_after_admission_pushes_failed_step(self):
@ -131,7 +134,7 @@ class AgentTurnTests(unittest.TestCase):
self.assertEqual(self.bpy.undo.pushes, [])
def test_returned_failed_receipt_pushes_nothing(self):
receipt = self.run_action(action="setObjectTransform", objectName="NoSuchObject", location=[1, 2, 3])
receipt = self.run_action(action="setObjectTransform", targetObjectName="NoSuchObject", location=[1, 2, 3])
self.assertEqual(receipt["status"], "failed")
self.assertEqual(self.bpy.undo.pushes, [])
@ -162,7 +165,7 @@ class AgentTurnTests(unittest.TestCase):
# fix batch s2
def test_no_scene_change_set_is_exactly_export_and_render(self):
self.assertEqual(bt.NO_SCENE_CHANGE_ACTIONS, ("exportGltf", "renderStill"))
self.assertEqual([a["name"] for a in at.table()["actions"] if not a["changesScene"]], ["exportGltf", "renderStill", "look"])
receipt = self.run_action(action="setWorld", color=[0.1, 0.2, 0.3])
self.assertEqual(receipt["status"], "accepted")
self.assertEqual(len(self.bpy.undo.pushes), 1)

View file

@ -121,7 +121,7 @@ class MaterialTests(unittest.TestCase):
[float("nan"), 0, 0], [float("inf"), 0, 0], [-0.1, 0, 0], [1.1, 0, 0], [0, 0, 0, 2],
[1.0000001, 0, 0], [-1e-9, 0, 0], [0, 0, 0, 1.0000001], [10**400, 0, 0], [0, -10**400, 0]):
receipt = self.assign(materialName="oxide red", color=bad)
self.assertEqual(receipt["status"], "failed", bad)
self.assertEqual(receipt["status"], "denied", bad)
self.assertIn("color", receipt["message"], bad)
self.assertEqual(dict(self.bpy.data.materials), {})
self.assertEqual(self.bpy.mesh.data.materials, [])
@ -143,7 +143,7 @@ class MaterialTests(unittest.TestCase):
def test_refused_colour_on_an_existing_material_leaves_it_alone(self):
self.assign(materialName="oxide red", color=[0.5, 0.1, 0.1])
self.assertEqual(self.assign(materialName="oxide red", color=[2, 0, 0])["status"], "failed")
self.assertEqual(self.assign(materialName="oxide red", color=[2, 0, 0])["status"], "denied")
self.assertEqual(self.base_color(), (0.5, 0.1, 0.1, 1.0))
def test_existing_tree_without_a_principled_node_gets_one(self):

View file

@ -204,8 +204,9 @@ class NodeActionTests(unittest.TestCase):
return receipt
def refused(self, **command):
"""Refused either at admission by the table ('denied') or by the handler against the scene ('failed')."""
receipt = self.run_action(**command)
self.assertEqual(receipt["status"], "failed", receipt["message"])
self.assertIn(receipt["status"], ("denied", "failed"), receipt["message"])
return receipt
def group(self, interface=None):

View file

@ -593,7 +593,7 @@ class HumanEditTests(PerceptionFixture):
# scene-last-writer-wins: an intent after her edit is accepted, and so is one that targets what she edited
rich(self.bpy.mesh)
self.target.track_human_edits(depsgraph(update("Cube", transform=True)))
receipt = self.run_action(action="setObjectTransform", objectName="Cube", location=[0, 0, 5])
receipt = self.run_action(action="setObjectTransform", targetObjectName="Cube", location=[0, 0, 5])
self.assertEqual(receipt["status"], "accepted", receipt["message"])
self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["status"], "accepted")
self.assertEqual(len(self.bpy.undo.pushes), 2)

View file

@ -20,6 +20,7 @@ package = types.ModuleType("brokkr_bridge")
package.__path__ = [str(ADDON)]
sys.modules.setdefault("brokkr_bridge", package)
from brokkr_bridge import action_table as at # noqa: E402
from brokkr_bridge import blender_target as bt # noqa: E402
from brokkr_bridge import scene_actions as sa # noqa: E402
@ -218,27 +219,18 @@ class ActionTests(unittest.TestCase):
# setCamera
def test_set_camera_sets_lens_type_panorama_and_active(self):
receipt = self.run_action(action="setCamera", targetObjectName="Cam", lens=35, cameraType="pano",
receipt = self.run_action(action="setCamera", targetObjectName="Cam", lens=35, cameraType="PANO",
panoramaType="EQUIRECTANGULAR", active=True, clipEnd=500)
self.assertEqual(receipt["status"], "accepted")
d = self.bpy.camera_data
self.assertEqual((d.lens, d.type, d.panorama_type, d.clip_end), (35.0, "PANO", "EQUIRECTANGULAR", 500.0))
self.assertIs(self.bpy.scene.camera, self.bpy.cam)
def test_set_camera_falls_back_to_the_cycles_panorama_property(self):
cycles = NS(panorama_type="FISHEYE_EQUISOLID",
bl_rna=NS(properties={"panorama_type": Enum("EQUIRECTANGULAR")}))
data = NS(lens=50.0, type="PERSP", cycles=cycles)
self.bpy.data.objects["Cam"] = NS(name="Cam", type="CAMERA", data=data)
receipt = self.run_action(action="setCamera", targetObjectName="Cam", panoramaType="EQUIRECTANGULAR")
self.assertEqual(receipt["status"], "accepted")
self.assertEqual(cycles.panorama_type, "EQUIRECTANGULAR")
def test_set_camera_refused_input_changes_nothing(self):
for bad in ({"lens": -1}, {"lens": "wide"}, {"lens": float("nan")}, {"cameraType": "FISHEYE"},
{"panoramaType": "NOPE"}, {"lens": True}):
receipt = self.run_action(action="setCamera", targetObjectName="Cam", clipEnd=9, **bad)
self.assertEqual(receipt["status"], "failed", bad)
self.assertEqual(receipt["status"], "denied", bad) # the table's refusal: admission, nothing ran
self.assertEqual(self.bpy.camera_data.clip_end, 100.0)
self.assertEqual(self.run_action(action="setCamera", targetObjectName="Lamp", lens=35)["status"], "failed")
self.assertEqual(self.run_action(action="setCamera", targetObjectName="Nope", lens=35)["status"], "failed")
@ -251,7 +243,7 @@ class ActionTests(unittest.TestCase):
def test_set_light_rejects_bad_values_whole(self):
for bad in ({"energy": -5}, {"color": [2, 0, 0]}, {"color": [1, 0]}, {"color": "red"}, {"lightType": "LASER"}):
self.assertEqual(self.run_action(action="setLight", targetObjectName="Lamp", **bad)["status"], "failed", bad)
self.assertEqual(self.run_action(action="setLight", targetObjectName="Lamp", **bad)["status"], "denied", bad)
self.assertEqual(self.bpy.light_data.energy, 1000.0)
self.assertEqual(self.run_action(action="setLight", targetObjectName="Cam", energy=1)["status"], "failed")
@ -265,7 +257,7 @@ class ActionTests(unittest.TestCase):
self.assertEqual(world.background.inputs["Strength"].default_value, 2.0)
def test_set_world_refuses_bad_colour_before_creating_a_world(self):
self.assertEqual(self.run_action(action="setWorld", color=[9, 0, 0])["status"], "failed")
self.assertEqual(self.run_action(action="setWorld", color=[9, 0, 0])["status"], "denied")
self.assertIsNone(self.bpy.scene.world)
# exportGltf
@ -335,18 +327,16 @@ class ActionTests(unittest.TestCase):
def test_export_refusals_never_reach_bpy_or_disk(self):
(self.root / "out" / "taken.glb").write_bytes(b"old")
denied = [{"filepath": 5}, {"filepath": "a.glb", "selection": []}, {"filepath": "a.glb", "selection": "Cube"},
{"filepath": "a.glb", "selection": [3]}, {"filepath": "a.glb", "extras": "yes"}, {"filepath": "a.glb", "yUp": 1}]
for case in denied: # the table refuses these at admission
self.assertEqual(self.run_action(action="exportGltf", **case)["status"], "denied", case)
cases = [
{"filepath": "a.obj"}, {"filepath": "a"}, {"filepath": ""}, {"filepath": 5},
{"filepath": "a.obj"}, {"filepath": "a"}, {"filepath": ""},
{"filepath": "../a.glb"}, {"filepath": str(self.root / "a.glb")},
{"filepath": "taken.glb"},
{"filepath": "a.glb", "selection": ["Nope"]},
{"filepath": "a.glb", "selection": ["Cube", "Nope"]},
{"filepath": "a.glb", "selection": []},
{"filepath": "a.glb", "selection": "Cube"},
{"filepath": "a.glb", "selection": [3]},
{"filepath": "a.glb", "extras": "yes"},
{"filepath": "a.glb", "yUp": 1},
{"filepath": "a.glb", "applyModifiers": None},
]
for case in cases:
self.assertEqual(self.run_action(action="exportGltf", **case)["status"], "failed", case)
@ -527,7 +517,7 @@ class ActionTests(unittest.TestCase):
# renderStill
def test_render_still_writes_inside_output_dir_and_restores_settings(self):
receipt = self.run_action(action="renderStill", outputPath="shots/a.png", engine="cycles",
receipt = self.run_action(action="renderStill", outputPath="shots/a.png", engine="CYCLES",
resolutionX=640, resolutionY=360, cameraName="Cam")
self.assertEqual(receipt["status"], "accepted")
engine, x, y, filepath, fmt, camera = self.bpy.rendered[0]
@ -547,10 +537,13 @@ class ActionTests(unittest.TestCase):
self.assertEqual(self.bpy.scene.render.engine, "BLENDER_EEVEE")
def test_render_still_outside_the_output_dir_or_with_bad_input_never_renders(self):
for case in ({"outputPath": "a.png", "resolutionX": 0}, {"outputPath": "a.png", "resolutionX": 3},
{"outputPath": "a.png", "resolutionX": 99999}, {"outputPath": "a.png", "resolutionX": 10.5},
{"outputPath": "a.png", "engine": ""}, {"outputPath": "a.png", "resolutionY": "x"}):
self.assertEqual(self.run_action(action="renderStill", **case)["status"], "denied", case)
cases = [{"outputPath": "../a.png"}, {"outputPath": str(self.root / "a.png")}, {"outputPath": "a.txt"},
{"outputPath": ""}, {"outputPath": "a.png", "engine": "NOPE"},
{"outputPath": "a.png", "resolutionX": 0}, {"outputPath": "a.png", "resolutionX": 99999},
{"outputPath": "a.png", "resolutionX": 10.5}, {"outputPath": "a.png", "cameraName": "Lamp"}]
{"outputPath": ""}, {"outputPath": "a.png", "engine": "NOPE"}, {"outputPath": "a.png", "engine": "cycles"},
{"outputPath": "a.png", "cameraName": "Lamp"}]
for case in cases:
self.assertEqual(self.run_action(action="renderStill", **case)["status"], "failed", case)
self.assertEqual(self.bpy.rendered, [])
@ -563,35 +556,38 @@ class ActionTests(unittest.TestCase):
receipt = self.run_action(action="createObject", objectType=kind, name="N")
self.assertEqual(receipt["status"], "accepted", kind)
self.assertEqual(self.bpy.created[-1][0], kind)
self.assertEqual(self.run_action(action="createObject", objectType="MESH", meshType="cube")["status"], "accepted")
self.assertEqual(self.run_action(action="createObject", objectType="MESH", meshType="CUBE")["status"], "accepted")
def test_create_object_refuses_other_types_naming_the_type_and_the_allowed_set(self):
for kind in ("TEXT", "CURVE", "mesh", "", None, 3):
def test_create_object_refuses_other_types_naming_the_field_and_the_allowed_set(self):
for kind in ("TEXT", "CURVE", "mesh", ""):
receipt = self.run_action(action="createObject", objectType=kind)
self.assertEqual(receipt["status"], "failed", kind)
for allowed in ("MESH", "LIGHT", "CAMERA", "EMPTY"):
self.assertIn(allowed, receipt["message"])
self.assertIn(repr(kind) if not isinstance(kind, str) else kind, receipt["message"])
self.assertEqual(receipt["status"], "denied", kind)
self.assertEqual(receipt["message"], "objectType must be one of MESH, LIGHT, CAMERA, EMPTY.")
receipt = self.run_action(action="createObject", objectType=3)
self.assertEqual((receipt["status"], receipt["message"]), ("denied", "objectType must be a string."))
self.assertEqual(self.bpy.created, [])
self.assertEqual(self.run_action(action="createObject", objectType=None)["status"], "accepted") # null is absent: EMPTY
self.assertEqual(self.bpy.created[-1][0], "EMPTY")
def test_create_object_refuses_a_mesh_type_other_than_cube(self):
for mesh_type in ("CYLINDER", "", 1, " CUBE", "CUBE "):
for mesh_type in ("CYLINDER", "", 1, " CUBE", "CUBE ", "cube"):
receipt = self.run_action(action="createObject", objectType="MESH", meshType=mesh_type)
self.assertEqual(receipt["status"], "failed", mesh_type)
self.assertIn("CUBE", receipt["message"])
self.assertEqual(receipt["status"], "denied", mesh_type)
self.assertIn("meshType must be", receipt["message"])
self.assertEqual(self.bpy.created, [])
def test_mesh_type_on_a_non_mesh_object_is_refused_not_ignored(self):
for object_type in ("LIGHT", "EMPTY", "CAMERA"):
receipt = self.run_action(action="createObject", objectType=object_type, meshType="CYLINDER")
self.assertEqual(receipt["status"], "failed", object_type)
self.assertIn("MESH", receipt["message"])
receipt = self.run_action(action="createObject", objectType=object_type, meshType="CUBE")
self.assertEqual(receipt["status"], "denied", object_type)
self.assertEqual(receipt["message"], "meshType applies only when objectType is one of MESH.")
self.assertEqual(self.run_action(action="createObject", meshType="CUBE")["status"], "denied") # objectType absent is EMPTY
self.assertEqual(self.bpy.created, [])
# renderStill: GPU engines that would abort a headless Blender
def test_render_still_refuses_gpu_engines_headless_when_a_test_render_fails(self):
self.bpy.app.background = True
for engine in ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT", "blender_workbench"):
for engine in ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT"):
self.bpy.scene.render.ENGINES = FakeRender.ENGINES + ("BLENDER_EEVEE_NEXT",)
with mock.patch.object(bt, "gl_render_failure", return_value="a one-pixel test render exited with status 134"):
receipt = self.run_action(action="renderStill", outputPath="a.png", engine=engine)
@ -844,10 +840,12 @@ class ActionTests(unittest.TestCase):
def test_a_refused_render_leaves_no_folders_behind(self):
(self.root / "out" / "taken").mkdir()
(self.root / "out" / "taken" / "a.png").write_bytes(b"x")
for case in ({"outputPath": "new/deep/a.png", "resolutionX": 0}, {"outputPath": "new/deep/a.png", "engine": ""}, {"outputPath": "new/deep/a.png", "engine": "NOPE"},
for case in ({"outputPath": "new/deep/a.png", "engine": "NOPE"},
{"outputPath": "new/deep/a.png", "cameraName": "Nope"}, {"outputPath": "new/deep/a.txt"},
{"outputPath": "taken/a.png"}):
self.assertEqual(self.run_action(action="renderStill", **case)["status"], "failed", case)
for case in ({"outputPath": "new/deep/a.png", "resolutionX": 0}, {"outputPath": "new/deep/a.png", "engine": ""}):
self.assertEqual(self.run_action(action="renderStill", **case)["status"], "denied", case)
self.assertIn("already exists", self.run_action(action="renderStill", outputPath="taken/a.png")["message"])
self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["taken"])
self.assertEqual(self.bpy.rendered, [])