Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

BL28: raea setup blender installs raea's add-on, and a script drives the person's own Blender live

shinyobjectz8a9236fffaf0
diff --git a/apps/tools/src/blender.rs b/apps/tools/src/blender.rs
index d5c908c2..db56d231 100644
--- a/apps/tools/src/blender.rs
+++ b/apps/tools/src/blender.rs
@@ -1,13 +1,15 @@
//! `raea setup blender` and `raea blender run` (docs/skills.feature SK11). Blender is GPL, so raea never bundles it: it
//! finds the person's Blender, or downloads the current LTS from blender.org into ~/.raea/tools/blender, and runs it as
-//! its own program. The setup also installs the MCP for Blender add-on (github.com/ahujasid/mcp-for-blender, MIT) into
-//! that Blender, so an agent's `blender` MCP server (raea skills install adds it) can drive a running Blender.
+//! its own program. The setup also installs two add-ons into that Blender: raea's own (sdk/blender/python/raea_blender),
+//! so a TypeScript script drives the Blender the person has open (RAEA_BLENDER=live; docs/blender.feature BL28), and
+//! MCP for Blender (github.com/ahujasid/mcp-for-blender, MIT), so an agent's `blender` MCP server (raea skills install
+//! adds it) can drive it too.
use std::path::{Path, PathBuf};
use std::process::Command;
type R<T> = Result<T, String>;
-pub const USAGE: &str = "raea setup blender [--check] [--download] (find Blender or download the LTS into ~/.raea/tools/blender, and install its MCP add-on)\n raea blender run SCRIPT.py [ARGS...] (blender --background --python SCRIPT.py -- ARGS, headless; blender/X.py missing from the project is copied from the library: convert, decimate, repair, split, bake, rig, cloth)\n raea blender run SCRIPT.ts [FILE.blend] [ARGS...] (a TypeScript script against Blender's whole Python API through raea/blender: bpy, bmesh, mathutils, typed; a headless Blender, FILE.blend opened, quit when the script ends)";
+pub const USAGE: &str = "raea setup blender [--check] [--download] (find Blender or download the LTS into ~/.raea/tools/blender, and install raea's add-on and the MCP add-on)\n raea blender run SCRIPT.py [ARGS...] (blender --background --python SCRIPT.py -- ARGS, headless; blender/X.py missing from the project is copied from the library: convert, decimate, repair, split, bake, rig, cloth)\n raea blender run SCRIPT.ts [FILE.blend] [ARGS...] (a TypeScript script against Blender's whole Python API through raea/blender: bpy, bmesh, mathutils, typed; a headless Blender, FILE.blend opened, quit when the script ends)";
/// The LTS series raea downloads; the newest patch in blender.org/release/Blender<LTS>/ is taken. Moved when Blender
/// ships a new LTS (blender.org/download/lts).
@@ -140,21 +142,33 @@ fn download() -> R<(PathBuf, String)> {
Ok((own_binary()?, format!("downloaded Blender {v} LTS from blender.org")))
}
-/// Python run inside Blender (background): prints the user add-ons folder, or whether the add-on is enabled.
+/// Python run inside Blender (background): prints the user add-ons folder.
const ADDONS_DIR: &str = "import bpy; print('RAEA_ADDONS=' + bpy.utils.user_resource('SCRIPTS', path='addons', create=True))";
-const ENABLE: &str = "import addon_utils, bpy; addon_utils.enable('blender_mcp', default_set=True, persistent=True); bpy.ops.wm.save_userpref(); print('RAEA_ENABLED=' + str(addon_utils.check('blender_mcp')[1]))";
-const CHECK: &str = "import addon_utils; print('RAEA_ENABLED=' + str(addon_utils.check('blender_mcp')[1]))";
fn py(bin: &Path, code: &str, key: &str) -> R<String> {
let out = run(Command::new(bin).args(["--background", "--factory-startup", "--python-expr", code]), "blender")?;
out.lines().find_map(|l| l.strip_prefix(key)).map(str::to_string).ok_or_else(|| format!("blender printed no {key}"))
}
-/// The add-on: uvx mcp-for-blender's own installer writes it into this Blender's add-ons folder, then Blender enables it.
+/// Whether an add-on is enabled in this Blender's saved preferences (--factory-startup would skip them).
+fn enabled(bin: &Path, module: &str) -> R<bool> {
+ let code = format!("import addon_utils; print('RAEA_ENABLED=' + str(addon_utils.check('{module}')[1]))");
+ run(Command::new(bin).args(["--background", "--python-expr", &code]), "blender").map(|o| o.contains("RAEA_ENABLED=True"))
+}
+
+/// Enables an add-on that is in the add-ons folder, and saves the preferences so it starts with Blender.
+fn enable(bin: &Path, module: &str, dir: &str, name: &str) -> R<()> {
+ let code = format!("import addon_utils, bpy; addon_utils.enable('{module}', default_set=True, persistent=True); bpy.ops.wm.save_userpref(); print('RAEA_ENABLED=' + str(addon_utils.check('{module}')[1]))");
+ let on = run(Command::new(bin).args(["--background", "--python-expr", &code]), "blender")?;
+ if !on.contains("RAEA_ENABLED=True") {
+ return Err(format!("the add-on is in {dir} but Blender didn't enable it: enable \"{name}\" in Preferences > Add-ons"));
+ }
+ Ok(())
+}
+
+/// The MCP add-on: uvx mcp-for-blender's own installer writes it into this Blender's add-ons folder, then Blender enables it.
fn addon(bin: &Path, check: bool) -> R<String> {
- // --factory-startup skips the person's add-ons for speed, so the check reads the saved preferences instead
- let state = |b: &Path| run(Command::new(b).args(["--background", "--python-expr", CHECK]), "blender").map(|o| o.contains("RAEA_ENABLED=True"));
- if state(bin)? {
+ if enabled(bin, "blender_mcp")? {
return Ok("MCP add-on enabled".into());
}
if check {
@@ -163,13 +177,43 @@ fn addon(bin: &Path, check: bool) -> R<String> {
let uvx = on_path(if cfg!(windows) { "uvx.exe" } else { "uvx" }).ok_or("the MCP add-on comes from uv's uvx: install uv (https://docs.astral.sh/uv/getting-started/installation/), then run raea setup blender again")?;
let dir = py(bin, ADDONS_DIR, "RAEA_ADDONS=")?;
run(Command::new(&uvx).args(["mcp-for-blender", "install-addon", "--addons-dir", &dir]), "uvx mcp-for-blender install-addon")?;
- let on = run(Command::new(bin).args(["--background", "--python-expr", ENABLE]), "blender")?;
- if !on.contains("RAEA_ENABLED=True") {
- return Err(format!("the add-on is in {dir} but Blender didn't enable it: enable \"MCP for Blender\" in Preferences > Add-ons"));
- }
+ enable(bin, "blender_mcp", &dir, "MCP for Blender")?;
Ok(format!("MCP add-on installed now ({dir})"))
}
+/// raea's add-on as raea ships it (its home's sdk/, else this checkout's): the folder and its Python files.
+fn bridge_files() -> R<(PathBuf, Vec<PathBuf>)> {
+ let shipped = raea_io_home::home().join("sdk/blender/python/raea_blender");
+ let here = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../sdk/blender/python/raea_blender");
+ let dir = [shipped.clone(), here].into_iter().find(|d| d.is_dir()).ok_or_else(|| format!("raea's Blender add-on isn't here ({}): reinstall raea", shipped.display()))?;
+ let mut files: Vec<PathBuf> = std::fs::read_dir(&dir).map_err(|e| format!("{}: {e}", dir.display()))?.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "py")).collect();
+ files.sort();
+ Ok((dir, files))
+}
+
+/// raea's add-on (BL28): copied into this Blender's add-ons folder, replacing an older copy, and enabled. Started with a
+/// window, that Blender serves raea/blender on 127.0.0.1 behind a token and writes ~/.raea/blender/live.json.
+fn bridge_addon(bin: &Path, check: bool) -> R<String> {
+ let (_, files) = bridge_files()?;
+ let dir = py(bin, ADDONS_DIR, "RAEA_ADDONS=")?;
+ let to = Path::new(&dir).join("raea_blender");
+ let current = files.iter().all(|f| f.file_name().is_some_and(|n| std::fs::read(to.join(n)).ok() == std::fs::read(f).ok()));
+ if current && enabled(bin, "raea_blender")? {
+ return Ok("raea's add-on enabled (live: start Blender, then RAEA_BLENDER=live or connect({ live: true }))".into());
+ }
+ if check {
+ return Ok(format!("raea's add-on {}: raea setup blender installs it", if to.is_dir() { "out of date or off" } else { "not installed" }));
+ }
+ let _ = std::fs::remove_dir_all(&to);
+ std::fs::create_dir_all(&to).map_err(|e| format!("{}: {e}", to.display()))?;
+ for f in &files {
+ let name = f.file_name().unwrap_or_default();
+ std::fs::copy(f, to.join(name)).map_err(|e| format!("{}: {e}", to.join(name).display()))?;
+ }
+ enable(bin, "raea_blender", &dir, "raea bridge")?;
+ Ok(format!("raea's add-on installed now ({}; live: start Blender, then RAEA_BLENDER=live or connect({{ live: true }}))", to.display()))
+}
+
/// `raea setup blender [--check] [--download]`.
pub fn setup(args: &[String]) -> R<String> {
let check = args.iter().any(|a| a == "--check");
@@ -184,9 +228,10 @@ pub fn setup(args: &[String]) -> R<String> {
}
};
let v = version(&bin)?;
+ let own = bridge_addon(&bin, check)?;
let add = addon(&bin, check)?;
let head = if check { "CHECKED " } else { "APPLIED " };
- Ok(format!("{head} {v} ({from})\n {}\n {add}\n headless: raea blender run SCRIPT.py; live: start Blender and the agent's `blender` MCP server connects (raea skills install adds it)", bin.display()))
+ Ok(format!("{head} {v} ({from})\n {}\n {own}\n {add}\n headless: raea blender run SCRIPT.py|.ts; live: start Blender and the agent's `blender` MCP server connects (raea skills install adds it)", bin.display()))
}
/// The library's scripts (sdk/guides/craft/bevy/blender: convert, decimate, repair, split, bake, rig, cloth): a fix
diff --git a/docs/blender.feature b/docs/blender.feature
index 7c2af272..19e7ab27 100644
--- a/docs/blender.feature
+++ b/docs/blender.feature
@@ -170,9 +170,20 @@ Feature: Blender as a measured workshop step: an asset passes through it on its
apart, since with no context Blender never calls an item function
And test/typing.ts sets a 2D curve's fill_mode to "BOTH" and still refuses `rotation_mode = "XYZW"`; run in
Blender, the same script prints fill_mode BOTH
+ @done
Scenario: BL28. The person's own Blender, live: raea's add-on serves the same bridge from a running Blender
- Given raea's add-on (sdk/blender/python/raea_blender) enabled in that Blender, and RAEA_BLENDER=live (or connect({ live: true }))
+ Given raea's add-on (sdk/blender/python/raea_blender) enabled in that Blender by `raea setup blender`, which copies
+ it into Blender's add-ons folder (replacing an older copy; `--check` says whether it's current and on), and
+ RAEA_BLENDER=live (or connect({ live: true }))
Then batches run on Blender's main thread between its redraws, in the 3D view's context
+ And a Blender with no window (a command-line render, setup's own checks) doesn't serve, so it never hides the one
+ the person has open; once that Blender quits, connect({ live: true }) refuses its live.json
+ And 11-11: test/live.ts (run by hand: it opens a window) set up Blender 5.2.1 in a scratch BLENDER_USER_RESOURCES,
+ started it with its window and drove it from TypeScript: a cube made, moved and put in edit mode, and
+ view3d.snap_cursor_to_center run, all on the main thread in the 3D view's context; 5 of 5 runs passed. It found
+ two bugs, both fixed: Blender 5.2 gives a timer the window but no area, so view3d operators had no 3D view; and
+ a slot freed by garbage collection was freed before the read an await had queued for it, in headless runs too
+ (test/bridge.test.ts forces that race)
Scenario: BL29. A clean machine on each platform (macOS, Windows, Linux) runs a TypeScript script through raea/blender
Given an empty HOME, `raea setup blender` then `raea blender run smoke.ts`
Then the script prints its PASS line, and the download size and the libraries a clean Linux needs are recorded
diff --git a/docs/manual/reference/cli/blender.md b/docs/manual/reference/cli/blender.md
index 1f8a1dff..3cf59e02 100644
--- a/docs/manual/reference/cli/blender.md
+++ b/docs/manual/reference/cli/blender.md
@@ -24,7 +24,7 @@ raea blender run blender/repair.py -- scan.glb scan-fixed.glb
## Usage
```sh
-raea setup blender [--check] [--download] (find Blender or download the LTS into ~/.raea/tools/blender, and install its MCP add-on)
+raea setup blender [--check] [--download] (find Blender or download the LTS into ~/.raea/tools/blender, and install raea's add-on and the MCP add-on)
raea blender run SCRIPT.py [ARGS...] (blender --background --python SCRIPT.py -- ARGS, headless; blender/X.py missing from the project is copied from the library: convert, decimate, repair, split, bake, rig, cloth)
raea blender run SCRIPT.ts [FILE.blend] [ARGS...] (a TypeScript script against Blender's whole Python API through raea/blender: bpy, bmesh, mathutils, typed; a headless Blender, FILE.blend opened, quit when the script ends)
```
diff --git a/docs/manual/reference/cli/index.md b/docs/manual/reference/cli/index.md
index e1acd307..f6f78908 100644
--- a/docs/manual/reference/cli/index.md
+++ b/docs/manual/reference/cli/index.md
@@ -121,6 +121,6 @@ What an agent reads and shows the person, and the tools raea installs.
| [`raea show`](show.md) | Show the person something in the raea app, as an item they can use and answer: stills, a video, a sound, a script, an interactive .tsx or a question. |
| [`raea skill`](skill.md) | Print the agent skill this raea ships, matched to its version, or one of its references. |
| [`raea skills`](skills.md) | Install raea's agent skill where Claude Code, Codex, Kimi or Gemini read skills, with its MCP server and hook. |
-| [`raea setup`](setup.md) | Find Blender, or download its current LTS, and install its MCP add-on. |
+| [`raea setup`](setup.md) | Find Blender, or download its current LTS, and install raea's add-on and the MCP add-on. |
<!-- generated:end -->
diff --git a/docs/manual/reference/cli/setup.md b/docs/manual/reference/cli/setup.md
index 2a8cc025..1539b59a 100644
--- a/docs/manual/reference/cli/setup.md
+++ b/docs/manual/reference/cli/setup.md
@@ -1,6 +1,6 @@
---
title: "raea setup"
-summary: "Find Blender, or download its current LTS, and install its MCP add-on."
+summary: "Find Blender, or download its current LTS, and install raea's add-on and the MCP add-on."
order: 128
sources: ["apps/tools/src/blender.rs"]
---
@@ -18,7 +18,7 @@ raea setup blender
## Usage
```sh
-raea setup blender [--check] [--download] (find Blender or download the LTS into ~/.raea/tools/blender, and install its MCP add-on)
+raea setup blender [--check] [--download] (find Blender or download the LTS into ~/.raea/tools/blender, and install raea's add-on and the MCP add-on)
raea setup godot [--check] (download Godot 4.6.1 with GodotJS, its TypeScript bindings (MIT), into ~/.raea/tools/godot: JavaScriptCore on the Mac, QuickJS on Windows and Linux; checked against its pinned sha256)
```
diff --git a/sdk/blender/python/raea_blender/__init__.py b/sdk/blender/python/raea_blender/__init__.py
index d83417d4..774b78c9 100644
--- a/sdk/blender/python/raea_blender/__init__.py
+++ b/sdk/blender/python/raea_blender/__init__.py
@@ -13,6 +13,11 @@ bl_info = {
def register():
+ import bpy
+ if bpy.app.background:
+ # a windowless Blender (a render from the command line, `raea setup blender`'s own checks) serves nobody, and
+ # its live.json would hide the Blender the person has open; headless runs serve through python/headless.py
+ return
from . import server
server.start_gui()
diff --git a/sdk/blender/python/raea_blender/server.py b/sdk/blender/python/raea_blender/server.py
index fca0c1fd..2c6c33c2 100644
--- a/sdk/blender/python/raea_blender/server.py
+++ b/sdk/blender/python/raea_blender/server.py
@@ -115,14 +115,15 @@ class Gui:
@contextlib.contextmanager
def ui_context():
- """A timer runs with no window in its context; operators that need one (object.mode_set, view3d.*) get the
- first window, its screen and its 3D view's main region, as a script run from Blender's UI would."""
+ """A timer runs with no area in its context (Blender 5.2 gives it the window, older ones nothing); operators that
+ need one (object.mode_set, view3d.*) get the window, its screen and its 3D view's main region, as a script run from
+ Blender's UI would."""
ctx = bpy.context
wm = ctx.window_manager
- if ctx.window is not None or wm is None or not wm.windows:
+ win = ctx.window or (wm.windows[0] if wm is not None and wm.windows else None)
+ if ctx.area is not None or win is None:
yield
return
- win = wm.windows[0]
kw = {"window": win, "screen": win.screen}
area = next((a for a in win.screen.areas if a.type == "VIEW_3D"), None)
if area is not None:
diff --git a/sdk/blender/src/session.ts b/sdk/blender/src/session.ts
index a76b6dd7..aaacd0b1 100644
--- a/sdk/blender/src/session.ts
+++ b/sdk/blender/src/session.ts
@@ -248,7 +248,9 @@ export class Session {
try {
while (this.#queue.length || (this.#frees.length && !this.closed)) {
const batch = this.#queue.splice(0);
- if (this.#frees.length && !this.closed) batch.unshift({ op: { o: "free", ids: this.#frees.splice(0) } });
+ // frees go last: an op queued before its proxy was collected still names the slot (the read an await queues
+ // while its call is in Blender), and `always` sends them again after a batch that fails before them
+ if (this.#frees.length && !this.closed) batch.push({ op: { o: "free", ids: this.#frees.splice(0) }, always: true });
await this.#send(batch);
}
} finally {
diff --git a/sdk/blender/test/bridge.test.ts b/sdk/blender/test/bridge.test.ts
index e1857d8a..80549f58 100644
--- a/sdk/blender/test/bridge.test.ts
+++ b/sdk/blender/test/bridge.test.ts
@@ -112,6 +112,19 @@ describe.skipIf(!has)("the bridge", () => {
expect(await py.exec<number>("result = sum(range(x))", { x: 5 })).toBe(10);
});
+ test("a result collected while its batch is in Blender is still read (frees go after the ops queued before them)", async () => {
+ // the call goes in one batch; the await queues its read for the next; the proxy, held by nothing after that, is
+ // collected while Blender works, so its slot's free joins the read in that next batch (BL28: 1 run in 6 failed so)
+ const results: Promise<number>[] = [];
+ for (let i = 0; i < 3; i++) {
+ results.push((async () => (await b.py.exec<number>(`import time\ntime.sleep(0.2)\nresult = ${i}`)) as number)());
+ await Promise.resolve();
+ (globalThis as { Bun?: { gc(full: boolean): void } }).Bun?.gc(true);
+ await new Promise((ok) => setTimeout(ok, 50));
+ }
+ expect(await Promise.all(results)).toEqual([0, 1, 2]);
+ });
+
test("bmesh and mathutils.geometry run in Blender", async () => {
const { bmesh, bpy, mathutils, py } = b;
const bm = bmesh.new();
diff --git a/sdk/blender/test/live.ts b/sdk/blender/test/live.ts
new file mode 100644
index 00000000..c9a0ac5f
--- /dev/null
+++ b/sdk/blender/test/live.ts
@@ -0,0 +1,70 @@
+// BL28, run by hand (it opens a Blender window, so `bun test` leaves it out):
+// bun test/live.ts SCRATCH_DIR (RAEA_BIN: the raea to set up with; else raea on PATH)
+// In SCRATCH_DIR, never the person's own preferences (BLENDER_USER_RESOURCES, RAEA_HOME): `raea setup blender` installs
+// and enables raea's add-on; a Blender started with its window serves the bridge; a script with RAEA_BLENDER=live runs
+// on its main thread in the 3D view; and once that Blender has quit, connect({ live: true }) refuses its live.json.
+import { execFileSync, spawn } from "node:child_process";
+import { mkdirSync, readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { connect, findBlender } from "../src";
+
+const dir = process.argv[2];
+if (!dir) throw new Error("usage: bun test/live.ts SCRATCH_DIR");
+const S = resolve(dir);
+mkdirSync(S, { recursive: true });
+const env = { ...process.env, BLENDER_USER_RESOURCES: `${S}/blender`, RAEA_HOME: `${S}/raea`, RAEA_BLENDER: "live" };
+Object.assign(process.env, env);
+const bin = findBlender()?.path;
+if (!bin) throw new Error("no Blender: raea setup blender finds or downloads one");
+
+const setup = execFileSync(process.env.RAEA_BIN ?? "raea", ["setup", "blender"], { env, encoding: "utf8" });
+console.log(setup.trim());
+if (!/raea's add-on (installed now|enabled)/.test(setup)) throw new Error("raea setup blender didn't install raea's add-on");
+
+const blender = spawn(bin, [], { env, stdio: ["ignore", "pipe", "pipe"] });
+const fail = (why: string): never => {
+ blender.kill("SIGKILL");
+ console.log(`FAIL ${why}`);
+ process.exit(1);
+};
+await new Promise<void>((ok, no) => {
+ let out = "";
+ blender.stdout.on("data", (d) => {
+ out += d;
+ if (out.includes("RAEA_BLENDER_READY")) ok();
+ });
+ blender.on("exit", (c) => no(new Error(`Blender exited (${c}) before the add-on served:\n${out}`)));
+});
+const live = JSON.parse(readFileSync(`${S}/raea/blender/live.json`, "utf8")) as { port: number; pid: number; blender: string };
+if (live.pid !== blender.pid) fail(`live.json names pid ${live.pid}, Blender is ${blender.pid}`);
+
+// the script's own bpy and py: RAEA_BLENDER=live is read on first use
+const { bpy, py } = await import("../src");
+const [main, background, area] = await py.exec<[boolean, boolean, string | null]>(
+ "import threading\nresult = [threading.current_thread() is threading.main_thread(), bpy.app.background, bpy.context.area.type if bpy.context.area else None]",
+);
+console.log(`batch: main thread ${main}, background ${background}, area ${area}`);
+if (!main || background || area !== "VIEW_3D") fail("a batch didn't run on the UI's main thread in the 3D view");
+
+const made = await bpy.ops.mesh.primitive_cube_add({ size: 2, location: [0, 0, 1] });
+const ob = (await bpy.context.active_object)!;
+ob.location.x = 3;
+const x = await ob.location.x;
+await bpy.ops.object.mode_set({ mode: "EDIT" });
+const mode = await ob.mode;
+await bpy.ops.object.mode_set({ mode: "OBJECT" });
+const snapped = await bpy.ops.view3d.snap_cursor_to_center();
+console.log(`cube: x=${x}, mode ${mode}, view3d.snap_cursor_to_center ${[...snapped]}`);
+if (!made.has("FINISHED") || x !== 3 || mode !== "EDIT" || !snapped.has("FINISHED")) fail("the typed API didn't act on the live Blender");
+
+const b = await connect({ live: true });
+const n = await b.py.len(b.bpy.data.objects);
+await b.close();
+if (n < 4) fail(`connect({ live: true }) saw ${n} objects, not the same Blender`);
+
+blender.kill("SIGKILL");
+await new Promise((ok) => blender.on("exit", ok));
+const stale = await connect({ live: true }).then(() => "connected", (e: Error) => e.message);
+if (stale === "connected") fail("connect({ live: true }) reached a Blender that had quit");
+console.log(`PASS BL28 (Blender ${live.blender}): batches on the main thread in the 3D view; a quit Blender's live.json refused`);
+process.exit(0);