Professional Blender 5.2 workflows as Agent Skills for Claude Code, Codex, Gemini CLI, Copilot and Cursor: modeling, UVs, PBR, baking, rigging, animation, export and QA.
Python 3dagent-skillsai-agentsblenderblender-pythonbpyclaude-codeclaude-skillscodexgame-assetsgemini-cligodotmcppbrriggingrobloxunityunreal-engine
Initial release: 20 Blender 5.2 agent skills
EL4CTEO4c2e2b34cd0b
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonnew file mode 100644index 0000000..9061733--- /dev/null+++ b/.claude-plugin/marketplace.json@@ -0,0 +1,12 @@+{+ "name": "blender-agent-skills",+ "description": "Blender 5.2 workflow skills for AI agents",+ "owner": { "name": "EL4CTEO" },+ "plugins": [+ {+ "name": "blender-agent-skills",+ "source": "./",+ "description": "20 tested Blender skills: model, UV, texture, bake, rig, animate, optimize, export, render, QA"+ }+ ]+}diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonnew file mode 100644index 0000000..eaebfec--- /dev/null+++ b/.claude-plugin/plugin.json@@ -0,0 +1,10 @@+{+ "name": "blender-agent-skills",+ "version": "0.1.0",+ "description": "Professional Blender 5.2 workflows for AI agents: modeling, retopo/UV, PBR, baking, rigging, animation, optimization, export (Roblox/Unity/Unreal/Godot/web), rendering, simulation, QA.",+ "author": { "name": "EL4CTEO" },+ "homepage": "https://github.com/EL4CTEO/blender-skills",+ "repository": "https://github.com/EL4CTEO/blender-skills",+ "license": "MIT",+ "keywords": ["blender", "bpy", "3d", "game-assets", "rigging", "pbr", "roblox", "unity", "unreal", "godot"]+}diff --git a/.gitattributes b/.gitattributesnew file mode 100644index 0000000..94631f7--- /dev/null+++ b/.gitattributes@@ -0,0 +1,4 @@+* text=auto eol=lf+*.ps1 text eol=crlf+*.png binary+*.blend binarydiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlnew file mode 100644index 0000000..2b7587b--- /dev/null+++ b/.github/workflows/ci.yml@@ -0,0 +1,42 @@+name: CI++on:+ push:+ branches: [main]+ pull_request:++jobs:+ validate:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-python@v5+ with:+ python-version: "3.13"+ - run: python tools/sync_shared.py --check+ - run: python tools/validate_skills.py+ - run: python tools/trigger_check.py+ - run: bash install/install.sh --project "$RUNNER_TEMP/p" --agent all --copy++ blender-tests:+ runs-on: ubuntu-latest+ env:+ BLENDER_VERSION: "5.2.2"+ BAS_SKIP_GPU: "1" # no GPU on hosted runners: render tests are skipped+ steps:+ - uses: actions/checkout@v4+ - uses: actions/cache@v4+ id: cache+ with:+ path: ~/blender+ key: blender-${{ env.BLENDER_VERSION }}+ - name: Download Blender+ if: steps.cache.outputs.cache-hit != 'true'+ run: |+ mkdir -p ~/blender+ curl -sL "https://download.blender.org/release/Blender${BLENDER_VERSION%.*}/blender-${BLENDER_VERSION}-linux-x64.tar.xz" \+ | tar -xJ -C ~/blender --strip-components=1+ - name: System libs+ run: sudo apt-get update && sudo apt-get install -y libxi6 libxkbcommon0 libxxf86vm1 libxfixes3 libxrender1 libgl1 libegl1 libsm6+ - name: Run tests+ run: BLENDER_EXE=~/blender/blender python3 tools/run_tests.pydiff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..cabf8d8--- /dev/null+++ b/.gitignore@@ -0,0 +1,10 @@+__pycache__/+*.pyc+*.blend1+*.blend2+dist/+render/+export/+textures/+.DS_Store+.claude/settings.local.jsondiff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 0000000..aea157d--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,38 @@+# Blender Agent Skills: agent instructions++This repo contains Agent Skills (`skills/<name>/SKILL.md`, agentskills.io format) for **Blender 5.2 LTS+**. Codex, OpenCode, Gemini CLI, Copilot and Cursor read them from `.agents/skills`; Claude Code reads them from `.claude/skills` (see `install/`).++## Using the skills+- Start any Blender task with `skills/blender-core/SKILL.md`. It routes to the specialized skill and defines how to run code: live through the blender-mcp `execute_blender_code`, or headless with `python skills/blender-core/scripts/run_in_blender.py <script.py> -- <args>`.+- Run scripts; don't read them. Every `skills/*/scripts/*.py` documents its flags in its docstring and prints one compact JSON result.+- Load a skill's `references/*.md` only when the SKILL.md points you there.+- Always finish geometry work with `skills/blender-asset-qa` (numbers + a visual check).++| Skill | Use for |+|---|---|+| blender-core | execution, 5.x API rules, routing (start here) |+| blender-scene-setup | units, naming, collections, linking, asset libraries |+| blender-hardsurface-modeling | bevels, booleans, weighted normals, props |+| blender-sculpting | organic forms, multires, procedural sculpt ops |+| blender-retopology-uv | retopo, UVs, texel density |+| blender-pbr-materials | Principled BSDF, texture sets, color spaces |+| blender-texture-baking | normal/AO/curvature/ID bakes, ORM |+| blender-geometry-nodes | procedural modeling, JSON node-tree builder |+| blender-character-rigging | Rigify, skinning, game skeletons |+| blender-facial-shapekeys | ARKit 52, visemes, correctives |+| blender-animation | actions/slots, NLA, mocap, bake, root motion |+| blender-game-optimization | budgets, LODs, draw calls |+| blender-export-pipelines | Roblox, Unity, Unreal, Godot, web, USD |+| blender-rendering | Cycles/EEVEE, color management, batch |+| blender-lighting-lookdev | lights, HDRI, cameras, turntables |+| blender-simulation | rigid body, cloth (classic + 5.2 nodes), fluids |+| blender-addon-development | extensions, operators, UI |+| blender-pipeline-automation | headless batch, conversion, CI |+| blender-asset-qa | review gate: z-fighting, floating parts, normals, UVs, weights |+| blender-workflow-recipes | end-to-end playbooks |++## Working on this repo+- Shared helper: edit `shared/_bpyx.py` only, then run `python tools/sync_shared.py`.+- Validate: `python tools/validate_skills.py` (spec, token budgets, links, script contract).+- Test: `python tools/run_tests.py [filter]` (needs Blender 5.2; set `BLENDER_EXE` if it isn't found). Set `BAS_SKIP_GPU=1` on machines without a GPU.+- Keep each SKILL.md ≤ ~2.5k tokens and each description ≤ 400 chars. Verify every API claim against a running Blender 5.2 before writing it.diff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 0000000..aa12fab--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,6 @@+# Changelog++## [Unreleased]+- 20 Blender 5.2 skills for AI agents (Claude Code, Codex, OpenCode, Gemini CLI, Copilot, Cursor).+- 26 tested scripts (MCP + headless): QA, baking, UV/texel density, retopo, LODs, export presets, Rigify, skinning, animation bake, GN builder, render, lookdev, simulation, batch.+- Installers for every agent, Claude Code plugin/marketplace, validator, headless test suite, CI.diff --git a/CLAUDE.md b/CLAUDE.mdnew file mode 100644index 0000000..43c994c--- /dev/null+++ b/CLAUDE.md@@ -0,0 +1 @@diff --git a/README.md b/README.mdnew file mode 100644index 0000000..67b4b14--- /dev/null+++ b/README.md@@ -0,0 +1,63 @@+# Blender Agent Skills++Professional Blender workflows packaged as **Agent Skills** for AI coding agents: Claude Code, Codex, OpenCode, Gemini CLI, GitHub Copilot and Cursor.++There are 20 skills covering the full 3D pipeline (modeling, UVs, PBR, baking, rigging, animation, optimization, export, rendering, simulation and QA), built for **Blender 5.2 LTS+**. Every script is tested in a real Blender.++## Install++**Claude Code** (plugin):+```+/plugin marketplace add EL4CTEO/blender-skills+/plugin install blender-agent-skills@blender-agent-skills+```++**Any agent** (clone, then run the installer):+```bash+git clone https://github.com/EL4CTEO/blender-skills+./blender-skills/install/install.sh # macOS / Linux+.\blender-skills\install\install.ps1 # Windows+```+The default installs into `~/.claude/skills` and `~/.agents/skills`. `.agents/skills` is read by Codex, OpenCode, Gemini CLI, Copilot and Cursor. Options: `--agent claude|codex|opencode|gemini|copilot|cursor|all`, `--project DIR` for a single project, `--uninstall`.++**Requirements:** Blender 5.2+. Optional: a Blender MCP server lets agents work in your open Blender. Without one, agents run Blender in the background.++## Skills++| Skill | What it does |+|---|---|+| `blender-core` | Start here: runs code, routes tasks, 5.x API rules |+| `blender-scene-setup` | Units, naming, collections, asset libraries |+| `blender-hardsurface-modeling` | Bevels, booleans, weighted normals |+| `blender-sculpting` | Organic sculpting workflow |+| `blender-retopology-uv` | Retopology, UVs, texel density |+| `blender-pbr-materials` | Correct PBR materials from textures |+| `blender-texture-baking` | Normal, AO and curvature maps, ORM |+| `blender-geometry-nodes` | Procedural modeling from simple JSON |+| `blender-character-rigging` | Rigify, skinning, game skeletons |+| `blender-facial-shapekeys` | ARKit 52 blendshapes, visemes |+| `blender-animation` | Actions, NLA, mocap, root motion |+| `blender-game-optimization` | Budgets, LODs, draw calls |+| `blender-export-pipelines` | Roblox, Unity, Unreal, Godot, web, USD |+| `blender-rendering` | Cycles and EEVEE, batch rendering |+| `blender-lighting-lookdev` | Studio lighting, HDRI, turntables |+| `blender-simulation` | Rigid bodies, cloth, fluids |+| `blender-addon-development` | Blender extensions |+| `blender-pipeline-automation` | Batch jobs and file conversion |+| `blender-asset-qa` | Catches z-fighting, floating parts, bad normals and weights |+| `blender-workflow-recipes` | Complete asset playbooks |++## Try it++> "Make a game-ready crate for Unreal with baked normals and LODs."+> "Rig this character with Rigify and export it to Unity with a walk cycle."+> "Check this model for z-fighting and floating parts, then export it for Roblox."++## Development++```bash+python tools/validate_skills.py # spec + token budget checks+python tools/run_tests.py # 43 headless Blender tests (BLENDER_EXE to override)+```++MIT Licensediff --git a/install/install.ps1 b/install/install.ps1new file mode 100644index 0000000..dc6639c--- /dev/null+++ b/install/install.ps1@@ -0,0 +1,56 @@+<#+Install blender-agent-skills for your AI agent(s) on Windows.+ .\install\install.ps1 [-Agent claude,agents,codex,opencode,gemini,copilot,cursor,all]+ [-Scope user|project] [-Project DIR] [-Link] [-Uninstall] [-Skills a,b]+Defaults: -Agent claude,agents -Scope user (copies; -Link makes junctions, no admin needed)+"agents" = ~/.agents/skills, read by Codex, OpenCode, Gemini CLI, GitHub Copilot and Cursor.+#>+param(+ [string[]]$Agent = @("claude", "agents"),+ [ValidateSet("user", "project")][string]$Scope = "user",+ [string]$Project = (Get-Location).Path,+ [switch]$Link,+ [switch]$Uninstall,+ [string[]]$Skills = @()+)+$ErrorActionPreference = "Stop"+$Root = Split-Path -Parent $PSScriptRoot+if ($PSBoundParameters.ContainsKey("Project")) { $Scope = "project" }+if ($Agent -contains "all") { $Agent = @("claude", "agents", "opencode", "gemini", "copilot", "cursor") }++function Get-Target([string]$a) {+ $u = $HOME; $p = $Project+ $map = @{+ "claude:user" = "$u\.claude\skills"; "claude:project" = "$p\.claude\skills"+ "agents:user" = "$u\.agents\skills"; "agents:project" = "$p\.agents\skills"+ "codex:user" = "$u\.agents\skills"; "codex:project" = "$p\.agents\skills"+ "opencode:user" = "$u\.config\opencode\skills"; "opencode:project" = "$p\.opencode\skills"+ "gemini:user" = "$u\.gemini\skills"; "gemini:project" = "$p\.gemini\skills"+ "copilot:user" = "$u\.copilot\skills"; "copilot:project" = "$p\.github\skills"+ "cursor:user" = "$u\.cursor\skills"; "cursor:project" = "$p\.cursor\skills"+ }+ $k = "${a}:$Scope"+ if (-not $map.ContainsKey($k)) { throw "unknown agent $a" }+ return $map[$k]+}++foreach ($a in $Agent) {+ $dst = Get-Target $a+ New-Item -ItemType Directory -Force $dst | Out-Null+ $n = 0+ foreach ($s in Get-ChildItem -Directory (Join-Path $Root "skills")) {+ if ($Skills.Count -and -not ($Skills -contains $s.Name)) { continue }+ $target = Join-Path $dst $s.Name+ if (Test-Path $target) {+ $item = Get-Item $target -Force+ if ($item.LinkType) { $item.Delete() } else { Remove-Item -Recurse -Force $target }+ }+ if (-not $Uninstall) {+ if ($Link) { New-Item -ItemType Junction -Path $target -Target $s.FullName | Out-Null }+ else { Copy-Item -Recurse $s.FullName $target -Exclude "__pycache__" }+ }+ $n+++ }+ $verb = if ($Uninstall) { "removed" } else { "installed" }+ Write-Output "$verb $n skills -> $dst ($a)"+}diff --git a/install/install.sh b/install/install.shnew file mode 100644index 0000000..d28b849--- /dev/null+++ b/install/install.sh@@ -0,0 +1,50 @@+#!/usr/bin/env bash+# Install blender-agent-skills for your AI agent(s).+# ./install/install.sh [--agent claude|agents|codex|opencode|gemini|copilot|cursor|all]...+# [--scope user|project] [--project DIR] [--copy] [--uninstall] [--skills a,b]+# Defaults: --agent claude --agent agents --scope user (symlinks; --copy to copy)+# "agents" = ~/.agents/skills, read by Codex, OpenCode, Gemini CLI, GitHub Copilot and Cursor.+set -euo pipefail+ROOT="$(cd "$(dirname "$0")/.." && pwd)"+AGENTS=() SCOPE=user PROJECT="$PWD" MODE=link UNINSTALL=0 ONLY=""+while [ $# -gt 0 ]; do+ case "$1" in+ --agent) AGENTS+=("$2"); shift 2 ;;+ --scope) SCOPE="$2"; shift 2 ;;+ --project) PROJECT="$(cd "$2" && pwd)"; SCOPE=project; shift 2 ;;+ --copy) MODE=copy; shift ;;+ --uninstall) UNINSTALL=1; shift ;;+ --skills) ONLY="$2"; shift 2 ;;+ -h|--help) sed -n '2,6p' "$0"; exit 0 ;;+ *) echo "unknown arg $1"; exit 1 ;;+ esac+done+[ ${#AGENTS[@]} -eq 0 ] && AGENTS=(claude agents)+[[ " ${AGENTS[*]} " == *" all "* ]] && AGENTS=(claude agents opencode gemini copilot cursor)++target() { # $1 agent -> skills dir+ local u="$HOME" p="$PROJECT"+ case "$1:$SCOPE" in+ claude:user) echo "$u/.claude/skills" ;; claude:project) echo "$p/.claude/skills" ;;+ agents:user|codex:user) echo "$u/.agents/skills" ;; agents:project|codex:project) echo "$p/.agents/skills" ;;+ opencode:user) echo "$u/.config/opencode/skills" ;; opencode:project) echo "$p/.opencode/skills" ;;+ gemini:user) echo "$u/.gemini/skills" ;; gemini:project) echo "$p/.gemini/skills" ;;+ copilot:user) echo "$u/.copilot/skills" ;; copilot:project) echo "$p/.github/skills" ;;+ cursor:user) echo "$u/.cursor/skills" ;; cursor:project) echo "$p/.cursor/skills" ;;+ *) echo "unknown agent $1" >&2; exit 1 ;;+ esac+}++for a in "${AGENTS[@]}"; do+ dst="$(target "$a")"; mkdir -p "$dst"; n=0+ for s in "$ROOT"/skills/*/; do+ name="$(basename "$s")"+ [ -n "$ONLY" ] && [[ ",$ONLY," != *",$name,"* ]] && continue+ rm -rf "${dst:?}/$name"+ if [ $UNINSTALL -eq 0 ]; then+ if [ $MODE = link ]; then ln -s "${s%/}" "$dst/$name"; else cp -R "${s%/}" "$dst/$name"; fi+ fi+ n=$((n+1))+ done+ echo "$([ $UNINSTALL -eq 1 ] && echo removed || echo installed) $n skills -> $dst ($a)"+donediff --git a/shared/_bpyx.py b/shared/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/shared/_bpyx.py@@ -0,0 +1,136 @@+"""_bpyx - tiny shared helpers for blender-agent-skills scripts (Blender 5.2+).++Source of truth: shared/_bpyx.py. Copies in skills/*/scripts/ are synced by+tools/sync_shared.py - never edit a copy.++Every skill script follows one contract:+ run(**kwargs) -> dict # call from MCP / Python (import the module)+ blender -b f.blend -P x.py -- --arg v # CLI: prints one line "@@JSON@@{...}"+"""+import argparse+import json+import sys++import bpy++MARK = "@@JSON@@"+++def argv():+ """Arguments after '--' (Blender ignores them)."""+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def _default(o):+ if hasattr(o, "__len__") and not isinstance(o, str):+ try:+ return [round(v, 5) if isinstance(v, float) else v for v in o]+ except TypeError:+ pass+ if isinstance(o, (set, frozenset)):+ return sorted(o)+ return str(o)+++def emit(data):+ """Print compact JSON on one marked line (parsed by run_in_blender.py)."""+ print(MARK + json.dumps(data, separators=(",", ":"), default=_default), flush=True)+ return data+++def parser(doc):+ """ArgumentParser whose help is the script docstring's first line."""+ return argparse.ArgumentParser(description=(doc or "").strip().splitlines()[0])+++def cli(run, p):+ """CLI entry: parse args after '--', run, emit JSON. Exit 1 on failure."""+ args = p.parse_args(argv())+ try:+ result = run(**vars(args))+ save = getattr(args, "save", None)+ if save:+ bpy.ops.wm.save_as_mainfile(filepath=bpy.path.abspath(save))+ result["saved"] = save+ emit(result)+ except Exception as e: # report, don't dump a traceback into agent context+ emit({"ok": False, "error": f"{type(e).__name__}: {e}"})+ if bpy.app.background:+ sys.exit(1)+++def add_common(p, save=True):+ """--objects / --save flags shared by most scripts."""+ p.add_argument("--objects", nargs="*", default=None,+ help="object names (default: selected, else all meshes)")+ if save:+ p.add_argument("--save", default=None, help="save .blend to this path after run")+ return p+++def objects(names=None, types=("MESH",)):+ """Resolve names -> objects. No names: selected of `types`, else all visible of `types`."""+ if names:+ missing = [n for n in names if n not in bpy.data.objects]+ if missing:+ raise KeyError(f"objects not found: {missing}")+ return [bpy.data.objects[n] for n in names]+ pool = [o for o in bpy.context.scene.objects if not types or o.type in types]+ sel = [o for o in pool if o.select_get()]+ return sel or [o for o in pool if o.visible_get()]+++def object_mode():+ """Leave edit/sculpt/pose modes; most data API work needs OBJECT mode."""+ ob = bpy.context.view_layer.objects.active+ if ob and ob.mode != "OBJECT":+ bpy.ops.object.mode_set(mode="OBJECT")+++def select_only(objs, active=None):+ """Select exactly `objs` and make `active` (default first) active."""+ for o in bpy.context.view_layer.objects:+ o.select_set(False)+ for o in objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = active or (objs[0] if objs else None)+++def node(tree, type_):+ """First node of `type_` (e.g. 'BSDF_PRINCIPLED'). Names are localized - never look up by name."""+ return next((n for n in tree.nodes if n.type == type_), None)+++def enum_ids(owner, prop):+ """Valid identifiers of an enum property (works on types or instances)."""+ return [i.identifier for i in owner.bl_rna.properties[prop].enum_items]+++def set_enum(owner, prop, value):+ """Assign an enum; on failure raise listing valid values (dynamic enums under-report)."""+ try:+ setattr(owner, prop, value)+ except TypeError as e:+ raise ValueError(f"{prop}={value!r} invalid: {e}") from None+++def mesh_tris(ob, evaluated=True):+ """Triangle count (evaluated = with modifiers)."""+ if evaluated:+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ try:+ me.calc_loop_triangles()+ return len(me.loop_triangles)+ finally:+ eo.to_mesh_clear()+ me = ob.data+ me.calc_loop_triangles()+ return len(me.loop_triangles)+++def r(v, n=4):+ """Round a float or a vector for compact JSON."""+ if isinstance(v, float):+ return round(v, n)+ return [round(x, n) for x in v]diff --git a/skills/blender-addon-development/SKILL.md b/skills/blender-addon-development/SKILL.mdnew file mode 100644index 0000000..ded27f9--- /dev/null+++ b/skills/blender-addon-development/SKILL.md@@ -0,0 +1,49 @@+---+name: blender-addon-development+description: Write Blender 5.2 add-ons as extensions - blender_manifest.toml, operators/panels/menus/property groups/preferences, bpy.props rules after 5.0, undo/redo, modal and timer patterns, gpu drawing (no bgl), bundling Python wheels, CLI validate/build/install, testing headless, extensions platform publishing. Use when creating or fixing a Blender add-on, tool, or UI.+license: MIT+metadata:+ author: blender-agent-skills+ version: "0.1.0"+---++# Add-on (Extension) Development++The execution model is in `blender-core`. Start from `assets/addon_template/` (validated, built, and registered in CI): `blender_manifest.toml`, `__init__.py`, `operators.py`, `ui.py`.++## Procedure+1. Copy the template, then set `id` (lowercase_underscores, permanent), `name`, `tagline` (no trailing period, ≤ 64 chars), `maintainer`, `version` (semver), `license` (SPDX, GPL-3.0-or-later for code using bpy), and `blender_version_min = "4.2.0"` or higher if you use newer APIs (e.g. `"5.2.0"` for the GN `properties.inputs` API).+2. Write classes with the prefix convention `MYTOOL_OT_x` (operator), `_PT_` (panel), `_MT_` (menu), `_PG_` (property group), `_AP_` (preferences), `_UL_` (UI list). `bl_idname` for operators is `my_tool.verb_noun`.+3. Validate and build:+ ```+ blender --command extension validate ./my_tool+ blender --command extension build --source-dir ./my_tool --output-dir ./dist+ blender --command extension install-file -r user_default -e ./dist/my_tool-1.0.0.zip+ ```+4. Test headless: register the package in-process, call operators with `temp_override`, and assert on data (see `tests/test_addon.py` in this repo).++## Rules (extension-era, 5.x)+- **Relative imports only** (`from . import ops`). The package name is decided by Blender, so preferences use `bl_idname = __package__`.+- No `bl_info` (it's ignored for extensions). Everything goes in the manifest.+- **No network or file access at import/register time.** Declare `[permissions]` (`files`, `network`, `clipboard`, `camera`, `microphone`) with a reason. Check `bpy.app.online_access` before any network call.+- **Third-party Python packages**: ship `.whl` files in `./wheels/` and list them under `wheels = [...]`. Never `pip install` at runtime. Platform-specific wheels require `platforms = [...]`.+- **Properties (5.0+)**: `bpy.props` values are attributes, not dict entries (`scene["my_prop"]` no longer reaches them). For read-only props use `options={'READ_ONLY'}`. `get_transform`/`set_transform` adapt values while keeping storage. Register with `PointerProperty(type=PG)` on an ID type, and `del` it on unregister.+- **Operators**: `bl_options={"REGISTER","UNDO"}` for undo plus a redo panel. `poll()` guards the context. Return `{"FINISHED"}`/`{"CANCELLED"}`. `self.report({"WARNING"}, msg)` for user feedback. Don't call other operators in loops if a data API exists.+- **UI**: `layout.use_property_split = True` gives modern alignment. Panels in the N-panel use `bl_region_type="UI"` + `bl_category`. Append menu entries with `VIEW3D_MT_*.append(func)` and remove them on unregister.+- **Unregister** everything in reverse order (classes, props, menus, handlers, timers, keymaps, draw handlers). Leaks break reloading.+- **Drawing** (overlays): `gpu` module + `gpu_extras.batch`. `bgl` was removed in 5.0. Textures come from `gpu.texture.from_image(img)`. For scene-linear images use `draw_texture_2d(..., is_scene_linear_with_rec709_srgb_target=True)`.+- **Long tasks**: a modal operator with a timer (`wm.event_timer_add`), or `bpy.app.timers.register` with chunked work. Never block the UI for seconds.+- **Handlers**: decorate persistent ones with `@bpy.app.handlers.persistent`. Keep them cheap (they run every frame/depsgraph update).+- **Keymaps**: add them to `wm.keyconfigs.addon`, store `(km, kmi)` pairs, and remove them on unregister.+- **Translations / i18n**: `bpy.app.translations.register(__package__, dict)`.++## Publishing (extensions.blender.org)+The Blender ID account uploads the built zip. Requirements: a valid manifest, a GPL-compatible license, no obfuscated code, no bundled binaries without source, and permissions declared. Screenshots/README go on the website listing. Update with a higher `version`.++## Gotchas+- `context.scene` inside a draw function can be `None` in some editors. Guard it.+- Storing Blender data references (`bpy.types.ID`) in Python globals crashes after undo or file load. Store names or `session_uid`, and look them up again.+- `bpy.utils.register_class` fails if annotations use `=` instead of `:` for properties.+- 5.0 made several bundled modules private (`rna_info`, `bl_ui_utils`...). Don't import them.+- 5.1 no longer loads the user site-packages by default. Bundle wheels instead of relying on user installs.+- 5.2: `PreferencesFilePaths.active_asset_library` indices are offset (the "All"/"Essentials" entries come first). `UILayout.template_palette(color=)` is removed. New: `UILayout.link`, `UILayout.textbox`, `bpy.data.all_ids`, `Window.screenshot`.diff --git a/skills/blender-addon-development/assets/addon_template/__init__.py b/skills/blender-addon-development/assets/addon_template/__init__.pynew file mode 100644index 0000000..454b023--- /dev/null+++ b/skills/blender-addon-development/assets/addon_template/__init__.py@@ -0,0 +1,25 @@+"""My Tool - Blender extension template (4.2+ extension format, verified on 5.2)."""+import bpy++from . import operators, ui++classes = (+ operators.MYTOOL_PG_settings,+ operators.MYTOOL_OT_offset_selected,+ ui.MYTOOL_PT_main,+ ui.MYTOOL_AP_preferences,+)+++def register():+ for c in classes:+ bpy.utils.register_class(c)+ bpy.types.Scene.my_tool = bpy.props.PointerProperty(type=operators.MYTOOL_PG_settings)+ bpy.types.VIEW3D_MT_object.append(ui.menu_func)+++def unregister():+ bpy.types.VIEW3D_MT_object.remove(ui.menu_func)+ del bpy.types.Scene.my_tool+ for c in reversed(classes):+ bpy.utils.unregister_class(c)diff --git a/skills/blender-addon-development/assets/addon_template/blender_manifest.toml b/skills/blender-addon-development/assets/addon_template/blender_manifest.tomlnew file mode 100644index 0000000..2e13d97--- /dev/null+++ b/skills/blender-addon-development/assets/addon_template/blender_manifest.toml@@ -0,0 +1,29 @@+schema_version = "1.0.0"++# Unique, lowercase, underscores only. Never change it after publishing.+id = "my_tool"+version = "1.0.0"+name = "My Tool"+tagline = "Short description without a trailing period"+maintainer = "Your Name <[email protected]>"+type = "add-on"++# website = "https://example.com/my_tool"+tags = ["Mesh", "Object"]++blender_version_min = "4.2.0"+# blender_version_max = "6.0.0"++license = ["SPDX:GPL-3.0-or-later"]+# copyright = ["2026 Your Name"]++# platforms = ["windows-x64", "macos-arm64", "linux-x64"] # only with platform-specific wheels+# wheels = ["./wheels/somepkg-1.0-py3-none-any.whl"]++# Declare only what you use; each needs a short reason.+# [permissions]+# files = "Import/export files"+# network = "Download assets"++[build]+paths_exclude_pattern = ["__pycache__/", "/.git/", "/tests/", "*.zip"]diff --git a/skills/blender-addon-development/assets/addon_template/operators.py b/skills/blender-addon-development/assets/addon_template/operators.pynew file mode 100644index 0000000..6df9fdc--- /dev/null+++ b/skills/blender-addon-development/assets/addon_template/operators.py@@ -0,0 +1,33 @@+import bpy+from bpy.props import EnumProperty, FloatProperty+++class MYTOOL_PG_settings(bpy.types.PropertyGroup):+ distance: FloatProperty(name="Distance", default=0.1, min=0.0, soft_max=10.0, unit="LENGTH")+ axis: EnumProperty(name="Axis", items=(("X", "X", ""), ("Y", "Y", ""), ("Z", "Z", "")), default="Z")+++class MYTOOL_OT_offset_selected(bpy.types.Operator):+ """Move selected objects along an axis""" # tooltip+ bl_idname = "my_tool.offset_selected"+ bl_label = "Offset Selected"+ bl_options = {"REGISTER", "UNDO"} # UNDO: one undo step; REGISTER: redo panel++ distance: FloatProperty(name="Distance", default=0.1, unit="LENGTH")+ axis: EnumProperty(name="Axis", items=(("X", "X", ""), ("Y", "Y", ""), ("Z", "Z", "")), default="Z")++ @classmethod+ def poll(cls, context):+ return context.mode == "OBJECT" and bool(context.selected_objects)++ def invoke(self, context, event):+ s = context.scene.my_tool # start from the panel settings+ self.distance, self.axis = s.distance, s.axis+ return self.execute(context)++ def execute(self, context):+ i = "XYZ".index(self.axis)+ for ob in context.selected_objects:+ ob.location[i] += self.distance+ self.report({"INFO"}, f"Moved {len(context.selected_objects)} objects")+ return {"FINISHED"}diff --git a/skills/blender-addon-development/assets/addon_template/ui.py b/skills/blender-addon-development/assets/addon_template/ui.pynew file mode 100644index 0000000..4e86f0d--- /dev/null+++ b/skills/blender-addon-development/assets/addon_template/ui.py@@ -0,0 +1,30 @@+import bpy+++class MYTOOL_PT_main(bpy.types.Panel):+ bl_label = "My Tool"+ bl_idname = "MYTOOL_PT_main"+ bl_space_type = "VIEW_3D"+ bl_region_type = "UI"+ bl_category = "My Tool" # sidebar (N) tab++ def draw(self, context):+ s = context.scene.my_tool+ col = self.layout.column(align=True)+ col.use_property_split = True+ col.prop(s, "distance")+ col.prop(s, "axis")+ self.layout.operator("my_tool.offset_selected", icon="ORIENTATION_GLOBAL")+++class MYTOOL_AP_preferences(bpy.types.AddonPreferences):+ bl_idname = __package__ # extensions: package name, never a hard-coded string++ verbose: bpy.props.BoolProperty(name="Verbose reports", default=False)++ def draw(self, context):+ self.layout.prop(self, "verbose")+++def menu_func(self, context):+ self.layout.operator("my_tool.offset_selected")diff --git a/skills/blender-animation/SKILL.md b/skills/blender-animation/SKILL.mdnew file mode 100644index 0000000..3186a09--- /dev/null+++ b/skills/blender-animation/SKILL.md@@ -0,0 +1,60 @@+---+name: blender-animation+description: Animation in Blender 5.2 - slotted/layered actions and the channelbag API, Python keyframing, F-curves, game loops, NLA clips, pose library, mocap/BVH retargeting via constraints, baking control rigs to export skeletons, root motion, per-clip export. Use for any keyframe, action, NLA, mocap, or animation-export task.+license: MIT+metadata:+ author: blender-agent-skills+ version: "0.1.0"+---++# Animation++The execution model is in `blender-core` (its `references/bpy-patterns.md` has verified keyframe/driver snippets). Rigs are in `blender-character-rigging`.++## 5.x data model (what changed)+- An **Action** holds **slots** (one per animated ID) and **layers → strips → channelbags → F-curves**. A single action can animate several objects (e.g. a rig and its camera) through different slots.+- Assign: `ob.animation_data.action = act`, then make sure `ob.animation_data.action_slot` is set (picked automatically when a suitable slot exists; otherwise `act.slots.new(id_type="OBJECT", name=ob.name)`).+- F-curves: `cb = anim_utils.action_ensure_channelbag_for_slot(act, slot)`, then `cb.fcurves.ensure(path, index=i, group_name=...)`. `action.fcurves` **no longer exists**.+- The simplest route is still `pb.keyframe_insert("rotation_quaternion", frame=f)`, which creates the action, slot and channelbag.++## Workflow (keyframe animation, studio style)+1. **Blocking**: key poses on every channel (`CONSTANT` interpolation, `bpy.context.preferences.edit.keyframe_new_interpolation_type`) on golden frames (contact, down, passing, up for walks).+2. **Breakdowns**: add in-betweens that define arcs and spacing.+3. **Spline**: switch to `BEZIER`, fix spacing in the Graph Editor, and clean overshoot. Auto-clamped handles avoid overshoot.+4. **Polish**: offsets/overlap (follow-through on hair, tails, cloth bones), arcs, moving holds (never a perfectly frozen character), and contact stability (feet locked with IK).+5. **Review**: MCP `look(mode="frames", frame_count=8)` or a Workbench playblast (`blender-rendering`).++## Game animation rules+- **One action per clip**, named `<Rig>_<Clip>` or just `<Clip>`, with a fake user so it survives saving.+- **Loops**: first and last frames identical. Export frames 1..N and let the engine drop the duplicate, or exclude the last frame (UE/Unity "loop pose" options). An F-curve `CYCLES` modifier helps preview but **doesn't export**, so bake it.+- **FPS**: author at 30 (or 24) and let engines resample. Set `scene.render.fps` before importing mocap.+- **Root motion**: the root bone carries the translation (and yaw). The hips keep the bob/sway. `scripts/bake_action.py --root-motion xy` moves the hips' ground motion to the root. In-place clips: the root stays at the origin.+- **Additive/overlay** clips (aim offsets, breathing) are exported as normal clips and marked additive in the engine.+- Keep the bone transform channels the engine expects. **Don't animate bone scale** unless the engine supports it (Roblox and many mobile pipelines don't).++## Bake control rig → export skeleton+```+scripts/bake_action.py -- --list+scripts/bake_action.py -- --source RIG_Body --target GAME_RIG_Body [--actions Walk Run] [--root-motion xy --hips spine]+```+This gives one baked action per clip (`GAME_RIG_Body|Walk`), cleaned, with fake users, plus one muted NLA track per clip (`CLIP_Walk`) so FBX (`bake_anim_use_nla_strips`/all actions) and glTF (`ACTIONS` mode) export every clip. The target's constraints are muted afterward so it plays the baked data; run `--follow` to drive it live again. Self-bake (IK/constraints → keys on the same rig): `--source X --target X`.++## Mocap and retargeting+- Import: `bpy.ops.import_anim.bvh(filepath=..., global_scale=0.01 if cm else 1, rotate_mode="NATIVE", update_scene_fps=True)`, `import_scene.fbx` (Mixamo, `automatic_bone_orientation=True`).+- Retarget without add-ons: put the target rig in the **same rest pose** (T vs A matters most), add `COPY_ROTATION` constraints (world or local-with-parent space) from each target bone to the matching source bone, plus `COPY_LOCATION` on the hips/root (scaled by the leg-length ratio). Then self-bake with `bake_action.py --source TARGET --target TARGET`, and delete the constraints.+- Clean mocap: decimate keys (`graph.decimate`, ratio 0.3–0.5), use an F-curve `SMOOTH` modifier or the Butterworth filter (`graph.butterworth_smooth`), and fix foot sliding with IK pins and then bake.+- Production retarget tools: Auto-Rig Pro (paid), Rokoko (free), and the engine-side retargeters (UE IK Retargeter, Unity Humanoid).++## NLA and pose library+- NLA: push actions down as strips (`track.strips.new(name, start, action)`) to layer/blend clips (blend type `REPLACE`/`ADD`/`COMBINE`), and use Tweak mode to edit. Strips need an action slot set when the action has several slots (`strip.action_slot`).+- The pose library (bundled `pose_library`) stores poses as **assets**: `poselib.create_pose_asset(pose_name=...)`, `poselib.apply_pose_asset` / `blend_pose_asset`. Use it for hand shapes, face poses, and a T/A rest pose.++## Shape keys and other properties+Any property can be keyed: `kb.keyframe_insert("value", frame=f)` (shape key), `mat.node_tree.nodes[...].inputs[...].keyframe_insert("default_value")` (materials, which engines usually ignore), custom props `ob.keyframe_insert('["prop"]')`.++## Gotchas+- `pb.matrix = ...` followed by `keyframe_insert` needs the right `scene.frame_set(f)` **first**, or an evaluation overwrites the pose.+- Connected bones (`use_connect`) can't translate. Hips/pelvis must be unconnected from the root.+- `bake_action` with visual keying reads **evaluated** poses, so constraints, IK and drivers are all captured. Mute the target's own constraints afterward (the script does), or they keep overriding the keys.+- Quaternion vs Euler: game bones should use `QUATERNION` (no gimbal lock, smooth slerp). Euler is fine for single-axis controls. Don't mix modes between keys.+- glTF sampling: `export_force_sampling` bakes every frame (the safe default). Non-linear F-curve modifiers and drivers only export when sampled.diff --git a/skills/blender-animation/scripts/_bpyx.py b/skills/blender-animation/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-animation/scripts/_bpyx.py@@ -0,0 +1,136 @@+"""_bpyx - tiny shared helpers for blender-agent-skills scripts (Blender 5.2+).++Source of truth: shared/_bpyx.py. Copies in skills/*/scripts/ are synced by+tools/sync_shared.py - never edit a copy.++Every skill script follows one contract:+ run(**kwargs) -> dict # call from MCP / Python (import the module)+ blender -b f.blend -P x.py -- --arg v # CLI: prints one line "@@JSON@@{...}"+"""+import argparse+import json+import sys++import bpy++MARK = "@@JSON@@"+++def argv():+ """Arguments after '--' (Blender ignores them)."""+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def _default(o):+ if hasattr(o, "__len__") and not isinstance(o, str):+ try:+ return [round(v, 5) if isinstance(v, float) else v for v in o]+ except TypeError:+ pass+ if isinstance(o, (set, frozenset)):+ return sorted(o)+ return str(o)+++def emit(data):+ """Print compact JSON on one marked line (parsed by run_in_blender.py)."""+ print(MARK + json.dumps(data, separators=(",", ":"), default=_default), flush=True)+ return data+++def parser(doc):+ """ArgumentParser whose help is the script docstring's first line."""+ return argparse.ArgumentParser(description=(doc or "").strip().splitlines()[0])+++def cli(run, p):+ """CLI entry: parse args after '--', run, emit JSON. Exit 1 on failure."""+ args = p.parse_args(argv())+ try:+ result = run(**vars(args))+ save = getattr(args, "save", None)+ if save:+ bpy.ops.wm.save_as_mainfile(filepath=bpy.path.abspath(save))+ result["saved"] = save+ emit(result)+ except Exception as e: # report, don't dump a traceback into agent context+ emit({"ok": False, "error": f"{type(e).__name__}: {e}"})+ if bpy.app.background:+ sys.exit(1)+++def add_common(p, save=True):+ """--objects / --save flags shared by most scripts."""+ p.add_argument("--objects", nargs="*", default=None,+ help="object names (default: selected, else all meshes)")+ if save:+ p.add_argument("--save", default=None, help="save .blend to this path after run")+ return p+++def objects(names=None, types=("MESH",)):+ """Resolve names -> objects. No names: selected of `types`, else all visible of `types`."""+ if names:+ missing = [n for n in names if n not in bpy.data.objects]+ if missing:+ raise KeyError(f"objects not found: {missing}")+ return [bpy.data.objects[n] for n in names]+ pool = [o for o in bpy.context.scene.objects if not types or o.type in types]+ sel = [o for o in pool if o.select_get()]+ return sel or [o for o in pool if o.visible_get()]+++def object_mode():+ """Leave edit/sculpt/pose modes; most data API work needs OBJECT mode."""+ ob = bpy.context.view_layer.objects.active+ if ob and ob.mode != "OBJECT":+ bpy.ops.object.mode_set(mode="OBJECT")+++def select_only(objs, active=None):+ """Select exactly `objs` and make `active` (default first) active."""+ for o in bpy.context.view_layer.objects:+ o.select_set(False)+ for o in objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = active or (objs[0] if objs else None)+++def node(tree, type_):+ """First node of `type_` (e.g. 'BSDF_PRINCIPLED'). Names are localized - never look up by name."""+ return next((n for n in tree.nodes if n.type == type_), None)+++def enum_ids(owner, prop):+ """Valid identifiers of an enum property (works on types or instances)."""+ return [i.identifier for i in owner.bl_rna.properties[prop].enum_items]+++def set_enum(owner, prop, value):+ """Assign an enum; on failure raise listing valid values (dynamic enums under-report)."""+ try:+ setattr(owner, prop, value)+ except TypeError as e:+ raise ValueError(f"{prop}={value!r} invalid: {e}") from None+++def mesh_tris(ob, evaluated=True):+ """Triangle count (evaluated = with modifiers)."""+ if evaluated:+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ try:+ me.calc_loop_triangles()+ return len(me.loop_triangles)+ finally:+ eo.to_mesh_clear()+ me = ob.data+ me.calc_loop_triangles()+ return len(me.loop_triangles)+++def r(v, n=4):+ """Round a float or a vector for compact JSON."""+ if isinstance(v, float):+ return round(v, n)+ return [round(x, n) for x in v]diff --git a/skills/blender-animation/scripts/bake_action.py b/skills/blender-animation/scripts/bake_action.pynew file mode 100644index 0000000..92e0c96--- /dev/null+++ b/skills/blender-animation/scripts/bake_action.py@@ -0,0 +1,158 @@+"""Bake animation clips from a control rig onto an export skeleton (visual keying), one action per+clip, optional root motion, clean curves, NLA strips for exporters; or list clips.++Typical: Rigify RIG_Body (animated) -> GAME_RIG_Body (from rigify_build --game-skeleton).+After baking, the target's constraints are MUTED so exporters play the baked actions+(--follow unmutes them to drive the target from the control rig again).+Usage:+ blender -b f.blend -P bake_action.py -- --list+ blender -b f.blend -P bake_action.py -- --source RIG_Body --target GAME_RIG_Body+ [--actions Walk Run] [--root-motion xy|xyz] [--hips spine] [--step 1] [--no-clean] [--save out.blend]+ blender -b f.blend -P bake_action.py -- --target GAME_RIG_Body --follow+ MCP: import bake_action; print(bake_action.run(source="RIG_Body", target="GAME_RIG_Body", root_motion="xy"))+Self-bake (constraints/IK/drivers -> keys on the same rig): --source X --target X.+"""+import os+import sys++import bpy+from bpy_extras import anim_utils+from mathutils import Matrix, Vector++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402+++def list_actions():+ out = []+ for a in bpy.data.actions:+ cbs = [cb for layer in a.layers for strip in layer.strips for cb in strip.channelbags]+ out.append({"name": a.name, "range": [round(a.frame_range[0], 2), round(a.frame_range[1], 2)],+ "slots": [f"{s.target_id_type}:{s.name_display}" for s in a.slots],+ "fcurves": sum(len(cb.fcurves) for cb in cbs), "users": a.users,+ "fake_user": a.use_fake_user, "cyclic": a.use_cyclic})+ return out+++def _assign(ob, act):+ ob.animation_data_create()+ ob.animation_data.action = act+ if ob.animation_data.action_slot is None:+ slot = next(iter(ob.animation_data.action_suitable_slots), None) or act.slots.new(+ id_type="OBJECT", name=ob.name)+ ob.animation_data.action_slot = slot+++def _mute(ob, state):+ for pb in ob.pose.bones:+ for c in pb.constraints:+ c.mute = state+++def _root_motion(tgt, act, frames, hips, axes):+ root = next((b for b in tgt.pose.bones if b.parent is None), None)+ hp = tgt.pose.bones.get(hips) if hips else None+ if hp is None: # first child chain bone under root+ hp = next((b for b in root.children), None) if root else None+ if root is None or hp is None or root == hp:+ return "skipped (need root bone with a hips child)"+ _assign(tgt, act)+ sc = bpy.context.scene+ start = None+ samples = []+ for f in frames:+ sc.frame_set(f)+ samples.append((f, hp.matrix.copy()))+ for f, m_h in samples:+ sc.frame_set(f)+ p = m_h.translation.copy()+ start = start or p.copy()+ d = p - start+ delta = Vector((d.x, d.y, d.z if axes == "xyz" else 0.0))+ root.matrix = Matrix.Translation(delta) @ root.bone.matrix_local # keep rest orientation+ bpy.context.view_layer.update()+ hp.matrix = m_h # keep hips where they were in armature space+ bpy.context.view_layer.update()+ root.keyframe_insert("location", frame=f)+ hp.keyframe_insert("location", frame=f)+ return f"{root.name} carries {axes} motion from {hp.name}"+++def run(source=None, target=None, actions=None, root_motion=None, hips=None, step=1, clean=True,+ follow=False, list=False, **_): # noqa: A002+ bx.object_mode()+ if list:+ return {"ok": True, "actions": list_actions()}+ tgt = bpy.data.objects[target]+ if follow:+ _mute(tgt, False)+ if tgt.animation_data:+ tgt.animation_data.action = None+ return {"ok": True, "following": True}+ src = bpy.data.objects[source]+ same = src == tgt+ acts = [bpy.data.actions[a] for a in actions] if actions else [+ a for a in bpy.data.actions if any(s.target_id_type == "OBJECT" for s in a.slots)+ and not a.name.startswith(("QA_", f"{tgt.name}|")) and (src.animation_data and (+ a == src.animation_data.action or a.use_fake_user or a.users))]+ if not acts:+ raise ValueError("no actions to bake (assign/fake-user them, or pass --actions)")+ opts = anim_utils.BakeOptions(only_selected=False, do_pose=True, do_object=False, do_visual_keying=True,+ do_constraint_clear=same, do_parents_clear=False, do_clean=clean,+ do_location=True, do_rotation=True, do_scale=True, do_bbone=False,+ do_custom_props=False)+ prev = src.animation_data.action if src.animation_data else None+ baked = []+ tgt.animation_data_create()+ for a in acts:+ _assign(src, a)+ f0, f1 = int(round(a.frame_range[0])), int(round(a.frame_range[1]))+ frames = range(f0, f1 + 1, step)+ _mute(tgt, False) if not same else None+ name = a.name if same else f"{tgt.name}|{a.name}"+ old = bpy.data.actions.get(name)+ if old and old != a:+ bpy.data.actions.remove(old)+ new = a if same else bpy.data.actions.new(name)+ new.use_fake_user = True+ if not same:+ _assign(tgt, new)+ anim_utils.bake_action(tgt, action=new, frames=frames, bake_options=opts)+ rec = {"clip": a.name, "action": new.name, "frames": [f0, f1]}+ if root_motion and not same:+ _mute(tgt, True)+ rec["root_motion"] = _root_motion(tgt, new, frames, hips, root_motion)+ new.use_cyclic = a.use_cyclic+ baked.append(rec)+ if not same:+ _mute(tgt, True)+ # one NLA track per clip (muted) so exporters can find every clip+ ad = tgt.animation_data+ for t in [t for t in ad.nla_tracks if t.name.startswith("CLIP_")]:+ ad.nla_tracks.remove(t)+ for rec in baked:+ act = bpy.data.actions[rec["action"]]+ tr = ad.nla_tracks.new()+ tr.name = f"CLIP_{rec['clip']}"+ st = tr.strips.new(rec["clip"], int(act.frame_range[0]), act)+ tr.mute = True+ st.name = rec["clip"]+ ad.action = bpy.data.actions[baked[0]["action"]]+ if prev is not None:+ _assign(src, prev)+ return {"ok": True, "baked": baked, "target_constraints_muted": not same}+++if __name__ == "__main__":+ p = bx.parser(__doc__)+ p.add_argument("--list", action="store_true")+ p.add_argument("--source", default=None)+ p.add_argument("--target", default=None)+ p.add_argument("--actions", nargs="*", default=None)+ p.add_argument("--root-motion", choices=["xy", "xyz"], default=None)+ p.add_argument("--hips", default=None)+ p.add_argument("--step", type=int, default=1)+ p.add_argument("--no-clean", dest="clean", action="store_false")+ p.add_argument("--follow", action="store_true")+ p.add_argument("--save", default=None)+ bx.cli(run, p)diff --git a/skills/blender-asset-qa/SKILL.md b/skills/blender-asset-qa/SKILL.mdnew file mode 100644index 0000000..b4ba4c7--- /dev/null+++ b/skills/blender-asset-qa/SKILL.md@@ -0,0 +1,55 @@+---+name: blender-asset-qa+description: Mandatory review gate for any mesh or asset created or edited in Blender. Detects z-fighting (coplanar overlaps), floating/detached parts, inverted or inconsistent normals, non-manifold/open geometry, degenerate faces, duplicate verts, n-gons, unapplied scale, UV problems, bad skin weights, and renders multi-angle review sheets. Use before calling any modeling, export or delivery task done.+license: MIT+metadata:+ author: blender-agent-skills+ version: "0.1.0"+---++# Asset QA (review gate)++Never assume a generated or edited mesh is correct. Check it with numbers, then look at it.++## Procedure+1. **Automated check**, passing one asset's objects together:+ `scripts/qa_check.py -- --objects Body Head Hat --profile game`+ Profiles: `game` (default), `render` (lenient), `print` (watertight required), `roblox` (20k tris/mesh, watertight, no n-gons, ≤4 influences).+2. **Fix every `errors` entry** (table below), then re-run until `"pass": true`. Each warning must be either fixed or explicitly accepted, with the reason reported to the user.+3. **Visual check, always**:+ - Live: MCP `look` with `mode="angles"` on the targets, once in `material`/`solid` shading and once in `wireframe`. Use `xray` for internals.+ - Headless: `scripts/review_shots.py -- --objects ... --mode random` (one color per object, which makes detached pieces obvious), then `--mode wire` for topology. Open the returned PNG.+4. Report: tris per object, issues fixed, and remaining accepted warnings.++## What each finding means → fix+| Finding | Cause | Fix |+|---|---|---|+| `zfighting` A<->B | two surfaces facing the same way within `--eps` (1 mm) that overlap | delete the hidden duplicate, or offset ≥ 2–5 mm along the normal, or boolean/merge them |+| `back_to_back` | faces touching with opposite normals (boxes glued face-to-face) | delete the hidden faces (wasted tris, bake artifacts) |+| `floating` | island/object not touching any other part within `--tol` | move it to make contact (snap), bridge it, or join and merge. If floating is intended (sparks, UI), check it separately |+| `enclosed` | part fully inside another, not touching (eyes, internal mechanics) | usually fine. Confirm it's intended |+| `inside_out_islands` | closed part with normals pointing in | `mesh.normals_make_consistent(inside=False)` on that part |+| `inconsistent_normals_edges` | neighbouring faces wound in opposite directions | recalc normals; if it persists, look for non-manifold seams |+| `nonmanifold_edges` / `wire_edges` | >2 faces per edge, or stray edges | dissolve/delete the extra faces; `delete_loose` |+| `boundary_edges` | open holes (bad for print/Roblox/bakes) | fill (`fill_holes`/`edge_face_add`) or cap |+| `degenerate_faces` / `zero_length_edges` | collapsed geometry | `dissolve_degenerate(threshold=1e-4)` |+| `duplicate_verts` | unwelded seams | `remove_doubles(threshold=1e-4)` (Merge by Distance); check UV seams after |+| `ngons` | faces with >4 sides | triangulate/quadrangulate locally; n-gons are fine only on flat hard-surface faces that never deform |+| unapplied/negative scale | object transform | `transform_apply(rotation=True, scale=True)`; negative scale flips normals on export |+| `uv_maps: 0` / zero-area UV / overlap | missing or bad unwrap | `blender-retopology-uv` |+| unweighted / >4 influences | skinning | `blender-character-rigging` (`weights_check.py`) |+| `ground_z` ≠ 0 | asset floats or sinks | move the origin to the bottom and set z = 0 (props) |++## Manual checks the script can't fully judge+- **Silhouette and proportions** at the target camera distance. Compare with references and real-world size (`ob.dimensions`).+- **Shading artifacts**: smoothing on hard edges (needs sharp edges/weighted normals), and pinching at poles on curved surfaces.+- **Intersections that look wrong** (a leg clipping a seat), even though they're "attached".+- **Interior/hidden geometry** that wastes tris (use `xray`).+- **Deformation**: pose the rig at extremes (elbow 140°, knee 150°, shoulder raised) and look for collapsing volume.+- **Material assignment**: every face has the intended material, with no default grey slots.++## Tuning+- `--eps` is the z-fight distance. Raise it to 0.005 for large environment scenes, and lower it to 0.0002 for tiny jewelry.+- `--tol` is the contact tolerance for detached parts. Raise it for chunky kitbash.+- `--no-modifiers` checks the base mesh. By default the evaluated (modifier) result is checked, which is what gets exported.+- Above `--max-tris` (300k), the z-fight and floating checks are skipped. Check high-poly sources per part instead.diff --git a/skills/blender-asset-qa/scripts/_bpyx.py b/skills/blender-asset-qa/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-asset-qa/scripts/_bpyx.py@@ -0,0 +1,136 @@+"""_bpyx - tiny shared helpers for blender-agent-skills scripts (Blender 5.2+).++Source of truth: shared/_bpyx.py. Copies in skills/*/scripts/ are synced by+tools/sync_shared.py - never edit a copy.++Every skill script follows one contract:+ run(**kwargs) -> dict # call from MCP / Python (import the module)+ blender -b f.blend -P x.py -- --arg v # CLI: prints one line "@@JSON@@{...}"+"""+import argparse+import json+import sys++import bpy++MARK = "@@JSON@@"+++def argv():+ """Arguments after '--' (Blender ignores them)."""+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def _default(o):+ if hasattr(o, "__len__") and not isinstance(o, str):+ try:+ return [round(v, 5) if isinstance(v, float) else v for v in o]+ except TypeError:+ pass+ if isinstance(o, (set, frozenset)):+ return sorted(o)+ return str(o)+++def emit(data):+ """Print compact JSON on one marked line (parsed by run_in_blender.py)."""+ print(MARK + json.dumps(data, separators=(",", ":"), default=_default), flush=True)+ return data+++def parser(doc):+ """ArgumentParser whose help is the script docstring's first line."""+ return argparse.ArgumentParser(description=(doc or "").strip().splitlines()[0])+++def cli(run, p):+ """CLI entry: parse args after '--', run, emit JSON. Exit 1 on failure."""+ args = p.parse_args(argv())+ try:+ result = run(**vars(args))+ save = getattr(args, "save", None)+ if save:+ bpy.ops.wm.save_as_mainfile(filepath=bpy.path.abspath(save))+ result["saved"] = save+ emit(result)+ except Exception as e: # report, don't dump a traceback into agent context+ emit({"ok": False, "error": f"{type(e).__name__}: {e}"})+ if bpy.app.background:+ sys.exit(1)+++def add_common(p, save=True):+ """--objects / --save flags shared by most scripts."""+ p.add_argument("--objects", nargs="*", default=None,+ help="object names (default: selected, else all meshes)")+ if save:+ p.add_argument("--save", default=None, help="save .blend to this path after run")+ return p+++def objects(names=None, types=("MESH",)):+ """Resolve names -> objects. No names: selected of `types`, else all visible of `types`."""+ if names:+ missing = [n for n in names if n not in bpy.data.objects]+ if missing:+ raise KeyError(f"objects not found: {missing}")+ return [bpy.data.objects[n] for n in names]+ pool = [o for o in bpy.context.scene.objects if not types or o.type in types]+ sel = [o for o in pool if o.select_get()]+ return sel or [o for o in pool if o.visible_get()]+++def object_mode():+ """Leave edit/sculpt/pose modes; most data API work needs OBJECT mode."""+ ob = bpy.context.view_layer.objects.active+ if ob and ob.mode != "OBJECT":+ bpy.ops.object.mode_set(mode="OBJECT")+++def select_only(objs, active=None):+ """Select exactly `objs` and make `active` (default first) active."""+ for o in bpy.context.view_layer.objects:+ o.select_set(False)+ for o in objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = active or (objs[0] if objs else None)+++def node(tree, type_):+ """First node of `type_` (e.g. 'BSDF_PRINCIPLED'). Names are localized - never look up by name."""+ return next((n for n in tree.nodes if n.type == type_), None)+++def enum_ids(owner, prop):+ """Valid identifiers of an enum property (works on types or instances)."""+ return [i.identifier for i in owner.bl_rna.properties[prop].enum_items]+++def set_enum(owner, prop, value):+ """Assign an enum; on failure raise listing valid values (dynamic enums under-report)."""+ try:+ setattr(owner, prop, value)+ except TypeError as e:+ raise ValueError(f"{prop}={value!r} invalid: {e}") from None+++def mesh_tris(ob, evaluated=True):+ """Triangle count (evaluated = with modifiers)."""+ if evaluated:+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ try:+ me.calc_loop_triangles()+ return len(me.loop_triangles)+ finally:+ eo.to_mesh_clear()+ me = ob.data+ me.calc_loop_triangles()+ return len(me.loop_triangles)+++def r(v, n=4):+ """Round a float or a vector for compact JSON."""+ if isinstance(v, float):+ return round(v, n)+ return [round(x, n) for x in v]diff --git a/skills/blender-asset-qa/scripts/qa_check.py b/skills/blender-asset-qa/scripts/qa_check.pynew file mode 100644index 0000000..8f14bb0--- /dev/null+++ b/skills/blender-asset-qa/scripts/qa_check.py@@ -0,0 +1,355 @@+"""Mesh/asset QA: z-fighting, detached parts, normals, topology, transforms, UVs, weights.++Pass the objects of ONE asset (they are checked together: islands far from all others = floating).+Usage:+ blender -b f.blend -P qa_check.py -- [--objects A B] [--profile game|render|print|roblox]+ [--eps 0.001] [--tol 0.002] [--no-modifiers] [--max-tris 300000]+ MCP: import qa_check; print(qa_check.run(objects=["Chair"], profile="game"))+Returns {"pass": bool, "errors": [...], "warnings": [...], "objects": {name: metrics}}.+"""+import math+import os+import sys+from collections import Counter, defaultdict++import bmesh+import bpy+from mathutils import Vector+from mathutils.bvhtree import BVHTree+from mathutils.kdtree import KDTree++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++# check -> severity per profile ("e" error, "w" warning, None skip)+PROFILES = {+ # zfight floating inverted inconsist nonmanif boundary degen dupes ngons scale uv weights+ "game": dict(zf="e", fl="e", inv="e", inc="e", nm="w", bd=None, dg="e", dup="w", ng="w", sc="e", uv="e", wt="e"),+ "render": dict(zf="e", fl="e", inv="w", inc="w", nm=None, bd=None, dg="w", dup="w", ng=None, sc="w", uv="w", wt="w"),+ "print": dict(zf="e", fl="e", inv="e", inc="e", nm="e", bd="e", dg="e", dup="e", ng=None, sc="w", uv=None, wt=None),+ "roblox": dict(zf="e", fl="e", inv="e", inc="e", nm="w", bd="w", dg="e", dup="w", ng="e", sc="e", uv="e", wt="e"),+}+TRI_LIMIT = {"roblox": 20000}+++def _mesh_world(ob, use_mods):+ """bmesh of the (evaluated) object in world space, triangulated copy kept separately."""+ bm = bmesh.new()+ if use_mods:+ dg = bpy.context.evaluated_depsgraph_get()+ bm.from_object(ob, dg)+ else:+ bm.from_mesh(ob.data)+ bm.transform(ob.matrix_world)+ bm.verts.ensure_lookup_table()+ bm.faces.ensure_lookup_table()+ return bm+++def _islands(bm):+ parent = list(range(len(bm.verts)))++ def find(i):+ while parent[i] != i:+ parent[i] = parent[parent[i]]+ i = parent[i]+ return i+ for e in bm.edges:+ a, b = find(e.verts[0].index), find(e.verts[1].index)+ if a != b:+ parent[a] = b+ roots = [find(i) for i in range(len(bm.verts))]+ remap = {r: n for n, r in enumerate(dict.fromkeys(roots))}+ return [remap[r] for r in roots]+++def _point_in_tri(p, a, b, c, n):+ for u, v in ((a, b), (b, c), (c, a)):+ if (v - u).cross(p - u).dot(n) < -1e-9:+ return False+ return True+++def _uv_stats(ob, bm_local):+ me = ob.data+ if not me.uv_layers:+ return {"uv_maps": 0}+ uv = bm_local.loops.layers.uv.active+ oob = total = zero = 0+ grid, n = defaultdict(set), 128+ step = max(1, len(bm_local.faces) // 30000) # sample huge meshes+ for f in list(bm_local.faces)[::step]:+ pts = [l[uv].uv.copy() for l in f.loops]+ for p in pts:+ total += 1+ if p.x < -1e-4 or p.y < -1e-4 or p.x > 1.0001 or p.y > 1.0001:+ oob += 1+ a2 = sum(pts[i].x * pts[(i + 1) % len(pts)].y - pts[(i + 1) % len(pts)].x * pts[i].y+ for i in range(len(pts)))+ if abs(a2) < 1e-12:+ zero += 1+ continue+ # coarse raster of face bbox cells whose centre is inside the polygon (fan triangles)+ xs, ys = [p.x for p in pts], [p.y for p in pts]+ for gx in range(max(0, int(min(xs) * n)), min(n, int(max(xs) * n) + 1)):+ for gy in range(max(0, int(min(ys) * n)), min(n, int(max(ys) * n) + 1)):+ c = Vector(((gx + .5) / n, (gy + .5) / n))+ for i in range(1, len(pts) - 1):+ t = (pts[0], pts[i], pts[i + 1])+ d = [(t[(k + 1) % 3] - t[k]).to_3d().cross((c - t[k]).to_3d()).z for k in range(3)]+ if all(x >= 0 for x in d) or all(x <= 0 for x in d):+ grid[(gx, gy)].add(f.index)+ break+ used = len(grid)+ overlap = sum(1 for s in grid.values() if len(s) > 1)+ return {"uv_maps": len(me.uv_layers), "uv_oob_pct": round(100 * oob / max(total, 1), 2),+ "uv_zero_area_faces": zero, "uv_overlap_pct": round(100 * overlap / max(used, 1), 2),+ "uv_coverage_pct": round(100 * used / n / n, 1)}+++def run(objects=None, profile="game", eps=0.001, tol=0.002, no_modifiers=False, max_tris=300000,+ uv=True, **_):+ bx.object_mode()+ sev = PROFILES[profile]+ obs = [o for o in bx.objects(objects) if o.type == "MESH"]+ if not obs:+ raise ValueError("no mesh objects to check")+ errors, warnings, per = [], [], {}++ def flag(key, msg):+ s = sev.get(key)+ if s == "e":+ errors.append(msg)+ elif s == "w":+ warnings.append(msg)++ # ---- gather world-space triangles of all objects --------------------------------+ verts, tris, tri_meta = [], [], [] # tri_meta: (obj_i, island_gid, normal)+ island_info = {} # gid -> dict(ob, verts, tris, bbox)+ gid_base = 0+ min_z = math.inf+ for oi, ob in enumerate(obs):+ bm = _mesh_world(ob, not no_modifiers)+ m = {}+ isl = _islands(bm)+ n_isl = max(isl) + 1 if isl else 0+ base_v = len(verts)+ verts.extend(v.co.copy() for v in bm.verts)+ if bm.verts:+ min_z = min(min_z, min(v.co.z for v in bm.verts))+ # topology+ ecount = Counter(len(e.link_faces) for e in bm.edges)+ m["verts"], m["faces"] = len(bm.verts), len(bm.faces)+ m["tris"] = sum(len(f.verts) - 2 for f in bm.faces)+ m["ngons"] = sum(1 for f in bm.faces if len(f.verts) > 4)+ m["boundary_edges"] = ecount.get(1, 0)+ m["nonmanifold_edges"] = sum(c for k, c in ecount.items() if k > 2)+ m["wire_edges"] = ecount.get(0, 0)+ m["loose_verts"] = sum(1 for v in bm.verts if not v.link_edges)+ m["degenerate_faces"] = sum(1 for f in bm.faces if f.calc_area() < 1e-10)+ m["zero_length_edges"] = sum(1 for e in bm.edges if e.calc_length() < 1e-7)+ directed = Counter((l.vert.index, l.link_loop_next.vert.index) for f in bm.faces for l in f.loops)+ m["inconsistent_normals_edges"] = sum(1 for k, c in directed.items() if c > 1)+ kd = KDTree(len(bm.verts))+ for v in bm.verts:+ kd.insert(v.co, v.index)+ kd.balance()+ m["duplicate_verts"] = sum(1 for v in bm.verts+ if len(kd.find_range(v.co, 1e-5)) > 1) // 2+ m["islands"] = n_isl+ # per-island volume sign + bbox (closed islands only for inversion test)+ vol, closed = defaultdict(float), defaultdict(lambda: True)+ for e in bm.edges:+ if len(e.link_faces) != 2:+ closed[isl[e.verts[0].index]] = False+ bm_t = bm.copy()+ bmesh.ops.triangulate(bm_t, faces=bm_t.faces[:])+ bm_t.verts.ensure_lookup_table()+ for f in bm_t.faces:+ a, b, c = (v.co for v in f.verts)+ g = isl[f.verts[0].index]+ vol[g] += a.dot(b.cross(c)) / 6.0+ tris.append(tuple(base_v + v.index for v in f.verts))+ tri_meta.append((oi, gid_base + g, f.normal.copy()))+ bm_t.free()+ m["inside_out_islands"] = sum(1 for g in range(n_isl) if closed[g] and vol[g] < -1e-9)+ groups = defaultdict(list)+ for i, g in enumerate(isl):+ groups[g].append(i)+ for g, idx in groups.items():+ pts = [bm.verts[i].co for i in idx]+ lo = Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts)))+ hi = Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts)))+ island_info[gid_base + g] = {"ob": ob.name, "verts": [base_v + i for i in idx],+ "center": (lo + hi) / 2, "size": (hi - lo).length,+ "closed": closed[g], "tris": []}+ gid_base += n_isl+ # transforms+ s = ob.scale+ m["scale"] = bx.r(tuple(s), 3)+ if any(abs(x - 1) > 1e-4 for x in s):+ flag("sc", f"{ob.name}: unapplied scale {m['scale']}")+ if s.x * s.y * s.z < 0:+ errors.append(f"{ob.name}: negative scale (flips normals on export)")+ # materials+ m["materials"] = len(ob.material_slots)+ if any(sl.material is None for sl in ob.material_slots) or not ob.material_slots:+ warnings.append(f"{ob.name}: missing/empty material slot")+ # weights+ arm_mod = next((md for md in ob.modifiers if md.type == "ARMATURE" and md.object), None)+ if arm_mod and ob.vertex_groups:+ deform = {b.name for b in arm_mod.object.data.bones if b.use_deform}+ gidx = {g.index for g in ob.vertex_groups if g.name in deform}+ unweighted = over4 = 0+ for v in ob.data.vertices:+ ws = [g for g in v.groups if g.group in gidx and g.weight > 1e-4]+ unweighted += not ws+ over4 += len(ws) > 4+ m["unweighted_verts"], m["verts_over_4_influences"] = unweighted, over4+ if unweighted:+ flag("wt", f"{ob.name}: {unweighted} verts with no deform weights")+ if over4:+ flag("wt", f"{ob.name}: {over4} verts with >4 bone influences")+ # uv+ if uv:+ bm_l = bmesh.new()+ bm_l.from_mesh(ob.data)+ m.update(_uv_stats(ob, bm_l))+ bm_l.free()+ if m["uv_maps"] == 0:+ flag("uv", f"{ob.name}: no UV map")+ else:+ if m["uv_zero_area_faces"]:+ flag("uv", f"{ob.name}: {m['uv_zero_area_faces']} zero-area UV faces")+ if m["uv_oob_pct"] > 0 and profile in ("roblox",):+ flag("uv", f"{ob.name}: {m['uv_oob_pct']}% UVs outside 0-1")+ if m["uv_overlap_pct"] > 5:+ warnings.append(f"{ob.name}: ~{m['uv_overlap_pct']}% UV overlap "+ "(ok only if mirrored/stacked on purpose; bakes break)")+ bm.free()+ # flags+ if m["inside_out_islands"]:+ flag("inv", f"{ob.name}: {m['inside_out_islands']} closed parts with normals pointing inward")+ if m["inconsistent_normals_edges"]:+ flag("inc", f"{ob.name}: {m['inconsistent_normals_edges']} edges with inconsistent face winding")+ if m["nonmanifold_edges"] or m["wire_edges"]:+ flag("nm", f"{ob.name}: non-manifold edges={m['nonmanifold_edges']} wire={m['wire_edges']}")+ if m["boundary_edges"]:+ flag("bd", f"{ob.name}: {m['boundary_edges']} open boundary edges (not watertight)")+ if m["degenerate_faces"] or m["zero_length_edges"]:+ flag("dg", f"{ob.name}: degenerate faces={m['degenerate_faces']} zero-len edges={m['zero_length_edges']}")+ if m["duplicate_verts"] or m["loose_verts"]:+ flag("dup", f"{ob.name}: duplicate verts={m['duplicate_verts']} loose verts={m['loose_verts']}")+ if m["ngons"]:+ flag("ng", f"{ob.name}: {m['ngons']} n-gons")+ lim = TRI_LIMIT.get(profile)+ if lim and m["tris"] > lim:+ errors.append(f"{ob.name}: {m['tris']} tris > {profile} limit {lim}")+ per[ob.name] = m++ if len(tris) > max_tris:+ warnings.append(f"{len(tris)} tris > max_tris {max_tris}: z-fighting/floating checks skipped")+ return _result(errors, warnings, per, min_z, tol, [], [], [])++ bvh = BVHTree.FromPolygons(verts, tris, epsilon=0.0)+ tri_sets = [set(t) for t in tris]+ for ti, (_, g, _) in enumerate(tri_meta):+ island_info[g]["tris"].append(ti)++ # ---- z-fighting: parallel faces within eps whose areas overlap --------------------+ zf_pairs, contact_pairs = set(), set()+ for ti, t in enumerate(tris):+ a, b, c = (verts[i] for i in t)+ n = tri_meta[ti][2]+ if n.length < 0.5:+ continue+ cen = (a + b + c) / 3+ for p in (cen, cen.lerp(a, .6), cen.lerp(b, .6), cen.lerp(c, .6)):+ for _, _, tj, _ in bvh.find_nearest_range(p, eps):+ if tj is None or tj == ti:+ continue+ if tri_sets[ti] & tri_sets[tj]:+ continue+ n2 = tri_meta[tj][2]+ d = n.dot(n2)+ if abs(d) < 0.999:+ continue+ a2, b2, c2 = (verts[i] for i in tris[tj])+ q = p - n2 * n2.dot(p - a2)+ if _point_in_tri(q, a2, b2, c2, n2):+ (zf_pairs if d > 0 else contact_pairs).add((min(ti, tj), max(ti, tj)))++ def _describe(pairs):+ out = Counter()+ for i, j in pairs:+ oa, ob_ = obs[tri_meta[i][0]].name, obs[tri_meta[j][0]].name+ out[f"{oa}<->{ob_}" if oa != ob_ else oa] += 1+ return [{"where": k, "tri_pairs": v} for k, v in out.most_common(20)]+ zf = _describe(zf_pairs)+ for z in zf:+ flag("zf", f"z-fighting: {z['where']} ({z['tri_pairs']} overlapping coplanar tri pairs)")+ contact = _describe(contact_pairs)+ for z in contact:+ warnings.append(f"hidden back-to-back faces: {z['where']} ({z['tri_pairs']} pairs) - delete to save tris")++ # ---- floating / detached islands ------------------------------------------------------+ floating, enclosed = [], []+ if len(island_info) > 1:+ tri_island = [m_[1] for m_ in tri_meta]+ biggest = max(island_info, key=lambda g: island_info[g]["size"])+ for g, info in island_info.items():+ if g == biggest:+ continue+ touching = False+ vs = info["verts"]+ step = max(1, len(vs) // 400)+ for vi in vs[::step]:+ for _, _, tj, _ in bvh.find_nearest_range(verts[vi], tol):+ if tj is not None and tri_island[tj] != g:+ touching = True+ break+ if touching:+ break+ if not touching and info["tris"]:+ sub = BVHTree.FromPolygons(verts, [tris[t] for t in info["tris"]], epsilon=0.0)+ touching = any(tri_island[j] != g for _, j in sub.overlap(bvh))+ if touching:+ continue+ # inside another closed island? (eyes in a head, internal parts) -> parity ray test+ org, hits, d = info["center"], 0, Vector((0.137, 0.271, 0.953)).normalized()+ p = org.copy()+ for _ in range(64):+ loc, _, tj, _ = bvh.ray_cast(p, d)+ if loc is None:+ break+ if tri_island[tj] != g:+ hits += 1+ p = loc + d * 1e-5+ rec = {"object": info["ob"], "island_verts": len(vs), "center": bx.r(tuple(info["center"]), 3)}+ (enclosed if hits % 2 == 1 else floating).append(rec)+ for f in floating:+ flag("fl", f"floating/detached part in {f['object']} ({f['island_verts']} verts at {f['center']})")+ if enclosed:+ warnings.append(f"{len(enclosed)} parts fully enclosed, not touching (eyes/internals?): "+ f"{[e['object'] for e in enclosed][:5]}")+ return _result(errors, warnings, per, min_z, tol, zf, floating, contact, enclosed)+++def _result(errors, warnings, per, min_z, tol, zf, floating, contact, enclosed=()):+ ground = None if min_z == math.inf else round(min_z, 4)+ if ground is not None and abs(ground) > max(tol, 1e-3):+ warnings.append(f"asset lowest point z={ground} (not resting on ground plane z=0)")+ return {"ok": True, "pass": not errors, "errors": errors, "warnings": warnings,+ "ground_z": ground, "zfighting": zf, "floating": floating,+ "back_to_back": contact, "enclosed": list(enclosed), "objects": per}+++if __name__ == "__main__":+ p = bx.add_common(bx.parser(__doc__), save=False)+ p.add_argument("--profile", default="game", choices=list(PROFILES))+ p.add_argument("--eps", type=float, default=0.001, help="z-fight plane distance (m)")+ p.add_argument("--tol", type=float, default=0.002, help="contact tolerance for detached parts (m)")+ p.add_argument("--no-modifiers", action="store_true")+ p.add_argument("--max-tris", type=int, default=300000)+ p.add_argument("--no-uv", dest="uv", action="store_false")+ bx.cli(run, p)diff --git a/skills/blender-asset-qa/scripts/review_shots.py b/skills/blender-asset-qa/scripts/review_shots.pynew file mode 100644index 0000000..b357530--- /dev/null+++ b/skills/blender-asset-qa/scripts/review_shots.py@@ -0,0 +1,142 @@+"""Render a multi-angle review contact sheet (headless-safe Workbench) for visual QA.++Modes: solid (studio light + cavity), random (color per object/part -> spot detached+parts), wire (black wireframe over solid -> topology), material (texture/material colors).+Usage:+ blender -b f.blend -P review_shots.py -- [--objects A B] [--out //review.png]+ [--views front right back left top three_quarter] [--mode solid|random|wire|material] [--res 512]+ MCP: prefer the `look` tool; this script is for agents without live viewport access.+Returns {"sheet": path, "views": [paths]} - open the PNG with your image reader.+"""+import math+import os+import sys+import tempfile++import bpy+import numpy as np+from mathutils import Vector++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++DIRS = {"front": (0, -1, 0.15), "back": (0, 1, 0.15), "right": (1, 0, 0.15), "left": (-1, 0, 0.15),+ "top": (0, -0.001, 1), "bottom": (0, 0.001, -1), "three_quarter": (1, -1, 0.6)}+++def _bounds(obs):+ bpy.context.view_layer.update() # bound_box is stale on freshly built objects+ pts = [o.matrix_world @ Vector(c) for o in obs for c in o.bound_box]+ lo = Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts)))+ hi = Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts)))+ return (lo + hi) / 2, max((hi - lo).length / 2, 1e-3)+++def run(objects=None, out="", views=None, mode="solid", res=512, **_):+ bx.object_mode()+ obs = bx.objects(objects, types=("MESH", "CURVE", "FONT", "SURFACE", "CURVES", "VOLUME"))+ if not obs:+ raise ValueError("nothing to render")+ views = views or ["front", "right", "top", "three_quarter"]+ sc = bpy.context.scene+ out = bpy.path.abspath(out) if out else os.path.join(+ os.path.dirname(bpy.data.filepath) or tempfile.gettempdir(), "review_sheet.png")+ os.makedirs(os.path.dirname(out) or ".", exist_ok=True)++ # snapshot settings we touch, restore after+ r, sh = sc.render, sc.display.shading+ saved = dict(engine=r.engine, rx=r.resolution_x, ry=r.resolution_y, pct=r.resolution_percentage,+ fp=r.filepath, cam=sc.camera, light=sh.light, color=sh.color_type,+ cavity=sh.show_cavity, outline=sh.show_object_outline, transp=r.film_transparent)+ hidden = {o: o.hide_render for o in sc.objects}+ temp = []+ try:+ for o in sc.objects:+ o.hide_render = o not in obs+ r.engine = "BLENDER_WORKBENCH"+ r.resolution_x = r.resolution_y = res+ r.resolution_percentage = 100+ r.film_transparent = False+ r.image_settings.media_type = "IMAGE"+ r.image_settings.file_format = "PNG"+ sh.light = "STUDIO"+ sh.show_cavity = mode in ("solid", "wire")+ sh.show_object_outline = True+ sh.color_type = {"random": "RANDOM", "material": "MATERIAL", "wire": "OBJECT"}.get(mode, "SINGLE")+ if mode == "wire":+ wire_t = _bounds(obs)[1] * 0.006+ for o in obs:+ if o.type != "MESH":+ continue+ w = o.copy()+ w.data = o.data+ w.modifiers.new("QA_Wire", "WIREFRAME").thickness = wire_t+ w.color = (0, 0, 0, 1)+ sc.collection.objects.link(w)+ temp.append(w)+ o.color = (0.8, 0.8, 0.8, 1)++ cam_data = bpy.data.cameras.new("QA_Cam")+ cam_data.lens = 50+ cam = bpy.data.objects.new("QA_Cam", cam_data)+ sc.collection.objects.link(cam)+ temp.append(cam)+ sc.camera = cam+ center, radius = _bounds(obs)+ fov = 2 * math.atan(cam_data.sensor_width / (2 * cam_data.lens))+ dist = radius / math.sin(fov / 2) * 1.05+ cam_data.clip_end = dist * 4+ cam_data.clip_start = dist / 1000+ paths = []+ for v in views:+ d = Vector(DIRS[v] if isinstance(v, str) else v).normalized()+ cam.location = center + d * dist+ cam.rotation_euler = (-d).to_track_quat("-Z", "Y").to_euler()+ p = os.path.splitext(out)[0] + f"_{v}.png"+ r.filepath = p+ bpy.ops.render.render(write_still=True)+ paths.append(p)++ # tile into a contact sheet+ imgs = []+ for p in paths:+ im = bpy.data.images.load(p, check_existing=False)+ a = np.empty(res * res * 4, dtype=np.float32)+ im.pixels.foreach_get(a)+ imgs.append(a.reshape(res, res, 4))+ bpy.data.images.remove(im)+ cols = 2 if len(imgs) <= 4 else 3+ rows = math.ceil(len(imgs) / cols)+ sheet = np.ones((rows * res, cols * res, 4), dtype=np.float32)+ for i, a in enumerate(imgs):+ rr, cc = rows - 1 - i // cols, i % cols # pixel rows are bottom-up+ sheet[rr * res:(rr + 1) * res, cc * res:(cc + 1) * res] = a+ im = bpy.data.images.new("QA_Sheet", cols * res, rows * res, alpha=True)+ im.pixels.foreach_set(sheet.ravel())+ im.filepath_raw = out+ im.file_format = "PNG"+ im.save()+ bpy.data.images.remove(im)+ finally:+ for o in temp:+ data = o.data if o.type == "CAMERA" else None+ bpy.data.objects.remove(o)+ if data:+ bpy.data.cameras.remove(data)+ for o, h in hidden.items():+ o.hide_render = h+ r.engine, r.resolution_x, r.resolution_y = saved["engine"], saved["rx"], saved["ry"]+ r.resolution_percentage, r.filepath, sc.camera = saved["pct"], saved["fp"], saved["cam"]+ r.film_transparent = saved["transp"]+ sh.light, sh.color_type, sh.show_cavity = saved["light"], saved["color"], saved["cavity"]+ sh.show_object_outline = saved["outline"]+ return {"ok": True, "sheet": out, "views": paths, "layout": f"{cols}x{rows}", "order": views}+++if __name__ == "__main__":+ p = bx.add_common(bx.parser(__doc__), save=False)+ p.add_argument("--out", default="")+ p.add_argument("--views", nargs="*", default=None, choices=list(DIRS))+ p.add_argument("--mode", default="solid", choices=["solid", "random", "wire", "material"])+ p.add_argument("--res", type=int, default=512)+ bx.cli(run, p)diff --git a/skills/blender-character-rigging/SKILL.md b/skills/blender-character-rigging/SKILL.mdnew file mode 100644index 0000000..86a9944--- /dev/null+++ b/skills/blender-character-rigging/SKILL.md@@ -0,0 +1,55 @@+---+name: blender-character-rigging+description: Character rigging in Blender 5.2 - Rigify metarig fit/generate, bone naming/roll/collections, DEF/MCH/control layers, IK/FK, robust skinning (heat + proxy fallback), weight-painting rules, correctives, engine game skeletons (Unity, Unreal, Roblox R15), rig validation and deformation stress tests. Use for armature, skinning or weights tasks.+license: MIT+metadata:+ author: blender-agent-skills+ version: "0.1.0"+---++# Character Rigging++The execution model is in `blender-core`. Faces and shape keys are in `blender-facial-shapekeys`, animation in `blender-animation`.++## Pipeline (scripts chain; each returns JSON)+1. **Prepare the mesh**: scale applied, facing **-Y**, feet at Z=0, centered on X=0, symmetric, in T- or A-pose (A-pose 30–45° deforms shoulders better). Run `blender-asset-qa` first.+2. **Metarig**: `scripts/rigify_build.py -- --add basic_human --fit Body` (`human` adds a full face rig; for games use `--no-face` + shape keys).+3. **Place the joints** (the fit only scales). Edit bones in X-ray against the mesh: joints sit at the **pivot of rotation** (inside the volume, not on the surface). The elbow and knee need a slight bend toward their natural direction (elbow back, knee forward) so the IK solves the right way. Symmetrize: `bpy.ops.armature.symmetrize()`. Check with `look` (`shading="xray"`).+4. **Generate**: `--metarig META_Body --generate` gives `RIG_Body` (control rig: FK/IK, IK/FK snapping, tweak bones, bone collections).+5. **Skin**: `scripts/bind_mesh.py -- --armature RIG_Body --meshes Body`. It uses heat weights, switches to the voxel-proxy transfer automatically when heat fails (non-manifold, kitbashed or AI meshes), then cleans to 4 influences and normalizes.+6. **Stress test**: `scripts/stress_poses.py -- --armature RIG_Body`, then `look(mode="frames", frames=[1,10,20,30,40,50])`. Fix collapsing elbows, candy-wrapped forearms, a sunken shoulder or a hip crease (below).+7. **Engine skeleton**: `rigify_build.py -- --rig RIG_Body --game-skeleton` gives `GAME_RIG_Body` = `root` + DEF bones in a clean hierarchy, with `DEF-` stripped, constrained to the control rig and with the meshes re-targeted. Animate with the control rig, then bake to the game skeleton and export it (`blender-animation` → `blender-export-pipelines`).+8. **Validate**: `scripts/rig_check.py -- --armature GAME_RIG_Body --profile unity|unreal|roblox [--fix]`.++## Bone rules+- **Layers of a production rig**: `DEF` (deforming, the only ones exported), `ORG` (original metarig copy), `MCH` (mechanism helpers), controls (what animators touch). Never weight to control/MCH bones.+- **Naming**: `.L`/`.R` suffixes (mirror tools, Rigify and `rig_check` depend on them). Unique, ASCII. Bone collections (`arm.collections.new("FK")`, `bcoll.assign(bone)`) replace the old bone layers.+- **Roll**: consistent local axes. Y points down the bone; recalc with `armature.calculate_roll(type="GLOBAL_POS_Z")` for limbs, or per chain. Mirrored bones must have mirrored roll (`rig_check` flags this).+- **Chains**: connected parent→child for limbs. Spine 3–5 bones, neck 1–2. Twist bones on the forearm and upper arm (Rigify's `.001` segments) prevent candy-wrapping.+- The root bone sits at the origin, Y-forward, carries no weights, and is used for root motion.+- **Scale**: armature object scale 1, rotation 0. Apply before skinning. Non-uniform bone scale animation breaks engines.++## Weight painting rules (what pros check)+- ≤ 4 influences per vertex (mobile/Roblox), ≤ 8 on PC if the engine supports it. Always normalized. Weights below 0.01 removed.+- **Smooth falloff across joints**: a 50/50 blend at the joint line, fading over ~1–2 edge loops. A hard 1/0 cut shows a crease; too wide gives rubbery limbs.+- **Elbows/knees**: weight the outer side to the upper bone longer so the joint keeps volume. Add a helper/corrective bone or corrective shape for sharp bends.+- **Shoulders**: blend the clavicle, upper arm and spine. Test arms raised above the head (stress frame 10).+- **Hips**: the thigh-pelvis blend in front stays tight (crease) and soft at the back (glutes).+- **Head/neck**: rigid head (100% head bone above the jawline), smooth neck blend. Props (helmets, armor plates) get 100% weight to a single bone, so they stay rigid with no stretching.+- **Mirror**: paint one side, then `object.vertex_group_mirror(all_groups=True, flip_group_names=True, use_topology=False)`, or work with X-mirror on.+- **Tools** (live): Weight Paint mode with auto-normalize on, the gradient tool, Smooth (`vertex_group_smooth`), Levels, and `object.data_transfer` from a good mesh (clothing gets its weights from the body).++## Correctives (beyond weights)+Corrective shape keys driven by bone rotation fix elbows, knees and shoulders in hero rigs. Sculpt the fix in the posed state (`modifier_apply_as_shapekey` or the Corrective Shape Keys add-on approach), then drive the key value from the bone's local rotation (driver `TRANSFORMS` var `ROT_X` in `LOCAL_SPACE`, mapped from 0 at rest to 1 at full bend). Games: correctives export as blendshapes. Drive them in the engine (UE Pose Driver / Unity script) or bake them into the animation.++## Engine skeleton specifics+- **Unity Humanoid**: Hips → Spine → Chest → Neck → Head, plus limbs. The game skeleton maps automatically (`rig_check --profile unity` shows the mapping). T-pose bind pose recommended.+- **Unreal**: retarget to the UE5 Mannequin with IK Retargeter. Matching names (`pelvis`, `spine_01`, `thigh_l`...) speeds up chain mapping (`--profile unreal` lists the gaps). No leaf bones.+- **Roblox R15**: a fixed hierarchy and names (`LowerTorso`, `UpperTorso`, `LeftUpperArm`...), `Root > HumanoidRootNode > LowerTorso`, no weights on Root, ≤ 4 influences. Build it manually or from Roblox's Blender template rather than Rigify. Details are in `blender-export-pipelines/references/roblox.md`.++## Gotchas+- `rigify_generate` needs the metarig **selected and active** (`temp_override` isn't enough). The scripts handle this.+- "Bone Heat Weighting: failed to find solution" comes from non-manifold, intersecting parts or tiny scale. `bind_mesh.py` falls back to proxy. Fix the scale first.+- Meshes parented with "Keep Transform" but with unapplied scale get a double transform. Apply the scale before parenting.+- Modifier order: Armature should come **after** shape-key-like deforms and **before** Subdivision/Corrective Smooth (Corrective Smooth after Armature reduces collapsing).+- 5.0: `bone.select` is gone. Use `pose_bone.select` or `edit_bone.select`. `bone.hide` affects edit bones too.diff --git a/skills/blender-character-rigging/scripts/_bpyx.py b/skills/blender-character-rigging/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-character-rigging/scripts/_bpyx.py@@ -0,0 +1,136 @@+"""_bpyx - tiny shared helpers for blender-agent-skills scripts (Blender 5.2+).++Source of truth: shared/_bpyx.py. Copies in skills/*/scripts/ are synced by+tools/sync_shared.py - never edit a copy.++Every skill script follows one contract:+ run(**kwargs) -> dict # call from MCP / Python (import the module)+ blender -b f.blend -P x.py -- --arg v # CLI: prints one line "@@JSON@@{...}"+"""+import argparse+import json+import sys++import bpy++MARK = "@@JSON@@"+++def argv():+ """Arguments after '--' (Blender ignores them)."""+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def _default(o):+ if hasattr(o, "__len__") and not isinstance(o, str):+ try:+ return [round(v, 5) if isinstance(v, float) else v for v in o]+ except TypeError:+ pass+ if isinstance(o, (set, frozenset)):+ return sorted(o)+ return str(o)+++def emit(data):+ """Print compact JSON on one marked line (parsed by run_in_blender.py)."""+ print(MARK + json.dumps(data, separators=(",", ":"), default=_default), flush=True)+ return data+++def parser(doc):+ """ArgumentParser whose help is the script docstring's first line."""+ return argparse.ArgumentParser(description=(doc or "").strip().splitlines()[0])+++def cli(run, p):+ """CLI entry: parse args after '--', run, emit JSON. Exit 1 on failure."""+ args = p.parse_args(argv())+ try:+ result = run(**vars(args))+ save = getattr(args, "save", None)+ if save:+ bpy.ops.wm.save_as_mainfile(filepath=bpy.path.abspath(save))+ result["saved"] = save+ emit(result)+ except Exception as e: # report, don't dump a traceback into agent context+ emit({"ok": False, "error": f"{type(e).__name__}: {e}"})+ if bpy.app.background:+ sys.exit(1)+++def add_common(p, save=True):+ """--objects / --save flags shared by most scripts."""+ p.add_argument("--objects", nargs="*", default=None,+ help="object names (default: selected, else all meshes)")+ if save:+ p.add_argument("--save", default=None, help="save .blend to this path after run")+ return p+++def objects(names=None, types=("MESH",)):+ """Resolve names -> objects. No names: selected of `types`, else all visible of `types`."""+ if names:+ missing = [n for n in names if n not in bpy.data.objects]+ if missing:+ raise KeyError(f"objects not found: {missing}")+ return [bpy.data.objects[n] for n in names]+ pool = [o for o in bpy.context.scene.objects if not types or o.type in types]+ sel = [o for o in pool if o.select_get()]+ return sel or [o for o in pool if o.visible_get()]+++def object_mode():+ """Leave edit/sculpt/pose modes; most data API work needs OBJECT mode."""+ ob = bpy.context.view_layer.objects.active+ if ob and ob.mode != "OBJECT":+ bpy.ops.object.mode_set(mode="OBJECT")+++def select_only(objs, active=None):+ """Select exactly `objs` and make `active` (default first) active."""+ for o in bpy.context.view_layer.objects:+ o.select_set(False)+ for o in objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = active or (objs[0] if objs else None)+++def node(tree, type_):+ """First node of `type_` (e.g. 'BSDF_PRINCIPLED'). Names are localized - never look up by name."""+ return next((n for n in tree.nodes if n.type == type_), None)+++def enum_ids(owner, prop):+ """Valid identifiers of an enum property (works on types or instances)."""+ return [i.identifier for i in owner.bl_rna.properties[prop].enum_items]+++def set_enum(owner, prop, value):+ """Assign an enum; on failure raise listing valid values (dynamic enums under-report)."""+ try:+ setattr(owner, prop, value)+ except TypeError as e:+ raise ValueError(f"{prop}={value!r} invalid: {e}") from None+++def mesh_tris(ob, evaluated=True):+ """Triangle count (evaluated = with modifiers)."""+ if evaluated:+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ try:+ me.calc_loop_triangles()+ return len(me.loop_triangles)+ finally:+ eo.to_mesh_clear()+ me = ob.data+ me.calc_loop_triangles()+ return len(me.loop_triangles)+++def r(v, n=4):+ """Round a float or a vector for compact JSON."""+ if isinstance(v, float):+ return round(v, n)+ return [round(x, n) for x in v]diff --git a/skills/blender-character-rigging/scripts/bind_mesh.py b/skills/blender-character-rigging/scripts/bind_mesh.pynew file mode 100644index 0000000..fc5cb85--- /dev/null+++ b/skills/blender-character-rigging/scripts/bind_mesh.py@@ -0,0 +1,109 @@+"""Skin meshes to an armature with robust automatic weights, then clean them for engines.++Methods: auto (bone heat), proxy (voxel-remeshed manifold proxy gets heat weights, transferred+back - use for non-manifold/AI/kitbashed meshes or when heat fails), envelope, empty (groups only).+auto falls back to proxy when heat weighting leaves verts unweighted.+Cleanup: remove weights < --clean, limit to --limit influences, normalize.+Usage:+ blender -b f.blend -P bind_mesh.py -- --armature RIG --meshes Body Head [--method auto|proxy|envelope|empty]+ [--limit 4] [--clean 0.01] [--save out.blend]+ MCP: import bind_mesh; print(bind_mesh.run(armature="rig", meshes=["Body"]))+"""+import os+import sys++import bpy++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402+++def _ctx(ob):+ return bpy.context.temp_override(object=ob, active_object=ob, selected_objects=[ob],+ selected_editable_objects=[ob])+++def unweighted(me_ob, arm):+ deform = {b.name for b in arm.data.bones if b.use_deform}+ gi = {g.index for g in me_ob.vertex_groups if g.name in deform}+ return sum(1 for v in me_ob.data.vertices if not any(g.group in gi and g.weight > 1e-4 for g in v.groups))+++def _parent(meshes, arm, kind):+ bx.select_only(meshes + [arm], active=arm)+ return bpy.ops.object.parent_set(type=kind, keep_transform=True)+++def _proxy_weights(ob, arm):+ proxy = ob.copy()+ proxy.data = ob.data.copy()+ proxy.modifiers.clear()+ proxy.vertex_groups.clear()+ proxy.parent = None+ proxy.matrix_world = ob.matrix_world+ bpy.context.scene.collection.objects.link(proxy)+ bpy.context.view_layer.update()+ proxy.data.remesh_voxel_size = max(ob.dimensions) / 150+ with _ctx(proxy):+ bpy.ops.object.voxel_remesh()+ _parent([proxy], arm, "ARMATURE_AUTO")+ ob.vertex_groups.clear()+ dt = ob.modifiers.new("WeightTransfer", "DATA_TRANSFER")+ dt.object = proxy+ dt.use_vert_data = True+ dt.data_types_verts = {"VGROUP_WEIGHTS"}+ dt.vert_mapping = "POLYINTERP_NEAREST"+ dt.layers_vgroup_select_src = "ALL"+ dt.layers_vgroup_select_dst = "NAME"+ with _ctx(ob):+ bpy.ops.object.datalayout_transfer(modifier=dt.name)+ bpy.ops.object.modifier_move_to_index(modifier=dt.name, index=0)+ bpy.ops.object.modifier_apply(modifier=dt.name)+ bpy.data.objects.remove(proxy)+++def cleanup(ob, limit=4, clean=0.01):+ if not ob.vertex_groups:+ return+ with _ctx(ob):+ bpy.ops.object.vertex_group_clean(group_select_mode="ALL", limit=clean, keep_single=True)+ bpy.ops.object.vertex_group_limit_total(group_select_mode="ALL", limit=limit)+ bpy.ops.object.vertex_group_normalize_all(group_select_mode="ALL", lock_active=False)+++def run(armature=None, meshes=None, method="auto", limit=4, clean=0.01, **_):+ bx.object_mode()+ arm = bpy.data.objects[armature]+ obs = bx.objects(meshes)+ for ob in obs: # clean slate: remove previous armature mods / parent+ for m in [m for m in ob.modifiers if m.type == "ARMATURE"]:+ ob.modifiers.remove(m)+ report = {}+ if method in ("auto", "envelope", "empty"):+ kind = {"auto": "ARMATURE_AUTO", "envelope": "ARMATURE_ENVELOPE", "empty": "ARMATURE_NAME"}[method]+ _parent(obs, arm, kind)+ for ob in obs:+ used = method+ if method == "proxy" or (method == "auto" and unweighted(ob, arm) > 0.02 * len(ob.data.vertices)):+ used = "proxy"+ _proxy_weights(ob, arm)+ if not any(m.type == "ARMATURE" for m in ob.modifiers):+ _parent([ob], arm, "ARMATURE_NAME")+ if method != "empty":+ cleanup(ob, limit, clean)+ mx = max((sum(1 for g in v.groups if g.weight > 1e-4) for v in ob.data.vertices), default=0)+ report[ob.name] = {"method": used, "groups": len(ob.vertex_groups),+ "unweighted_verts": unweighted(ob, arm), "max_influences": mx}+ bx.select_only([arm])+ return {"ok": True, "armature": arm.name, "meshes": report}+++if __name__ == "__main__":+ p = bx.parser(__doc__)+ p.add_argument("--armature", required=True)+ p.add_argument("--meshes", nargs="*", default=None)+ p.add_argument("--method", default="auto", choices=["auto", "proxy", "envelope", "empty"])+ p.add_argument("--limit", type=int, default=4)+ p.add_argument("--clean", type=float, default=0.01)+ p.add_argument("--save", default=None)+ bx.cli(run, p)diff --git a/skills/blender-character-rigging/scripts/rig_check.py b/skills/blender-character-rigging/scripts/rig_check.pynew file mode 100644index 0000000..0f63aa5--- /dev/null+++ b/skills/blender-character-rigging/scripts/rig_check.py@@ -0,0 +1,181 @@+"""Validate a skeleton + its skinned meshes for animation/engine export; optional safe fixes.++Skeleton: applied transforms, single root at origin, zero-length bones, L/R pairs + mirrored+roll, deform count, constraints on deform bones (need baking), profile naming (roblox R15,+unity humanoid, unreal mannequin).+Skin: unweighted verts, >N influences, non-normalized, weights on non-deform/root bones,+groups without bones, L/R weight asymmetry.+Usage:+ blender -b f.blend -P rig_check.py -- --armature RIG [--meshes Body] [--profile game|roblox|unity|unreal]+ [--fix] [--limit 4] [--save out.blend]+ MCP: import rig_check; print(rig_check.run(armature="GAME_rig", profile="unity"))+"""+import os+import re+import sys++import bpy+from mathutils.kdtree import KDTree++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++R15 = ["LowerTorso", "UpperTorso", "Head", "LeftUpperArm", "LeftLowerArm", "LeftHand", "RightUpperArm",+ "RightLowerArm", "RightHand", "LeftUpperLeg", "LeftLowerLeg", "LeftFoot", "RightUpperLeg",+ "RightLowerLeg", "RightFoot"]+# Unity Humanoid required bones -> name patterns commonly seen (Rigify/Mixamo/UE/Blender)+HUMANOID = {+ "Hips": r"hips|pelvis$|^spine$|root_?hips", "Spine": r"spine(\.001|_01|1)?$|^spine$",+ "Head": r"head$", "LeftUpperLeg": r"(thigh|upleg|upperleg|upper_leg)[._]?l|left.?(up|upper).?leg",+ "LeftLowerLeg": r"(shin|calf|^leg|lowerleg|lower_leg)[._]?l|left.?(lower)?leg$",+ "LeftFoot": r"foot[._]?l|left.?foot", "RightUpperLeg": r"(thigh|upleg|upperleg|upper_leg)[._]?r|right.?(up|upper).?leg",+ "RightLowerLeg": r"(shin|calf|lowerleg|lower_leg)[._]?r|right.?(lower)?leg$",+ "RightFoot": r"foot[._]?r|right.?foot", "LeftUpperArm": r"(upper_?arm|upperarm|^arm)[._]?l|left.?arm",+ "LeftLowerArm": r"(forearm|lowerarm|lower_arm)[._]?l|left.?fore.?arm", "LeftHand": r"hand[._]?l|left.?hand",+ "RightUpperArm": r"(upper_?arm|upperarm|^arm)[._]?r|right.?arm",+ "RightLowerArm": r"(forearm|lowerarm|lower_arm)[._]?r|right.?fore.?arm", "RightHand": r"hand[._]?r|right.?hand",+}+UE = ["root", "pelvis", "spine_01", "spine_02", "spine_03", "neck_01", "head", "clavicle_l", "upperarm_l",+ "lowerarm_l", "hand_l", "clavicle_r", "upperarm_r", "lowerarm_r", "hand_r", "thigh_l", "calf_l",+ "foot_l", "ball_l", "thigh_r", "calf_r", "foot_r", "ball_r"]+++def _mirror(name):+ for a, b in ((".L", ".R"), ("_L", "_R"), (".l", ".r"), ("_l", "_r"), ("Left", "Right"), ("left", "right")):+ if a in name:+ return name.replace(a, b)+ if b in name:+ return name.replace(b, a)+ return None+++def run(armature=None, meshes=None, profile="game", fix=False, limit=4, **_):+ bx.object_mode()+ arm = bpy.data.objects[armature]+ bones = arm.data.bones+ errors, warnings = [], []+ if any(abs(s - 1) > 1e-4 for s in arm.scale) or any(abs(r) > 1e-4 for r in arm.rotation_euler):+ errors.append(f"armature object transform not applied (scale {tuple(arm.scale)}, rot {tuple(arm.rotation_euler)})")+ roots = [b for b in bones if b.parent is None]+ deform = [b for b in bones if b.use_deform]+ if len([b for b in roots if b.use_deform or b.children]) > 1:+ warnings.append(f"{len(roots)} root bones {[b.name for b in roots][:5]} - engines expect one hierarchy root")+ if roots and (arm.matrix_world @ roots[0].head_local).length > 1e-3:+ warnings.append(f"root bone '{roots[0].name}' not at world origin")+ zero = [b.name for b in bones if b.length < 1e-5]+ if zero:+ errors.append(f"zero-length bones: {zero[:10]}")+ unpaired, roll_bad = [], []+ for b in bones:+ m = _mirror(b.name)+ if m and m != b.name:+ if m not in bones:+ unpaired.append(b.name)+ if unpaired:+ warnings.append(f"L/R bones without mirror partner: {unpaired[:10]}")+ # mirrored roll check in edit mode data (z-axis of mirrored bones should mirror)+ for b in bones:+ m = _mirror(b.name)+ if m and m in bones and b.name < m:+ za, zb = b.z_axis, bones[m].z_axis+ if abs(za.x + zb.x) > 0.05 or abs(za.y - zb.y) > 0.05 or abs(za.z - zb.z) > 0.05:+ roll_bad.append(b.name)+ if roll_bad:+ warnings.append(f"asymmetric bone roll vs mirror: {roll_bad[:10]} (recalc roll / symmetrize)")+ constrained = [pb.name for pb in arm.pose.bones if pb.constraints and arm.data.bones[pb.name].use_deform]+ if constrained:+ warnings.append(f"{len(constrained)} deform bones have constraints - bake animation before export")+ names = [b.name for b in deform]+ prof = {}+ if profile == "roblox":+ missing = [n for n in R15 if n not in bones]+ prof["r15_missing"] = missing+ if missing:+ errors.append(f"R15 bones missing: {missing}")+ elif profile == "unity":+ mapped = {k: next((n for n in names if re.search(p, n, re.I)), None) for k, p in HUMANOID.items()}+ prof["humanoid_map"] = mapped+ miss = [k for k, v in mapped.items() if v is None]+ if miss:+ warnings.append(f"Humanoid auto-map may fail for: {miss} (map manually in Unity Avatar)")+ elif profile == "unreal":+ missing = [n for n in UE if n not in bones]+ prof["mannequin_missing"] = missing+ if missing:+ warnings.append(f"{len(missing)} UE mannequin names missing - IK Retargeter needs manual chains")+ if len(deform) > 300:+ warnings.append(f"{len(deform)} deform bones - heavy for games")++ skin = {}+ obs = bx.objects(meshes) if meshes else [o for o in bpy.data.objects if o.type == "MESH" and any(+ m.type == "ARMATURE" and m.object == arm for m in o.modifiers)]+ deform_names = {b.name for b in deform}+ root_names = {b.name for b in roots}+ for ob in obs:+ if fix:+ from bind_mesh import cleanup+ cleanup(ob, limit=limit, clean=0.001)+ for g in [g for g in ob.vertex_groups if g.name not in bones]:+ ob.vertex_groups.remove(g)+ gi = {g.index: g.name for g in ob.vertex_groups}+ unw = over = unnorm = on_root = on_nondeform = 0+ for v in ob.data.vertices:+ ws = [(gi.get(g.group), g.weight) for g in v.groups if g.weight > 1e-4]+ dws = [w for n, w in ws if n in deform_names]+ unw += not dws+ over += len(dws) > limit+ unnorm += bool(dws) and abs(sum(dws) - 1) > 0.01+ on_root += any(n in root_names for n, _ in ws)+ on_nondeform += any(n in bones and n not in deform_names for n, _ in ws)+ orphan_groups = [g.name for g in ob.vertex_groups if g.name not in bones]+ empty_deform = [n for n in deform_names if n not in ob.vertex_groups]+ # symmetry: weight of X at v vs mirrored group at mirrored vertex+ asym = 0+ kd = KDTree(len(ob.data.vertices))+ for v in ob.data.vertices:+ kd.insert(v.co, v.index)+ kd.balance()+ verts = ob.data.vertices+ for v in verts[:: max(1, len(verts) // 2000)]:+ co = v.co.copy()+ co.x = -co.x+ _, j, d = kd.find(co)+ if j is None or d > 1e-3 or v.co.x < 1e-4:+ continue+ a = {gi.get(g.group): g.weight for g in v.groups}+ b = {gi.get(g.group): g.weight for g in verts[j].groups}+ for n, w in a.items():+ m = _mirror(n) if n else None+ if m and abs(w - b.get(m, 0)) > 0.1:+ asym += 1+ break+ s = {"verts": len(verts), "unweighted": unw, f"over_{limit}": over, "not_normalized": unnorm,+ "weights_on_root": on_root, "weights_on_nondeform": on_nondeform,+ "groups_without_bone": orphan_groups[:10], "asymmetric_verts_sampled": asym,+ "deform_bones_without_group": len(empty_deform)}+ skin[ob.name] = s+ if unw:+ errors.append(f"{ob.name}: {unw} unweighted verts (they won't move)")+ if over:+ errors.append(f"{ob.name}: {over} verts > {limit} influences")+ if unnorm:+ warnings.append(f"{ob.name}: {unnorm} verts with weights not summing to 1")+ if on_root and profile == "roblox":+ errors.append(f"{ob.name}: {on_root} verts weighted to root (Roblox forbids)")+ if orphan_groups:+ warnings.append(f"{ob.name}: vertex groups without bones {orphan_groups[:5]}")+ if asym:+ warnings.append(f"{ob.name}: ~{asym} sampled verts with asymmetric L/R weights (mirror weights?)")+ return {"ok": True, "pass": not errors, "errors": errors, "warnings": warnings,+ "bones": len(bones), "deform_bones": len(deform), "profile": prof, "skin": skin, "fixed": fix}+++if __name__ == "__main__":+ p = bx.parser(__doc__)+ p.add_argument("--armature", required=True)+ p.add_argument("--meshes", nargs="*", default=None)+ p.add_argument("--profile", default="game", choices=["game", "roblox", "unity", "unreal"])+ p.add_argument("--fix", action="store_true")+ p.add_argument("--limit", type=int, default=4)+ p.add_argument("--save", default=None)+ bx.cli(run, p)diff --git a/skills/blender-character-rigging/scripts/rigify_build.py b/skills/blender-character-rigging/scripts/rigify_build.pynew file mode 100644index 0000000..c447509--- /dev/null+++ b/skills/blender-character-rigging/scripts/rigify_build.py@@ -0,0 +1,190 @@+"""Rigify pipeline: add + fit metarig, generate control rig, build an engine-ready game skeleton.++Steps (combine freely):+ --add TYPE add metarig (basic_human | human | basic_quadruped | horse | wolf | cat | bird | shark)+ --fit MESH scale/center the metarig to the mesh height (joint placement is still yours)+ --no-face remove the face rig from 'human' (games: use shape keys or a light face rig)+ --generate generate the control rig from --metarig (or the one just added)+ --game-skeleton build GAME_<rig>: clean hierarchy of root + DEF bones (prefix stripped),+ Copy Transforms to the control rig; re-targets skinned meshes to it.+Usage:+ blender -b f.blend -P rigify_build.py -- --add basic_human --fit Body --generate --game-skeleton [--save out.blend]+ MCP: import rigify_build as r; print(r.run(add="basic_human", fit="Body", generate=True))+After --add/--fit: place joints (edit bones) to the mesh, check with look (xray), then --generate.+"""+import os+import sys++import addon_utils+import bpy+from mathutils import Vector++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++ADD_OPS = {"basic_human": "armature_basic_human_metarig_add", "human": "armature_human_metarig_add",+ "basic_quadruped": "armature_basic_quadruped_metarig_add", "horse": "armature_horse_metarig_add",+ "wolf": "armature_wolf_metarig_add", "cat": "armature_cat_metarig_add",+ "bird": "armature_bird_metarig_add", "shark": "armature_shark_metarig_add"}+++def _ensure_rigify():+ if "rigify" not in bpy.context.preferences.addons:+ addon_utils.enable("rigify", default_set=True, persistent=False)+++def _bounds(ob):+ bpy.context.view_layer.update()+ pts = [ob.matrix_world @ Vector(c) for c in ob.bound_box]+ lo = Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts)))+ hi = Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts)))+ return lo, hi+++def _fit(meta, mesh):+ lo, hi = _bounds(mesh)+ ml, mh = _bounds(meta)+ s = (hi.z - lo.z) / max(mh.z - ml.z, 1e-6)+ meta.scale = (s, s, s)+ bpy.context.view_layer.update()+ ml, mh = _bounds(meta)+ meta.location += Vector(((lo.x + hi.x) / 2 - (ml.x + mh.x) / 2, (lo.y + hi.y) / 2 - (ml.y + mh.y) / 2,+ lo.z - ml.z))+ bx.select_only([meta])+ bpy.ops.object.transform_apply(location=False, rotation=True, scale=True)+ return round(s, 4)+++def _remove_face(meta):+ bx.select_only([meta])+ bpy.ops.object.mode_set(mode="EDIT")+ eb = meta.data.edit_bones+ face = eb.get("face")+ n = 0+ if face:+ for b in [face] + list(face.children_recursive):+ eb.remove(b)+ n += 1+ bpy.ops.object.mode_set(mode="OBJECT")+ return n+++def _generate(meta):+ _ensure_rigify()+ bx.select_only([meta])+ res = bpy.ops.pose.rigify_generate()+ if res != {"FINISHED"}:+ raise RuntimeError("rigify_generate failed (check metarig bone types / Rigify messages)")+ rig = meta.data.rigify_target_rig+ return rig+++def game_skeleton(rig, strip=True):+ """root + DEF bones with DEF-only parenting, constrained to the control rig."""+ name = f"GAME_{rig.name}"+ old = bpy.data.objects.get(name)+ if old:+ bpy.data.objects.remove(old)+ arm = bpy.data.armatures.new(name)+ gs = bpy.data.objects.new(name, arm)+ for c in rig.users_collection:+ c.objects.link(gs)+ gs.matrix_world = rig.matrix_world+ defs = [b for b in rig.data.bones if b.use_deform]+ names = {b.name for b in defs}++ def deform_parent(b):+ p = b.parent+ while p:+ if p.name in names and p.name != b.name:+ return p.name+ cand = "DEF-" + p.name[4:] if p.name.startswith(("ORG-", "MCH-")) else None+ if cand in names and cand != b.name:+ return cand+ p = p.parent+ return None++ new = (lambda n: n[4:] if strip and n.startswith("DEF-") else n)+ bx.select_only([gs])+ bpy.ops.object.mode_set(mode="EDIT")+ eb = arm.edit_bones+ root = eb.new("root")+ root.head, root.tail = (0, 0, 0), (0, 0.1 * max(rig.dimensions.z, 0.1), 0)+ root.use_deform = False+ for b in defs:+ e = eb.new(new(b.name))+ e.head, e.tail = b.head_local, b.tail_local+ e.matrix = b.matrix_local+ e.use_deform = True+ for b in defs:+ e = eb[new(b.name)]+ par = deform_parent(b)+ e.parent = eb[new(par)] if par else root+ e.use_connect = False+ bpy.ops.object.mode_set(mode="OBJECT")+ for b in defs:+ c = gs.pose.bones[new(b.name)].constraints.new("COPY_TRANSFORMS")+ c.target, c.subtarget = rig, b.name+ rc = gs.pose.bones["root"].constraints.new("COPY_TRANSFORMS")+ rc.target, rc.subtarget = rig, "root" if "root" in rig.pose.bones else ""+ # re-target skinned meshes+ moved = []+ for ob in bpy.data.objects:+ for m in ob.modifiers:+ if m.type == "ARMATURE" and m.object == rig:+ m.object = gs+ if strip:+ for g in ob.vertex_groups:+ if g.name.startswith("DEF-"):+ g.name = g.name[4:]+ if ob.parent == rig:+ mw = ob.matrix_world.copy()+ ob.parent = gs+ ob.matrix_world = mw+ moved.append(ob.name)+ return gs, len(defs), moved+++def run(add=None, metarig=None, fit=None, no_face=False, generate=False, game_skel=False,+ rig=None, strip_prefix=True, **_):+ bx.object_mode()+ _ensure_rigify()+ out = {"ok": True}+ meta = bpy.data.objects[metarig] if metarig else None+ if add:+ getattr(bpy.ops.object, ADD_OPS[add])()+ meta = bpy.context.view_layer.objects.active+ meta.name = f"META_{fit}" if fit else "metarig"+ out["metarig"] = meta.name+ if fit and meta:+ out["fit_scale"] = _fit(meta, bpy.data.objects[fit])+ if no_face and meta:+ out["face_bones_removed"] = _remove_face(meta)+ if generate:+ if meta is None:+ raise ValueError("--generate needs --metarig or --add")+ r = _generate(meta)+ r.name = f"RIG_{fit}" if fit else r.name+ meta.hide_set(True)+ out["rig"] = r.name+ out["bones"] = len(r.data.bones)+ out["deform_bones"] = sum(b.use_deform for b in r.data.bones)+ rig = r.name+ if game_skel:+ gs, n, moved = game_skeleton(bpy.data.objects[rig], strip_prefix)+ out["game_skeleton"] = {"name": gs.name, "bones": n + 1, "retargeted_meshes": moved}+ return out+++if __name__ == "__main__":+ p = bx.parser(__doc__)+ p.add_argument("--add", choices=list(ADD_OPS), default=None)+ p.add_argument("--metarig", default=None)+ p.add_argument("--fit", default=None, help="mesh to fit the metarig to")+ p.add_argument("--no-face", action="store_true")+ p.add_argument("--generate", action="store_true")+ p.add_argument("--game-skeleton", dest="game_skel", action="store_true")+ p.add_argument("--rig", default=None, help="existing generated rig (for --game-skeleton)")+ p.add_argument("--keep-prefix", dest="strip_prefix", action="store_false")+ p.add_argument("--save", default=None)+ bx.cli(run, p)diff --git a/skills/blender-character-rigging/scripts/stress_poses.py b/skills/blender-character-rigging/scripts/stress_poses.pynew file mode 100644index 0000000..df67d29--- /dev/null+++ b/skills/blender-character-rigging/scripts/stress_poses.py@@ -0,0 +1,127 @@+"""Create a QA_Stress action with extreme poses to review deformation (elbows, knees, shoulders, hips, spine, neck).++Works on Rigify control rigs (poses FK controls, switches IK->FK) and plain/game skeletons+(Rigify DEF/game names, Mixamo, UE, Roblox R15). Character must face -Y, Z up.+Frames: 1 rest | 10 arms raised | 20 elbows 130 + arms forward | 30 hip flex + knee 120 (L)+ | 40 crouch | 50 spine twist + head turn.+Usage:+ blender -b f.blend -P stress_poses.py -- --armature RIG [--save out.blend]+ then: MCP look(mode="frames", frames=[1,10,20,30,40,50]) or render the frames; remove with --clear.+ MCP: import stress_poses; print(stress_poses.run(armature="RIG"))+"""+import math+import os+import re+import sys++import bpy+from mathutils import Matrix, Vector++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++ROLES = { # role -> regex (searched in order of preference: fk controls first)+ "upper_arm": r"^(upper_arm_fk|upper_arm|upperarm|arm|leftarm|rightarm|(left|right)upperarm|mixamorig:(left|right)arm)",+ "forearm": r"^(forearm_fk|forearm|lowerarm|(left|right)lowerarm|(left|right)forearm|mixamorig:(left|right)forearm)",+ "thigh": r"^(thigh_fk|thigh|upperleg|upleg|(left|right)upperleg|(left|right)upleg|mixamorig:(left|right)upleg)",+ "shin": r"^(shin_fk|shin|calf|lowerleg|leg|(left|right)lowerleg|(left|right)leg|mixamorig:(left|right)leg)",+ "spine": r"^(torso|spine_fk\.001|spine\.002|spine_02|spine2|uppertorso|mixamorig:spine1)$",+ "head": r"^(head|mixamorig:head)$",+}+++def _side(name):+ n = name.lower()+ if re.search(r"(\.l$|_l$|\.l\.|left)", n):+ return "L"+ if re.search(r"(\.r$|_r$|\.r\.|right)", n):+ return "R"+ return None+++def _find(arm, role, side=None):+ pat = re.compile(ROLES[role], re.I)+ cands = []+ for pb in arm.pose.bones:+ base = re.sub(r"^(def-|org-|mch-)", "", pb.name, flags=re.I)+ base = re.sub(r"[._]?(l|r)(\.\d+)?$", "", base, flags=re.I) if role not in ("spine", "head") else base+ if pat.match(base) and (side is None or _side(pb.name) == side):+ if pb.name.lower().startswith(("mch-", "org-")):+ continue+ cands.append(pb)+ cands.sort(key=lambda p: (0 if "_fk" in p.name else 1, p.name.lower().startswith("def-"), len(p.name)))+ return cands[0] if cands else None+++def _rotate(arm, pb, axis, deg):+ """Rotate a pose bone about a WORLD axis through its head (rig-agnostic: ignores bone roll)."""+ bpy.context.view_layer.update()+ head = pb.head.copy()+ R = Matrix.Rotation(math.radians(deg), 4, Vector(axis))+ pb.matrix = Matrix.Translation(head) @ R @ Matrix.Translation(-head) @ pb.matrix+ bpy.context.view_layer.update()+++POSES = { # frame -> list of (role, side, world axis, degrees); L side is +X when facing -Y+ 1: [],+ 10: [("upper_arm", "L", (0, 1, 0), -70), ("upper_arm", "R", (0, 1, 0), 70)],+ 20: [("upper_arm", "L", (0, 0, 1), -60), ("upper_arm", "R", (0, 0, 1), 60),+ ("forearm", "L", (0, 0, 1), -130), ("forearm", "R", (0, 0, 1), 130)],+ 30: [("thigh", "L", (1, 0, 0), -90), ("shin", "L", (1, 0, 0), 120)],+ 40: [("thigh", "L", (1, 0, 0), -100), ("thigh", "R", (1, 0, 0), -100),+ ("shin", "L", (1, 0, 0), 130), ("shin", "R", (1, 0, 0), 130)],+ 50: [("spine", None, (0, 0, 1), 45), ("head", None, (0, 0, 1), 70)],+}+++def run(armature=None, clear=False, **_):+ bx.object_mode()+ arm = bpy.data.objects[armature]+ act = bpy.data.actions.get("QA_Stress")+ if clear:+ if act:+ bpy.data.actions.remove(act)+ for pb in arm.pose.bones:+ pb.matrix_basis = Matrix()+ return {"ok": True, "cleared": True}+ for pb in arm.pose.bones: # Rigify: switch limbs to FK so FK controls drive the pose+ for k in ("IK_FK",):+ if k in pb.keys():+ pb[k] = 1.0+ if act:+ bpy.data.actions.remove(act)+ arm.animation_data_create()+ act = bpy.data.actions.new("QA_Stress")+ arm.animation_data.action = act+ found = {}+ bx.select_only([arm])+ bpy.ops.object.mode_set(mode="POSE")+ try:+ for frame, ops in POSES.items():+ bpy.context.scene.frame_set(frame)+ for pb in arm.pose.bones:+ pb.matrix_basis = Matrix()+ for role, side, axis, deg in ops:+ pb = _find(arm, role, side)+ key = f"{role}.{side}" if side else role+ found[key] = pb.name if pb else None+ if pb:+ _rotate(arm, pb, axis, deg)+ for pb in arm.pose.bones:+ for path in ("location", "rotation_quaternion", "rotation_euler", "scale"):+ pb.keyframe_insert(path, frame=frame)+ finally:+ bpy.ops.object.mode_set(mode="OBJECT")+ sc = bpy.context.scene+ sc.frame_start, sc.frame_end = 1, 50+ missing = [k for k, v in found.items() if v is None]+ return {"ok": True, "action": act.name, "frames": list(POSES), "bones_used": found,+ "missing_roles": missing}+++if __name__ == "__main__":+ p = bx.parser(__doc__)+ p.add_argument("--armature", required=True)+ p.add_argument("--clear", action="store_true")+ p.add_argument("--save", default=None)+ bx.cli(run, p)diff --git a/skills/blender-core/SKILL.md b/skills/blender-core/SKILL.mdnew file mode 100644index 0000000..6a432e6--- /dev/null+++ b/skills/blender-core/SKILL.md@@ -0,0 +1,78 @@+---+name: blender-core+description: Foundation for any Blender 5.2+ task an agent drives - running bpy via MCP (live) or headless CLI, context overrides, locale-safe node lookup, enum discovery, 5.x API changes, verification. Use first for any Blender, bpy, .blend or 3D-asset request; routes to the specialized blender-* skills.+license: MIT+compatibility: Blender 5.2 LTS or newer. Optional blender-mcp server for live sessions.+metadata:+ author: blender-agent-skills+ version: "0.1.0"+---++# Blender Core (5.2 LTS+)++## Route to the specialized skill+| Task | Skill |+|---|---|+| Units, collections, naming, linking, asset libraries | `blender-scene-setup` |+| Hard-surface modeling, bevels, booleans, normals | `blender-hardsurface-modeling` |+| Sculpting, multires, remesh | `blender-sculpting` |+| Retopology, UV unwrap, texel density | `blender-retopology-uv` |+| PBR materials, color spaces, texture sets | `blender-pbr-materials` |+| Baking high→low maps (normal, AO, curvature, ...) | `blender-texture-baking` |+| Geometry Nodes, procedural modeling | `blender-geometry-nodes` |+| Body rigging, Rigify, weight painting | `blender-character-rigging` |+| Face rig, shape keys, ARKit, visemes | `blender-facial-shapekeys` |+| Keyframes, actions, NLA, baking, root motion | `blender-animation` |+| Poly budgets, LODs, draw calls, cleanup | `blender-game-optimization` |+| Export: glTF/FBX/USD to Roblox, Unity, Unreal, Godot, web | `blender-export-pipelines` |+| Cycles/EEVEE settings, compositor, batch render | `blender-rendering` |+| Lighting, HDRI, camera, turntable | `blender-lighting-lookdev` |+| Cloth, rigid body, fluids, hair, GN physics | `blender-simulation` |+| Writing add-ons / extensions | `blender-addon-development` |+| Batch/headless pipelines, file conversion | `blender-pipeline-automation` |+| Checking a mesh/asset before delivery (always) | `blender-asset-qa` |+| End-to-end playbooks (prop, character, Roblox, product shot) | `blender-workflow-recipes` |++## Execute+**Live (blender-mcp `execute_blender_code`)**: work in small steps and print only what you need. To call a skill script, import it:+```python+import sys, importlib; sys.path.insert(0, r"<skills_dir>/blender-asset-qa/scripts")+import qa_check; importlib.reload(qa_check); print(qa_check.run(objects=["Chair"]))+```+Each MCP call runs in a **fresh namespace**: re-`import` in every call. That's cheap because modules stay cached in `sys.modules`. `reload` only after editing a script.+**Headless (any agent with a shell)**: this prints only the script's JSON (`@@JSON@@` lines):+```+python <skills_dir>/blender-core/scripts/run_in_blender.py --blend in.blend <script.py> -- --objects Chair --save out.blend+python <skills_dir>/blender-core/scripts/run_in_blender.py --expr "import bpy; print(len(bpy.data.objects))"+```+Raw form: `blender -b in.blend --factory-startup --python-exit-code 1 -P x.py -- args`. Every script here exposes `run(**kw) -> dict` and the same flags after `--`.+**First call in a session**: `scripts/env_report.py`, which returns the version, engines, GPU, add-ons, units, color management and scene counts.++## Rules+- **Data API over operators**: use `bpy.data`, `bmesh`, `mesh.attributes`, and `foreach_get/set` with numpy. Operators depend on context and selection, and many need a 3D View, which background mode doesn't have.+- If an operator is unavoidable: `with bpy.context.temp_override(object=ob, active_object=ob, selected_objects=[ob], selected_editable_objects=[ob]): bpy.ops...`. Check that the result is `{'FINISHED'}`.+- **Edit mode isolation**: `ob.data` isn't updated while in Edit Mode. Use `bmesh.from_edit_mesh` + `bmesh.update_edit_mesh`, or switch to OBJECT mode before reading.+- **Nodes**: find them by `type` (`n.type == "BSDF_PRINCIPLED"`), never by `name`, because names are localized. Sockets by English name or `identifier` are fine.+- **Enums**: read the valid values with `[i.identifier for i in T.bl_rna.properties[p].enum_items]`. Dynamic enums (`render.engine`, `view_transform`, `look`) under-report, so assign them inside `try/except TypeError` (the message lists the valid values).+- **Engines**: `BLENDER_EEVEE`, `CYCLES`, `BLENDER_WORKBENCH`. Cycles device: `scene.cycles.device = "GPU"` + preferences `compute_device_type`.+- **Evaluated data**: use `ob.evaluated_get(depsgraph)`, then `.to_mesh()`, then always `.to_mesh_clear()`. Call `view_layer.update()` before reading `matrix_world` after a change.+- **Freed data**: applying or removing a modifier, or removing an object or ID, frees it. Collect names first (`[m.name for m in ob.modifiers]`) and never touch the old Python reference afterward, because it returns garbage or crashes.+- **Never trust default names** ("Cube.001"). Keep object references, rename explicitly, and look objects up via `bpy.data.objects[name]`.+- **Scale**: 1 unit = 1 m. Apply rotation/scale (`transform_apply`) before bevels, modifiers with distances, rigging, physics, baking and export.+- **Paths**: `bpy.path.abspath("//textures/x.png")` resolves relative to the .blend. Save explicitly; use `save_as_mainfile(filepath=..., copy=True)` for backups.+- **Live sessions are the user's work**: never `read_factory_settings`, never delete data you didn't create, and save a backup copy before destructive batch edits.+- **GPU module in background**: call `gpu.init()` first (5.2+). `bgl` no longer exists.+- **Big meshes**: no per-vertex `bpy.ops`. Use numpy `foreach_get` (see references/bpy-patterns.md).++## 5.x API changes that break old tutorials/LLM memory+`action.fcurves` → channelbags · `scene.node_tree` → `scene.compositing_node_group` · `material.use_nodes` is deprecated (new materials already have nodes) · `mod["Socket_2"]` → `mod.properties.inputs.Socket_2.value` (5.2) · `BLENDER_EEVEE_NEXT` → `BLENDER_EEVEE` · Boolean `FAST` → `FLOAT` · bone layers → bone collections · `bl_info` add-ons → extensions (`blender_manifest.toml`) · `bpy.props` values are no longer dict-accessible (`scene["cycles"]`). Full table: [references/api-changes-5x.md](references/api-changes-5x.md).++## Verify (required before saying "done")+1. Numbers, not adjectives: report tris, objects, materials, dimensions (`ob.dimensions`) and the output files written.+2. Geometry changed → run `blender-asset-qa` `qa_check.py` (z-fighting, detached parts, non-manifold, flipped normals, scale).+3. Look at it: MCP `look` (`mode="angles"`, shading `material`/`wireframe`). Headless: `blender-asset-qa/scripts/review_shots.py` renders contact sheets.+4. Re-read your own output: confirm that exported files exist and that their size is non-zero.++## References+- [references/api-changes-5x.md](references/api-changes-5x.md): 4.x→5.2 migration table. Load it when code fails with AttributeError/KeyError.+- [references/bpy-patterns.md](references/bpy-patterns.md): verified snippets for bmesh, attributes, numpy, temp_override, depsgraph, drivers, append/link, handlers and timers.diff --git a/skills/blender-core/references/api-changes-5x.md b/skills/blender-core/references/api-changes-5x.mdnew file mode 100644index 0000000..dd6df3b--- /dev/null+++ b/skills/blender-core/references/api-changes-5x.md@@ -0,0 +1,88 @@+# bpy migration: 4.x → 5.2 (what LLM memory / old tutorials get wrong)++Each row was verified against Blender 5.2.2. Format: **old → new** (version).++## Core / properties+| Old | New |+|---|---|+| `scene["cycles"]`, dict access to `bpy.props` values | attribute access only; ID-props and RNA props are separate (5.0) |+| `bpy.props` `get` without `set` for read-only | `options={'READ_ONLY'}`; `set` without `get` is an error (5.0) |+| `get_transform`/`set_transform` | new prop callbacks that keep default storage (5.0) |+| user site-packages auto-loaded | no longer loaded by default (5.1) |+| Python 3.11 | Python 3.13 (5.1) |+| — | `bpy.data.all_ids` iterates over every ID (5.2) |+| — | `gpu.init()` required for `gpu` in `--background` (5.2) |+| IDProperty nesting unlimited | capped at 1024 levels (5.2) |+| mathutils float64 buffers | float32 buffers; numpy views are non-contiguous (5.0) |++## Mesh / modeling+| Old | New |+|---|---|+| `mesh.use_auto_smooth`, `auto_smooth_angle` | removed (4.1). Use `bpy.ops.object.shade_smooth_by_angle(angle=…)` or the "Smooth by Angle" modifier asset (`shade_auto_smooth`) |+| `mesh.calc_normals_split()`, `loop.normal` | `mesh.corner_normals` (read-only), `mesh.normals_domain` (4.1) |+| custom normals need auto smooth | they work directly: `mesh.normals_split_custom_set(...)` (4.1) |+| face maps | removed. Use a boolean face attribute (4.0) |+| Boolean solver `FAST` | `FLOAT`. Solvers: `EXACT` (default), `FLOAT`, `MANIFOLD` (4.5+) (5.0) |+| per-UV-map selection, `BMLoopUV.select*` | shared `.uv_select_*` attributes; `bm.uv_select_flush()` etc. (5.0) |+| UV pin auto-creates attribute | use the `*_ensure()` functions (5.0) |+| `brush.sculpt_tool` | `brush.sculpt_brush_type` (5.0); brushes are assets (4.3) |+| `tool_settings.unified_paint_settings` | `tool_settings.sculpt.unified_paint_settings` (mode-specific) (5.0) |+| radial symmetry on tool settings | `mesh.radial_symmetry` (5.0) |+| `brush.use_airbrush/use_anchor/use_space/...` | `brush.stroke_method` enum (5.1) |+| `brush.use_automasking_*`, `automasking_*` | `brush.mesh_automasking_settings.*` (5.2) |++## Nodes+| Old | New |+|---|---|+| `ng.inputs.new()` / `ng.outputs.new()` | `ng.interface.new_socket(name, in_out='INPUT', socket_type='NodeSocketFloat')` (4.0) |+| `mod["Socket_2"] = 1.0`, `mod["Socket_2_use_attribute"]` | `mod.properties.inputs.Socket_2.value = 1.0`; `.type = "ATTRIBUTE"`; `.attribute_name` (5.2). Use `getattr(mod.properties.inputs, sock.identifier)` |+| Compare / Random Value socket identifiers | changed (5.2): look up by name, not identifier |+| `scene.node_tree`, `scene.use_nodes = True` | `scene.compositing_node_group = bpy.data.node_groups.new(n, "CompositorNodeTree")` (5.0) |+| `material.use_nodes = True` | deprecated (5.0). New materials already have Principled + Output. Same for `world.use_nodes` |+| File Output `base_path`, `file_slots`, `layer_slots` | `directory`, `file_name`, `file_output_items` (5.0) |+| `CompositorNodeGamma`, `...MixRGB`, etc. | shader-node equivalents (`ShaderNodeGamma`, `ShaderNodeMix`) (5.0) |+| Color node output "RGBA" | "Color" (5.0) |+| Principled `Subsurface`, `Specular`, `Transmission`, `Coat`/`Clearcoat`, `Sheen`, `Emission` | `Subsurface Weight`, `Specular IOR Level`, `Transmission Weight`, `Coat Weight`, `Sheen Weight`, `Emission Color` (4.0) |+| — | Principled `Thin Wall` input (5.2); `Diffuse Roughness`, `Thin Film Thickness/IOR` (4.2–4.3) |+| `SpaceNodeEditor.geometry_nodes_type` | `node_tree_sub_type` (5.0) |+| Point Density texture node | removed (5.0) |++## Materials / rendering+| Old | New |+|---|---|+| engine `BLENDER_EEVEE_NEXT` (4.2–4.5) | `BLENDER_EEVEE` (5.0) |+| `material.blend_method`, `shadow_method` | `material.surface_render_method` = `DITHERED` / `BLENDED`; `shadow_method` removed (4.2). Use `visible_shadow` on the object |+| `scene.eevee.use_gtao`, `gtao_distance` | removed; `view_layer.eevee.ambient_occlusion_distance` (5.0) |+| render pass names `DiffCol`, `Z`, ... | `Diffuse Color`, `Depth`, ... (5.0) |+| `image_settings.file_format = "FFMPEG"` alone | set `image_settings.media_type` (`IMAGE`/`MULTI_LAYER_IMAGE`/`VIDEO`) **before** `file_format` (5.0) |+| Filmic default | AgX default (4.0). Views: Standard, AgX, Khronos PBR Neutral, ACES 1.3/2.0, Filmic, ... |+| — | Cycles texture cache: `scene.render.use_texture_cache`, `use_auto_generate_texture_cache` (.tx) (5.2) |+| `bgl`, `Image.bindcode`, GLSL-source shaders | `gpu` module, `gpu.texture.from_image()` (5.0) |++## Animation / rigging+| Old | New |+|---|---|+| `action.fcurves`, `action.groups`, `action.id_root` | slotted/layered actions. `cb = anim_utils.action_ensure_channelbag_for_slot(action, slot)` → `cb.fcurves.new/ensure/find`, `cb.groups`; `slot.target_id_type` (removed in 5.0; slots since 4.4) |+| `fcurves.new(path, index, action_group)` | `cb.fcurves.new(path, index=0, group_name="")` |+| assigning `animation_data.action` was enough | also set/check `animation_data.action_slot` (auto-picked on assign if suitable) |+| `ANIM_OT_convert_legacy_action` | removed. All actions are layered (5.1) |+| `armature.layers`, `bone.layers`, bone groups | bone collections: `arm.collections.new("FK")`, `bcoll.assign(bone)`, `bone.color.palette`, `pose_bone.color` (4.0) |+| `bone.select`, `select_head/tail` | removed from Bone; use `pose_bone.select` / `edit_bone.select*` (5.0) |+| `context.space_data.action` | removed (5.0) |++## Add-ons / UI / misc+| Old | New |+|---|---|+| `bl_info` dict add-on | extension with `blender_manifest.toml` (4.2). Legacy add-ons still load |+| `UILayout.template_list(columns=)` | no effect (deprecated 5.1) |+| `UIList.layout_type = "GRID"` | removed (5.0) |+| `AssetHandle`, `context.active_file` (asset shelf) | `AssetRepresentation`, `context.asset` (5.0) |+| `GPencilStroke`, `scene.grease_pencil` (annotations) | `AnnotationStroke`, `scene.annotation` (5.0) |+| `GreasePencilv3`, `bpy.data.grease_pencils_v3` | `GreasePencil`, `bpy.data.grease_pencils` (5.0) |+| VSE `frame_final_start/end/duration` | `left_handle`, `right_handle`, `duration` (5.1; old names deprecated) |+| VSE uses `context.scene` | `context.sequencer_scene` (5.0) |+| USD export `export_textures`, `visible_objects_only` | removed (5.0) |+| `PreferencesFilePaths.active_asset_library` index == `asset_libraries` index | offset: list starts with "All Libraries", "Essentials" (5.2) |+| log output format | changed (5.0). Don't regex-parse the render progress |++When something is missing: `dir(obj)`, `T.bl_rna.properties.keys()`, `T.bl_rna.functions.keys()`, or `op.get_rna_type().properties` show the truth faster than docs.diff --git a/skills/blender-core/references/bpy-patterns.md b/skills/blender-core/references/bpy-patterns.mdnew file mode 100644index 0000000..9d5489d--- /dev/null+++ b/skills/blender-core/references/bpy-patterns.md@@ -0,0 +1,187 @@+# bpy patterns (Blender 5.2, each block runs standalone; CI executes them)++## Create a mesh from data (fastest, no operators)+```python+import bpy+verts = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)]+me = bpy.data.meshes.new("Quad")+me.from_pydata(verts, [], [(0, 1, 2, 3)])+me.validate(); me.update()+ob = bpy.data.objects.new("Quad", me)+bpy.context.scene.collection.objects.link(ob)+```++## bmesh edit (object mode) and write back+```python+import bpy, bmesh+me = bpy.data.meshes.new("BM"); ob = bpy.data.objects.new("BM", me)+bpy.context.scene.collection.objects.link(ob)+bm = bmesh.new()+bmesh.ops.create_cube(bm, size=1.0)+bmesh.ops.bevel(bm, geom=bm.edges[:], offset=0.05, segments=2, affect="EDGES", profile=0.5)+bmesh.ops.remove_doubles(bm, verts=bm.verts[:], dist=1e-5)+bm.to_mesh(me); bm.free()+```+In Edit Mode use `bm = bmesh.from_edit_mesh(me)` … `bmesh.update_edit_mesh(me)` and don't free it.++## numpy bulk read/write (100x faster than Python loops)+```python+import bpy, numpy as np+me = bpy.data.meshes.new("NP"); me.from_pydata([(0,0,0),(1,0,0),(0,1,0)], [], [(0,1,2)])+co = np.empty(len(me.vertices) * 3, dtype=np.float32)+me.vertices.foreach_get("co", co)+co = co.reshape(-1, 3); co[:, 2] += 0.5+me.vertices.foreach_set("co", co.ravel()); me.update()+```++## Generic attributes (float/int/bool/color on any domain)+```python+import bpy+me = bpy.data.meshes.new("Attr"); me.from_pydata([(0,0,0),(1,0,0),(0,1,0)], [], [(0,1,2)])+a = me.attributes.get("mask") or me.attributes.new("mask", "FLOAT", "POINT")+a.data.foreach_set("value", [0.0, 0.5, 1.0])+col = me.color_attributes.new("Col", "BYTE_COLOR", "CORNER")+me.color_attributes.active_color = col+```++## Operator with context override (works headless)+```python+import bpy+me = bpy.data.meshes.new("Ov"); me.from_pydata([(0,0,0),(1,0,0),(0,1,0)], [], [(0,1,2)])+ob = bpy.data.objects.new("Ov", me); bpy.context.scene.collection.objects.link(ob)+ob.modifiers.new("Weld", "WELD")+with bpy.context.temp_override(object=ob, active_object=ob, selected_objects=[ob],+ selected_editable_objects=[ob]):+ assert bpy.ops.object.modifier_apply(modifier="Weld") == {"FINISHED"}+```++## Evaluated mesh (modifiers applied) without changing the object+```python+import bpy+me = bpy.data.meshes.new("Ev"); me.from_pydata([(0,0,0),(1,0,0),(0,1,0)], [], [(0,1,2)])+ob = bpy.data.objects.new("Ev", me); bpy.context.scene.collection.objects.link(ob)+ob.modifiers.new("Sub", "SUBSURF").levels = 2+dg = bpy.context.evaluated_depsgraph_get()+eo = ob.evaluated_get(dg); tmp = eo.to_mesh()+n_faces = len(tmp.polygons)+eo.to_mesh_clear()+baked = bpy.data.meshes.new_from_object(eo) # persistent copy, if you need one+```++## Materials: find nodes by type, link textures+```python+import bpy+mat = bpy.data.materials.new("M") # already has Principled + Output (5.0+)+nt = mat.node_tree+bsdf = next(n for n in nt.nodes if n.type == "BSDF_PRINCIPLED")+tex = nt.nodes.new("ShaderNodeTexImage")+tex.image = bpy.data.images.new("Base", 64, 64)+tex.image.colorspace_settings.name = "sRGB" # data maps: "Non-Color"+nt.links.new(tex.outputs["Color"], bsdf.inputs["Base Color"])+bsdf.inputs["Roughness"].default_value = 0.6+```++## Geometry Nodes modifier inputs (5.2 RNA API)+```python+import bpy+ng = bpy.data.node_groups.new("GN", "GeometryNodeTree")+ng.interface.new_socket("Geometry", in_out="INPUT", socket_type="NodeSocketGeometry")+ng.interface.new_socket("Geometry", in_out="OUTPUT", socket_type="NodeSocketGeometry")+sock = ng.interface.new_socket("Scale", in_out="INPUT", socket_type="NodeSocketFloat")+gi, go = ng.nodes.new("NodeGroupInput"), ng.nodes.new("NodeGroupOutput")+ng.links.new(gi.outputs["Geometry"], go.inputs["Geometry"])+me = bpy.data.meshes.new("G"); ob = bpy.data.objects.new("G", me)+bpy.context.scene.collection.objects.link(ob)+mod = ob.modifiers.new("GN", "NODES"); mod.node_group = ng+getattr(mod.properties.inputs, sock.identifier).value = 2.0+```++## Keyframes with slotted actions (5.0+)+```python+import bpy+from bpy_extras import anim_utils+ob = bpy.data.objects.new("Anim", None); bpy.context.scene.collection.objects.link(ob)+act = bpy.data.actions.new("Anim_Move")+ob.animation_data_create(); ob.animation_data.action = act+slot = ob.animation_data.action_slot or act.slots.new(id_type="OBJECT", name=ob.name)+ob.animation_data.action_slot = slot+cb = anim_utils.action_ensure_channelbag_for_slot(act, slot)+for i in range(3):+ fc = cb.fcurves.ensure("location", index=i, group_name="Object Transforms")+ fc.keyframe_points.insert(1, 0.0); fc.keyframe_points.insert(24, 2.0 if i == 0 else 0.0)+```+The simple route works too: `ob.keyframe_insert("location", frame=1)` creates the action and slot.++## Drivers+```python+import bpy+ob = bpy.data.objects.new("Drv", None); bpy.context.scene.collection.objects.link(ob)+ctl = bpy.data.objects.new("Ctl", None); bpy.context.scene.collection.objects.link(ctl)+fc = ob.driver_add("location", 2)+d = fc.driver; d.type = "SCRIPTED"+v = d.variables.new(); v.name = "x"; v.type = "TRANSFORMS"+v.targets[0].id = ctl; v.targets[0].transform_type = "LOC_X"; v.targets[0].transform_space = "LOCAL_SPACE"+d.expression = "x * 0.5"+```+Prefer simple expressions (`var`, `x*0.5`, `max(a,b)`), which run without Python auto-exec. Use `d.type="SUM"/"AVERAGE"` when possible.++## Append / link from another .blend+```python+import bpy, os, tempfile+src = os.path.join(tempfile.gettempdir(), "bas_lib.blend")+bpy.data.materials.new("LibMat").use_fake_user = True+bpy.data.libraries.write(src, {bpy.data.materials["LibMat"]}, fake_user=True)+with bpy.data.libraries.load(src, link=False) as (data_from, data_to): # link=True to link+ data_to.materials = [n for n in data_from.materials if n == "LibMat"]+```+Linked objects need a library override to be edited: `ob.override_hierarchy_create(scene, view_layer)`.++## Collections and safe naming+```python+import bpy+def ensure_collection(name, parent=None):+ col = bpy.data.collections.get(name) or bpy.data.collections.new(name)+ parent = parent or bpy.context.scene.collection+ if col.name not in parent.children:+ parent.children.link(col)+ return col+ob = bpy.data.objects.new("SM_Crate", None)+ensure_collection("Export").objects.link(ob)+```++## Apply transforms without selection juggling+```python+import bpy+from mathutils import Matrix+me = bpy.data.meshes.new("T"); me.from_pydata([(0,0,0),(1,0,0),(0,1,0)], [], [(0,1,2)])+ob = bpy.data.objects.new("T", me); bpy.context.scene.collection.objects.link(ob)+ob.scale = (2, 2, 2); ob.rotation_euler = (0, 0, 1.0)+bpy.context.view_layer.update()+loc, rot, sca = ob.matrix_basis.decompose()+ob.data.transform(Matrix.LocRotScale(None, rot, sca)) # bake rot+scale into mesh+ob.matrix_basis = Matrix.Translation(loc)+```+For multi-user mesh data, call `ob.data = ob.data.copy()` first, or every user gets transformed.++## Handlers and timers (live sessions / add-ons)+```python+import bpy+def on_frame(scene, depsgraph=None):+ pass+bpy.app.handlers.frame_change_post.append(on_frame)+bpy.app.handlers.frame_change_post.remove(on_frame)+bpy.app.timers.register(lambda: None, first_interval=0.5) # return float to repeat, None to stop+```++## Render a still headless+```python+import bpy, os, tempfile+sc = bpy.context.scene+sc.render.engine = "BLENDER_WORKBENCH"+sc.render.resolution_x = sc.render.resolution_y = 64+sc.render.image_settings.media_type = "IMAGE"; sc.render.image_settings.file_format = "PNG"+cam = bpy.data.objects.new("Cam", bpy.data.cameras.new("Cam")); sc.collection.objects.link(cam)+cam.location = (0, -5, 0); cam.rotation_euler = (1.5708, 0, 0); sc.camera = cam+sc.render.filepath = os.path.join(tempfile.gettempdir(), "bas_still.png")+bpy.ops.render.render(write_still=True)+```diff --git a/skills/blender-core/scripts/_bpyx.py b/skills/blender-core/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-core/scripts/_bpyx.py@@ -0,0 +1,136 @@+"""_bpyx - tiny shared helpers for blender-agent-skills scripts (Blender 5.2+).++Source of truth: shared/_bpyx.py. Copies in skills/*/scripts/ are synced by+tools/sync_shared.py - never edit a copy.++Every skill script follows one contract:+ run(**kwargs) -> dict # call from MCP / Python (import the module)+ blender -b f.blend -P x.py -- --arg v # CLI: prints one line "@@JSON@@{...}"+"""+import argparse+import json+import sys++import bpy++MARK = "@@JSON@@"+++def argv():+ """Arguments after '--' (Blender ignores them)."""+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def _default(o):+ if hasattr(o, "__len__") and not isinstance(o, str):+ try:+ return [round(v, 5) if isinstance(v, float) else v for v in o]+ except TypeError:+ pass+ if isinstance(o, (set, frozenset)):+ return sorted(o)+ return str(o)+++def emit(data):+ """Print compact JSON on one marked line (parsed by run_in_blender.py)."""+ print(MARK + json.dumps(data, separators=(",", ":"), default=_default), flush=True)+ return data+++def parser(doc):+ """ArgumentParser whose help is the script docstring's first line."""+ return argparse.ArgumentParser(description=(doc or "").strip().splitlines()[0])+++def cli(run, p):+ """CLI entry: parse args after '--', run, emit JSON. Exit 1 on failure."""+ args = p.parse_args(argv())+ try:+ result = run(**vars(args))+ save = getattr(args, "save", None)+ if save:+ bpy.ops.wm.save_as_mainfile(filepath=bpy.path.abspath(save))+ result["saved"] = save+ emit(result)+ except Exception as e: # report, don't dump a traceback into agent context+ emit({"ok": False, "error": f"{type(e).__name__}: {e}"})+ if bpy.app.background:+ sys.exit(1)+++def add_common(p, save=True):+ """--objects / --save flags shared by most scripts."""+ p.add_argument("--objects", nargs="*", default=None,+ help="object names (default: selected, else all meshes)")+ if save:+ p.add_argument("--save", default=None, help="save .blend to this path after run")+ return p+++def objects(names=None, types=("MESH",)):+ """Resolve names -> objects. No names: selected of `types`, else all visible of `types`."""+ if names:+ missing = [n for n in names if n not in bpy.data.objects]+ if missing:+ raise KeyError(f"objects not found: {missing}")+ return [bpy.data.objects[n] for n in names]+ pool = [o for o in bpy.context.scene.objects if not types or o.type in types]+ sel = [o for o in pool if o.select_get()]+ return sel or [o for o in pool if o.visible_get()]+++def object_mode():+ """Leave edit/sculpt/pose modes; most data API work needs OBJECT mode."""+ ob = bpy.context.view_layer.objects.active+ if ob and ob.mode != "OBJECT":+ bpy.ops.object.mode_set(mode="OBJECT")+++def select_only(objs, active=None):+ """Select exactly `objs` and make `active` (default first) active."""+ for o in bpy.context.view_layer.objects:+ o.select_set(False)+ for o in objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = active or (objs[0] if objs else None)+++def node(tree, type_):+ """First node of `type_` (e.g. 'BSDF_PRINCIPLED'). Names are localized - never look up by name."""+ return next((n for n in tree.nodes if n.type == type_), None)+++def enum_ids(owner, prop):+ """Valid identifiers of an enum property (works on types or instances)."""+ return [i.identifier for i in owner.bl_rna.properties[prop].enum_items]+++def set_enum(owner, prop, value):+ """Assign an enum; on failure raise listing valid values (dynamic enums under-report)."""+ try:+ setattr(owner, prop, value)+ except TypeError as e:+ raise ValueError(f"{prop}={value!r} invalid: {e}") from None+++def mesh_tris(ob, evaluated=True):+ """Triangle count (evaluated = with modifiers)."""+ if evaluated:+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ try:+ me.calc_loop_triangles()+ return len(me.loop_triangles)+ finally:+ eo.to_mesh_clear()+ me = ob.data+ me.calc_loop_triangles()+ return len(me.loop_triangles)+++def r(v, n=4):+ """Round a float or a vector for compact JSON."""+ if isinstance(v, float):+ return round(v, n)+ return [round(x, n) for x in v]diff --git a/skills/blender-core/scripts/env_report.py b/skills/blender-core/scripts/env_report.pynew file mode 100644index 0000000..36a95d3--- /dev/null+++ b/skills/blender-core/scripts/env_report.py@@ -0,0 +1,60 @@+"""Report Blender version, engines, GPU, add-ons, units and scene stats as JSON.++Usage:+ blender -b [file.blend] -P env_report.py+ MCP: import env_report; print(env_report.run())+"""+import os+import sys++import addon_utils+import bpy++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402+++def _gpu():+ try:+ prefs = bpy.context.preferences.addons["cycles"].preferences+ prefs.refresh_devices()+ return {"backend": prefs.compute_device_type,+ "devices": sorted({d.name for d in prefs.devices if d.type != "CPU"})}+ except Exception as e:+ return {"error": str(e)}+++def run():+ sc = bpy.context.scene+ try:+ sc.render.engine = "__probe__"+ except TypeError as e:+ engines = str(e).split("in (")[-1].rstrip(")").replace("'", "").split(", ")+ us = sc.unit_settings+ kinds = {}+ for o in sc.objects:+ kinds[o.type] = kinds.get(o.type, 0) + 1+ enabled = sorted(bpy.context.preferences.addons.keys())+ return {+ "ok": True,+ "blender": bpy.app.version_string,+ "python": sys.version.split()[0],+ "background": bpy.app.background,+ "file": bpy.data.filepath or None,+ "engines": engines,+ "engine": sc.render.engine,+ "gpu": _gpu(),+ "addons_enabled": enabled,+ "rigify_available": any(m.__name__ == "rigify" for m in addon_utils.modules()),+ "units": {"system": us.system, "scale_length": us.scale_length, "length": us.length_unit},+ "color": {"view": sc.view_settings.view_transform, "look": sc.view_settings.look,+ "display": sc.display_settings.display_device},+ "frame_range": [sc.frame_start, sc.frame_end, sc.render.fps],+ "objects": kinds,+ "data": {k: len(getattr(bpy.data, k)) for k in+ ("meshes", "materials", "images", "actions", "node_groups", "collections")},+ }+++if __name__ == "__main__":+ bx.cli(lambda **k: run(), bx.parser(__doc__))diff --git a/skills/blender-core/scripts/run_in_blender.py b/skills/blender-core/scripts/run_in_blender.pynew file mode 100644index 0000000..6c4036f--- /dev/null+++ b/skills/blender-core/scripts/run_in_blender.py@@ -0,0 +1,91 @@+#!/usr/bin/env python3+"""Run a skill script in headless Blender and print only its JSON result.++Host-side (system Python 3.9+, no bpy). Finds Blender automatically:+$BLENDER_EXE > PATH > standard install dirs (newest version wins).++Usage:+ python run_in_blender.py [--blend FILE] [--user-prefs] SCRIPT.py [-- script args]+ python run_in_blender.py --expr "import bpy; print(bpy.app.version_string)"+ python run_in_blender.py --which # print the Blender path it would use+Exit code: 0 ok, 1 script error, 2 Blender not found.+"""+import glob+import json+import os+import re+import shutil+import subprocess+import sys++MARK = "@@JSON@@"+++def _ver(path):+ m = re.search(r"(\d+)\.(\d+)", path)+ return (int(m.group(1)), int(m.group(2))) if m else (0, 0)+++def find_blender():+ env = os.environ.get("BLENDER_EXE")+ if env and os.path.isfile(env):+ return env+ hit = shutil.which("blender")+ if hit:+ return hit+ pats = {+ "win32": [r"C:\Program Files\Blender Foundation\Blender *\blender.exe",+ os.path.expandvars(r"%LOCALAPPDATA%\Programs\Blender Foundation\Blender *\blender.exe"),+ r"C:\Program Files (x86)\Steam\steamapps\common\Blender\blender.exe"],+ "darwin": ["/Applications/Blender*.app/Contents/MacOS/Blender",+ os.path.expanduser("~/Applications/Blender*.app/Contents/MacOS/Blender")],+ }.get(sys.platform, ["/usr/bin/blender", "/opt/blender*/blender", "/snap/bin/blender",+ os.path.expanduser("~/blender*/blender")])+ found = [p for pat in pats for p in glob.glob(pat) if os.path.isfile(p)]+ return max(found, key=_ver) if found else None+++def main():+ a = sys.argv[1:]+ rest = []+ if "--" in a:+ i = a.index("--")+ a, rest = a[:i], a[i + 1:]+ exe = find_blender()+ if not exe:+ print(json.dumps({"ok": False, "error": "Blender not found; set BLENDER_EXE"}))+ return 2+ if "--which" in a:+ print(exe)+ return 0+ cmd = [exe, "-b"]+ if "--blend" in a:+ cmd.append(a[a.index("--blend") + 1])+ if "--user-prefs" not in a:+ cmd.append("--factory-startup")+ cmd += ["--python-exit-code", "1"]+ if "--expr" in a:+ cmd += ["--python-expr", a[a.index("--expr") + 1]]+ else:+ scripts = [x for x in a if x.endswith(".py")]+ if not scripts:+ print(__doc__)+ return 1+ cmd += ["-P", scripts[0]]+ cmd += ["--"] + rest+ p = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace")+ out = [ln[len(MARK):] for ln in p.stdout.splitlines() if ln.startswith(MARK)]+ if out:+ print("\n".join(out))+ elif "--expr" in a:+ # free-form expression: show stdout minus Blender banner noise+ noise = ("Blender ", "Read prefs", "Read blend", "Blender quit", "Color management")+ print("\n".join(ln for ln in p.stdout.splitlines() if ln and not ln.startswith(noise)))+ if p.returncode != 0 and not out:+ tail = (p.stderr or p.stdout).strip().splitlines()[-15:]+ print(json.dumps({"ok": False, "returncode": p.returncode, "log_tail": tail}))+ return 0 if p.returncode == 0 else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/skills/blender-export-pipelines/SKILL.md b/skills/blender-export-pipelines/SKILL.mdnew file mode 100644index 0000000..c013b62--- /dev/null+++ b/skills/blender-export-pipelines/SKILL.md@@ -0,0 +1,62 @@+---+name: blender-export-pipelines+description: Export from Blender 5.2 with verified presets - Roblox (FBX/glTF, cages, R15, SurfaceAppearance), Unity (FBX, Humanoid), Unreal (FBX skeletal, Nanite, UCX), Godot/web (GLB, meshopt/Draco, WebP), USD. Scale/axes, smoothing, tangents, leaf bones, clips, batch export, post-export verification. Use whenever an asset leaves Blender.+license: MIT+metadata:+ author: blender-agent-skills+ version: "0.1.0"+---++# Export Pipelines++The execution model is in `blender-core`. Run `blender-asset-qa` (and `blender-game-optimization` for budgets) **before** exporting.++## One call+```+scripts/export_asset.py -- --preset unreal_skeletal --objects SK_Hero --out //export/SK_Hero.fbx+scripts/export_asset.py -- --preset web --collection Export --out //export/scene.glb+scripts/export_asset.py -- --preset unity --objects SM_A SM_B SM_C --batch --out //export/x.fbx # one file each, at origin+```+Presets: `roblox`, `roblox_gltf`, `unity`, `unity_skeletal`, `unreal`, `unreal_skeletal`, `godot`, `web`, `gltf`, `usd`. Pass any exporter kwarg with `--set key=value`. Every preset is tested with a round-trip that keeps scale and avoids a 100× armature scale.++## Engine reference (load only the one you need)+- [references/roblox.md](references/roblox.md): MeshParts, avatar bodies (R15), accessories, layered clothing cages, SurfaceAppearance, limits+- [references/unity.md](references/unity.md): FBX settings, Humanoid rigs, URP/HDRP maps, animation clips+- [references/unreal.md](references/unreal.md): static/skeletal FBX, root bone, collision UCX, LODs, Nanite, ORM/DirectX+- [references/godot-web.md](references/godot-web.md): glTF/GLB, import suffixes, three.js/Babylon, compression, KHR extensions++## Universal pre-export checklist+1. **Scale**: scene unit scale 1.0, objects at scale 1, rotation applied (except intentional object transforms). The presets handle unit conversion.+2. **Pivot/origin** where the engine expects it: props at the bottom-center, characters at the world origin between the feet, facing **-Y** (Blender front). Every preset converts that to the engine's forward.+3. **Modifiers**: the presets export the evaluated mesh. Mirror, bevel and weighted normals are kept; booleans become real geometry.+4. **Normals**: custom/weighted normals export. Smooth shading, plus hard edges marked sharp.+5. **Triangulation**: FBX presets triangulate (`use_triangles`) so the bake and engine tangents match. glTF always triangulates.+6. **Materials**: image-texture → Principled chains only, with names `M_*` and textures `T_*`. Procedural nodes don't export, so bake them first.+7. **Armature**: deform bones only, no leaf bones, rest pose = bind pose, 4 weights per vertex max, and the root at the origin.+8. **Animation**: one action per clip, named `Rig_Clip`. Bake constraints/IK to keys (`blender-animation`). FBX exports the active/NLA action per preset settings; glTF `ACTIONS` mode exports every action that has a slot for the armature.+9. **Naming**: unique, ASCII, no spaces. Engines key materials/meshes by name across reimports.++## Format choice+| Need | Format |+|---|---|+| Unity, Unreal (most stable for skeletal) | FBX |+| Godot, web, Roblox (supported), Unreal 5.x Interchange, Blender↔Blender | glTF 2.0 (`.glb`) |+| Film/VFX, Omniverse, Apple AR (`.usdz`), layout interchange | USD |+| Static geometry for printing/CAD | OBJ / STL (`wm.obj_export`, `wm.stl_export`) |+| Point caches / deforming sims | Alembic (`wm.alembic_export`) |++## Verify after export (required)+- The script returns `ok`, the file size, and for `.glb` a parsed summary (meshes, materials, images, animations, skins, tris, extensions). Compare it with what you expected.+- For FBX/USD: re-import into an empty scene (`import_scene.fbx` / `wm.usd_import`) and check `dimensions`, the armature scale (must be 1, not 100) and the action count.+- In the engine: scale against a reference (UE mannequin 180 cm, Unity capsule 2 m, Roblox character 5 studs), normals/smoothing, the normal map's green channel, and animation root motion.++## Collection exporters (re-export in one click, 4.2+)+See `blender-scene-setup`: `collection.exporters` stores the format + settings per collection, and `bpy.ops.wm.collection_export_all()` re-exports everything.++## Gotchas+- FBX `use_tspace` fails silently on n-gons. Triangulate first (the presets do).+- `bake_space_transform` (Apply Transform) is experimental. Use it for Unity static meshes only, never with armatures.+- glTF exports **actions** linked through slots/NLA. An action with no user on the armature is skipped (`export_animation_mode` options: `ACTIONS`, `ACTIVE_ACTIONS`, `NLA_TRACKS`, `SCENE`, `BROADCAST`).+- glTF needs image textures in PNG/JPEG/WebP. EXR/TIFF get converted (`export_image_format`).+- Linked library data exports fine, but make it local or override it if you need to modify it first.+- Shape keys: FBX exports them as blendshapes, glTF as morph targets (`export_morph`). Modifiers before the Armature modifier can block shape-key export in FBX (apply them first).diff --git a/skills/blender-export-pipelines/references/godot-web.md b/skills/blender-export-pipelines/references/godot-web.mdnew file mode 100644index 0000000..0368e44--- /dev/null+++ b/skills/blender-export-pipelines/references/godot-web.md@@ -0,0 +1,21 @@+# Godot 4.x and Web (glTF 2.0)++## glTF basics (presets `godot`, `web`, `gltf`)+- `.glb` (binary, embedded textures) for delivery, `.gltf` + bin + images for debugging. Y-up, meters, right-handed. The exporter converts Blender Z-up automatically.+- Supported material: Principled BSDF → `pbrMetallicRoughness` (metallicRoughness texture: **G = roughness, B = metallic**; occlusion R via the "glTF Material Output" group → ORM in one texture), normal (OpenGL), emissive (+ `KHR_materials_emissive_strength`), alpha (OPAQUE/MASK/BLEND).+- Extensions the Blender exporter can write: `KHR_materials_transmission`, `_volume`, `_ior`, `_specular`, `_clearcoat`, `_sheen`, `_iridescence`, `_anisotropy`, `_dispersion`, `_emissive_strength`, `KHR_texture_transform`, `KHR_lights_punctual`, `KHR_mesh_quantization`, `EXT_mesh_gpu_instancing`, `EXT_texture_webp`, `KHR_draco_mesh_compression`, `EXT/KHR_meshopt_compression`.+- Custom properties → glTF `extras` (`export_extras=True`), which Godot exposes as metadata.++## Godot 4 import+- Drop `.glb` (or `.blend`, if the Blender path is set in Godot's settings; it converts via glTF) into the project.+- Name suffixes on objects (Godot import hints): `-col` (mesh + static collision), `-colonly` (collision only, mesh removed), `-convcolonly` (convex), `-rigid` (RigidBody), `-navmesh`, `-noimp` (skip), `-loop`/`-cycle` on animation names (loop). Use them on Blender object names, e.g. `Crate-colonly`.+- Animations: each action → AnimationPlayer clip. Godot retargets humanoids via SkeletonProfileHumanoid (Bone Map in import dock).+- LOD: Godot auto-generates mesh LODs on import (`meshes/generate_lods`). No manual LODs needed.+- Lightmaps: enable "Light Baking: Static Lightmaps" on import to auto-unwrap UV2, or provide one.++## Web (three.js, Babylon.js, model-viewer, R3F)+- Preset `web`: GLB + **meshopt** compression (`EXT_meshopt_compression`, or `KHR_meshopt_compression` via `--set export_meshopt_extension=KHR_meshopt_compression`) + **WebP** textures (q85). `--draco` switches to Draco (smaller for static, slower decode; needs the DRACOLoader).+- Budgets: hero model ≤ 2–5 MB GLB, total scene ≤ 10–20 MB, textures 1–2k, ≤ 50–100 draw calls on mobile web.+- Further compression outside Blender (recommended): `gltf-transform optimize in.glb out.glb --texture-compress ktx2` (KTX2/Basis textures: big GPU memory savings), `gltfpack -cc -tc` (the Blender exporter can call gltfpack: `export_use_gltfpack`).+- three.js: `GLTFLoader` + `MeshoptDecoder`/`DRACOLoader`/`KTX2Loader`. Set `renderer.outputColorSpace = SRGBColorSpace` and tone mapping (`AgX`/`Neutral`) to match Blender's view transform (Khronos PBR Neutral ↔ `NeutralToneMapping`).+- Validate with the Khronos glTF Validator and view in https://gltf-viewer.donmccurdy.com or model-viewer.diff --git a/skills/blender-export-pipelines/references/roblox.md b/skills/blender-export-pipelines/references/roblox.mdnew file mode 100644index 0000000..d07843b--- /dev/null+++ b/skills/blender-export-pipelines/references/roblox.md@@ -0,0 +1,42 @@+# Roblox (Creator Hub specs, verified 2026-10)++## Units and export+- 1 stud ≈ 0.28 m. Default R15 character ≈ 5 studs tall.+- Blender FBX: **Apply Scalings = FBX Unit Scale**, every other scale 1.0, Path Mode **Copy** + **Embed Textures**, **Add Leaf Bones off**, Bake Animation **off** unless exporting a clip. That's preset `roblox`.+- Alternatives from the docs: Transform Scale 0.01, or scene Unit Scale 0.01 (the docs warn this causes Blender issues).+- glTF (`.gltf/.glb`) is supported and needs no scale tricks: preset `roblox_gltf`.+- The Roblox docs recommend Unit System None + Rotation Degrees in Blender to "match studs". Optional; keep Metric if you rely on the presets.+- **One animation per exported file.** Export each clip separately.++## Mesh rules (all MeshParts)+- ≤ **20,000 triangles per mesh**. Watertight, no holes/backfaces, no zero thickness, quads preferred, no n-gons.+- **One UV set**, all UVs inside 0–1 (overlaps allowed).+- Use `blender-asset-qa --profile roblox`.+- `RenderFidelity=Automatic` creates LODs, so don't ship LOD meshes. Set `CollisionFidelity` (Box/Hull/Default/PreciseConvexDecomposition) on simple parts.++## Textures / SurfaceAppearance+- Maps: `ColorMap` (RGB + alpha), `NormalMap` (**OpenGL, tangent space**, flat = 127,127,255), `MetalnessMap` (8-bit gray), `RoughnessMap` (8-bit gray), `EmissiveMaskContent` (8-bit gray) + `EmissiveTint`/`EmissiveStrength`. No packed ORM, so export separate grayscale maps.+- Max 4096²; PBR maps are commonly limited to 1024². Size guidance: 5×5 studs → 256², 10×10 → 512², 20×20 → 1024². Marketplace max 2048².+- `AlphaMode`: Overlay (default; alpha shows the part color), Transparency (cutout/blend), TintMask (alpha = where `Color` tints), Opaque.+- Files: PNG/JPG/TGA/BMP. Upload via Studio (`AssetService:CreateAssetAsync` for batch).++## Rigging (any skinned mesh)+- Freeze bones: scale 1, rotation 0. Root bone at 0,0,0. ≤ **4 influences per vertex**, **no weights on Root**, symmetric weights.+- `blender-character-rigging` → `rig_check.py --profile roblox`.++## Avatar character bodies (R15)+- 15 meshes named `<Part>_Geo`: Head, UpperTorso, LowerTorso, Left/Right UpperArm, LowerArm, Hand, UpperLeg, LowerLeg, Foot. Each is watertight and capped at the joints.+- Facing **+Z, up +Y** in Roblox space (Blender preset conversion: front = -Y in Blender). Pose: I/A/T. Pivots at 0,0,0.+- Tri budgets: DynamicHead 4,000, Torso 1,750, each Arm/Leg 1,248, total **10,742**.+- Body scale (studs, X/Y/Z): min 1.35/3.6/0.7. Max Normal 8.6/9.5/2.25, Slender 6/9.5/2, Classic 8/9.1/2.+- Skeleton: `Root > HumanoidRootNode > LowerTorso > UpperTorso > (Head, arms)`, legs from LowerTorso. Root and LowerTorso at the origin. Up to 37 optional bones (Spine, Chest, Clavicles, fingers...) need `HumanoidRigDescription`.+- Attachments (empties) with `_Att` suffix: FaceCenter, FaceFront, Hat, Hair (head); Left/RightCollar, Neck, BodyBack, BodyFront (UpperTorso); Root (0,0,0), WaistFront/Back/Center (LowerTorso); Left/RightShoulder, Left/RightGrip; Left/RightFoot.+- Each body part needs an **outer cage** `<Part>_OuterCage`. Don't delete cage verts or change cage UVs.+- Marketplace: opaque body parts, ≥50% bounding-box fill, Material Plastic, VertexColor 1,1,1. Skin-tone areas transparent in the ColorMap.+- Dynamic heads: FACS poses as animation/shape data (see the Creator Hub "dynamic heads" page). Map ARKit-style shapes with `blender-facial-shapekeys`.++## Accessories and layered clothing+- Rigid accessories: ~4,000 tris max. Layered clothing: 4,000 tris max. Texture ≤ 1024² recommended.+- Layered clothing needs `<Name>_InnerCage` + `<Name>_OuterCage`, built from the Roblox template cages (same vert count/order/UVs as the template). The inner cage hugs the body, the outer cage hugs the clothing surface.+- Skin the clothing to the R15 rig (same bone names). Cages stay unskinned or follow the rig per template.+- Validate in Studio with the Accessory Fitting Tool.diff --git a/skills/blender-export-pipelines/references/unity.md b/skills/blender-export-pipelines/references/unity.mdnew file mode 100644index 0000000..80b5a87--- /dev/null+++ b/skills/blender-export-pipelines/references/unity.md@@ -0,0 +1,27 @@+# Unity (2022 LTS / Unity 6)++## FBX settings (presets `unity`, `unity_skeletal`)+- Apply Scalings **FBX All**, Forward **-Z**, Up **Y**. Static meshes: **Apply Transform** (`bake_space_transform=True`), which removes the -90° X rotation and the 100 scale on root objects. Never use it with armatures. Skeletal: Apply Transform off, and in Unity enable **Bake Axis Conversion** in the Model importer if the root shows a -90° X rotation.+- Smoothing: Face. Triangulate on (stable tangents). Leaf bones off. Deform bones only.+- Unity importer: Model tab Scale Factor 1, Convert Units on. Normals = Import, Tangents = Import (or Calculate Mikktspace).++## Humanoid (Mecanim) rigs+- Minimum 15 bones: Hips, Spine, Head, Upper/Lower legs, Feet, Upper/Lower arms, Hands. Chest, Neck, Shoulders, Toes, fingers and eyes are optional.+- Bind pose in **T-pose** (Unity can enforce it in Configure Avatar). Hips is the root of the deform hierarchy. An extra `root` bone above Hips is fine for root motion.+- Clean names (`.L/.R` map fine, or Rigify `DEF-*` after export with deform-only). Avoid twist bones parented out of chain; Unity ignores them for retargeting but they still skin.+- Root motion: animate the `root`/Hips; in the clip import settings, set Root Transform Rotation/Position "Based upon" Original/Body Orientation.++## Animation clips+- Export all actions in one FBX (`--set bake_anim_use_all_actions=true`) or one FBX per clip (`[email protected]` naming lets Unity share the avatar). Loop: match first/last frames, set Loop Time in Unity.+- Blendshapes export as FBX shape keys (Model tab: Import BlendShapes; Blend Shape Normals: Calculate).++## Materials+- Unity doesn't build PBR materials from FBX usefully. Recreate them in Unity, or use extract + remap.+- URP Lit: BaseMap (sRGB), NormalMap (OpenGL), Metallic map: **R = Metallic, A = Smoothness** (smoothness = 1 − roughness). Occlusion separate.+- HDRP Lit: MaskMap **R = Metallic, G = AO, B = Detail mask, A = Smoothness**.+- Build the packed maps in Blender (`blender-texture-baking` → numpy channel pack) or in Unity with a packing tool.++## Other+- Lightmap UV2: ship one (`uv_pack.py --lightmap`) or tick "Generate Lightmap UVs".+- LOD: name meshes `X_LOD0/1/2`. Unity auto-creates a LOD Group from the suffixes.+- glTF in Unity needs a package (glTFast). FBX remains the default.diff --git a/skills/blender-export-pipelines/references/unreal.md b/skills/blender-export-pipelines/references/unreal.mdnew file mode 100644index 0000000..02a19ed--- /dev/null+++ b/skills/blender-export-pipelines/references/unreal.md@@ -0,0 +1,32 @@+# Unreal Engine 5.x++## FBX settings (presets `unreal`, `unreal_skeletal`)+- Scene unit scale 1.0 (meters). Apply Scalings **FBX Units Scale**: the unit goes into the FBX header, so UE converts to cm **without** a 100× scale on the armature/root bone. A root bone that imports with scale 100 means the wrong apply-scale mode was used.+- Forward -Z / Up Y (UE converts the axis system). Smoothing **Face** (avoids the "no smoothing groups" warning). Triangulate on. Tangents on.+- Skeletal: **Add Leaf Bones off**, **Only Deform Bones on**, armature node type Null. If the armature object is named `Armature`, UE drops it and the first bone becomes the root. Otherwise the object becomes an extra root bone, so name the object `root` if you want that explicitly.+- UE 5.4+ also imports glTF/USD through Interchange. FBX remains the most battle-tested path for skeletal meshes.++## Skeleton conventions+- Mannequin (UE5 Manny/Quinn) hierarchy: `root > pelvis > spine_01..05 > neck_01..02 > head`, `clavicle_l/r > upperarm > lowerarm > hand`, `thigh > calf > foot > ball`, plus twist/IK bones. Matching the names and bone orientation lets the IK Retargeter auto-map them.+- The UE Mannequin's skeletal mesh faces **+Y** in its asset space (the Character Blueprint rotates the mesh -90° to face +X). After the first import, compare your mesh with the Mannequin in the Skeletal Mesh editor. If they differ, rotate the armature ±90° around Z in Blender, apply, and re-export, so retargeting and root motion line up.+- Bone orientation: Blender bones are Y-along. If you need UE-style X-along bones for engine-side tools, set `primary_bone_axis="X"`, `secondary_bone_axis="-Y"` with `--set`.++## Static meshes+- Collision: `UCX_<MeshName>_00` (convex, ≤ 255 verts, not overlapping), `UBX_` boxes, `USP_` spheres, `UCP_` capsules, exported in the same FBX as the mesh.+- LODs: `<Mesh>_LOD0..N` in one FBX, with "Import Mesh LODs" enabled, or let UE auto-generate them.+- Lightmap UV: UE can generate one (Generate Lightmap UVs). Ship UV2 only for hand-made lightmaps.+- Sockets: empties named `SOCKET_<Name>` parented to the mesh.++## Nanite (static, UE 5.0+; skinned meshes experimental in 5.5+)+- Ship dense geometry directly (millions of tris). No LODs, no normal-map bake needed for geometric detail. Keep UV seams sensible (Nanite's error metric respects them).+- Opaque and masked materials are supported. Translucency isn't. Small/thin meshes (foliage) need care (Preserve Area option).+- Enable on import ("Build Nanite") or per asset.++## Materials and textures+- BaseColor (sRGB), Normal (**DirectX**: bake with `--directx`, or tick "Flip Green Channel" on the texture), **ORM** (R=AO, G=Roughness, B=Metallic; uncheck sRGB, compression Masks).+- Name textures `T_<Asset>_BC/_N/_ORM`. Materials become `M_` and instances `MI_`.++## Animation+- One action per clip. FBX exports the active action, NLA strips, or all actions (`bake_anim_use_all_actions`). Import the animation FBX against the existing Skeleton asset.+- Root motion: animate the `root` bone (not the armature object). Enable Root Motion on the anim sequence.+- Morph targets come from shape keys. Enable "Import Morph Targets".diff --git a/skills/blender-export-pipelines/scripts/_bpyx.py b/skills/blender-export-pipelines/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-export-pipelines/scripts/_bpyx.py@@ -0,0 +1,136 @@+"""_bpyx - tiny shared helpers for blender-agent-skills scripts (Blender 5.2+).++Source of truth: shared/_bpyx.py. Copies in skills/*/scripts/ are synced by+tools/sync_shared.py - never edit a copy.++Every skill script follows one contract:+ run(**kwargs) -> dict # call from MCP / Python (import the module)+ blender -b f.blend -P x.py -- --arg v # CLI: prints one line "@@JSON@@{...}"+"""+import argparse+import json+import sys++import bpy++MARK = "@@JSON@@"+++def argv():+ """Arguments after '--' (Blender ignores them)."""+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def _default(o):+ if hasattr(o, "__len__") and not isinstance(o, str):+ try:+ return [round(v, 5) if isinstance(v, float) else v for v in o]+ except TypeError:+ pass+ if isinstance(o, (set, frozenset)):+ return sorted(o)+ return str(o)+++def emit(data):+ """Print compact JSON on one marked line (parsed by run_in_blender.py)."""+ print(MARK + json.dumps(data, separators=(",", ":"), default=_default), flush=True)+ return data+++def parser(doc):+ """ArgumentParser whose help is the script docstring's first line."""+ return argparse.ArgumentParser(description=(doc or "").strip().splitlines()[0])+++def cli(run, p):+ """CLI entry: parse args after '--', run, emit JSON. Exit 1 on failure."""+ args = p.parse_args(argv())+ try:+ result = run(**vars(args))+ save = getattr(args, "save", None)+ if save:+ bpy.ops.wm.save_as_mainfile(filepath=bpy.path.abspath(save))+ result["saved"] = save+ emit(result)+ except Exception as e: # report, don't dump a traceback into agent context+ emit({"ok": False, "error": f"{type(e).__name__}: {e}"})+ if bpy.app.background:+ sys.exit(1)+++def add_common(p, save=True):+ """--objects / --save flags shared by most scripts."""+ p.add_argument("--objects", nargs="*", default=None,+ help="object names (default: selected, else all meshes)")+ if save:+ p.add_argument("--save", default=None, help="save .blend to this path after run")+ return p+++def objects(names=None, types=("MESH",)):+ """Resolve names -> objects. No names: selected of `types`, else all visible of `types`."""+ if names:+ missing = [n for n in names if n not in bpy.data.objects]+ if missing:+ raise KeyError(f"objects not found: {missing}")+ return [bpy.data.objects[n] for n in names]+ pool = [o for o in bpy.context.scene.objects if not types or o.type in types]+ sel = [o for o in pool if o.select_get()]+ return sel or [o for o in pool if o.visible_get()]+++def object_mode():+ """Leave edit/sculpt/pose modes; most data API work needs OBJECT mode."""+ ob = bpy.context.view_layer.objects.active+ if ob and ob.mode != "OBJECT":+ bpy.ops.object.mode_set(mode="OBJECT")+++def select_only(objs, active=None):+ """Select exactly `objs` and make `active` (default first) active."""+ for o in bpy.context.view_layer.objects:+ o.select_set(False)+ for o in objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = active or (objs[0] if objs else None)+++def node(tree, type_):+ """First node of `type_` (e.g. 'BSDF_PRINCIPLED'). Names are localized - never look up by name."""+ return next((n for n in tree.nodes if n.type == type_), None)+++def enum_ids(owner, prop):+ """Valid identifiers of an enum property (works on types or instances)."""+ return [i.identifier for i in owner.bl_rna.properties[prop].enum_items]+++def set_enum(owner, prop, value):+ """Assign an enum; on failure raise listing valid values (dynamic enums under-report)."""+ try:+ setattr(owner, prop, value)+ except TypeError as e:+ raise ValueError(f"{prop}={value!r} invalid: {e}") from None+++def mesh_tris(ob, evaluated=True):+ """Triangle count (evaluated = with modifiers)."""+ if evaluated:+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ try:+ me.calc_loop_triangles()+ return len(me.loop_triangles)+ finally:+ eo.to_mesh_clear()+ me = ob.data+ me.calc_loop_triangles()+ return len(me.loop_triangles)+++def r(v, n=4):+ """Round a float or a vector for compact JSON."""+ if isinstance(v, float):+ return round(v, n)+ return [round(x, n) for x in v]diff --git a/skills/blender-export-pipelines/scripts/export_asset.py b/skills/blender-export-pipelines/scripts/export_asset.pynew file mode 100644index 0000000..01fcb5b--- /dev/null+++ b/skills/blender-export-pipelines/scripts/export_asset.py@@ -0,0 +1,176 @@+"""Export objects/collections with engine presets, then verify the file.++Presets: roblox (FBX), roblox_gltf, unity (FBX), unity_skeletal, unreal (FBX), unreal_skeletal,+godot (GLB), web (GLB + meshopt + WebP), gltf (plain GLB), usd (USDZ/USD).+Selection: --objects (children included) or --collection; default = selected/visible meshes+armatures.+--batch exports each top-level object to its own file at the world origin.+Usage:+ blender -b f.blend -P export_asset.py -- --preset unreal --objects SM_Crate --out //export/SM_Crate.fbx+ [--collection Export] [--batch] [--no-anim] [--draco] [--set key=value ...]+ MCP: import export_asset; print(export_asset.run(preset="godot", objects=["Hero"], out="//export/Hero.glb"))+GLB results include a parsed summary (meshes, materials, images, animations, skins, extensions).+"""+import json+import os+import struct+import sys++import bpy+from mathutils import Vector++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++FBX_BASE = dict(use_selection=True, object_types={"MESH", "ARMATURE", "EMPTY"}, use_mesh_modifiers=True,+ mesh_smooth_type="FACE", add_leaf_bones=False, use_armature_deform_only=True,+ armature_nodetype="NULL", use_triangles=True, use_tspace=True, use_custom_props=False,+ bake_anim=True, bake_anim_use_all_actions=False, bake_anim_use_nla_strips=False,+ bake_anim_force_startend_keying=True, bake_anim_simplify_factor=0.0, path_mode="AUTO")+GLTF_BASE = dict(use_selection=True, export_format="GLB", export_yup=True, export_apply=True,+ export_texcoords=True, export_normals=True, export_tangents=False,+ export_materials="EXPORT", export_image_format="AUTO", export_animations=True,+ export_animation_mode="ACTIONS", export_skins=True, export_morph=True,+ export_influence_nb=4, export_def_bones=True, export_leaf_bone=False,+ export_extras=False, export_cameras=False, export_lights=False)++PRESETS = {+ # Roblox: FBX Unit Scale imports at the same scale (Creator Hub); embed textures; no leaf bones+ "roblox": ("fbx", dict(apply_scale_options="FBX_SCALE_UNITS", path_mode="COPY", embed_textures=True,+ use_tspace=False)),+ "roblox_gltf": ("gltf", dict(export_influence_nb=4)),+ # Unity: FBX All + Apply Transform -> scale 1, no -90 X rotation on import+ "unity": ("fbx", dict(apply_scale_options="FBX_SCALE_ALL", bake_space_transform=True,+ axis_forward="-Z", axis_up="Y")),+ "unity_skeletal": ("fbx", dict(apply_scale_options="FBX_SCALE_ALL", bake_space_transform=False,+ axis_forward="-Z", axis_up="Y")),+ # Unreal: unit scale in the FBX header (no 100x root scale); smoothing groups; deform bones only+ "unreal": ("fbx", dict(apply_scale_options="FBX_SCALE_UNITS", axis_forward="-Z", axis_up="Y")),+ "unreal_skeletal": ("fbx", dict(apply_scale_options="FBX_SCALE_UNITS", axis_forward="-Z", axis_up="Y",+ primary_bone_axis="Y", secondary_bone_axis="X")),+ "godot": ("gltf", dict(export_extras=True)),+ "web": ("gltf", dict(export_image_format="WEBP", export_image_quality=85,+ export_meshopt_compression_enable=True)),+ "gltf": ("gltf", {}),+ "usd": ("usd", dict(selected_objects_only=True, export_materials=True, generate_preview_surface=True,+ export_armatures=True, only_deform_bones=True, export_shapekeys=True,+ export_textures_mode="NEW", relative_paths=True, convert_orientation=False)),+}+EXT = {"fbx": ".fbx", "gltf": ".glb", "usd": ".usdz"}+++def glb_summary(path):+ """Parse the JSON chunk of a .glb (no import needed)."""+ with open(path, "rb") as f:+ magic, _, _ = struct.unpack("<4sII", f.read(12))+ if magic != b"glTF":+ return {"error": "not a GLB"}+ clen, ctype = struct.unpack("<II", f.read(8))+ doc = json.loads(f.read(clen))+ tris = 0+ for m in doc.get("meshes", []):+ for p in m.get("primitives", []):+ acc = doc["accessors"][p["indices"]] if "indices" in p else None+ tris += (acc["count"] // 3) if acc else 0+ return {k: len(doc.get(k, [])) for k in ("nodes", "meshes", "materials", "images", "animations", "skins")} | {+ "tris": tris, "extensions": doc.get("extensionsUsed", []),+ "animation_names": [a.get("name") for a in doc.get("animations", [])][:20]}+++def _gather(objects, collection):+ if collection:+ col = bpy.data.collections[collection]+ return [o for o in col.all_objects if o.type in {"MESH", "ARMATURE", "EMPTY", "CURVE"}]+ obs = bx.objects(objects, types=("MESH", "ARMATURE", "EMPTY"))+ out = []+ for o in obs:+ out.append(o)+ out += [c for c in o.children_recursive if c.type in {"MESH", "ARMATURE", "EMPTY"}]+ if o.parent and o.parent.type == "ARMATURE":+ out.append(o.parent)+ return list(dict.fromkeys(out))+++def _export(fmt, path, kw):+ if fmt == "fbx":+ return bpy.ops.export_scene.fbx(filepath=path, **kw)+ if fmt == "gltf":+ return bpy.ops.export_scene.gltf(filepath=path, **kw)+ return bpy.ops.wm.usd_export(filepath=path, **kw)+++def _coerce(v):+ for t in (int, float):+ try:+ return t(v)+ except ValueError:+ pass+ return {"true": True, "false": False}.get(v.lower(), v)+++def run(preset="gltf", objects=None, collection=None, out="", batch=False, no_anim=False,+ draco=False, set=None, **_): # noqa: A002+ bx.object_mode()+ fmt, extra = PRESETS[preset]+ kw = dict(FBX_BASE if fmt == "fbx" else GLTF_BASE if fmt == "gltf" else {})+ kw.update(extra)+ if no_anim:+ kw.update({"bake_anim": False} if fmt == "fbx" else {"export_animations": False} if fmt == "gltf"+ else {"export_animation": False})+ if draco and fmt == "gltf":+ kw.update(export_draco_mesh_compression_enable=True, export_meshopt_compression_enable=False)+ for item in set or []:+ k, v = item.split("=", 1)+ kw[k] = _coerce(v)+ obs = _gather(objects, collection)+ if not obs:+ raise ValueError("nothing to export")+ warn = [f"{o.name}: unapplied scale {tuple(round(s, 3) for s in o.scale)}" for o in obs+ if o.type == "MESH" and any(abs(s - 1) > 1e-4 for s in o.scale)]+ warn += [f"{o.name}: n-gons present; tangents need tris/quads" for o in obs+ if o.type == "MESH" and fmt == "fbx" and kw.get("use_tspace") and not kw.get("use_triangles")+ and any(len(p.vertices) > 4 for p in o.data.polygons)]+ out = bpy.path.abspath(out) if out else os.path.join(+ os.path.dirname(bpy.data.filepath) or os.getcwd(), "export", f"{obs[0].name}{EXT[fmt]}")+ if fmt == "usd" and not out.endswith((".usd", ".usda", ".usdc", ".usdz")):+ out += ".usdz"+ os.makedirs(os.path.dirname(out), exist_ok=True)+ jobs = []+ if batch:+ roots = [o for o in obs if o.parent is None or o.parent not in obs]+ for r in roots:+ members = [r] + [c for c in r.children_recursive if c in obs]+ jobs.append((os.path.join(os.path.dirname(out), f"{r.name}{EXT[fmt]}"), members, r))+ else:+ jobs.append((out, obs, None))+ files = []+ for path, members, root in jobs:+ bx.select_only(members, active=members[0])+ loc = None+ if root is not None:+ loc = root.location.copy()+ root.location = Vector()+ try:+ res = _export(fmt, path, kw)+ finally:+ if loc is not None:+ root.location = loc+ rec = {"file": path, "ok": res == {"FINISHED"} and os.path.exists(path),+ "kb": round(os.path.getsize(path) / 1024, 1) if os.path.exists(path) else 0,+ "objects": [m.name for m in members]}+ if path.endswith(".glb") and rec["ok"]:+ rec["summary"] = glb_summary(path)+ files.append(rec)+ return {"ok": all(f["ok"] for f in files), "preset": preset, "format": fmt, "files": files,+ "warnings": warn}+++if __name__ == "__main__":+ p = bx.add_common(bx.parser(__doc__), save=False)+ p.add_argument("--preset", default="gltf", choices=list(PRESETS))+ p.add_argument("--collection", default=None)+ p.add_argument("--out", default="")+ p.add_argument("--batch", action="store_true")+ p.add_argument("--no-anim", action="store_true")+ p.add_argument("--draco", action="store_true")+ p.add_argument("--set", nargs="*", default=None, help="extra exporter kwargs key=value")+ bx.cli(run, p)diff --git a/skills/blender-facial-shapekeys/SKILL.md b/skills/blender-facial-shapekeys/SKILL.mdnew file mode 100644index 0000000..a6ea2bb--- /dev/null+++ b/skills/blender-facial-shapekeys/SKILL.md@@ -0,0 +1,54 @@+---+name: blender-facial-shapekeys+description: Facial rigs and shape keys in Blender 5.2 - ARKit 52 blendshapes, visemes for lip-sync, sculpting expressions, splitting symmetric shapes into Left/Right, mirroring, corrective and combination shapes, drivers and control rigs, bone+blendshape hybrids, export to engines (Unity, Unreal, Roblox dynamic heads, VRM/web). Use for faces, expressions, lip-sync, or any shape-key work.+license: MIT+metadata:+ author: blender-agent-skills+ version: "0.1.0"+---++# Facial Rig & Shape Keys++The execution model is in `blender-core`. The body rig is in `blender-character-rigging`.++## Choose the approach+| Approach | Use | Notes |+|---|---|---|+| **Blendshapes (ARKit 52)** | games, VTubers, mocap (iPhone/Live Link Face), web/VRM | the industry interchange set; each shape is sculpted |+| **Bones** (jaw, eyes, lids, brows, lips) | stylized, low memory, mobile | jaw + eyes as bones are almost always right |+| **Hybrid** | most production game heads | jaw/eye/tongue bones + blendshapes for everything soft |+| **Rigify face** (`human` metarig) | film-style keyframe animation inside Blender | 100+ face bones, heavy for engines |++## Procedure (blendshapes)+1. The head mesh needs clean loops around the eyes and mouth (`blender-retopology-uv`), with eyes, teeth and tongue as separate objects parented or weighted to bones.+2. `scripts/shapekeys.py -- --mesh Head --create arkit` (or `--create visemes` for the 15 Oculus visemes) creates empty, correctly named keys.+3. Sculpt each key (live: sculpt mode on the active key, `use_shape_key_edit_mode`). Symmetric expressions can be sculpted once, then `--split eyeBlink` gives `eyeBlinkLeft/Right` with a soft blend across X=0 (`--falloff` m).+4. `--mirror browDownLeft` builds `browDownRight` (topology-independent mirror).+5. `--report` lists unsculpted keys, the max offset per key, and missing ARKit names. A shape is done only when every key moves and nothing is left over.+6. Optional: `--drivers FaceCtrl` adds a controller with 0–1 custom properties driving each key, for keyframing in Blender.+7. Check the extremes and **combinations** (jawOpen + mouthSmile, eyeBlink + eyeSquint) with `look`. Fix them with corrective combination keys driven by the product of two keys.++## Shape key rules+- Shapes are **deltas from Basis**. Never change the Basis topology after creating keys (adding or removing verts destroys every key).+- One action per key. No head or neck movement inside face keys (bones do that). Keep eyelids sliding over the eye surface, not through it (check with `blender-asset-qa` zfighting on lid/eye).+- Range 0–1. `slider_max` can be raised for exaggeration, but engines clamp to 0–1.+- Relative keys (`use_relative=True`, the default) are the only kind that exports.+- Name exactly per spec (case-sensitive): `eyeBlinkLeft`, not `EyeBlink_L`. Engines map by name.+- Keys on meshes with Subdivision: sculpt at level 0, and keep the subdivision modifier **after** the shape keys (they're evaluated first anyway).+- Applying modifiers on a mesh with shape keys fails. Use `modifier_apply_as_shapekey` for deform modifiers, or apply them before creating keys.++## Correctives and combination shapes+- Corrective for a bone pose: sculpt in the posed state, then drive with a `TRANSFORMS` variable (`ROT_X`, `LOCAL_SPACE`, mapped to 0–1).+- Combination: key `jawOpen_mouthSmile` with driver `SCRIPTED` expression `a*b`, from the two key values (`SINGLE_PROP` `key_blocks["jawOpen"].value`). Simple expressions don't need Python auto-run.++## Engine notes+- **Unity**: FBX blendshapes. In the Model importer, set Blend Shape Normals = Calculate (or Import if smoothing was exported). ARKit names map to the AR Foundation face-tracking samples.+- **Unreal**: morph targets ("Import Morph Targets"). Live Link Face / MetaHuman Animator use ARKit names, and the Pose Asset maps the curves. No leaf bones.+- **Roblox dynamic heads**: FACS-based poses with Roblox-specific names, authored as animation frames on a head rig (Creator Hub "Dynamic heads" spec). Build from the official Blender template. ARKit sculpts can be reused by renaming/mapping. Head ≤ 4,000 tris.+- **VRM / web (three-vrm, ReadyPlayerMe-style)**: ARKit 52 + visemes as glTF morph targets (`export_morph=True`). Keep the morph-normal export on only if shading needs it (it doubles the size).+- Drop unused keys before export. Every key costs memory per vertex (glTF sparse accessors help).++## Gotchas+- `ob.shape_key_add(from_mix=False)` copies the Basis. `from_mix=True` bakes the current mix (useful for combos, dangerous by accident).+- `shape_key_mirror(use_topology=False)` needs a mesh symmetric on X. Run it on the **active** key (the script handles this).+- Driver variables on shape keys use the Key ID (`ob.data.shape_keys`), not the mesh: `fc = kb.driver_add("value")`.diff --git a/skills/blender-facial-shapekeys/scripts/_bpyx.py b/skills/blender-facial-shapekeys/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-facial-shapekeys/scripts/_bpyx.py@@ -0,0 +1,136 @@+"""_bpyx - tiny shared helpers for blender-agent-skills scripts (Blender 5.2+).++Source of truth: shared/_bpyx.py. Copies in skills/*/scripts/ are synced by+tools/sync_shared.py - never edit a copy.++Every skill script follows one contract:+ run(**kwargs) -> dict # call from MCP / Python (import the module)+ blender -b f.blend -P x.py -- --arg v # CLI: prints one line "@@JSON@@{...}"+"""+import argparse+import json+import sys++import bpy++MARK = "@@JSON@@"+++def argv():+ """Arguments after '--' (Blender ignores them)."""+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def _default(o):+ if hasattr(o, "__len__") and not isinstance(o, str):+ try:+ return [round(v, 5) if isinstance(v, float) else v for v in o]+ except TypeError:+ pass+ if isinstance(o, (set, frozenset)):+ return sorted(o)+ return str(o)+++def emit(data):+ """Print compact JSON on one marked line (parsed by run_in_blender.py)."""+ print(MARK + json.dumps(data, separators=(",", ":"), default=_default), flush=True)+ return data+++def parser(doc):+ """ArgumentParser whose help is the script docstring's first line."""+ return argparse.ArgumentParser(description=(doc or "").strip().splitlines()[0])+++def cli(run, p):+ """CLI entry: parse args after '--', run, emit JSON. Exit 1 on failure."""+ args = p.parse_args(argv())+ try:+ result = run(**vars(args))+ save = getattr(args, "save", None)+ if save:+ bpy.ops.wm.save_as_mainfile(filepath=bpy.path.abspath(save))+ result["saved"] = save+ emit(result)+ except Exception as e: # report, don't dump a traceback into agent context+ emit({"ok": False, "error": f"{type(e).__name__}: {e}"})+ if bpy.app.background:+ sys.exit(1)+++def add_common(p, save=True):+ """--objects / --save flags shared by most scripts."""+ p.add_argument("--objects", nargs="*", default=None,+ help="object names (default: selected, else all meshes)")+ if save:+ p.add_argument("--save", default=None, help="save .blend to this path after run")+ return p+++def objects(names=None, types=("MESH",)):+ """Resolve names -> objects. No names: selected of `types`, else all visible of `types`."""+ if names:+ missing = [n for n in names if n not in bpy.data.objects]+ if missing:+ raise KeyError(f"objects not found: {missing}")+ return [bpy.data.objects[n] for n in names]+ pool = [o for o in bpy.context.scene.objects if not types or o.type in types]+ sel = [o for o in pool if o.select_get()]+ return sel or [o for o in pool if o.visible_get()]+++def object_mode():+ """Leave edit/sculpt/pose modes; most data API work needs OBJECT mode."""+ ob = bpy.context.view_layer.objects.active+ if ob and ob.mode != "OBJECT":+ bpy.ops.object.mode_set(mode="OBJECT")+++def select_only(objs, active=None):+ """Select exactly `objs` and make `active` (default first) active."""+ for o in bpy.context.view_layer.objects:+ o.select_set(False)+ for o in objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = active or (objs[0] if objs else None)+++def node(tree, type_):+ """First node of `type_` (e.g. 'BSDF_PRINCIPLED'). Names are localized - never look up by name."""+ return next((n for n in tree.nodes if n.type == type_), None)+++def enum_ids(owner, prop):+ """Valid identifiers of an enum property (works on types or instances)."""+ return [i.identifier for i in owner.bl_rna.properties[prop].enum_items]+++def set_enum(owner, prop, value):+ """Assign an enum; on failure raise listing valid values (dynamic enums under-report)."""+ try:+ setattr(owner, prop, value)+ except TypeError as e:+ raise ValueError(f"{prop}={value!r} invalid: {e}") from None+++def mesh_tris(ob, evaluated=True):+ """Triangle count (evaluated = with modifiers)."""+ if evaluated:+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ try:+ me.calc_loop_triangles()+ return len(me.loop_triangles)+ finally:+ eo.to_mesh_clear()+ me = ob.data+ me.calc_loop_triangles()+ return len(me.loop_triangles)+++def r(v, n=4):+ """Round a float or a vector for compact JSON."""+ if isinstance(v, float):+ return round(v, n)+ return [round(x, n) for x in v]diff --git a/skills/blender-facial-shapekeys/scripts/shapekeys.py b/skills/blender-facial-shapekeys/scripts/shapekeys.pynew file mode 100644index 0000000..3997419--- /dev/null+++ b/skills/blender-facial-shapekeys/scripts/shapekeys.py@@ -0,0 +1,136 @@+"""Shape-key toolkit for faces: create ARKit-52 / viseme sets, split symmetric keys L/R,+mirror keys, report sculpt status, and wire driver controls.++Usage:+ blender -b f.blend -P shapekeys.py -- --mesh Head --create arkit|visemes+ blender -b f.blend -P shapekeys.py -- --mesh Head --split eyeBlink [--falloff 0.02] [--style arkit|dot]+ blender -b f.blend -P shapekeys.py -- --mesh Head --mirror browDownLeft+ blender -b f.blend -P shapekeys.py -- --mesh Head --report+ blender -b f.blend -P shapekeys.py -- --mesh Head --drivers FaceCtrl (custom props 0..1 per key)+ MCP: import shapekeys; print(shapekeys.run(mesh="Head", create="arkit"))+"""+import os+import sys++import bpy+import numpy as np++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++ARKIT = [+ "browDownLeft", "browDownRight", "browInnerUp", "browOuterUpLeft", "browOuterUpRight",+ "cheekPuff", "cheekSquintLeft", "cheekSquintRight",+ "eyeBlinkLeft", "eyeBlinkRight", "eyeLookDownLeft", "eyeLookDownRight", "eyeLookInLeft",+ "eyeLookInRight", "eyeLookOutLeft", "eyeLookOutRight", "eyeLookUpLeft", "eyeLookUpRight",+ "eyeSquintLeft", "eyeSquintRight", "eyeWideLeft", "eyeWideRight",+ "jawForward", "jawLeft", "jawOpen", "jawRight",+ "mouthClose", "mouthDimpleLeft", "mouthDimpleRight", "mouthFrownLeft", "mouthFrownRight",+ "mouthFunnel", "mouthLeft", "mouthLowerDownLeft", "mouthLowerDownRight", "mouthPressLeft",+ "mouthPressRight", "mouthPucker", "mouthRight", "mouthRollLower", "mouthRollUpper",+ "mouthShrugLower", "mouthShrugUpper", "mouthSmileLeft", "mouthSmileRight", "mouthStretchLeft",+ "mouthStretchRight", "mouthUpperUpLeft", "mouthUpperUpRight", "noseSneerLeft", "noseSneerRight",+ "tongueOut",+]+VISEMES = ["viseme_sil", "viseme_PP", "viseme_FF", "viseme_TH", "viseme_DD", "viseme_kk", "viseme_CH",+ "viseme_SS", "viseme_nn", "viseme_RR", "viseme_aa", "viseme_E", "viseme_I", "viseme_O", "viseme_U"]+++def _keys(ob):+ if ob.data.shape_keys is None:+ ob.shape_key_add(name="Basis", from_mix=False)+ return ob.data.shape_keys.key_blocks+++def _co(kb):+ a = np.empty(len(kb.data) * 3, dtype=np.float32)+ kb.data.foreach_get("co", a)+ return a.reshape(-1, 3)+++def run(mesh=None, create=None, split=None, mirror=None, report=False, drivers=None, falloff=0.02,+ style="arkit", **_):+ bx.object_mode()+ ob = bpy.data.objects[mesh]+ kbs = _keys(ob)+ out = {"ok": True, "mesh": ob.name}+ if create:+ names = ARKIT if create == "arkit" else VISEMES+ made = [n for n in names if n not in kbs]+ for n in made:+ ob.shape_key_add(name=n, from_mix=False)+ out["created"] = len(made)+ if split:+ src = kbs[split]+ basis = _co(kbs[0])+ delta = _co(src) - basis+ x = basis[:, 0]+ w_left = np.clip(0.5 + x / (2 * max(falloff, 1e-6)), 0, 1) # character left = +X+ names = ((f"{split}Left", f"{split}Right") if style == "arkit" else (f"{split}.L", f"{split}.R"))+ for nm, w in zip(names, (w_left, 1 - w_left)):+ kb = kbs.get(nm) or ob.shape_key_add(name=nm, from_mix=False)+ kb.data.foreach_set("co", (basis + delta * w[:, None]).ravel())+ out["split"] = list(names)+ if mirror:+ src = kbs[mirror]+ target = mirror.replace("Left", "Right") if "Left" in mirror else mirror.replace("Right", "Left") \+ if "Right" in mirror else mirror.replace(".L", ".R") if ".L" in mirror else mirror.replace(".R", ".L")+ if target == mirror:+ raise ValueError("key name has no Left/Right/.L/.R side")+ old = kbs.get(target)+ if old:+ ob.shape_key_remove(old)+ ob.active_shape_key_index = list(kbs).index(src)+ with bpy.context.temp_override(object=ob, active_object=ob):+ bpy.ops.object.shape_key_add(from_mix=False)+ new = ob.active_shape_key+ new.data.foreach_set("co", _co(src).ravel())+ new.name = target+ with bpy.context.temp_override(object=ob, active_object=ob):+ res = bpy.ops.object.shape_key_mirror(use_topology=False)+ out["mirrored"] = {"from": mirror, "to": target, "op": list(res)}+ if drivers:+ ctrl = bpy.data.objects.get(drivers) or bpy.data.objects.new(drivers, None)+ if ctrl.name not in bpy.context.scene.objects:+ bpy.context.scene.collection.objects.link(ctrl)+ n = 0+ for kb in list(kbs)[1:]:+ ctrl[kb.name] = 0.0+ ui = ctrl.id_properties_ui(kb.name)+ ui.update(min=0.0, max=1.0, soft_min=0.0, soft_max=1.0)+ kb.driver_remove("value")+ fc = kb.driver_add("value")+ d = fc.driver+ d.type = "AVERAGE"+ v = d.variables.new()+ v.type = "SINGLE_PROP"+ v.targets[0].id = ctrl+ v.targets[0].data_path = f'["{kb.name}"]'+ n += 1+ out["drivers"] = {"controller": ctrl.name, "count": n}+ if report or not any((create, split, mirror, drivers)):+ basis = _co(kbs[0])+ rows = {}+ for kb in list(kbs)[1:]:+ d = np.linalg.norm(_co(kb) - basis, axis=1)+ rows[kb.name] = round(float(d.max()), 5)+ out["keys"] = len(kbs) - 1+ out["unsculpted"] = [k for k, v in rows.items() if v < 1e-6]+ out["max_offset"] = {k: v for k, v in rows.items() if v >= 1e-6}+ if create == "arkit" or any(k in kbs for k in ARKIT):+ out["arkit_missing"] = [n for n in ARKIT if n not in kbs]+ return out+++if __name__ == "__main__":+ p = bx.parser(__doc__)+ p.add_argument("--mesh", required=True)+ p.add_argument("--create", choices=["arkit", "visemes"], default=None)+ p.add_argument("--split", default=None)+ p.add_argument("--mirror", default=None)+ p.add_argument("--report", action="store_true")+ p.add_argument("--drivers", default=None, help="controller object name")+ p.add_argument("--falloff", type=float, default=0.02, help="blend width across X=0 (m)")+ p.add_argument("--style", choices=["arkit", "dot"], default="arkit")+ p.add_argument("--save", default=None)+ bx.cli(run, p)diff --git a/skills/blender-game-optimization/SKILL.md b/skills/blender-game-optimization/SKILL.mdnew file mode 100644index 0000000..8c27505--- /dev/null+++ b/skills/blender-game-optimization/SKILL.md@@ -0,0 +1,67 @@+---+name: blender-game-optimization+description: Optimize Blender assets for real-time engines - triangle/material/texture/bone budgets per platform (mobile, Roblox, web, VR, console, PC), LOD chains, decimation modes, mesh cleanup, draw-call reduction (material merging, atlases, trim sheets), instancing, vertex-split costs, collision proxies, texture memory. Use when an asset is too heavy, before export, or when targeting a platform budget.+license: MIT+metadata:+ author: blender-agent-skills+ version: "0.1.0"+---++# Game Optimization++The execution model is in `blender-core`. Always re-run `blender-asset-qa` after optimizing.++## Procedure+1. **Measure**: `scripts/mesh_stats.py -- --objects ... --budget mobile|roblox|web|vr|console|pc`. It returns tris, estimated draw calls, materials, texture VRAM, bones, and the over-budget items.+2. **Clean**: `make_lods.py --cleanup` (merge by distance 0.1 mm, dissolve degenerate, delete loose). Remove hidden faces: back-to-back faces and faces under other parts (`qa_check` → `back_to_back`, plus manual xray).+3. **Reduce in this order** (cheapest visual loss first): hidden/interior geometry → unnecessary edge loops on flat areas (Limited Dissolve 1–5°) → over-segmented cylinders → Decimate → bake detail to normals (`blender-texture-baking`).+4. **Materials**: merge to 1–2 per asset (atlas / trim sheet / shared tiling material). Each material slot per mesh is roughly one draw call.+5. **LODs**: `scripts/make_lods.py -- --objects SM_X --rename` creates `_LOD1.._LOD3` at 50/25/12.5%. Check every LOD silhouette with `look`/`review_shots`.+6. **Re-measure**, then QA, then export (`blender-export-pipelines`).++## Budgets (guidance per asset, 2026)+| Platform | Hero char tris | Prop tris | Mats/asset | Max texture | Bones |+|---|---|---|---|---|---|+| Mobile | 5–15k | 0.3–3k | 1–2 | 1024 | ≤75 |+| Roblox | body ≤10,742 (head 4k, torso 1.75k, limb 1,248); accessory/clothing 4k | ≤20k per MeshPart | 1 (SurfaceAppearance) | 1024 (PBR), 4k max | R15 + optional |+| Web (three.js/Babylon) | 10–30k | 1–10k | 1–2 | 2048 | ≤100 |+| Standalone VR (Quest) | 10–40k | 1–10k | 1–3 | 2048 | ≤100 |+| Console / PC | 50–150k | 5–50k | 2–6 | 4096 | 150–300 |+| UE5 Nanite (static) | — | millions OK | few | 4096+ | n/a |+Whole-scene limits matter more than single assets: mobile ≈ 100–300k tris visible and < 100–200 draw calls; PC ≈ millions of tris and < 2–5k draw calls.++## Decimate modes+| Mode | Use | Notes |+|---|---|---|+| `COLLAPSE` (ratio) | organic, scans, LODs | `use_symmetry`, vertex group factor to protect faces/hands; triangulates |+| `UNSUBDIV` (iterations) | meshes made by subdividing quads | restores the quad grid cleanly |+| `DISSOLVE` (planar, angle) | hard-surface / CAD | delimit `{"SEAM","SHARP","MATERIAL","UV"}`; keeps the silhouette, makes n-gons → triangulate on export |+Protect UV seams and silhouette: decimate a copy, then compare. If UVs tear at LOD1, the ratio is too aggressive for that topology, so re-unwrap or use a manual LOD.++## The hidden cost: vertex splits+GPU vertex count = unique (position, normal, UV, color) combinations. Every UV seam and hard edge **duplicates** vertices, so engine vertex counts are often 1.5–3× Blender's. Minimize seams where they aren't needed, keep hard edges = seams (so the split happens once), and don't add vertex colors or extra UV sets you don't use.++## LOD rules+- Halve the tris per level. Switch at screen size ~0.5 / 0.25 / 0.125 (UE "Screen Size", Unity LOD Group %, Godot `lod_bias` auto).+- LODs keep the same materials (or fewer: merge them at LOD2+), same pivot, same bounds.+- Skeletal LODs: remove finger/face bones at LOD2+ (the engine bone-reduction tools handle this). Keep the skinning on the same skeleton.+- Far LOD / foliage: impostor/billboard. Unreal Nanite (static, opaque/masked) and Godot's auto mesh LOD can replace a hand-made chain.+- Roblox: no manual LODs. `RenderFidelity=Automatic` does it. Keep each MeshPart ≤ 20k tris and use a simple `CollisionFidelity` (Box/Hull) for non-walkable parts.++## Draw calls and batching+- **Merge** static meshes that share a material and are always seen together (join objects). **Don't merge** across large areas, because that defeats frustum/occlusion culling.+- **Instancing**: repeated objects as linked duplicates (Alt+D, shared mesh) or collection instances. They export as instances (glTF `EXT_mesh_gpu_instancing` with `export_gpu_instances`) or as one mesh + transforms in the engine.+- **Atlases/trim sheets**: put many props on one texture set. Trim sheets let walls, panels and pipes share one 2k material.+- **Texture memory** (upper bound, uncompressed RGBA8 + mips): 1k = 5.3 MB, 2k = 21 MB, 4k = 85 MB. Engines compress (BC7/ASTC ≈ 4–8×). Pack grayscale maps into ORM channels to cut it 3×.++## Collision+Keep collision separate and simple: boxes/convex hulls of ≤ 32–255 verts. UE `UCX_<Mesh>_##`, Godot `-colonly`/`-convcolonly` suffix, Unity MeshCollider on a simplified mesh, Roblox `CollisionFidelity`. Never use the render mesh as a physics mesh for anything that moves.++## Rig and animation cost+Limit to 4 influences per vertex (`vertex_group_limit_total(limit=4)` + normalize). Remove non-deforming bones from the export (`use_armature_deform_only`). Bake constraints and drivers to keys. Shape keys cost memory per vertex, so drop unused ones and keep only deltas (glTF sparse accessors handle this).++## Gotchas+- Decimate on meshes with unapplied modifiers: `make_lods.py` evaluates them first. Other paths need you to apply them.+- Join (`Ctrl+J`) merges materials and UV maps by **name**. Rename the UV maps identically first, or the UVs get lost.+- The `Weld` modifier is the non-destructive merge by distance. Use `mode="CONNECTED"` to avoid welding separate parts.+- Triangulate before measuring if the engine will. Quads already count as 2 tris in the stats.diff --git a/skills/blender-game-optimization/scripts/_bpyx.py b/skills/blender-game-optimization/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-game-optimization/scripts/_bpyx.py@@ -0,0 +1,136 @@+"""_bpyx - tiny shared helpers for blender-agent-skills scripts (Blender 5.2+).++Source of truth: shared/_bpyx.py. Copies in skills/*/scripts/ are synced by+tools/sync_shared.py - never edit a copy.++Every skill script follows one contract:+ run(**kwargs) -> dict # call from MCP / Python (import the module)+ blender -b f.blend -P x.py -- --arg v # CLI: prints one line "@@JSON@@{...}"+"""+import argparse+import json+import sys++import bpy++MARK = "@@JSON@@"+++def argv():+ """Arguments after '--' (Blender ignores them)."""+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def _default(o):+ if hasattr(o, "__len__") and not isinstance(o, str):+ try:+ return [round(v, 5) if isinstance(v, float) else v for v in o]+ except TypeError:+ pass+ if isinstance(o, (set, frozenset)):+ return sorted(o)+ return str(o)+++def emit(data):+ """Print compact JSON on one marked line (parsed by run_in_blender.py)."""+ print(MARK + json.dumps(data, separators=(",", ":"), default=_default), flush=True)+ return data+++def parser(doc):+ """ArgumentParser whose help is the script docstring's first line."""+ return argparse.ArgumentParser(description=(doc or "").strip().splitlines()[0])+++def cli(run, p):+ """CLI entry: parse args after '--', run, emit JSON. Exit 1 on failure."""+ args = p.parse_args(argv())+ try:+ result = run(**vars(args))+ save = getattr(args, "save", None)+ if save:+ bpy.ops.wm.save_as_mainfile(filepath=bpy.path.abspath(save))+ result["saved"] = save+ emit(result)+ except Exception as e: # report, don't dump a traceback into agent context+ emit({"ok": False, "error": f"{type(e).__name__}: {e}"})+ if bpy.app.background:+ sys.exit(1)+++def add_common(p, save=True):+ """--objects / --save flags shared by most scripts."""+ p.add_argument("--objects", nargs="*", default=None,+ help="object names (default: selected, else all meshes)")+ if save:+ p.add_argument("--save", default=None, help="save .blend to this path after run")+ return p+++def objects(names=None, types=("MESH",)):+ """Resolve names -> objects. No names: selected of `types`, else all visible of `types`."""+ if names:+ missing = [n for n in names if n not in bpy.data.objects]+ if missing:+ raise KeyError(f"objects not found: {missing}")+ return [bpy.data.objects[n] for n in names]+ pool = [o for o in bpy.context.scene.objects if not types or o.type in types]+ sel = [o for o in pool if o.select_get()]+ return sel or [o for o in pool if o.visible_get()]+++def object_mode():+ """Leave edit/sculpt/pose modes; most data API work needs OBJECT mode."""+ ob = bpy.context.view_layer.objects.active+ if ob and ob.mode != "OBJECT":+ bpy.ops.object.mode_set(mode="OBJECT")+++def select_only(objs, active=None):+ """Select exactly `objs` and make `active` (default first) active."""+ for o in bpy.context.view_layer.objects:+ o.select_set(False)+ for o in objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = active or (objs[0] if objs else None)+++def node(tree, type_):+ """First node of `type_` (e.g. 'BSDF_PRINCIPLED'). Names are localized - never look up by name."""+ return next((n for n in tree.nodes if n.type == type_), None)+++def enum_ids(owner, prop):+ """Valid identifiers of an enum property (works on types or instances)."""+ return [i.identifier for i in owner.bl_rna.properties[prop].enum_items]+++def set_enum(owner, prop, value):+ """Assign an enum; on failure raise listing valid values (dynamic enums under-report)."""+ try:+ setattr(owner, prop, value)+ except TypeError as e:+ raise ValueError(f"{prop}={value!r} invalid: {e}") from None+++def mesh_tris(ob, evaluated=True):+ """Triangle count (evaluated = with modifiers)."""+ if evaluated:+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ try:+ me.calc_loop_triangles()+ return len(me.loop_triangles)+ finally:+ eo.to_mesh_clear()+ me = ob.data+ me.calc_loop_triangles()+ return len(me.loop_triangles)+++def r(v, n=4):+ """Round a float or a vector for compact JSON."""+ if isinstance(v, float):+ return round(v, n)+ return [round(x, n) for x in v]diff --git a/skills/blender-game-optimization/scripts/make_lods.py b/skills/blender-game-optimization/scripts/make_lods.pynew file mode 100644index 0000000..24b9662--- /dev/null+++ b/skills/blender-game-optimization/scripts/make_lods.py@@ -0,0 +1,94 @@+"""Generate an LOD chain (<name>_LOD1..N) with Decimate, preserving UV seams/normals/silhouette.++Default ratios halve the triangles per level: 1.0, 0.5, 0.25, 0.125. LOD0 is the source (renamed+<base>_LOD0 if --rename). Also cleans the mesh first (merge by distance, delete loose, degenerate).+Usage:+ blender -b f.blend -P make_lods.py -- --objects SM_Crate [--ratios 0.5 0.25 0.125]+ [--symmetry] [--cleanup] [--rename] [--collection LODs] [--save out.blend]+ MCP: import make_lods; print(make_lods.run(objects=["SM_Crate"], ratios=[0.5, 0.2]))+"""+import os+import sys++import bmesh+import bpy++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402+++def cleanup(ob, dist=1e-4):+ """Merge by distance, dissolve degenerate, delete loose. Returns removed vert count."""+ bm = bmesh.new()+ bm.from_mesh(ob.data)+ n0 = len(bm.verts)+ bmesh.ops.remove_doubles(bm, verts=bm.verts[:], dist=dist)+ bmesh.ops.dissolve_degenerate(bm, edges=bm.edges[:], dist=dist)+ loose = [v for v in bm.verts if not v.link_faces]+ bmesh.ops.delete(bm, geom=loose, context="VERTS")+ bm.to_mesh(ob.data)+ bm.free()+ return n0 - len(ob.data.vertices)+++def run(objects=None, ratios=None, symmetry=False, do_cleanup=False, rename=False,+ collection=None, **_):+ bx.object_mode()+ ratios = ratios or [0.5, 0.25, 0.125]+ out = {}+ for src in bx.objects(objects):+ base = src.name.split("_LOD")[0]+ rec = {}+ if do_cleanup:+ rec["cleanup_removed_verts"] = cleanup(src)+ if rename and not src.name.endswith("_LOD0"):+ src.name = f"{base}_LOD0"+ col = None+ if collection:+ col = bpy.data.collections.get(collection) or bpy.data.collections.new(collection)+ if col.name not in bpy.context.scene.collection.children:+ bpy.context.scene.collection.children.link(col)+ tris0 = bx.mesh_tris(src)+ rec["LOD0"] = tris0+ for i, ratio in enumerate(ratios, start=1):+ name = f"{base}_LOD{i}"+ old = bpy.data.objects.get(name)+ if old:+ bpy.data.objects.remove(old)+ lod = src.copy()+ lod.data = src.data.copy()+ lod.name = lod.data.name = name+ for c in [col] if col else src.users_collection:+ c.objects.link(lod)+ # apply existing modifiers into the copy, then decimate+ dg = bpy.context.evaluated_depsgraph_get()+ me = bpy.data.meshes.new_from_object(src.evaluated_get(dg))+ old_me, lod.data = lod.data, me+ bpy.data.meshes.remove(old_me)+ me.name = name+ lod.modifiers.clear()+ d = lod.modifiers.new("Decimate", "DECIMATE")+ d.decimate_type = "COLLAPSE"+ d.ratio = ratio+ d.use_symmetry = symmetry+ d.use_collapse_triangulate = True+ with bpy.context.temp_override(object=lod, active_object=lod, selected_objects=[lod],+ selected_editable_objects=[lod]):+ bpy.ops.object.modifier_apply(modifier=d.name)+ lod.hide_set(True)+ lod.hide_render = True+ rec[f"LOD{i}"] = bx.mesh_tris(lod, evaluated=False)+ out[src.name] = rec+ return {"ok": True, "lods": out,+ "screen_size_hint": {"LOD1": 0.5, "LOD2": 0.25, "LOD3": 0.125},+ "note": "check each LOD silhouette (look/review_shots) and UV seams; LOD3+ may need a billboard/imposter"}+++if __name__ == "__main__":+ p = bx.add_common(bx.parser(__doc__))+ p.add_argument("--ratios", nargs="*", type=float, default=None)+ p.add_argument("--symmetry", action="store_true")+ p.add_argument("--cleanup", dest="do_cleanup", action="store_true")+ p.add_argument("--rename", action="store_true")+ p.add_argument("--collection", default=None)+ bx.cli(run, p)diff --git a/skills/blender-game-optimization/scripts/mesh_stats.py b/skills/blender-game-optimization/scripts/mesh_stats.pynew file mode 100644index 0000000..d53b173--- /dev/null+++ b/skills/blender-game-optimization/scripts/mesh_stats.py@@ -0,0 +1,86 @@+"""Budget report: tris/verts per object, materials (draw calls), textures + VRAM, vs a platform budget.++Usage:+ blender -b f.blend -P mesh_stats.py -- [--objects A B] [--budget mobile|roblox|console|pc|vr|web]+ MCP: import mesh_stats; print(mesh_stats.run(budget="mobile"))+"""+import os+import sys++import bpy++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++# per-ASSET guidance, not hard engine limits (Roblox: 20k tris/mesh, 10,742 tris/R15 body - Creator Hub)+BUDGETS = {+ "mobile": {"char_tris": 15000, "prop_tris": 3000, "materials": 2, "tex": 1024, "bones": 75},+ "roblox": {"char_tris": 10742, "prop_tris": 20000, "materials": 1, "tex": 1024, "bones": None},+ "web": {"char_tris": 30000, "prop_tris": 10000, "materials": 2, "tex": 2048, "bones": 100},+ "vr": {"char_tris": 40000, "prop_tris": 10000, "materials": 3, "tex": 2048, "bones": 100},+ "console": {"char_tris": 80000, "prop_tris": 30000, "materials": 4, "tex": 4096, "bones": 250},+ "pc": {"char_tris": 150000, "prop_tris": 50000, "materials": 6, "tex": 4096, "bones": 300},+}+++def _vram(img):+ w, h = img.size+ bpp = 16 if img.is_float else 4+ return w * h * bpp * 4 / 3 # + mip chain, uncompressed upper bound+++def run(objects=None, budget=None, **_):+ bx.object_mode()+ obs = bx.objects(objects, types=("MESH",))+ per, mats, imgs = {}, set(), set()+ total_tris = total_verts = 0+ is_char = False+ for ob in obs:+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ me.calc_loop_triangles()+ t, v = len(me.loop_triangles), len(me.vertices)+ eo.to_mesh_clear()+ used = {s.material for s in ob.material_slots if s.material}+ mats |= used+ for m in used:+ for n in m.node_tree.nodes if m.node_tree else []:+ if n.type == "TEX_IMAGE" and n.image:+ imgs.add(n.image)+ arm = next((m.object for m in ob.modifiers if m.type == "ARMATURE" and m.object), None)+ is_char |= arm is not None+ per[ob.name] = {"tris": t, "verts": v, "materials": len(used),+ "modifiers": [m.type for m in ob.modifiers],+ "uv_maps": len(ob.data.uv_layers), "shape_keys":+ len(ob.data.shape_keys.key_blocks) if ob.data.shape_keys else 0}+ total_tris += t+ total_verts += v+ bones = max((len(m.object.data.bones) for ob in obs for m in ob.modifiers+ if m.type == "ARMATURE" and m.object), default=0)+ tex = [{"name": i.name, "size": list(i.size), "mb": round(_vram(i) / 2**20, 1)} for i in imgs]+ rep = {"ok": True, "objects": per, "total_tris": total_tris, "total_verts": total_verts,+ "draw_calls_est": sum(p["materials"] or 1 for p in per.values()),+ "unique_materials": len(mats), "textures": tex,+ "texture_vram_mb_uncompressed": round(sum(_vram(i) for i in imgs) / 2**20, 1),+ "bones": bones, "kind": "character" if is_char else "prop"}+ if budget:+ b = BUDGETS[budget]+ lim = b["char_tris"] if is_char else b["prop_tris"]+ over = []+ if total_tris > lim:+ over.append(f"tris {total_tris} > {lim}")+ if len(mats) > b["materials"]:+ over.append(f"materials {len(mats)} > {b['materials']} (merge/atlas)")+ big = [t["name"] for t in tex if max(t["size"]) > b["tex"]]+ if big:+ over.append(f"textures > {b['tex']}px: {big}")+ if b["bones"] and bones > b["bones"]:+ over.append(f"bones {bones} > {b['bones']}")+ rep["budget"] = {"name": budget, "limits": b, "over": over, "pass": not over}+ return rep+++if __name__ == "__main__":+ p = bx.add_common(bx.parser(__doc__), save=False)+ p.add_argument("--budget", choices=list(BUDGETS), default=None)+ bx.cli(run, p)diff --git a/skills/blender-geometry-nodes/SKILL.md b/skills/blender-geometry-nodes/SKILL.mdnew file mode 100644index 0000000..ac3433c--- /dev/null+++ b/skills/blender-geometry-nodes/SKILL.md@@ -0,0 +1,59 @@+---+name: blender-geometry-nodes+description: Geometry Nodes in Blender 5.2 - fields, domains, attributes, instancing, zones (simulation/repeat/for-each), closures/bundles, lists, SDF grids, node tools, baking, plus a JSON-to-node-tree builder and socket inspector. Use for scattering, procedural assets/environments, parametric tools and modifier inputs.+license: MIT+metadata:+ author: blender-agent-skills+ version: "0.1.0"+---++# Geometry Nodes++The execution model is in `blender-core`. Build trees with `scripts/gn_builder.py`, a compact JSON spec that's far cheaper than raw bpy. Look up exact socket names first, because they change between versions:+```+scripts/gn_builder.py -- --describe GeometryNodeDistributePointsOnFaces GeometryNodeInstanceOnPoints+scripts/gn_builder.py -- --spec scatter.json --apply Ground --set Density=20 Seed=3 Mask=@paint_mask+```+`--set Name=@attr` feeds a modifier input from a named attribute. The result reports evaluated vert/face counts and node warnings. The spec format is in the script docstring; full examples are in [references/recipes.md](references/recipes.md).++## Core concepts (get these right or nothing works)+- **Geometry** flows left→right through sockets with **circle** shapes. **Fields** (diamond sockets) are functions evaluated per element **on the node that consumes them**, in that node's domain/context.+- **Domains**: Point, Edge, Face, Face Corner, Spline, Instance, Layer. `Capture Attribute` freezes a field at a point in the graph (before topology changes), and `Evaluate on Domain` converts between domains.+- **Attributes**: built-ins (`position`, `normal`, `sharp_face`, `material_index`, `UVMap`...) plus named ones via `Store Named Attribute`. Named attributes persist after the modifier. That's how GN data reaches shaders (Attribute node) and exporters (glTF `export_attributes`, which exports names starting with `_`).+- **Instances** are cheap (one mesh, many transforms). **Realize Instances** only when you must edit per-instance geometry or export a single mesh. Realize as late as possible.+- Inputs exposed on the group interface become **modifier inputs** (5.2: `mod.properties.inputs.<identifier>.value`). Panels group them, menu sockets give enums.++## Zones and advanced types+| Feature | Nodes | Use |+|---|---|---|+| Simulation zone | `GeometryNodeSimulationInput/Output` (paired) | per-frame state: growth, particles, erosion; bake to keep |+| Repeat zone | `GeometryNodeRepeatInput/Output` | iterate N times (L-systems, relaxation, recursive subdivision) |+| For Each Element | `GeometryNodeForeachGeometryElementInput/Output` | run a sub-graph per element (per building lot, per island) |+| Closures / Bundles (5.0+) | `NodeClosureInput/Output`, `NodeCombineBundle`/`NodeSeparateBundle`, Evaluate Closure | pass functions/structured data around; reusable "strategy" node groups |+| Lists (5.2) | `GeometryNodeFieldToList`, `ListGetItem`, `ListLength`, `SortList`, `FilterList` | real arrays, not fields |+| Grids/SDF (4.x–5.x) | `MeshToSDFGrid`, `SDFGridBoolean`, `SDFGridFillet`, `SDFGridOffset`, `GridToMesh` | smooth booleans, remeshing, fillets, voxel effects |+| Physics (5.2, experimental) | `GeometryNodeXPBDSolver` + bundles | node-based cloth/hair, see `blender-simulation` |+| Gizmos | `GizmoLinear/Dial/Transform` | viewport handles for inputs |+Zones need `input.pair_with_output(output)` (spec key `pairs`), plus items on the output node (`repeat_items`, `state_items`, ...; spec 4th node field).++## Procedure+1. Sketch the data flow: source geometry → selection/masks (fields) → generate/instance → transform/randomize → realize/merge → set materials/shading → output.+2. `--describe` every node type you'll use, then write the spec and build. Check `node_warnings` and the evaluated counts.+3. Expose only meaningful inputs (density, seed, scale range, materials), with min/max set.+4. Look at it (`look`), check `blender-asset-qa` if the result will be exported (realized geometry), and check `blender-game-optimization` for instance counts and tris.+5. Ship: either keep it procedural (the .blend/asset library), or apply the modifier / `visual_geometry_to_objects` for exporters.++## Rules+- Randomness: always expose a `Seed`, and use `Random Value` with the ID/Index field so results stay stable when counts change.+- Scale-independent setups use `Object Info` (Relative) and real units. Apply the object scale or read it explicitly.+- Materials: `Set Material` inside the tree. The material must exist in the file, and instances keep their own materials.+- Shading: GN output loses auto-smooth unless you add `Set Shade Smooth` + (5.x) the `Smooth by Angle` essentials group, or store `sharp_edge`.+- UVs: primitives output `UVMap` via their UV output. Store it with `Store Named Attribute` (Face Corner, 2D Vector, name `UVMap`) or it's dropped.+- Performance: avoid realizing millions of instances, prefer Points + instances for scatter, use `Merge by Distance` sparingly, and simulation zones need baking for playback/export (`object.geometry_node_bake_single` or modifier `bakes`).+- Node tools (`ng.is_tool = True`, `is_mode_edit` etc.) turn a group into an operator in the 3D View menus, for editing workflows.++## Gotchas+- 5.2: `mod["Socket_2"]` no longer works. Use `getattr(mod.properties.inputs, ident).value`, and `.type = "ATTRIBUTE"` + `.attribute_name` for attribute inputs. Compare and Random Value **sockets changed**: Random Value now has single dynamic `Min`/`Max`/`Value` sockets typed by `data_type`. Link by name, and `--describe` when unsure.+- Sockets that are disabled for the current mode/data type are still in `node.inputs` with the same name. The builder picks the **enabled** one. Set `data_type`/`mode` props first (the builder sets props before links).+- `nt.interface.new_socket(...)` is the 4.0+ API (`ng.inputs.new` is gone).+- Exporters see the **evaluated** mesh. Instances become glTF instancing (`export_gpu_instances`) or are realized on export.diff --git a/skills/blender-geometry-nodes/references/recipes.md b/skills/blender-geometry-nodes/references/recipes.mdnew file mode 100644index 0000000..ca90979--- /dev/null+++ b/skills/blender-geometry-nodes/references/recipes.md@@ -0,0 +1,66 @@+# gn_builder recipes (specs verified on 5.2)++Pass these as `spec=` (MCP) or save them as JSON for `--spec`. Run `--describe` to check socket names when you change node types.++## Scatter instances on a surface+```json+{"name": "GN_Scatter",+ "inputs": [["Geometry","GEOMETRY"], ["Density","FLOAT",10,{"min":0}], ["Seed","INT",0],+ ["Instance","OBJECT"], ["Scale Min","FLOAT",0.8], ["Scale Max","FLOAT",1.2]],+ "outputs": [["Geometry","GEOMETRY"]],+ "nodes": {+ "dist": ["GeometryNodeDistributePointsOnFaces", {"distribute_method":"RANDOM"}],+ "obj": ["GeometryNodeObjectInfo", {"transform_space":"RELATIVE"}],+ "rnd": ["FunctionNodeRandomValue", {"data_type":"FLOAT"}],+ "inst": ["GeometryNodeInstanceOnPoints"],+ "join": ["GeometryNodeJoinGeometry"]},+ "links": [["in.Geometry","dist.Mesh"], ["in.Density","dist.Density"], ["in.Seed","dist.Seed"],+ ["in.Instance","obj.Object"], ["dist.Points","inst.Points"], ["obj.Geometry","inst.Instance"],+ ["dist.Rotation","inst.Rotation"],+ ["in.Scale Min","rnd.Min"], ["in.Scale Max","rnd.Max"], ["in.Seed","rnd.Seed"], ["rnd.Value","inst.Scale"],+ ["inst.Instances","join.Geometry"], ["in.Geometry","join.Geometry"], ["join.Geometry","out.Geometry"]]}+```+5.2: Random Value has dynamic sockets (`Min`, `Max`, `ID`, `Seed` → `Value`) whose type follows `data_type`. Older tutorials use index-based duplicates, which no longer exist. Distribute Points outputs `Rotation` (aligned to the normal) directly.++## Pipe / cable along a curve+```json+{"name": "GN_Pipe",+ "inputs": [["Geometry","GEOMETRY"], ["Radius","FLOAT",0.05], ["Resolution","INT",12]],+ "outputs": [["Geometry","GEOMETRY"]],+ "nodes": {"circle": ["GeometryNodeCurvePrimitiveCircle"],+ "c2m": ["GeometryNodeCurveToMesh", {}, {"Fill Caps": true}],+ "smooth": ["GeometryNodeSetShadeSmooth"]},+ "links": [["in.Resolution","circle.Resolution"], ["in.Radius","circle.Radius"],+ ["in.Geometry","c2m.Curve"], ["circle.Curve","c2m.Profile Curve"],+ ["c2m.Mesh","smooth.Geometry"], ["smooth.Geometry","out.Geometry"]]}+```+Apply to a curve object (`bpy.data.curves.new(..., "CURVE")`). Add `Resample Curve` for even segments.++## Repeat zone (iterative subdivide)+```json+{"name": "GN_Repeat", "inputs": [["Geometry","GEOMETRY"], ["Count","INT",3]], "outputs": [["Geometry","GEOMETRY"]],+ "nodes": {"rin": ["GeometryNodeRepeatInput"], "rout": ["GeometryNodeRepeatOutput"],+ "sub": ["GeometryNodeSubdivideMesh", {}, {"Level": 1}]},+ "pairs": [["rin","rout"]],+ "links": [["in.Count","rin.Iterations"], ["in.Geometry","rin.Geometry"], ["rin.Geometry","sub.Mesh"],+ ["sub.Mesh","rout.Geometry"], ["rout.Geometry","out.Geometry"]]}+```+The repeat output starts with one `Geometry` item. Add more state with the 4th node field: `{"repeat_items": [["GEOMETRY","Geometry"], ["FLOAT","Value"]]}`.++## Store a mask attribute for shaders/export+```json+{"name": "GN_HeightMask", "inputs": [["Geometry","GEOMETRY"]], "outputs": [["Geometry","GEOMETRY"]],+ "nodes": {"pos": ["GeometryNodeInputPosition"], "sep": ["ShaderNodeSeparateXYZ"],+ "store": ["GeometryNodeStoreNamedAttribute", {"data_type":"FLOAT","domain":"POINT"}, {"Name":"_height"}]},+ "links": [["in.Geometry","store.Geometry"], ["pos.Position","sep.Vector"], ["sep.Z","store.Value"],+ ["store.Geometry","out.Geometry"]]}+```+Read it in a material with an Attribute node (`attribute_name="_height"`). glTF exports `_`-prefixed attributes with `export_attributes=True`.++## Shader tree with the same builder+```json+{"tree": "shader", "material": "M_Rust",+ "nodes": {"out": ["ShaderNodeOutputMaterial"], "bsdf": ["ShaderNodeBsdfPrincipled"],+ "noise": ["ShaderNodeTexNoise", {}, {"Scale": 8.0}], "ramp": ["ShaderNodeValToRGB"]},+ "links": [["noise.Fac","ramp.Fac"], ["ramp.Color","bsdf.Base Color"], ["bsdf.BSDF","out.Surface"]]}+```diff --git a/skills/blender-geometry-nodes/scripts/_bpyx.py b/skills/blender-geometry-nodes/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-geometry-nodes/scripts/_bpyx.py@@ -0,0 +1,136 @@+"""_bpyx - tiny shared helpers for blender-agent-skills scripts (Blender 5.2+).++Source of truth: shared/_bpyx.py. Copies in skills/*/scripts/ are synced by+tools/sync_shared.py - never edit a copy.++Every skill script follows one contract:+ run(**kwargs) -> dict # call from MCP / Python (import the module)+ blender -b f.blend -P x.py -- --arg v # CLI: prints one line "@@JSON@@{...}"+"""+import argparse+import json+import sys++import bpy++MARK = "@@JSON@@"+++def argv():+ """Arguments after '--' (Blender ignores them)."""+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def _default(o):+ if hasattr(o, "__len__") and not isinstance(o, str):+ try:+ return [round(v, 5) if isinstance(v, float) else v for v in o]+ except TypeError:+ pass+ if isinstance(o, (set, frozenset)):+ return sorted(o)+ return str(o)+++def emit(data):+ """Print compact JSON on one marked line (parsed by run_in_blender.py)."""+ print(MARK + json.dumps(data, separators=(",", ":"), default=_default), flush=True)+ return data+++def parser(doc):+ """ArgumentParser whose help is the script docstring's first line."""+ return argparse.ArgumentParser(description=(doc or "").strip().splitlines()[0])+++def cli(run, p):+ """CLI entry: parse args after '--', run, emit JSON. Exit 1 on failure."""+ args = p.parse_args(argv())+ try:+ result = run(**vars(args))+ save = getattr(args, "save", None)+ if save:+ bpy.ops.wm.save_as_mainfile(filepath=bpy.path.abspath(save))+ result["saved"] = save+ emit(result)+ except Exception as e: # report, don't dump a traceback into agent context+ emit({"ok": False, "error": f"{type(e).__name__}: {e}"})+ if bpy.app.background:+ sys.exit(1)+++def add_common(p, save=True):+ """--objects / --save flags shared by most scripts."""+ p.add_argument("--objects", nargs="*", default=None,+ help="object names (default: selected, else all meshes)")+ if save:+ p.add_argument("--save", default=None, help="save .blend to this path after run")+ return p+++def objects(names=None, types=("MESH",)):+ """Resolve names -> objects. No names: selected of `types`, else all visible of `types`."""+ if names:+ missing = [n for n in names if n not in bpy.data.objects]+ if missing:+ raise KeyError(f"objects not found: {missing}")+ return [bpy.data.objects[n] for n in names]+ pool = [o for o in bpy.context.scene.objects if not types or o.type in types]+ sel = [o for o in pool if o.select_get()]+ return sel or [o for o in pool if o.visible_get()]+++def object_mode():+ """Leave edit/sculpt/pose modes; most data API work needs OBJECT mode."""+ ob = bpy.context.view_layer.objects.active+ if ob and ob.mode != "OBJECT":+ bpy.ops.object.mode_set(mode="OBJECT")+++def select_only(objs, active=None):+ """Select exactly `objs` and make `active` (default first) active."""+ for o in bpy.context.view_layer.objects:+ o.select_set(False)+ for o in objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = active or (objs[0] if objs else None)+++def node(tree, type_):+ """First node of `type_` (e.g. 'BSDF_PRINCIPLED'). Names are localized - never look up by name."""+ return next((n for n in tree.nodes if n.type == type_), None)+++def enum_ids(owner, prop):+ """Valid identifiers of an enum property (works on types or instances)."""+ return [i.identifier for i in owner.bl_rna.properties[prop].enum_items]+++def set_enum(owner, prop, value):+ """Assign an enum; on failure raise listing valid values (dynamic enums under-report)."""+ try:+ setattr(owner, prop, value)+ except TypeError as e:+ raise ValueError(f"{prop}={value!r} invalid: {e}") from None+++def mesh_tris(ob, evaluated=True):+ """Triangle count (evaluated = with modifiers)."""+ if evaluated:+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ try:+ me.calc_loop_triangles()+ return len(me.loop_triangles)+ finally:+ eo.to_mesh_clear()+ me = ob.data+ me.calc_loop_triangles()+ return len(me.loop_triangles)+++def r(v, n=4):+ """Round a float or a vector for compact JSON."""+ if isinstance(v, float):+ return round(v, n)+ return [round(x, n) for x in v]diff --git a/skills/blender-geometry-nodes/scripts/gn_builder.py b/skills/blender-geometry-nodes/scripts/gn_builder.pynew file mode 100644index 0000000..5ade425--- /dev/null+++ b/skills/blender-geometry-nodes/scripts/gn_builder.py@@ -0,0 +1,208 @@+"""Build node trees (Geometry Nodes, shader, compositor) from a compact JSON spec, apply them as+modifiers with input values (5.2 RNA API), and describe node types' sockets.++Spec (JSON file or dict):+{ "name": "Scatter", "tree": "geometry" | "shader" | "compositor",+ "material": "M_X", # shader: build inside this material+ "inputs": [["Geometry","GEOMETRY"], ["Density","FLOAT",10,{"min":0}]],+ "outputs": [["Geometry","GEOMETRY"]],+ "nodes": { "dist": ["GeometryNodeDistributePointsOnFaces", {"distribute_method":"RANDOM"},+ {"Density": 5.0}], # [type, props, input defaults]+ "rep_in": ["GeometryNodeRepeatInput"], "rep_out": ["GeometryNodeRepeatOutput", {},+ {}, {"repeat_items": [["GEOMETRY","Geometry"]]}] }, # 4th: item collections+ "pairs": [["rep_in","rep_out"]], # zones: repeat / simulation / foreach / closure+ "links": [["in.Geometry","dist.Mesh"], ["dist.Points","inst.Points"], ["math.0","x.1"]] }+Socket refs: node.SocketName or node.<index>; "in"/"out" = group input/output.+Usage:+ blender -b f.blend -P gn_builder.py -- --spec tree.json [--apply Plane] [--set Density=20] [--save out.blend]+ blender -b -P gn_builder.py -- --describe GeometryNodeDistributePointsOnFaces [ShaderNodeMix ...]+ MCP: import gn_builder as g; print(g.run(spec={...}, apply="Plane", set=["Density=20"]))+"""+import json+import os+import sys++import bpy++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++SOCK = {k: f"NodeSocket{v}" for k, v in {+ "GEOMETRY": "Geometry", "FLOAT": "Float", "INT": "Int", "BOOLEAN": "Bool", "BOOL": "Bool",+ "VECTOR": "Vector", "COLOR": "Color", "RGBA": "Color", "STRING": "String", "OBJECT": "Object",+ "COLLECTION": "Collection", "MATERIAL": "Material", "IMAGE": "Image", "ROTATION": "Rotation",+ "MATRIX": "Matrix", "MENU": "Menu", "SHADER": "Shader", "BUNDLE": "Bundle", "CLOSURE": "Closure"}.items()}+TREE = {"geometry": "GeometryNodeTree", "shader": "ShaderNodeTree", "compositor": "CompositorNodeTree"}+++def describe(types):+ """Inputs/outputs (name, type, default) of node types, from a throwaway tree."""+ out = {}+ for t in types:+ kind = ("GeometryNodeTree" if t.startswith("GeometryNode") or t.startswith(("FunctionNode", "Node"))+ else "CompositorNodeTree" if t.startswith("CompositorNode") else "ShaderNodeTree")+ ng = bpy.data.node_groups.new("__describe__", kind)+ try:+ n = ng.nodes.new(t)++ def sock(s):+ d = getattr(s, "default_value", None)+ if d is not None and hasattr(d, "__len__") and not isinstance(d, str):+ d = [round(x, 4) for x in d]+ elif isinstance(d, float):+ d = round(d, 4)+ return [s.name, s.type, d] if d is not None and not isinstance(d, bpy.types.ID) else [s.name, s.type]+ props = {p.identifier: [i.identifier for i in p.enum_items] if p.type == "ENUM" else p.type+ for p in n.bl_rna.properties if not p.is_readonly+ and p.identifier not in bpy.types.Node.bl_rna.properties}+ out[t] = {"inputs": [sock(s) for s in n.inputs if s.enabled],+ "outputs": [sock(s) for s in n.outputs if s.enabled], "props": props}+ except RuntimeError as e:+ out[t] = {"error": str(e)}+ finally:+ bpy.data.node_groups.remove(ng)+ return out+++def _sock(nodes, ref, outputs):+ name, _, key = ref.partition(".")+ n = nodes[name]+ coll = n.outputs if outputs else n.inputs+ if key.isdigit():+ return coll[int(key)]+ s = next((s for s in coll if s.name == key and s.enabled), None) or coll.get(key)+ if s is None:+ raise KeyError(f"{ref}: no {'output' if outputs else 'input'} '{key}' on {n.bl_idname}; "+ f"have {[s.name for s in coll if s.enabled]}")+ return s+++def build(spec):+ kind = spec.get("tree", "geometry")+ if kind == "shader" and spec.get("material"):+ mat = bpy.data.materials.get(spec["material"]) or bpy.data.materials.new(spec["material"])+ nt = mat.node_tree+ if spec.get("clear", True):+ nt.nodes.clear()+ else:+ nt = bpy.data.node_groups.get(spec["name"])+ if nt is None:+ nt = bpy.data.node_groups.new(spec["name"], TREE[kind])+ nt.nodes.clear()+ nt.interface.clear()+ for io, key in (("INPUT", "inputs"), ("OUTPUT", "outputs")):+ for item in spec.get(key, []):+ s = nt.interface.new_socket(item[0], in_out=io, socket_type=SOCK[item[1].upper()])+ if len(item) > 2 and item[2] is not None and hasattr(s, "default_value"):+ s.default_value = item[2]+ for k, v in (item[3] if len(item) > 3 else {}).items():+ setattr(s, {"min": "min_value", "max": "max_value"}.get(k, k), v)+ if kind == "geometry":+ nt.is_modifier = True+ nodes = {}+ if kind != "shader" or not spec.get("material"):+ nodes["in"] = nt.nodes.new("NodeGroupInput")+ nodes["out"] = nt.nodes.new("NodeGroupOutput")+ for key, val in spec.get("nodes", {}).items():+ val = [val] if isinstance(val, str) else val+ n = nt.nodes.new(val[0])+ n.name = n.label = key+ for k, v in (val[1] if len(val) > 1 else {}).items():+ if k == "data_type" and hasattr(n, "data_type"):+ n.data_type = v+ else:+ setattr(n, k, bpy.data.objects.get(v) if k == "object" else v)+ for coll_name, items in (val[3] if len(val) > 3 else {}).items():+ coll = getattr(n, coll_name)+ coll.clear()+ for it in items:+ coll.new(*it)+ nodes[key] = n+ for a, b in spec.get("pairs", []):+ nodes[a].pair_with_output(nodes[b])+ for key, val in spec.get("nodes", {}).items(): # defaults after pairing (zone sockets exist now)+ val = [val] if isinstance(val, str) else val+ for k, v in (val[2] if len(val) > 2 else {}).items():+ s = _sock(nodes, f"{key}.{k}", outputs=False)+ s.default_value = bpy.data.objects.get(v, v) if isinstance(v, str) and s.type == "OBJECT" else v+ for a, b in spec.get("links", []):+ nt.links.new(_sock(nodes, a, True), _sock(nodes, b, False))+ _layout(nt)+ return nt+++def _layout(nt):+ """Column layout by longest path from inputs (readable trees for humans)."""+ depth = {n: 0 for n in nt.nodes}+ for _ in range(len(nt.nodes)):+ changed = False+ for l in nt.links:+ d = depth[l.from_node] + 1+ if d > depth[l.to_node]:+ depth[l.to_node], changed = d, True+ if not changed:+ break+ rows = {}+ for n, d in sorted(depth.items(), key=lambda kv: kv[1]):+ r = rows.get(d, 0)+ n.location = (d * 260, -r * 220)+ rows[d] = r + 1+++def apply(nt, ob_name, values):+ ob = bpy.data.objects[ob_name]+ mod = next((m for m in ob.modifiers if m.type == "NODES" and m.node_group == nt), None) \+ or ob.modifiers.new(nt.name, "NODES")+ mod.node_group = nt+ ids = {i.name: i.identifier for i in nt.interface.items_tree if getattr(i, "in_out", "") == "INPUT"}+ for k, v in values.items():+ item = getattr(mod.properties.inputs, ids[k])+ if isinstance(v, str) and v.startswith("@"): # @attr_name -> read from attribute+ item.type, item.attribute_name = "ATTRIBUTE", v[1:]+ else:+ item.value = bpy.data.objects.get(v, v) if isinstance(v, str) else v+ return mod+++def _parse_val(s):+ for t in (int, float):+ try:+ return t(s)+ except ValueError:+ pass+ if "," in s:+ return tuple(float(x) for x in s.split(","))+ return {"true": True, "false": False}.get(s.lower(), s)+++def run(spec=None, apply_to=None, set=None, describe_types=None, **_): # noqa: A002+ if describe_types:+ return {"ok": True, "nodes": describe(describe_types)}+ if isinstance(spec, str):+ with open(bpy.path.abspath(spec), encoding="utf-8") as f:+ spec = json.load(f)+ nt = build(spec)+ res = {"ok": True, "tree": nt.name, "nodes": len(nt.nodes), "links": len(nt.links)}+ if apply_to:+ vals = dict(kv.split("=", 1) for kv in set or [])+ mod = apply(nt, apply_to, {k: _parse_val(v) for k, v in vals.items()})+ ob = bpy.data.objects[apply_to]+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ res["evaluated"] = {"verts": len(me.vertices), "faces": len(me.polygons)} if me else None+ eo.to_mesh_clear()+ res["modifier"] = mod.name+ warn = [w.message for w in getattr(mod, "node_warnings", [])]+ if warn:+ res["node_warnings"] = warn[:10]+ return res+++if __name__ == "__main__":+ p = bx.parser(__doc__)+ p.add_argument("--spec", default=None)+ p.add_argument("--apply", dest="apply_to", default=None)+ p.add_argument("--set", nargs="*", default=None)+ p.add_argument("--describe", dest="describe_types", nargs="*", default=None)+ p.add_argument("--save", default=None)+ bx.cli(run, p)diff --git a/skills/blender-hardsurface-modeling/SKILL.md b/skills/blender-hardsurface-modeling/SKILL.mdnew file mode 100644index 0000000..5f54854--- /dev/null+++ b/skills/blender-hardsurface-modeling/SKILL.md@@ -0,0 +1,63 @@+---+name: blender-hardsurface-modeling+description: Hard-surface and prop modeling in Blender 5.2 - blockout-to-detail flow, non-destructive modifier stacks (Mirror, Boolean Exact/Manifold, Bevel, Weighted Normal, Smooth by Angle), mid-poly vs subdivision vs high-to-low workflows, shading/custom normals, cylinder segment budgets, edge attributes from Python. Use for weapons, vehicles, props, architecture, mechanical parts.+license: MIT+metadata:+ author: blender-agent-skills+ version: "0.1.0"+---++# Hard-Surface Modeling++The execution model is in `blender-core`. Run `blender-asset-qa` after every modeling pass.++## Pick the workflow first+| Workflow | When | Output |+|---|---|---|+| **Mid-poly** (bevel + weighted normals, no bake) | modern games, props seen up close, fast iteration | game mesh directly; tiling materials/trim sheets |+| **High → low** (high via booleans+bevel or subd, low baked) | hero assets, unique textures, tight tri budgets | `_high` + `_low` → `blender-texture-baking` |+| **Subdivision** (support loops/creases + Subsurf) | renders, product viz, film | smooth surfaces, edges held by loops/creases |++## Procedure+1. **Blockout** at real scale (`ob.dimensions`) from primitives. Settle the silhouette and proportions before any detail. Check against references.+2. **Apply scale** (`transform_apply(scale=True)`) before bevels, booleans or solidify, because modifier distances use object space.+3. **Primary → secondary → tertiary** forms. Booleans for cuts and panels, then bevels. Small tertiary details go in normal maps/decals, or into the high-poly as "floaters" for baking.+4. **UV the base mesh now** (mid-poly). Bevel/Boolean modifiers propagate UVs, but after bevels no edge is sharp enough to auto-seam. Then **build the stack** with `scripts/apply_stack.py -- --objects Body --preset midpoly --cutters Cut1 Cut2`. Order: Mirror → Booleans → Bevel → Weighted Normal → (Triangulate at export).+5. **Shading check**: smooth shading + Weighted Normal (keep sharp). There must be no gradients across flat faces. View with a matcap or `look` in `solid` shading.+6. **QA** with `blender-asset-qa`, then apply the stack only on an export copy (`--apply`), keeping the editable source.++## Stack rules+- **Booleans**: put cutters in a `Cutters` collection with display `WIRE` and `hide_render=True`. Solver: `EXACT` (robust default), `MANIFOLD` (much faster, but inputs must be closed manifold), `FLOAT` (legacy fast, fragile with coplanar faces). With many cutters, use `operand_type="COLLECTION"`.+- Avoid coplanar boolean faces: extend cutters slightly past the surface. They also cause z-fighting.+- **Bevel**: `limit_method="ANGLE"` (30°), or `"WEIGHT"` with a `bevel_weight_edge` attribute for hand-picked edges. Turn on `use_clamp_overlap`, `harden_normals=True`, `miter_outer="MITER_ARC"`. Width ≈ 0.5–2% of the part's size, kept consistent across the asset.+- **Weighted Normal** after Bevel: `mode="FACE_AREA"`, `keep_sharp=True`, weight 50. Needs smooth faces (remove the `sharp_face` attribute or call `shade_smooth`).+- **Smooth by Angle** (4.1+, replaces auto smooth): `bpy.ops.object.shade_auto_smooth(angle=rad)` adds a GN modifier, or `shade_smooth_by_angle` sets `sharp_edge` destructively.+- **Mirror**: `use_clip=True`, `use_mirror_merge=True`. Model one half only at x ≥ 0.+- **Subdivision**: hold edges with support loops (a loop 1–5% of the face width from the edge) or `crease_edge` (0–1). Turn on `use_limit_surface`. Don't use creases if the asset goes to an engine.+- **Triangulate** only for export/baking (`keep_custom_normals=True`, `BEAUTY`). Triangulating the bake mesh and the export mesh identically keeps normal maps synced.++## Topology rules+- **N-gons**: fine on flat, non-deforming faces in mid-poly/game meshes. Never use them on curved surfaces or anything that subdivides or deforms.+- **Poles** (5+ edges) should sit on flat areas, never on a curvature peak or bevel.+- **Cylinder segments by on-screen size**: small (bolts) 6–8, medium (handles) 12–16, large (barrels) 24–32, hero/close-up 48+. Use multiples of 4 or 8 so booleans/mirrors line up with existing loops.+- **No long, thin triangles** across visible curved areas (shading and LOD artifacts).+- **Panel lines**: inset + extrude in (mid-poly) or a boolean groove on the high-poly, then bake.+- Spend density where the silhouette needs it, not on flat faces.++## Edge/face attributes from Python (4.0+ names)+```python+me = ob.data+bw = me.attributes.get("bevel_weight_edge") or me.attributes.new("bevel_weight_edge", "FLOAT", "EDGE")+cr = me.attributes.get("crease_edge") or me.attributes.new("crease_edge", "FLOAT", "EDGE")+sh = me.attributes.get("sharp_edge") or me.attributes.new("sharp_edge", "BOOLEAN", "EDGE")+bw.data[edge_index].value = 1.0; sh.data[edge_index].value = True+me.edges[edge_index].use_seam = True # seams are still an edge property+```+Select sharp edges by angle in bmesh: `e.calc_face_angle(0) > math.radians(30)`.++## Gotchas+- A bevel that looks blobby or flips usually means unapplied/non-uniform scale or overlapping geometry (turn on clamp).+- A Boolean that returns nothing or garbage: the cutter isn't closed/manifold (Exact copes, Manifold fails), or its normals are inverted.+- Weighted Normal has no effect: faces are flat-shaded, or an earlier modifier destroyed the custom normals.+- 5.2: the GN `Mesh Bevel` node exists for procedural bevels inside node trees (`blender-geometry-nodes`).+- Trim-sheet/mid-poly assets: UVs go to the trim strips (`blender-retopology-uv`) and materials tile (`blender-pbr-materials`).diff --git a/skills/blender-hardsurface-modeling/scripts/_bpyx.py b/skills/blender-hardsurface-modeling/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-hardsurface-modeling/scripts/_bpyx.py@@ -0,0 +1,136 @@+"""_bpyx - tiny shared helpers for blender-agent-skills scripts (Blender 5.2+).++Source of truth: shared/_bpyx.py. Copies in skills/*/scripts/ are synced by+tools/sync_shared.py - never edit a copy.++Every skill script follows one contract:+ run(**kwargs) -> dict # call from MCP / Python (import the module)+ blender -b f.blend -P x.py -- --arg v # CLI: prints one line "@@JSON@@{...}"+"""+import argparse+import json+import sys++import bpy++MARK = "@@JSON@@"+++def argv():+ """Arguments after '--' (Blender ignores them)."""+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def _default(o):+ if hasattr(o, "__len__") and not isinstance(o, str):+ try:+ return [round(v, 5) if isinstance(v, float) else v for v in o]+ except TypeError:+ pass+ if isinstance(o, (set, frozenset)):+ return sorted(o)+ return str(o)+++def emit(data):+ """Print compact JSON on one marked line (parsed by run_in_blender.py)."""+ print(MARK + json.dumps(data, separators=(",", ":"), default=_default), flush=True)+ return data+++def parser(doc):+ """ArgumentParser whose help is the script docstring's first line."""+ return argparse.ArgumentParser(description=(doc or "").strip().splitlines()[0])+++def cli(run, p):+ """CLI entry: parse args after '--', run, emit JSON. Exit 1 on failure."""+ args = p.parse_args(argv())+ try:+ result = run(**vars(args))+ save = getattr(args, "save", None)+ if save:+ bpy.ops.wm.save_as_mainfile(filepath=bpy.path.abspath(save))+ result["saved"] = save+ emit(result)+ except Exception as e: # report, don't dump a traceback into agent context+ emit({"ok": False, "error": f"{type(e).__name__}: {e}"})+ if bpy.app.background:+ sys.exit(1)+++def add_common(p, save=True):+ """--objects / --save flags shared by most scripts."""+ p.add_argument("--objects", nargs="*", default=None,+ help="object names (default: selected, else all meshes)")+ if save:+ p.add_argument("--save", default=None, help="save .blend to this path after run")+ return p+++def objects(names=None, types=("MESH",)):+ """Resolve names -> objects. No names: selected of `types`, else all visible of `types`."""+ if names:+ missing = [n for n in names if n not in bpy.data.objects]+ if missing:+ raise KeyError(f"objects not found: {missing}")+ return [bpy.data.objects[n] for n in names]+ pool = [o for o in bpy.context.scene.objects if not types or o.type in types]+ sel = [o for o in pool if o.select_get()]+ return sel or [o for o in pool if o.visible_get()]+++def object_mode():+ """Leave edit/sculpt/pose modes; most data API work needs OBJECT mode."""+ ob = bpy.context.view_layer.objects.active+ if ob and ob.mode != "OBJECT":+ bpy.ops.object.mode_set(mode="OBJECT")+++def select_only(objs, active=None):+ """Select exactly `objs` and make `active` (default first) active."""+ for o in bpy.context.view_layer.objects:+ o.select_set(False)+ for o in objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = active or (objs[0] if objs else None)+++def node(tree, type_):+ """First node of `type_` (e.g. 'BSDF_PRINCIPLED'). Names are localized - never look up by name."""+ return next((n for n in tree.nodes if n.type == type_), None)+++def enum_ids(owner, prop):+ """Valid identifiers of an enum property (works on types or instances)."""+ return [i.identifier for i in owner.bl_rna.properties[prop].enum_items]+++def set_enum(owner, prop, value):+ """Assign an enum; on failure raise listing valid values (dynamic enums under-report)."""+ try:+ setattr(owner, prop, value)+ except TypeError as e:+ raise ValueError(f"{prop}={value!r} invalid: {e}") from None+++def mesh_tris(ob, evaluated=True):+ """Triangle count (evaluated = with modifiers)."""+ if evaluated:+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ try:+ me.calc_loop_triangles()+ return len(me.loop_triangles)+ finally:+ eo.to_mesh_clear()+ me = ob.data+ me.calc_loop_triangles()+ return len(me.loop_triangles)+++def r(v, n=4):+ """Round a float or a vector for compact JSON."""+ if isinstance(v, float):+ return round(v, n)+ return [round(x, n) for x in v]diff --git a/skills/blender-hardsurface-modeling/scripts/apply_stack.py b/skills/blender-hardsurface-modeling/scripts/apply_stack.pynew file mode 100644index 0000000..878c6c4--- /dev/null+++ b/skills/blender-hardsurface-modeling/scripts/apply_stack.py@@ -0,0 +1,104 @@+"""Build (and optionally apply) a production hard-surface modifier stack.++Presets:+ midpoly : booleans -> Bevel(angle, harden normals) -> Weighted Normal(keep sharp) [games]+ subd : booleans -> Bevel(1 seg, support edge) -> Subdivision(2) + Smooth by Angle [renders]+ render : booleans -> Bevel(4 seg, arc miter) -> Weighted Normal [renders]+Bevel width defaults to 1% of the object's largest dimension (override with --width, metres).+Usage:+ blender -b f.blend -P apply_stack.py -- --objects Body [--preset midpoly] [--width 0.01]+ [--segments 3] [--angle 30] [--cutters CutA CutB] [--solver EXACT|MANIFOLD|FLOAT]+ [--triangulate] [--apply] [--save out.blend]+ MCP: import apply_stack; print(apply_stack.run(objects=["Body"], cutters=["Hole"]))+"""+import math+import os+import sys++import bpy++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++PREFIX = "HS_" # our modifiers; re-running replaces them+++def _smooth_faces(me):+ a = me.attributes.get("sharp_face")+ if a:+ me.attributes.remove(a)+++def run(objects=None, preset="midpoly", width=None, segments=None, angle=30.0, cutters=None,+ solver="EXACT", operation="DIFFERENCE", triangulate=False, apply=False, **_):+ bx.object_mode()+ obs = bx.objects(objects)+ cut_obs = [bpy.data.objects[n] for n in cutters or []]+ for c in cut_obs:+ c.display_type = "WIRE"+ c.hide_render = True+ c.visible_shadow = False+ report = {}+ for ob in obs:+ if ob in cut_obs:+ continue+ for m in [m for m in ob.modifiers if m.name.startswith(PREFIX)]:+ ob.modifiers.remove(m)+ _smooth_faces(ob.data) # harden normals / weighted normals need smooth shading+ w = width or max(ob.dimensions) * 0.01 / max(max(ob.scale), 1e-6)+ for c in cut_obs:+ b = ob.modifiers.new(f"{PREFIX}Bool_{c.name}", "BOOLEAN")+ b.object, b.operation = c, operation+ bx.set_enum(b, "solver", solver)+ bev = ob.modifiers.new(f"{PREFIX}Bevel", "BEVEL")+ bev.width = w+ bev.limit_method = "ANGLE"+ bev.angle_limit = math.radians(angle)+ bev.use_clamp_overlap = True+ bev.miter_outer = "MITER_ARC"+ if preset == "subd":+ bev.segments = segments or 1+ sub = ob.modifiers.new(f"{PREFIX}Subd", "SUBSURF")+ sub.levels, sub.render_levels = 2, 2+ with bpy.context.temp_override(object=ob, active_object=ob, selected_objects=[ob],+ selected_editable_objects=[ob]):+ bpy.ops.object.shade_auto_smooth(angle=math.radians(angle))+ sba = ob.modifiers[-1]+ sba.name = f"{PREFIX}SmoothByAngle"+ else:+ bev.segments = segments or (3 if preset == "midpoly" else 4)+ bev.profile = 0.5+ bev.harden_normals = True+ wn = ob.modifiers.new(f"{PREFIX}WeightedNormal", "WEIGHTED_NORMAL")+ wn.mode, wn.weight, wn.keep_sharp = "FACE_AREA", 50, True+ if triangulate:+ t = ob.modifiers.new(f"{PREFIX}Triangulate", "TRIANGULATE")+ t.keep_custom_normals = True+ t.quad_method, t.ngon_method = "BEAUTY", "BEAUTY"+ before = bx.mesh_tris(ob, evaluated=False)+ after = bx.mesh_tris(ob)+ applied = []+ if apply:+ # names first: a modifier struct is freed once applied (reading it after = garbage/crash)+ for name in [m.name for m in ob.modifiers if m.name.startswith(PREFIX)]:+ with bpy.context.temp_override(object=ob, active_object=ob, selected_objects=[ob],+ selected_editable_objects=[ob]):+ res = bpy.ops.object.modifier_apply(modifier=name)+ applied.append(name if res == {"FINISHED"} else f"FAILED:{name}")+ report[ob.name] = {"bevel_width": round(w, 5), "tris_base": before, "tris_final": after,+ "stack": [m.name for m in ob.modifiers], "applied": applied}+ return {"ok": True, "preset": preset, "objects": report}+++if __name__ == "__main__":+ p = bx.add_common(bx.parser(__doc__))+ p.add_argument("--preset", default="midpoly", choices=["midpoly", "subd", "render"])+ p.add_argument("--width", type=float, default=None)+ p.add_argument("--segments", type=int, default=None)+ p.add_argument("--angle", type=float, default=30.0)+ p.add_argument("--cutters", nargs="*", default=None)+ p.add_argument("--solver", default="EXACT", choices=["EXACT", "MANIFOLD", "FLOAT"])+ p.add_argument("--operation", default="DIFFERENCE", choices=["DIFFERENCE", "UNION", "INTERSECT"])+ p.add_argument("--triangulate", action="store_true")+ p.add_argument("--apply", action="store_true")+ bx.cli(run, p)diff --git a/skills/blender-lighting-lookdev/SKILL.md b/skills/blender-lighting-lookdev/SKILL.mdnew file mode 100644index 0000000..0f6469e--- /dev/null+++ b/skills/blender-lighting-lookdev/SKILL.md@@ -0,0 +1,52 @@+---+name: blender-lighting-lookdev+description: Lighting, cameras and look-dev in Blender 5.2 - studio 3-point and product lighting, HDRI environments, sun/sky exteriors, interiors, light linking, physically based light units, camera focal lengths/composition/DOF, cyclorama backdrops, looping turntables for asset presentation. Use when presenting assets, setting up scenes for rendering, or judging materials under consistent light.+license: MIT+metadata:+ author: blender-agent-skills+ version: "0.1.0"+---++# Lighting & Look-dev++The execution model is in `blender-core`. Render settings are in `blender-rendering`.++## One call: presentation scene+```+scripts/turntable.py -- --objects Hero --rig studio --backdrop --frames 120 --lens 85+scripts/turntable.py -- --objects Hero --rig both --hdri //hdri/studio_small_09_2k.exr --hdri-strength 0.8+```+This builds a camera framed to the bounding sphere (on the narrower frame axis), a key/fill/rim area-light rig scaled to the asset, an optional 18%-grey cyclorama, and a pivot that orbits camera + lights + backdrop in a seamless loop. **The asset itself isn't modified.** Everything lives in the `LD_Lookdev` collection, and re-running replaces it. Set the render resolution **before** running, because framing depends on the aspect ratio.++## Lighting recipes+| Situation | Setup |+|---|---|+| Asset / product review | 3-point: key 45° side, 30–40° up; fill opposite at ⅓ power and lower; rim behind for silhouette. Large soft area lights (size ≈ object), neutral grey backdrop, Khronos PBR Neutral view |+| Reflective product (metal, glass, car paint) | large softboxes/strip lights *reflected* in the surface, plus a black/white gradient environment. Shape the reflections, not the illumination |+| Exterior day | Sun light (angle 0.5° for sharp, 2–5° for softer) + sky (`ShaderNodeTexSky`, `sky_type` `MULTIPLE_SCATTERING`/`SINGLE_SCATTERING`; 5.x replaced "Nishita"; `PREETHAM`/`HOSEK_WILKIE` legacy) with `sun_elevation`/`sun_rotation` matching the Sun light, or an HDRI of the matching time of day |+| Interior | HDRI/sky through the windows + portal area lights in the openings, bounces ≥ 4, then practical lights (lamps) at real wattage |+| Character / portrait | soft key from above-front, a reflector-like fill, rim or hair light, an eye catchlight. 85–135 mm lens |+| Stylized / game screenshot | match the engine: one directional + ambient/HDRI, no fancy GI, so it looks like it will in-game |+- **HDRI**: Poly Haven (CC0) via the blender-mcp `search_assets`/`import_asset`, or `ShaderNodeTexEnvironment` + Mapping (Z rotation aligns the sun). Strength 0.5–1.5. Clamp sun hotspots if they cause fireflies.+- **Light linking** (4.0+, Cycles + EEVEE): set `light_obj.light_linking.receiver_collection` / `blocker_collection` (on the light **object**) to light only what you choose, like a hero rim that doesn't touch the backdrop. Portals: `light.cycles.is_portal = True` on area lights in window openings.+- **Units**: point/spot/area in Watts (a 60 W bulb ≈ point light 40–60 W in Blender), sun in W/m² (irradiance; 1000 ≈ physical midday, but use 3–10 with AgX for natural results), emission strength ≈ W/m². Keep lights physically plausible and control the overall image with exposure.+- **Shadows**: light size controls softness. A bigger, closer light is softer. Contact shadows should exist where objects touch, so check that nothing floats (`blender-asset-qa` `ground_z`).++## Camera rules+- Focal length: 24–35 mm environments/interiors (keep verticals straight: camera level, or shift instead of tilting), 50 mm natural, **85–135 mm products and portraits** (no distortion), 200 mm+ compressed telephoto.+- Composition: rule of thirds / centered symmetric for products, horizon off-center, leading lines, headroom. Show the silhouette (3/4 view at slight elevation 10–25°).+- DOF (`cam.data.dof.use_dof`, `focus_object`, `aperture_fstop`): f/2.8–5.6 for products at real scale. DOF depends on scale, so a wrong scene scale ruins it.+- Clip start/end tight around the subject (the script does this), which avoids precision artifacts.+- Sensor fit AUTO uses the larger axis. Portrait renders need framing on the width.++## Look-dev procedure (material approval)+1. Neutral setup: `--rig studio` or a neutral HDRI, grey backdrop, Khronos PBR Neutral or AgX (pick one and keep it).+2. Add a calibration chart object if needed (a grey 18% sphere, a chrome sphere, a Macbeth chart) next to the asset.+3. Turntable at 24–30 fps, 120–240 frames, 85 mm. Render previews with `render_batch.py --preset preview --format MP4`.+4. Check the materials under 2–3 different HDRIs. A good PBR material holds up in all of them (`blender-pbr-materials` sanity checks).++## Gotchas+- World lighting is invisible if `world.node_tree` has no Background → World Output link (the script ensures one).+- EEVEE needs `use_raytracing` for good reflections. Light probes (Volume/Sphere/Plane) still help static GI in interiors.+- Area lights that are too small and bright make fireflies in Cycles. Increase the size, decrease the power.+- A turntable that rotates the **asset** changes its transforms and animation data, which is why this rig orbits the camera instead.diff --git a/skills/blender-lighting-lookdev/scripts/_bpyx.py b/skills/blender-lighting-lookdev/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-lighting-lookdev/scripts/_bpyx.py@@ -0,0 +1,136 @@+"""_bpyx - tiny shared helpers for blender-agent-skills scripts (Blender 5.2+).++Source of truth: shared/_bpyx.py. Copies in skills/*/scripts/ are synced by+tools/sync_shared.py - never edit a copy.++Every skill script follows one contract:+ run(**kwargs) -> dict # call from MCP / Python (import the module)+ blender -b f.blend -P x.py -- --arg v # CLI: prints one line "@@JSON@@{...}"+"""+import argparse+import json+import sys++import bpy++MARK = "@@JSON@@"+++def argv():+ """Arguments after '--' (Blender ignores them)."""+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def _default(o):+ if hasattr(o, "__len__") and not isinstance(o, str):+ try:+ return [round(v, 5) if isinstance(v, float) else v for v in o]+ except TypeError:+ pass+ if isinstance(o, (set, frozenset)):+ return sorted(o)+ return str(o)+++def emit(data):+ """Print compact JSON on one marked line (parsed by run_in_blender.py)."""+ print(MARK + json.dumps(data, separators=(",", ":"), default=_default), flush=True)+ return data+++def parser(doc):+ """ArgumentParser whose help is the script docstring's first line."""+ return argparse.ArgumentParser(description=(doc or "").strip().splitlines()[0])+++def cli(run, p):+ """CLI entry: parse args after '--', run, emit JSON. Exit 1 on failure."""+ args = p.parse_args(argv())+ try:+ result = run(**vars(args))+ save = getattr(args, "save", None)+ if save:+ bpy.ops.wm.save_as_mainfile(filepath=bpy.path.abspath(save))+ result["saved"] = save+ emit(result)+ except Exception as e: # report, don't dump a traceback into agent context+ emit({"ok": False, "error": f"{type(e).__name__}: {e}"})+ if bpy.app.background:+ sys.exit(1)+++def add_common(p, save=True):+ """--objects / --save flags shared by most scripts."""+ p.add_argument("--objects", nargs="*", default=None,+ help="object names (default: selected, else all meshes)")+ if save:+ p.add_argument("--save", default=None, help="save .blend to this path after run")+ return p+++def objects(names=None, types=("MESH",)):+ """Resolve names -> objects. No names: selected of `types`, else all visible of `types`."""+ if names:+ missing = [n for n in names if n not in bpy.data.objects]+ if missing:+ raise KeyError(f"objects not found: {missing}")+ return [bpy.data.objects[n] for n in names]+ pool = [o for o in bpy.context.scene.objects if not types or o.type in types]+ sel = [o for o in pool if o.select_get()]+ return sel or [o for o in pool if o.visible_get()]+++def object_mode():+ """Leave edit/sculpt/pose modes; most data API work needs OBJECT mode."""+ ob = bpy.context.view_layer.objects.active+ if ob and ob.mode != "OBJECT":+ bpy.ops.object.mode_set(mode="OBJECT")+++def select_only(objs, active=None):+ """Select exactly `objs` and make `active` (default first) active."""+ for o in bpy.context.view_layer.objects:+ o.select_set(False)+ for o in objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = active or (objs[0] if objs else None)+++def node(tree, type_):+ """First node of `type_` (e.g. 'BSDF_PRINCIPLED'). Names are localized - never look up by name."""+ return next((n for n in tree.nodes if n.type == type_), None)+++def enum_ids(owner, prop):+ """Valid identifiers of an enum property (works on types or instances)."""+ return [i.identifier for i in owner.bl_rna.properties[prop].enum_items]+++def set_enum(owner, prop, value):+ """Assign an enum; on failure raise listing valid values (dynamic enums under-report)."""+ try:+ setattr(owner, prop, value)+ except TypeError as e:+ raise ValueError(f"{prop}={value!r} invalid: {e}") from None+++def mesh_tris(ob, evaluated=True):+ """Triangle count (evaluated = with modifiers)."""+ if evaluated:+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ try:+ me.calc_loop_triangles()+ return len(me.loop_triangles)+ finally:+ eo.to_mesh_clear()+ me = ob.data+ me.calc_loop_triangles()+ return len(me.loop_triangles)+++def r(v, n=4):+ """Round a float or a vector for compact JSON."""+ if isinstance(v, float):+ return round(v, n)+ return [round(x, n) for x in v]diff --git a/skills/blender-lighting-lookdev/scripts/turntable.py b/skills/blender-lighting-lookdev/scripts/turntable.pynew file mode 100644index 0000000..8cb4f12--- /dev/null+++ b/skills/blender-lighting-lookdev/scripts/turntable.py@@ -0,0 +1,176 @@+"""Look-dev scene in one call: framed camera, light rig (studio 3-point / HDRI / both), optional+cyclorama backdrop and a looping turntable (camera + lights orbit; the asset is untouched).++Usage:+ blender -b f.blend -P turntable.py -- --objects Hero [--rig studio|hdri|both] [--hdri path.exr]+ [--hdri-strength 1] [--frames 120] [--lens 85] [--backdrop] [--elevation 15] [--save out.blend]+ MCP: import turntable; print(turntable.run(objects=["Hero"], rig="studio", frames=120))+Then render with blender-rendering/render_batch.py (e.g. --frames 1-120 --format MP4).+"""+import math+import os+import sys++import bmesh+import bpy+from mathutils import Matrix, Vector++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++PREFIX = "LD_"+++def _bounds(obs):+ bpy.context.view_layer.update()+ pts = [o.matrix_world @ Vector(c) for o in obs for c in o.bound_box]+ lo = Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts)))+ hi = Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts)))+ return lo, hi+++def _clear():+ for o in [o for o in bpy.data.objects if o.name.startswith(PREFIX)]:+ data = o.data+ bpy.data.objects.remove(o)+ if data is not None and data.users == 0:+ for coll in (bpy.data.lights, bpy.data.cameras, bpy.data.meshes):+ if data.name in coll and coll[data.name] == data:+ coll.remove(data)+ break+++def _area(name, power, size, loc, target, col, color=(1, 1, 1)):+ ld = bpy.data.lights.new(PREFIX + name, "AREA")+ ld.energy, ld.size, ld.color = power, size, color+ ld.shape = "DISK"+ lo = bpy.data.objects.new(PREFIX + name, ld)+ lo.location = loc+ lo.rotation_euler = (target - Vector(loc)).to_track_quat("-Z", "Y").to_euler()+ col.objects.link(lo)+ return lo+++def _backdrop(lo, hi, col):+ w = max(hi.x - lo.x, hi.y - lo.y, hi.z - lo.z) * 6+ bm = bmesh.new()+ a = bm.verts.new((-w / 2, -w / 2, 0))+ b = bm.verts.new((w / 2, -w / 2, 0))+ c = bm.verts.new((w / 2, w / 2, 0))+ d = bm.verts.new((-w / 2, w / 2, 0))+ e = bm.verts.new((w / 2, w / 2, w * 0.6))+ f = bm.verts.new((-w / 2, w / 2, w * 0.6))+ bm.faces.new((a, b, c, d))+ bm.faces.new((d, c, e, f))+ me = bpy.data.meshes.new(PREFIX + "Backdrop")+ bm.to_mesh(me)+ bm.free()+ ob = bpy.data.objects.new(PREFIX + "Backdrop", me)+ ob.location = (((lo.x + hi.x) / 2), ((lo.y + hi.y) / 2), lo.z)+ bev = ob.modifiers.new("Curve", "BEVEL")+ bev.width, bev.segments, bev.limit_method = w * 0.25, 16, "ANGLE"+ for p in me.polygons:+ p.use_smooth = True+ mat = bpy.data.materials.new(PREFIX + "Backdrop")+ bsdf = bx.node(mat.node_tree, "BSDF_PRINCIPLED")+ bsdf.inputs["Base Color"].default_value = (0.18, 0.18, 0.18, 1) # 18% grey+ bsdf.inputs["Roughness"].default_value = 0.8+ me.materials.append(mat)+ col.objects.link(ob)+ return ob+++def run(objects=None, rig="studio", hdri=None, hdri_strength=1.0, frames=120, lens=85.0,+ backdrop=False, elevation=15.0, **_):+ bx.object_mode()+ obs = bx.objects(objects, types=("MESH", "CURVE", "FONT", "CURVES", "ARMATURE"))+ _clear()+ sc = bpy.context.scene+ col = bpy.data.collections.get(PREFIX + "Lookdev") or bpy.data.collections.new(PREFIX + "Lookdev")+ if col.name not in sc.collection.children:+ sc.collection.children.link(col)+ lo, hi = _bounds(obs)+ center = (lo + hi) / 2+ radius = max((hi - lo).length / 2, 1e-3)+ pivot = bpy.data.objects.new(PREFIX + "Pivot", None)+ pivot.location = center+ col.objects.link(pivot)+ cam_d = bpy.data.cameras.new(PREFIX + "Cam")+ cam_d.lens = lens+ fov = 2 * math.atan(cam_d.sensor_width / (2 * lens)) # horizontal (sensor_fit AUTO, landscape)+ aspect = sc.render.resolution_x / sc.render.resolution_y+ fov = min(fov, 2 * math.atan(math.tan(fov / 2) / aspect)) if aspect >= 1 else fov * aspect+ dist = radius / math.sin(fov / 2) * 1.1 # fits the bounding sphere on the narrower axis+ cam_d.clip_start, cam_d.clip_end = dist / 100, dist * 20+ cam = bpy.data.objects.new(PREFIX + "Cam", cam_d)+ el = math.radians(elevation)+ cam.location = center + Vector((0, -math.cos(el), math.sin(el))) * dist+ cam.rotation_euler = (center - cam.location).to_track_quat("-Z", "Y").to_euler()+ col.objects.link(cam)+ sc.camera = cam+ rigged = [cam]+ nlights = 0+ if rig in ("studio", "both"):+ d = dist * 0.8+ key_power = 60 * d * d+ for name, az, elv, k, size in (("Key", -45, 35, 1.0, 1.0), ("Fill", 50, 15, 0.35, 1.5),+ ("Rim", 160, 40, 0.8, 0.6)):+ a, e = math.radians(az), math.radians(elv)+ loc = center + Vector((math.sin(a) * math.cos(e), -math.cos(a) * math.cos(e), math.sin(e))) * d+ rigged.append(_area(name, key_power * k, radius * size, loc, center, col))+ nlights += 1+ world = sc.world or bpy.data.worlds.new("World")+ sc.world = world+ wt = world.node_tree+ bg = bx.node(wt, "BACKGROUND")+ out_n = bx.node(wt, "OUTPUT_WORLD")+ if rig in ("hdri", "both") and hdri:+ env = next((n for n in wt.nodes if n.type == "TEX_ENVIRONMENT"), None) or wt.nodes.new("ShaderNodeTexEnvironment")+ env.image = bpy.data.images.load(bpy.path.abspath(hdri), check_existing=True)+ wt.links.new(env.outputs["Color"], bg.inputs["Color"])+ bg.inputs["Strength"].default_value = hdri_strength+ nlights += 1+ else:+ for l in list(bg.inputs["Color"].links):+ wt.links.remove(l)+ bg.inputs["Color"].default_value = (0.05, 0.05, 0.05, 1)+ bg.inputs["Strength"].default_value = 1.0 if rig == "hdri" else 0.5+ if out_n and not out_n.inputs["Surface"].is_linked:+ wt.links.new(bg.outputs["Background"], out_n.inputs["Surface"])+ if backdrop:+ rigged.append(_backdrop(lo, hi, col))+ bpy.context.view_layer.update() # pivot matrix must be evaluated before parenting+ for o in rigged: # camera, lights and backdrop orbit together; the asset stays untouched+ o.parent = pivot+ o.matrix_parent_inverse = pivot.matrix_world.inverted()+ if frames and frames > 1:+ sc.frame_start, sc.frame_end = 1, frames+ pivot.rotation_euler = (0, 0, 0)+ pivot.keyframe_insert("rotation_euler", index=2, frame=1)+ pivot.rotation_euler = (0, 0, 2 * math.pi) # full turn lands on frame N+1+ pivot.keyframe_insert("rotation_euler", index=2, frame=frames + 1)+ for fc in _fcurves(pivot):+ for kp in fc.keyframe_points:+ kp.interpolation = "LINEAR"+ return {"ok": True, "camera": cam.name, "lens": lens, "distance": round(dist, 3), "lights": nlights,+ "frames": frames, "pivot": pivot.name, "collection": col.name,+ "note": "frame N+1 == frame 1, so 1..N loops seamlessly"}+++def _fcurves(ob):+ from bpy_extras import anim_utils+ ad = ob.animation_data+ cb = anim_utils.action_get_channelbag_for_slot(ad.action, ad.action_slot)+ return list(cb.fcurves) if cb else []+++if __name__ == "__main__":+ p = bx.add_common(bx.parser(__doc__))+ p.add_argument("--rig", default="studio", choices=["studio", "hdri", "both"])+ p.add_argument("--hdri", default=None)+ p.add_argument("--hdri-strength", type=float, default=1.0)+ p.add_argument("--frames", type=int, default=120)+ p.add_argument("--lens", type=float, default=85.0)+ p.add_argument("--backdrop", action="store_true")+ p.add_argument("--elevation", type=float, default=15.0)+ bx.cli(run, p)diff --git a/skills/blender-pbr-materials/SKILL.md b/skills/blender-pbr-materials/SKILL.mdnew file mode 100644index 0000000..7637db6--- /dev/null+++ b/skills/blender-pbr-materials/SKILL.md@@ -0,0 +1,57 @@+---+name: blender-pbr-materials+description: Physically based materials in Blender 5.2 - metal/roughness rules, Principled BSDF inputs, color spaces (sRGB vs Non-Color), measured albedo/F0 values, texture-set auto-wiring, ORM channel packing, DirectX vs OpenGL normals, alpha modes, displacement, view transforms (AgX, Khronos PBR Neutral), engine-ready material rules. Use when creating, fixing, or exporting materials and textures.+license: MIT+metadata:+ author: blender-agent-skills+ version: "0.1.0"+---++# PBR Materials++The execution model is in `blender-core`. Measured values are in [references/pbr-values.md](references/pbr-values.md).++## Fast paths+- Texture set → material: `scripts/build_pbr_material.py -- --name M_Crate --textures //tex/crate --objects SM_Crate`. It detects maps by filename (Poly Haven, ambientCG, Substance, UE suffixes), sets color spaces, splits ORM, flips DirectX normals, and routes AO to glTF.+- Solid physically-plausible material: `--preset gold|iron|plastic|rubber|wood|glass|skin|...` with an optional `--color R G B` (sRGB).++## The rules (violations are what make renders look "CG")+1. **Metallic is binary**: 0 (dielectric) or 1 (raw metal). Use in-between values only on transition pixels (dust or rust edges on metal). Painted metal counts as dielectric.+2. **Base color = albedo with no lighting**: no baked shadows/AO/highlights. Dielectric range is sRGB ~30–240 (linear 0.012–0.87): charcoal ≈ 50, fresh snow ≈ 240. Metals: base color = F0 reflectance, sRGB 180–255, never dark.+3. **Roughness carries the realism**. Break it up with grunge, smudges and wear. A constant roughness value looks fake; vary it ±0.1–0.2 across a surface.+4. **Color spaces**: Base Color and Emission use `sRGB`. Roughness, Metallic, Normal, AO, Height, Opacity and ORM use `Non-Color`. A wrong color space is the #1 bug (washed-out normals, wrong roughness).+5. **Specular**: leave `IOR` 1.5 and `Specular IOR Level` 0.5 for almost all dielectrics. Change IOR only for known materials (water 1.33, glass 1.5, diamond 2.42).+6. **Normal maps**: Blender, glTF, Unity and Roblox use **OpenGL** (Y+). Unreal and Substance's DirectX preset use **DirectX** (Y-), so flip G when converting. The bake and the target must use the same tangent basis (MikkTSpace) and the same triangulation.+7. **AO**: the Principled BSDF has no AO input. For engines, ship AO in the ORM red channel. For Cycles renders, don't multiply AO into base color, because the renderer computes occlusion.++## Principled BSDF (5.2) quick map+`Base Color`, `Metallic`, `Roughness`, `IOR`, `Alpha`, `Normal`, `Thin Wall` (5.2: leaves/paper/fabric sheets without volume), `Subsurface Weight/Radius/Scale` (skin, wax; Scale in meters ≈ 0.005–0.02 for skin), `Specular IOR Level`, `Specular Tint`, `Anisotropic`, `Transmission Weight` (glass/liquids), `Coat Weight/Roughness/Normal` (car paint, varnish), `Sheen Weight` (cloth, velvet), `Emission Color/Strength` (strength in W/m²-ish units; 1–10 for screens, 50+ for bulbs), `Thin Film Thickness/IOR` (soap, oil, coated lenses), `Diffuse Roughness`.++## Engine export rules+| Target | Maps | Packing | Normal |+|---|---|---|---|+| glTF / web / Godot | baseColor(+alpha), metallicRoughness, normal, occlusion, emissive | glTF: **R=AO G=Rough B=Metal** (ORM) | OpenGL |+| Unreal | BaseColor, Normal, ORM | R=AO G=Rough B=Metal | DirectX (UE flips on import if the texture is marked) |+| Unity URP/HDRP | BaseMap, Normal, MetallicSmoothness / HDRP MaskMap | URP: R=Metal A=**Smoothness** (1-rough). HDRP Mask: R=Metal G=AO B=DetailMask A=Smoothness | OpenGL |+| Roblox SurfaceAppearance | ColorMap(+alpha), NormalMap, MetalnessMap, RoughnessMap, EmissiveMaskContent | separate grayscale maps, no packing | OpenGL, tangent space |+- Only image-texture → BSDF chains export. Procedural nodes, Mix nodes and math become nothing in engines, so bake them first (`blender-texture-baking`).+- One material per texture set. Every extra material is an extra draw call (`blender-game-optimization`).+- Power-of-two textures (512/1024/2048/4096). Use PNG/TGA for data maps, never JPEG for normals.++## Alpha+`mat.surface_render_method = "DITHERED"` (cutout/alpha-clip, sorts correctly, good for foliage/hair cards) or `"BLENDED"` (true transparency, glass/UI). Connect `Alpha`. glTF exports CLIP/BLEND from the alpha setup. Prefer dithered/clip for games.++## Displacement+Height map → `Displacement` node → Material Output `Displacement`. `mat.displacement_method`: `BUMP` (shading only, everywhere), `BOTH`/`DISPLACEMENT` (Cycles, needs dense or adaptively subdivided geometry: Subdivision modifier `use_adaptive_subdivision`). Scale is in meters; midlevel 0.5 for 8-bit, 0 for 32-bit EXR.++## View transform (judge materials under the right one)+`scene.view_settings.view_transform`: **AgX** (default, photographic), **Khronos PBR Neutral** (what-you-see-is-the-albedo; use for asset/product review and glTF parity), **Standard** (UI/graphics/textures that must match pixels), ACES 1.3/2.0 (VFX pipelines). Never bake or author textures while looking through Filmic/AgX with an extreme "Look".++## Procedural → texture+Procedural setups (noise/voronoi wear, curvature masks via `Geometry > Pointiness` (Cycles) or `Ambient Occlusion` node, edge wear via `Bevel` node normals) are fine for renders. For engines, bake them to the texture set (`blender-texture-baking`). Node Wrangler (bundled) `Ctrl+Shift+T` does the same as `build_pbr_material.py`, but needs the UI.++## Gotchas+- `material.use_nodes` is deprecated in 5.x. New materials already have Principled + Output.+- `mat.diffuse_color` only affects the viewport (Solid mode/workbench), not renders or export.+- Images loaded headless need `image.colorspace_settings.name` set **before** baking or export.+- Shared texture images used by several materials: change the color space once, because it's per image.diff --git a/skills/blender-pbr-materials/references/pbr-values.md b/skills/blender-pbr-materials/references/pbr-values.mdnew file mode 100644index 0000000..e2d750f--- /dev/null+++ b/skills/blender-pbr-materials/references/pbr-values.md@@ -0,0 +1,47 @@+# Measured PBR values++Linear values plug straight into socket `default_value`. sRGB values are for textures and color pickers.+Sources: Unreal Engine physically-based materials docs, physicallybased.info, DONTNOD charts.++## Metals (base color = F0, metallic 1)+| Metal | Linear RGB | sRGB 8-bit | Typical roughness |+|---|---|---|---|+| Silver | 0.972, 0.960, 0.915 | 252, 250, 245 | 0.1–0.3 |+| Aluminum | 0.913, 0.922, 0.924 | 245, 246, 246 | 0.2–0.5 |+| Gold | 1.000, 0.766, 0.336 | 255, 226, 155 | 0.1–0.35 |+| Copper | 0.955, 0.638, 0.538 | 250, 208, 192 | 0.2–0.45 |+| Brass | 0.910, 0.778, 0.423 | 244, 228, 173 | 0.2–0.4 |+| Iron / steel | 0.560, 0.570, 0.580 | 196, 199, 199 | 0.3–0.6 (brushed 0.25 + anisotropic) |+| Chromium | 0.550, 0.556, 0.554 | 196, 197, 196 | 0.02–0.15 |+| Titanium | 0.542, 0.497, 0.449 | 194, 187, 177 | 0.3–0.5 |+| Nickel | 0.660, 0.609, 0.526 | 211, 203, 190 | 0.2–0.4 |+| Platinum | 0.672, 0.637, 0.585 | 213, 208, 200 | 0.15–0.35 |++## Dielectrics (metallic 0, IOR 1.5 unless noted)+| Material | sRGB albedo (approx) | Roughness |+|---|---|---|+| Charcoal / black rubber | 50, 50, 50 | 0.8–0.95 |+| Asphalt (fresh / worn) | 60 / 90 | 0.8–0.95 |+| Car tire | 40 | 0.85 |+| Black plastic | 30–45 | 0.3–0.6 |+| White plastic | 220–230 | 0.2–0.5 |+| Concrete | 130–150 | 0.8–0.95 |+| Brick (red) | 150, 80, 60 | 0.8–0.9 |+| Wood (oak, unfinished) | 160, 120, 80 | 0.6–0.8; varnished 0.2 + Coat |+| Fabric (cotton) | (color) ≤ 230 | 0.8–1.0 + Sheen 0.3–0.6 |+| Leather | (color) | 0.4–0.7 |+| Skin (light / dark) | 230, 180, 160 / 90, 60, 45 | 0.4–0.6, Subsurface 1, IOR 1.4 |+| Grass | 75, 110, 45 | 0.6–0.8 |+| Sand | 190, 170, 130 | 0.8–0.95 |+| Fresh snow | 240, 240, 240 | 0.6–0.8 |+| Water | 255 + Transmission 1 | 0.0–0.05, IOR 1.33 |+| Glass | 255 + Transmission 1 | 0.0, IOR 1.5 (Thin Wall for windows: 5.2) |+| Car paint | (color) | 0.3–0.5 base, Coat 1 rough 0.03 |+| Ceramic / porcelain | 230–240 | 0.05–0.2 |++## Sanity checks for a texture set+- Average base color luminance for dielectrics: sRGB 50–200 (mean ~120). Pure black (0) or pure white (255) pixels on dielectrics are almost always wrong.+- Metal base color below sRGB 180: the metallic mask or albedo is wrong (it's probably dirt that should be dielectric).+- Roughness map near-uniform (std dev < 0.02): add variation.+- Normal map average ≈ (128, 128, 255). If the average blue is < 200 or the RGB is far off, the color space is wrong, or it's a height map labeled as normal.+- Check with `img.pixels.foreach_get(arr)` + numpy (`arr.reshape(-1,4)[:,:3].mean(0)`).diff --git a/skills/blender-pbr-materials/scripts/_bpyx.py b/skills/blender-pbr-materials/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-pbr-materials/scripts/_bpyx.py@@ -0,0 +1,136 @@+"""_bpyx - tiny shared helpers for blender-agent-skills scripts (Blender 5.2+).++Source of truth: shared/_bpyx.py. Copies in skills/*/scripts/ are synced by+tools/sync_shared.py - never edit a copy.++Every skill script follows one contract:+ run(**kwargs) -> dict # call from MCP / Python (import the module)+ blender -b f.blend -P x.py -- --arg v # CLI: prints one line "@@JSON@@{...}"+"""+import argparse+import json+import sys++import bpy++MARK = "@@JSON@@"+++def argv():+ """Arguments after '--' (Blender ignores them)."""+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def _default(o):+ if hasattr(o, "__len__") and not isinstance(o, str):+ try:+ return [round(v, 5) if isinstance(v, float) else v for v in o]+ except TypeError:+ pass+ if isinstance(o, (set, frozenset)):+ return sorted(o)+ return str(o)+++def emit(data):+ """Print compact JSON on one marked line (parsed by run_in_blender.py)."""+ print(MARK + json.dumps(data, separators=(",", ":"), default=_default), flush=True)+ return data+++def parser(doc):+ """ArgumentParser whose help is the script docstring's first line."""+ return argparse.ArgumentParser(description=(doc or "").strip().splitlines()[0])+++def cli(run, p):+ """CLI entry: parse args after '--', run, emit JSON. Exit 1 on failure."""+ args = p.parse_args(argv())+ try:+ result = run(**vars(args))+ save = getattr(args, "save", None)+ if save:+ bpy.ops.wm.save_as_mainfile(filepath=bpy.path.abspath(save))+ result["saved"] = save+ emit(result)+ except Exception as e: # report, don't dump a traceback into agent context+ emit({"ok": False, "error": f"{type(e).__name__}: {e}"})+ if bpy.app.background:+ sys.exit(1)+++def add_common(p, save=True):+ """--objects / --save flags shared by most scripts."""+ p.add_argument("--objects", nargs="*", default=None,+ help="object names (default: selected, else all meshes)")+ if save:+ p.add_argument("--save", default=None, help="save .blend to this path after run")+ return p+++def objects(names=None, types=("MESH",)):+ """Resolve names -> objects. No names: selected of `types`, else all visible of `types`."""+ if names:+ missing = [n for n in names if n not in bpy.data.objects]+ if missing:+ raise KeyError(f"objects not found: {missing}")+ return [bpy.data.objects[n] for n in names]+ pool = [o for o in bpy.context.scene.objects if not types or o.type in types]+ sel = [o for o in pool if o.select_get()]+ return sel or [o for o in pool if o.visible_get()]+++def object_mode():+ """Leave edit/sculpt/pose modes; most data API work needs OBJECT mode."""+ ob = bpy.context.view_layer.objects.active+ if ob and ob.mode != "OBJECT":+ bpy.ops.object.mode_set(mode="OBJECT")+++def select_only(objs, active=None):+ """Select exactly `objs` and make `active` (default first) active."""+ for o in bpy.context.view_layer.objects:+ o.select_set(False)+ for o in objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = active or (objs[0] if objs else None)+++def node(tree, type_):+ """First node of `type_` (e.g. 'BSDF_PRINCIPLED'). Names are localized - never look up by name."""+ return next((n for n in tree.nodes if n.type == type_), None)+++def enum_ids(owner, prop):+ """Valid identifiers of an enum property (works on types or instances)."""+ return [i.identifier for i in owner.bl_rna.properties[prop].enum_items]+++def set_enum(owner, prop, value):+ """Assign an enum; on failure raise listing valid values (dynamic enums under-report)."""+ try:+ setattr(owner, prop, value)+ except TypeError as e:+ raise ValueError(f"{prop}={value!r} invalid: {e}") from None+++def mesh_tris(ob, evaluated=True):+ """Triangle count (evaluated = with modifiers)."""+ if evaluated:+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ try:+ me.calc_loop_triangles()+ return len(me.loop_triangles)+ finally:+ eo.to_mesh_clear()+ me = ob.data+ me.calc_loop_triangles()+ return len(me.loop_triangles)+++def r(v, n=4):+ """Round a float or a vector for compact JSON."""+ if isinstance(v, float):+ return round(v, n)+ return [round(x, n) for x in v]diff --git a/skills/blender-pbr-materials/scripts/build_pbr_material.py b/skills/blender-pbr-materials/scripts/build_pbr_material.pynew file mode 100644index 0000000..a190a67--- /dev/null+++ b/skills/blender-pbr-materials/scripts/build_pbr_material.py@@ -0,0 +1,236 @@+"""Build a correct metal/rough PBR material from texture files or a measured preset.++Texture mode: give --textures dir (or files); maps are detected by name suffix+(basecolor/albedo/diffuse/_bc/_col, normal/_n/nor_gl/nor_dx, rough, metal, ao/occlusion,+orm/arm (R=AO G=Rough B=Metal), height/disp, emissive/emission, opacity/alpha).+Color spaces are set (color -> sRGB, data -> Non-Color); DirectX normals get G flipped;+AO is wired into a "glTF Material Output" group so glTF exports it.+Preset mode: --preset gold|silver|copper|iron|aluminum|chrome|titanium|brass|plastic|rubber|+wood|concrete|glass|water|skin|fabric|paint|ceramic [--color R G B (sRGB 0-1)].+Usage:+ blender -b f.blend -P build_pbr_material.py -- --name M_Crate --textures //tex/crate [--objects A B]+ [--tile 1] [--alpha clip|blend] [--displacement bump|both] [--save out.blend]+ blender -b f.blend -P build_pbr_material.py -- --name M_Gold --preset gold --objects Ring+ MCP: import build_pbr_material as b; print(b.run(name="M_Crate", textures="C:/tex/crate", objects=["SM_Crate"]))+"""+import os+import re+import sys++import bpy++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++# filename token -> map (Poly Haven, ambientCG, Substance, Quixel, UE-style suffixes)+TOKENS = {+ "orm": "orm", "arm": "orm",+ "normaldx": "normal_dx", "nordx": "normal_dx", "ndx": "normal_dx",+ "normal": "normal", "normalgl": "normal", "norgl": "normal", "nor": "normal", "nrm": "normal",+ "n": "normal", "normalopengl": "normal", "normaldirectx": "normal_dx",+ "basecolor": "basecolor", "basecolour": "basecolor", "albedo": "basecolor", "diffuse": "basecolor",+ "diff": "basecolor", "col": "basecolor", "color": "basecolor", "colour": "basecolor",+ "bc": "basecolor", "d": "basecolor", "a": "basecolor",+ "roughness": "roughness", "rough": "roughness", "rgh": "roughness", "r": "roughness",+ "metallic": "metallic", "metalness": "metallic", "metal": "metallic", "mtl": "metallic", "m": "metallic",+ "ao": "ao", "occlusion": "ao", "ambientocclusion": "ao", "occ": "ao",+ "height": "height", "displacement": "height", "disp": "height", "bump": "height", "h": "height",+ "emissive": "emission", "emission": "emission", "emit": "emission", "glow": "emission", "e": "emission",+ "opacity": "opacity", "alpha": "opacity", "mask": "opacity", "transparency": "opacity",+}+IMG_EXT = (".png", ".jpg", ".jpeg", ".tga", ".tif", ".tiff", ".exr", ".webp", ".bmp")++# linear base color (F0 for metals) / roughness / metallic / extras (Unreal/physicallybased.info data)+PRESETS = {+ "gold": ((1.0, 0.766, 0.336), 0.25, 1), "silver": ((0.972, 0.960, 0.915), 0.2, 1),+ "copper": ((0.955, 0.638, 0.538), 0.3, 1), "iron": ((0.560, 0.570, 0.580), 0.45, 1),+ "aluminum": ((0.913, 0.922, 0.924), 0.35, 1), "chrome": ((0.550, 0.556, 0.554), 0.08, 1),+ "titanium": ((0.542, 0.497, 0.449), 0.35, 1), "brass": ((0.910, 0.778, 0.423), 0.3, 1),+ "plastic": ((0.214, 0.214, 0.214), 0.4, 0), "rubber": ((0.023, 0.023, 0.023), 0.85, 0),+ "wood": ((0.287, 0.153, 0.074), 0.65, 0), "concrete": ((0.262, 0.258, 0.246), 0.9, 0),+ "glass": ((1.0, 1.0, 1.0), 0.0, 0), "water": ((1.0, 1.0, 1.0), 0.0, 0),+ "skin": ((0.651, 0.426, 0.338), 0.5, 0), "fabric": ((0.3, 0.3, 0.3), 0.9, 0),+ "paint": ((0.5, 0.05, 0.05), 0.35, 0), "ceramic": ((0.8, 0.8, 0.78), 0.15, 0),+}+++def _srgb_to_lin(c):+ return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4+++def classify(path):+ """Map type from filename tokens, scanning from the end (suffixes win)."""+ stem = os.path.splitext(os.path.basename(path))[0].lower()+ toks = [t for t in re.split(r"[_\-. ]+", stem) if t]+ for i in range(len(toks) - 1, -1, -1):+ for cand in ((toks[i - 1] + toks[i]) if i else None, toks[i]):+ if cand and cand in TOKENS and not (cand == toks[i] and i == 0 and len(toks) > 1 and len(cand) == 1):+ return TOKENS[cand]+ return None+++def _find_textures(textures):+ files = []+ for t in textures if isinstance(textures, (list, tuple)) else [textures]:+ t = bpy.path.abspath(t)+ if os.path.isdir(t):+ files += [os.path.join(t, f) for f in sorted(os.listdir(t)) if f.lower().endswith(IMG_EXT)]+ elif os.path.isfile(t):+ files.append(t)+ maps = {}+ for f in files:+ k = classify(f)+ if k and k not in maps:+ maps[k] = f+ if "normal_dx" in maps and "normal" not in maps:+ maps["normal"] = maps["normal_dx"]+ maps["_dx"] = True+ return maps+++def _gltf_output_group():+ name = "glTF Material Output"+ g = bpy.data.node_groups.get(name)+ if g is None:+ g = bpy.data.node_groups.new(name, "ShaderNodeTree")+ g.interface.new_socket("Occlusion", in_out="INPUT", socket_type="NodeSocketFloat")+ g.nodes.new("NodeGroupOutput")+ g.nodes.new("NodeGroupInput").location = (-200, 0)+ return g+++def run(name="M_Material", textures=None, preset=None, color=None, objects=None, tile=1.0,+ alpha=None, displacement="bump", dx_normal=False, **_):+ mat = bpy.data.materials.get(name) or bpy.data.materials.new(name)+ nt = mat.node_tree+ for n in list(nt.nodes):+ nt.nodes.remove(n)+ out = nt.nodes.new("ShaderNodeOutputMaterial")+ out.location = (400, 0)+ bsdf = nt.nodes.new("ShaderNodeBsdfPrincipled")+ nt.links.new(bsdf.outputs["BSDF"], out.inputs["Surface"])+ found = {}+ if preset:+ base, rough, metal = PRESETS[preset]+ if color:+ base = tuple(_srgb_to_lin(c) for c in color)+ bsdf.inputs["Base Color"].default_value = (*base, 1)+ bsdf.inputs["Roughness"].default_value = rough+ bsdf.inputs["Metallic"].default_value = metal+ if preset in ("glass", "water"):+ bsdf.inputs["Transmission Weight"].default_value = 1.0+ bsdf.inputs["IOR"].default_value = 1.33 if preset == "water" else 1.5+ if preset == "skin":+ bsdf.inputs["Subsurface Weight"].default_value = 1.0+ bsdf.inputs["Subsurface Radius"].default_value = (1.0, 0.35, 0.2)+ bsdf.inputs["Subsurface Scale"].default_value = 0.01+ if preset == "fabric":+ bsdf.inputs["Sheen Weight"].default_value = 0.5+ if preset == "paint":+ bsdf.inputs["Coat Weight"].default_value = 1.0+ bsdf.inputs["Coat Roughness"].default_value = 0.05+ found["preset"] = preset+ if textures:+ maps = _find_textures(textures)+ dx = dx_normal or maps.pop("_dx", False)+ maps.pop("normal_dx", None)+ coord = nt.nodes.new("ShaderNodeTexCoord")+ coord.location = (-1300, 0)+ mapping = nt.nodes.new("ShaderNodeMapping")+ mapping.location = (-1100, 0)+ mapping.inputs["Scale"].default_value = (tile, tile, tile)+ nt.links.new(coord.outputs["UV"], mapping.inputs["Vector"])++ def tex(key, y, color_space):+ img = bpy.data.images.load(maps[key], check_existing=True)+ img.colorspace_settings.name = color_space+ n = nt.nodes.new("ShaderNodeTexImage")+ n.image, n.location, n.label = img, (-700, y), key+ nt.links.new(mapping.outputs["Vector"], n.inputs["Vector"])+ found[key] = os.path.basename(maps[key])+ return n+ ao_out = None+ if "basecolor" in maps:+ n = tex("basecolor", 400, "sRGB")+ nt.links.new(n.outputs["Color"], bsdf.inputs["Base Color"])+ if alpha and "opacity" not in maps:+ nt.links.new(n.outputs["Alpha"], bsdf.inputs["Alpha"])+ if "orm" in maps:+ n = tex("orm", 100, "Non-Color")+ sep = nt.nodes.new("ShaderNodeSeparateColor")+ sep.location = (-400, 100)+ nt.links.new(n.outputs["Color"], sep.inputs["Color"])+ nt.links.new(sep.outputs["Green"], bsdf.inputs["Roughness"])+ nt.links.new(sep.outputs["Blue"], bsdf.inputs["Metallic"])+ ao_out = sep.outputs["Red"]+ else:+ if "roughness" in maps:+ nt.links.new(tex("roughness", 100, "Non-Color").outputs["Color"], bsdf.inputs["Roughness"])+ if "metallic" in maps:+ nt.links.new(tex("metallic", -100, "Non-Color").outputs["Color"], bsdf.inputs["Metallic"])+ if "ao" in maps:+ ao_out = tex("ao", 250, "Non-Color").outputs["Color"]+ if ao_out is not None: # Principled has no AO input: glTF group carries it to export+ g = nt.nodes.new("ShaderNodeGroup")+ g.node_tree, g.location = _gltf_output_group(), (400, -250)+ nt.links.new(ao_out, g.inputs["Occlusion"])+ if "normal" in maps:+ n = tex("normal", -350, "Non-Color")+ nm = nt.nodes.new("ShaderNodeNormalMap")+ nm.location = (-200, -350)+ src = n.outputs["Color"]+ if dx: # DirectX (Y-) -> OpenGL (Y+): invert green+ sep = nt.nodes.new("ShaderNodeSeparateColor")+ inv = nt.nodes.new("ShaderNodeMath")+ inv.operation, inv.inputs[0].default_value = "SUBTRACT", 1.0+ comb = nt.nodes.new("ShaderNodeCombineColor")+ sep.location, inv.location, comb.location = (-450, -500), (-450, -650), (-300, -500)+ nt.links.new(src, sep.inputs["Color"])+ nt.links.new(sep.outputs["Green"], inv.inputs[1])+ nt.links.new(sep.outputs["Red"], comb.inputs["Red"])+ nt.links.new(inv.outputs["Value"], comb.inputs["Green"])+ nt.links.new(sep.outputs["Blue"], comb.inputs["Blue"])+ src = comb.outputs["Color"]+ found["normal_flipped_from_dx"] = True+ nt.links.new(src, nm.inputs["Color"])+ nt.links.new(nm.outputs["Normal"], bsdf.inputs["Normal"])+ if "emission" in maps:+ nt.links.new(tex("emission", -550, "sRGB").outputs["Color"], bsdf.inputs["Emission Color"])+ bsdf.inputs["Emission Strength"].default_value = 1.0+ if "opacity" in maps:+ nt.links.new(tex("opacity", -750, "Non-Color").outputs["Color"], bsdf.inputs["Alpha"])+ if "height" in maps:+ h = tex("height", -950, "Non-Color")+ d = nt.nodes.new("ShaderNodeDisplacement")+ d.location = (200, -500)+ d.inputs["Scale"].default_value = 0.02+ d.inputs["Midlevel"].default_value = 0.5+ nt.links.new(h.outputs["Color"], d.inputs["Height"])+ nt.links.new(d.outputs["Displacement"], out.inputs["Displacement"])+ mat.displacement_method = "BOTH" if displacement == "both" else "BUMP"+ if not found:+ raise ValueError(f"no recognizable texture maps in {textures}")+ if alpha:+ mat.surface_render_method = "BLENDED" if alpha == "blend" else "DITHERED"+ assigned = []+ if objects:+ for ob in bx.objects(objects):+ if ob.data.materials:+ ob.data.materials[0] = mat+ else:+ ob.data.materials.append(mat)+ assigned.append(ob.name)+ return {"ok": True, "material": mat.name, "maps": found, "assigned": assigned}+++if __name__ == "__main__":+ p = bx.add_common(bx.parser(__doc__))+ p.add_argument("--name", default="M_Material")+ p.add_argument("--textures", nargs="*", default=None)+ p.add_argument("--preset", choices=sorted(PRESETS), default=None)+ p.add_argument("--color", nargs=3, type=float, default=None, help="sRGB 0-1 override")+ p.add_argument("--tile", type=float, default=1.0)+ p.add_argument("--alpha", choices=["clip", "blend"], default=None)+ p.add_argument("--displacement", choices=["bump", "both"], default="bump")+ p.add_argument("--dx-normal", action="store_true")+ bx.cli(run, p)diff --git a/skills/blender-pipeline-automation/SKILL.md b/skills/blender-pipeline-automation/SKILL.mdnew file mode 100644index 0000000..eee933b--- /dev/null+++ b/skills/blender-pipeline-automation/SKILL.md@@ -0,0 +1,60 @@+---+name: blender-pipeline-automation+description: Automate Blender 5.2 at scale - headless CLI flags, batch convert/inventory/run-any-skill-script over folders of .blend/.fbx/.glb/.obj/.usd, sharding, bpy pip module, library linking, path management, render-farm and CI patterns. Use for batch jobs, format conversion, library maintenance and pipeline tooling.+license: MIT+metadata:+ author: blender-agent-skills+ version: "0.1.0"+---++# Pipeline Automation++The execution model is in `blender-core` (`run_in_blender.py` finds Blender and prints only the JSON results).++## Batch one-liners+```+blender -b -P scripts/batch_process.py -- --in "assets/**/*.fbx" --op convert --to glb --out export/+blender -b -P scripts/batch_process.py -- --in library/ --op report # inventory JSON lines+blender -b -P scripts/batch_process.py -- --in "src/*.blend" --op script \+ --script ../blender-asset-qa/scripts/qa_check.py --kwargs '{"profile":"game"}' # QA a whole library+blender -b -P scripts/batch_process.py -- --in src/ --op script --script ../blender-game-optimization/scripts/make_lods.py \+ --kwargs '{"rename":true}' --save-to processed/ # LODs for every file+```+Each file is streamed as one JSON line with `ok`, timing and results. Failures don't stop the batch, and the summary lists them. **Parallel**: start N processes with `--shard 0/N` … `--shard N-1/N` (Blender uses one core for Python, so processes scale with CPU/GPU count).++## Headless CLI essentials+| Flag | Meaning |+|---|---|+| `-b` | background, no UI. Put it **first** |+| `file.blend` | open before running scripts. Order matters: args run left to right |+| `-P script.py` / `--python-expr "..."` | run Python |+| `--python-exit-code 1` | non-zero exit if the script raises (CI) |+| `--factory-startup` | ignore user prefs/add-ons (reproducible). Bundled add-ons still load |+| `--addons rigify,io_scene_fbx` | enable specific add-ons |+| `-E CYCLES -o //out/#### -F PNG -s 1 -e 10 -a` / `-f 5` | render (`blender-rendering`) |+| `--command extension build/validate/install-file` | extension tooling (`blender-addon-development`) |+| `-- --my args` | everything after `--` goes to the script (`sys.argv[sys.argv.index("--")+1:]`) |+| `--log "*"`, `--debug-python` | debugging. 5.0 changed the log format, so don't regex progress lines |+Environment variables: `BLENDER_USER_SCRIPTS`, `BLENDER_USER_EXTENSIONS`, `BLENDER_SYSTEM_PYTHON`. Use `OCIO` for custom color configs.++## bpy as a Python module+`pip install bpy==5.2.*` (Python 3.13, matching the Blender release) gives `import bpy` in plain Python, which is handy for pytest/CI/web services. It has no UI and no GPU module by default, and it's large (~300 MB). Version-lock it with the Blender you target. The `bpy` wheel and the CLI behave the same for data API work.++## Library patterns+- **Append/link**: `bpy.data.libraries.load(path, link=...)` (see `blender-core/references/bpy-patterns.md`). 5.2: `data_from.libraries` exposes nested library paths when loading.+- **Write a subset**: `bpy.data.libraries.write(path, {datablocks}, fake_user=True, path_remap="RELATIVE_ALL")` builds asset/library files from a session.+- **Find files**: `bpy.data.file_path_foreach(...)` (5.2 flags: `EXPAND_TOKENS` for UDIMs, `EXPAND_SEQUENCES`, `EXPAND_CACHES`), and `bpy.utils.blend_paths(absolute=True)` lists every external path.+- **Remap/relocate**: `bpy.ops.file.find_missing_files(directory=...)`, `make_paths_relative`, `pack_all`. Libraries: `lib.filepath = new; lib.reload()`.+- **Iterate every ID**: `bpy.data.all_ids` (5.2), and `bpy.data.orphans_purge(do_recursive=True)` for cleanup.++## Robustness rules+- One task per process where possible. Long Blender sessions leak (images, undo). `batch_process.py` reuses the process but resets with `read_factory_settings(use_empty=True)` / `open_mainfile`.+- Never write into the source folder by default. Use separate `--out`/`--save-to`, and write with `copy=True`.+- Make scripts idempotent: re-running replaces their own outputs (named prefixes, `exist_ok`).+- Log JSON, not prose: one object per file/job, so agents and CI can parse it cheaply.+- Pin the Blender version (5.2 LTS) for a project. Record `bpy.app.version_string` + hash (`bpy.app.build_hash`) in the outputs.+- Paths: `bpy.path.abspath("//x")` is relative to the **opened** .blend. In headless batches use absolute paths, or set them after `open_mainfile`.+- GPU in containers: Cycles CUDA/OptiX needs the NVIDIA container runtime. Otherwise use CPU. EEVEE needs a GPU/EGL even headless.++## CI recipe (GitHub Actions)+Download the Linux tarball (`https://download.blender.org/release/Blender5.2/blender-5.2.2-linux-x64.tar.xz`), cache it, then `blender -b --factory-startup --python-exit-code 1 -P tests/run_all.py`. This repo's `.github/workflows/ci.yml` is a working example.diff --git a/skills/blender-pipeline-automation/scripts/_bpyx.py b/skills/blender-pipeline-automation/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-pipeline-automation/scripts/_bpyx.py@@ -0,0 +1,136 @@+"""_bpyx - tiny shared helpers for blender-agent-skills scripts (Blender 5.2+).++Source of truth: shared/_bpyx.py. Copies in skills/*/scripts/ are synced by+tools/sync_shared.py - never edit a copy.++Every skill script follows one contract:+ run(**kwargs) -> dict # call from MCP / Python (import the module)+ blender -b f.blend -P x.py -- --arg v # CLI: prints one line "@@JSON@@{...}"+"""+import argparse+import json+import sys++import bpy++MARK = "@@JSON@@"+++def argv():+ """Arguments after '--' (Blender ignores them)."""+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def _default(o):+ if hasattr(o, "__len__") and not isinstance(o, str):+ try:+ return [round(v, 5) if isinstance(v, float) else v for v in o]+ except TypeError:+ pass+ if isinstance(o, (set, frozenset)):+ return sorted(o)+ return str(o)+++def emit(data):+ """Print compact JSON on one marked line (parsed by run_in_blender.py)."""+ print(MARK + json.dumps(data, separators=(",", ":"), default=_default), flush=True)+ return data+++def parser(doc):+ """ArgumentParser whose help is the script docstring's first line."""+ return argparse.ArgumentParser(description=(doc or "").strip().splitlines()[0])+++def cli(run, p):+ """CLI entry: parse args after '--', run, emit JSON. Exit 1 on failure."""+ args = p.parse_args(argv())+ try:+ result = run(**vars(args))+ save = getattr(args, "save", None)+ if save:+ bpy.ops.wm.save_as_mainfile(filepath=bpy.path.abspath(save))+ result["saved"] = save+ emit(result)+ except Exception as e: # report, don't dump a traceback into agent context+ emit({"ok": False, "error": f"{type(e).__name__}: {e}"})+ if bpy.app.background:+ sys.exit(1)+++def add_common(p, save=True):+ """--objects / --save flags shared by most scripts."""+ p.add_argument("--objects", nargs="*", default=None,+ help="object names (default: selected, else all meshes)")+ if save:+ p.add_argument("--save", default=None, help="save .blend to this path after run")+ return p+++def objects(names=None, types=("MESH",)):+ """Resolve names -> objects. No names: selected of `types`, else all visible of `types`."""+ if names:+ missing = [n for n in names if n not in bpy.data.objects]+ if missing:+ raise KeyError(f"objects not found: {missing}")+ return [bpy.data.objects[n] for n in names]+ pool = [o for o in bpy.context.scene.objects if not types or o.type in types]+ sel = [o for o in pool if o.select_get()]+ return sel or [o for o in pool if o.visible_get()]+++def object_mode():+ """Leave edit/sculpt/pose modes; most data API work needs OBJECT mode."""+ ob = bpy.context.view_layer.objects.active+ if ob and ob.mode != "OBJECT":+ bpy.ops.object.mode_set(mode="OBJECT")+++def select_only(objs, active=None):+ """Select exactly `objs` and make `active` (default first) active."""+ for o in bpy.context.view_layer.objects:+ o.select_set(False)+ for o in objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = active or (objs[0] if objs else None)+++def node(tree, type_):+ """First node of `type_` (e.g. 'BSDF_PRINCIPLED'). Names are localized - never look up by name."""+ return next((n for n in tree.nodes if n.type == type_), None)+++def enum_ids(owner, prop):+ """Valid identifiers of an enum property (works on types or instances)."""+ return [i.identifier for i in owner.bl_rna.properties[prop].enum_items]+++def set_enum(owner, prop, value):+ """Assign an enum; on failure raise listing valid values (dynamic enums under-report)."""+ try:+ setattr(owner, prop, value)+ except TypeError as e:+ raise ValueError(f"{prop}={value!r} invalid: {e}") from None+++def mesh_tris(ob, evaluated=True):+ """Triangle count (evaluated = with modifiers)."""+ if evaluated:+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ try:+ me.calc_loop_triangles()+ return len(me.loop_triangles)+ finally:+ eo.to_mesh_clear()+ me = ob.data+ me.calc_loop_triangles()+ return len(me.loop_triangles)+++def r(v, n=4):+ """Round a float or a vector for compact JSON."""+ if isinstance(v, float):+ return round(v, n)+ return [round(x, n) for x in v]diff --git a/skills/blender-pipeline-automation/scripts/batch_process.py b/skills/blender-pipeline-automation/scripts/batch_process.pynew file mode 100644index 0000000..a72ee25--- /dev/null+++ b/skills/blender-pipeline-automation/scripts/batch_process.py@@ -0,0 +1,154 @@+"""Batch over many files in one Blender process: convert formats, inventory report, or run any+skill script's run(**kwargs) per file and save. Sharding for parallel processes.++Inputs: .blend .fbx .glb .gltf .obj .stl .ply .usd .usda .usdc .usdz .abc (folder, glob, or list)+Usage:+ blender -b -P batch_process.py -- --in "assets/**/*.fbx" --op convert --to glb --out export/+ blender -b -P batch_process.py -- --in assets/ --op report+ blender -b -P batch_process.py -- --in "src/*.blend" --op script --script skills/blender-asset-qa/scripts/qa_check.py+ --kwargs '{"profile":"game"}' [--save-to out/]+ parallel: run N processes with --shard 0/4, 1/4, 2/4, 3/4+ MCP (careful: replaces the open file): import batch_process; batch_process.run(inp="C:/assets", op="report")+Prints one JSON line per file (@@JSON@@ when run via run_in_blender.py) and a summary.+"""+import glob+import importlib.util+import json+import os+import sys+import time++import bpy++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++IMPORTERS = {+ ".fbx": lambda p: bpy.ops.import_scene.fbx(filepath=p),+ ".glb": lambda p: bpy.ops.import_scene.gltf(filepath=p),+ ".gltf": lambda p: bpy.ops.import_scene.gltf(filepath=p),+ ".obj": lambda p: bpy.ops.wm.obj_import(filepath=p),+ ".stl": lambda p: bpy.ops.wm.stl_import(filepath=p),+ ".ply": lambda p: bpy.ops.wm.ply_import(filepath=p),+ ".abc": lambda p: bpy.ops.wm.alembic_import(filepath=p),+ **{e: (lambda p: bpy.ops.wm.usd_import(filepath=p)) for e in (".usd", ".usda", ".usdc", ".usdz")},+}+EXPORTERS = {+ "glb": lambda p, kw: bpy.ops.export_scene.gltf(filepath=p, export_format="GLB", **kw),+ "fbx": lambda p, kw: bpy.ops.export_scene.fbx(filepath=p, **({"add_leaf_bones": False} | kw)),+ "obj": lambda p, kw: bpy.ops.wm.obj_export(filepath=p, **kw),+ "stl": lambda p, kw: bpy.ops.wm.stl_export(filepath=p, **kw),+ "usd": lambda p, kw: bpy.ops.wm.usd_export(filepath=p, **kw),+ "usdz": lambda p, kw: bpy.ops.wm.usd_export(filepath=p, **kw),+ "blend": lambda p, kw: bpy.ops.wm.save_as_mainfile(filepath=p, copy=True),+}+++def gather(inp):+ items = inp if isinstance(inp, (list, tuple)) else [inp]+ files = []+ for it in items:+ it = bpy.path.abspath(it)+ if os.path.isdir(it):+ files += [os.path.join(r, f) for r, _, fs in os.walk(it) for f in fs]+ else:+ files += glob.glob(it, recursive=True)+ exts = set(IMPORTERS) | {".blend"}+ return sorted({f for f in files if os.path.splitext(f)[1].lower() in exts})+++def load(path):+ ext = os.path.splitext(path)[1].lower()+ if ext == ".blend":+ bpy.ops.wm.open_mainfile(filepath=path, load_ui=False)+ else:+ bpy.ops.wm.read_factory_settings(use_empty=True)+ IMPORTERS[ext](path)+++def inventory():+ dg = bpy.context.evaluated_depsgraph_get()+ tris, mats, dims = 0, set(), None+ for ob in bpy.context.scene.objects:+ if ob.type == "MESH":+ eo = ob.evaluated_get(dg)+ me = eo.to_mesh()+ me.calc_loop_triangles()+ tris += len(me.loop_triangles)+ eo.to_mesh_clear()+ mats |= {s.material.name for s in ob.material_slots if s.material}+ missing = [i.name for i in bpy.data.images if i.source == "FILE" and not i.packed_file+ and not os.path.exists(bpy.path.abspath(i.filepath))]+ kinds = {}+ for ob in bpy.context.scene.objects:+ kinds[ob.type] = kinds.get(ob.type, 0) + 1+ return {"objects": kinds, "tris": tris, "materials": len(mats), "images": len(bpy.data.images),+ "missing_images": missing[:10], "actions": len(bpy.data.actions)}+++def _module(path):+ sys.path.insert(0, os.path.dirname(os.path.abspath(path)))+ spec = importlib.util.spec_from_file_location("batch_target", path)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++def run(inp=None, op="report", to="glb", out="", script=None, kwargs=None, save_to=None, shard=None,+ set=None, stream=False, **_): # noqa: A002+ files = gather(inp)+ if shard:+ i, n = (int(x) for x in shard.split("/"))+ files = files[i::n]+ out_dir = os.path.abspath(bpy.path.abspath(out)) if out else None+ if out_dir:+ os.makedirs(out_dir, exist_ok=True)+ kw = json.loads(kwargs) if isinstance(kwargs, str) else (kwargs or {})+ exp_kw = dict(x.split("=", 1) for x in set or [])+ exp_kw = {k: {"true": True, "false": False}.get(v.lower(), v) for k, v in exp_kw.items()}+ mod = _module(script) if op == "script" else None+ results, t0 = [], time.time()+ for f in files:+ rec = {"file": f}+ t = time.time()+ try:+ load(f)+ if op == "report":+ rec.update(inventory())+ elif op == "convert":+ name = os.path.splitext(os.path.basename(f))[0] + "." + ("usdz" if to == "usdz" else to)+ dst = os.path.join(out_dir or os.path.dirname(f), name)+ res = EXPORTERS[to](dst, exp_kw)+ rec.update(out=dst, ok=res == {"FINISHED"} and os.path.exists(dst))+ elif op == "script":+ rec["result"] = mod.run(**kw)+ if save_to:+ os.makedirs(bpy.path.abspath(save_to), exist_ok=True)+ dst = os.path.join(bpy.path.abspath(save_to), os.path.splitext(os.path.basename(f))[0] + ".blend")+ bpy.ops.wm.save_as_mainfile(filepath=dst, copy=True)+ rec["saved"] = dst+ rec.setdefault("ok", True)+ except Exception as e:+ rec.update(ok=False, error=f"{type(e).__name__}: {e}")+ rec["sec"] = round(time.time() - t, 2)+ results.append(rec)+ if stream: # CLI: one JSON line per file as it finishes+ bx.emit(rec)+ return {"ok": all(r.get("ok") for r in results), "op": op, "files": len(files),+ "failed": [r["file"] for r in results if not r.get("ok")], "sec": round(time.time() - t0, 1),+ "results": "streamed" if stream else results}+++if __name__ == "__main__":+ p = bx.parser(__doc__)+ p.add_argument("--in", dest="inp", nargs="+", required=True)+ p.add_argument("--op", default="report", choices=["report", "convert", "script"])+ p.add_argument("--to", default="glb", choices=list(EXPORTERS))+ p.add_argument("--out", default="")+ p.add_argument("--script", default=None)+ p.add_argument("--kwargs", default=None, help="JSON dict passed to the script's run()")+ p.add_argument("--save-to", default=None)+ p.add_argument("--shard", default=None, help="i/n")+ p.add_argument("--set", nargs="*", default=None, help="exporter kwargs key=value")+ p.set_defaults(stream=True)+ bx.cli(run, p)diff --git a/skills/blender-rendering/SKILL.md b/skills/blender-rendering/SKILL.mdnew file mode 100644index 0000000..1912e41--- /dev/null+++ b/skills/blender-rendering/SKILL.md@@ -0,0 +1,70 @@+---+name: blender-rendering+description: Render with Blender 5.2 Cycles/EEVEE/Workbench - quality presets, GPU setup, adaptive sampling, denoising, light paths, color management (AgX, Khronos PBR Neutral, ACES), PNG/EXR/MP4 output, passes, the 5.0 compositor API, CLI and multi-camera batch rendering. Use for any still, animation or turntable render.+license: MIT+metadata:+ author: blender-agent-skills+ version: "0.1.0"+---++# Rendering++The execution model is in `blender-core`. Scene lighting and cameras are in `blender-lighting-lookdev`.++## One call+```+scripts/render_batch.py -- --engine CYCLES --preset final --res 1920 1080 --out //render/hero_#### --frames 1+scripts/render_batch.py -- --preset preview --frames 1-120 --format MP4 --out //render/turntable+scripts/render_batch.py -- --cameras CamA CamB CamC --format EXR_MULTI --out //render/shots/+```+Presets: `preview` (Cycles 64 spp, threshold 0.05, 50% res; EEVEE 16), `final` (512 spp, 0.01; EEVEE 128 + raytracing), `product` (1024 spp, transparent background). GPU is picked automatically (OptiX > CUDA > HIP > Metal > oneAPI), and the denoiser matches (OptiX or OpenImageDenoise).++## Engine choice+| Engine | Use | Notes |+|---|---|---|+| Cycles | final quality, product, archviz, glass/SSS/caustics, baking | path tracer; set the GPU; adaptive sampling + denoise |+| EEVEE (5.x, ex-"Next") | fast look-dev, stylized, motion graphics, previews | ray-traced reflections/GI (`use_raytracing`), virtual shadow maps; needs a GPU even headless |+| Workbench | playblasts, clay/matcap reviews, QA sheets | instant, no lighting accuracy |+Engine ids: `CYCLES`, `BLENDER_EEVEE`, `BLENDER_WORKBENCH`.++## Cycles quality levers (ordered by impact)+1. **Adaptive sampling** (`adaptive_threshold` 0.01 final / 0.05 preview) + **denoise** (OIDN with albedo+normal passes, `denoising_input_passes="RGB_ALBEDO_NORMAL"`). Raising samples alone is the least efficient fix.+2. **Light paths**: interiors need diffuse bounces ≥ 4. Product shots: total 12, glossy 4, transmission 8–12 for glass. Clamp indirect 5–10 kills fireflies at a small energy cost.+3. **Light tree** (`use_light_tree`, on) for many lights. **Path guiding** (CPU only) for difficult indirect light.+4. Fewer, larger lights beat many small ones. Emissive meshes are noisier than area lights.+5. Persistent data (`render.use_persistent_data`) speeds up animations and turntables. Use `simplify` (max subdivision, texture limit) for previews.+6. 5.2: **texture cache** (`render.use_texture_cache`, `use_auto_generate_texture_cache`) cuts memory in texture-heavy scenes by generating `.tx` mip tiles.++## Color management (decide once per project)+- **AgX** (default): photographic, handles bright highlights. Looks: `AgX - Punchy`, `- Base Contrast`...+- **Khronos PBR Neutral**: shows albedo faithfully. Use it for product/e-commerce and asset reviews, and to match three.js `NeutralToneMapping`.+- **Standard**: graphics/UI/texture output that must match pixel values.+- **ACES 1.3 / 2.0**: VFX pipelines (plates, other DCCs).+- Use exposure (`view_settings.exposure`), not light power, for global brightness tweaks. Display device sRGB, or Display P3 / Rec.2100 for HDR delivery.++## Output formats+- Stills: PNG 8/16-bit (RGBA when the film is transparent) or JPEG for web previews.+- Comp/VFX: **EXR multilayer** (`EXR_MULTI`, DWAA 16-bit) with passes (Denoising Data, Cryptomatte, AO, Mist, Z). 5.0 renamed passes: `Diffuse Color`, `Depth`, etc.+- Video: render **frames first** (PNG/EXR), then encode (FFmpeg or the VSE), because a crash mid-MP4 loses everything. Direct MP4 is fine for previews. Set `image_settings.media_type` **before** `file_format` (5.0+).+- Transparent: `film_transparent=True` + PNG/EXR. A glass-only alpha needs `film_transparent_glass`.++## Compositor (5.0+ API)+```python+ng = bpy.data.node_groups.new("Comp", "CompositorNodeTree"); scene.compositing_node_group = ng+ng.interface.new_socket("Image", in_out="OUTPUT", socket_type="NodeSocketColor")+rl, glare, out = ng.nodes.new("CompositorNodeRLayers"), ng.nodes.new("CompositorNodeGlare"), ng.nodes.new("NodeGroupOutput")+ng.links.new(rl.outputs["Image"], glare.inputs["Image"]); ng.links.new(glare.outputs["Image"], out.inputs[0])+```+There's no Composite node anymore: the group output is the final image. Many node options are now **input sockets** (Glare `Type`, `Threshold`, `Strength`), so `--describe` them with `blender-geometry-nodes/scripts/gn_builder.py`. File Output node: `directory`, `file_name`, `file_output_items`.++## CLI rendering (render farms, CI)+- `blender -b scene.blend -E CYCLES -o //out/frame_#### -F PNG -s 1 -e 120 -a` renders an animation. `-f 10` renders a single frame. Python args go after `--`.+- `-- --cycles-device OPTIX` (or CUDA/HIP/METAL/ONEAPI) selects the device without Python.+- Split frames across machines with `-s/-e`, or with Placeholders + No Overwrite (`render.use_placeholder`, `use_overwrite=False`) on shared storage.++## Gotchas+- `scene.render.engine` enum under-reports (add-on engines). Assign in try/except (the script does).+- EEVEE in background still needs a GPU context. In CI without a GPU, use Cycles CPU or Workbench.+- `bpy.ops.render.render(write_still=True)` writes `render.filepath`. Without `write_still`, the result only lives in `Render Result`.+- Noise in glass/caustics: enable caustics only if needed (`caustics_refractive`), raise transmission bounces, or fake it with Thin Wall (5.2) for windows.+- Fireflies: clamp indirect, a filter glossy / blur glossy (`blur_glossy` 0.5–1), and bigger light sources.diff --git a/skills/blender-rendering/scripts/_bpyx.py b/skills/blender-rendering/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-rendering/scripts/_bpyx.py@@ -0,0 +1,136 @@+"""_bpyx - tiny shared helpers for blender-agent-skills scripts (Blender 5.2+).++Source of truth: shared/_bpyx.py. Copies in skills/*/scripts/ are synced by+tools/sync_shared.py - never edit a copy.++Every skill script follows one contract:+ run(**kwargs) -> dict # call from MCP / Python (import the module)+ blender -b f.blend -P x.py -- --arg v # CLI: prints one line "@@JSON@@{...}"+"""+import argparse+import json+import sys++import bpy++MARK = "@@JSON@@"+++def argv():+ """Arguments after '--' (Blender ignores them)."""+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def _default(o):+ if hasattr(o, "__len__") and not isinstance(o, str):+ try:+ return [round(v, 5) if isinstance(v, float) else v for v in o]+ except TypeError:+ pass+ if isinstance(o, (set, frozenset)):+ return sorted(o)+ return str(o)+++def emit(data):+ """Print compact JSON on one marked line (parsed by run_in_blender.py)."""+ print(MARK + json.dumps(data, separators=(",", ":"), default=_default), flush=True)+ return data+++def parser(doc):+ """ArgumentParser whose help is the script docstring's first line."""+ return argparse.ArgumentParser(description=(doc or "").strip().splitlines()[0])+++def cli(run, p):+ """CLI entry: parse args after '--', run, emit JSON. Exit 1 on failure."""+ args = p.parse_args(argv())+ try:+ result = run(**vars(args))+ save = getattr(args, "save", None)+ if save:+ bpy.ops.wm.save_as_mainfile(filepath=bpy.path.abspath(save))+ result["saved"] = save+ emit(result)+ except Exception as e: # report, don't dump a traceback into agent context+ emit({"ok": False, "error": f"{type(e).__name__}: {e}"})+ if bpy.app.background:+ sys.exit(1)+++def add_common(p, save=True):+ """--objects / --save flags shared by most scripts."""+ p.add_argument("--objects", nargs="*", default=None,+ help="object names (default: selected, else all meshes)")+ if save:+ p.add_argument("--save", default=None, help="save .blend to this path after run")+ return p+++def objects(names=None, types=("MESH",)):+ """Resolve names -> objects. No names: selected of `types`, else all visible of `types`."""+ if names:+ missing = [n for n in names if n not in bpy.data.objects]+ if missing:+ raise KeyError(f"objects not found: {missing}")+ return [bpy.data.objects[n] for n in names]+ pool = [o for o in bpy.context.scene.objects if not types or o.type in types]+ sel = [o for o in pool if o.select_get()]+ return sel or [o for o in pool if o.visible_get()]+++def object_mode():+ """Leave edit/sculpt/pose modes; most data API work needs OBJECT mode."""+ ob = bpy.context.view_layer.objects.active+ if ob and ob.mode != "OBJECT":+ bpy.ops.object.mode_set(mode="OBJECT")+++def select_only(objs, active=None):+ """Select exactly `objs` and make `active` (default first) active."""+ for o in bpy.context.view_layer.objects:+ o.select_set(False)+ for o in objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = active or (objs[0] if objs else None)+++def node(tree, type_):+ """First node of `type_` (e.g. 'BSDF_PRINCIPLED'). Names are localized - never look up by name."""+ return next((n for n in tree.nodes if n.type == type_), None)+++def enum_ids(owner, prop):+ """Valid identifiers of an enum property (works on types or instances)."""+ return [i.identifier for i in owner.bl_rna.properties[prop].enum_items]+++def set_enum(owner, prop, value):+ """Assign an enum; on failure raise listing valid values (dynamic enums under-report)."""+ try:+ setattr(owner, prop, value)+ except TypeError as e:+ raise ValueError(f"{prop}={value!r} invalid: {e}") from None+++def mesh_tris(ob, evaluated=True):+ """Triangle count (evaluated = with modifiers)."""+ if evaluated:+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ try:+ me.calc_loop_triangles()+ return len(me.loop_triangles)+ finally:+ eo.to_mesh_clear()+ me = ob.data+ me.calc_loop_triangles()+ return len(me.loop_triangles)+++def r(v, n=4):+ """Round a float or a vector for compact JSON."""+ if isinstance(v, float):+ return round(v, n)+ return [round(x, n) for x in v]diff --git a/skills/blender-rendering/scripts/render_batch.py b/skills/blender-rendering/scripts/render_batch.pynew file mode 100644index 0000000..1254ed0--- /dev/null+++ b/skills/blender-rendering/scripts/render_batch.py@@ -0,0 +1,165 @@+"""Render stills/animations with quality presets, per-camera batches, any output format.++Presets: preview (fast look-dev), final (production), product (clean, transparent bg).+Formats: PNG, JPEG, EXR (half float), EXR_MULTI (all passes), MP4 (H.264), WEBM.+Usage:+ blender -b f.blend -P render_batch.py -- [--engine CYCLES|BLENDER_EEVEE|BLENDER_WORKBENCH]+ [--preset preview|final|product] [--res 1920 1080] [--percent 100] [--samples N]+ [--out //render/shot_####] [--format PNG] [--frames 1-120 | 1,12,24] [--cameras CamA CamB]+ [--view AgX|"Khronos PBR Neutral"|Standard] [--look "AgX - Punchy"] [--transparent] [--device GPU|CPU]+ MCP: import render_batch as r; print(r.run(preset="preview", frames="1"))+Returns written files and seconds per image.+"""+import os+import sys+import time++import bpy++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++PRESETS = {+ "preview": {"cycles": dict(samples=64, adaptive_threshold=0.05, use_denoising=True),+ "eevee": dict(taa_render_samples=16, use_raytracing=False), "percent": 50},+ "final": {"cycles": dict(samples=512, adaptive_threshold=0.01, use_denoising=True),+ "eevee": dict(taa_render_samples=128, use_raytracing=True), "percent": 100},+ "product": {"cycles": dict(samples=1024, adaptive_threshold=0.005, use_denoising=True),+ "eevee": dict(taa_render_samples=256, use_raytracing=True), "percent": 100,+ "transparent": True},+}+FORMATS = {"PNG": ("IMAGE", "PNG", ".png"), "JPEG": ("IMAGE", "JPEG", ".jpg"),+ "EXR": ("IMAGE", "OPEN_EXR", ".exr"), "EXR_MULTI": ("MULTI_LAYER_IMAGE", "OPEN_EXR_MULTILAYER", ".exr"),+ "MP4": ("VIDEO", "FFMPEG", ".mp4"), "WEBM": ("VIDEO", "FFMPEG", ".webm")}+++def _gpu(sc, device):+ if device == "CPU":+ sc.cycles.device = "CPU"+ return "CPU"+ prefs = bpy.context.preferences.addons["cycles"].preferences+ for backend in ("OPTIX", "CUDA", "HIP", "METAL", "ONEAPI"):+ try:+ prefs.compute_device_type = backend+ except TypeError:+ continue+ prefs.refresh_devices()+ if any(d.type != "CPU" for d in prefs.devices):+ for d in prefs.devices:+ d.use = d.type != "CPU"+ sc.cycles.device = "GPU"+ return backend+ sc.cycles.device = "CPU"+ return "CPU"+++def _frames(spec, sc):+ if not spec:+ return [sc.frame_current]+ out = []+ for part in str(spec).split(","):+ if "-" in part:+ a, b = part.split("-")+ out += list(range(int(a), int(b) + 1))+ else:+ out.append(int(part))+ return out+++def run(engine=None, preset="preview", res=None, percent=None, samples=None, out="//render/####",+ format="PNG", frames=None, cameras=None, view=None, look=None, transparent=None, # noqa: A002+ device="GPU", **_):+ sc = bpy.context.scene+ r = sc.render+ if engine:+ bx.set_enum(r, "engine", engine)+ pr = PRESETS[preset]+ info = {"engine": r.engine}+ if r.engine == "CYCLES":+ info["device"] = _gpu(sc, device)+ for k, v in pr["cycles"].items():+ setattr(sc.cycles, k, v)+ sc.cycles.use_adaptive_sampling = True+ if samples:+ sc.cycles.samples = samples+ if info["device"] == "OPTIX":+ sc.cycles.denoiser = "OPTIX"+ else:+ sc.cycles.denoiser = "OPENIMAGEDENOISE"+ elif r.engine == "BLENDER_EEVEE":+ for k, v in pr["eevee"].items():+ setattr(sc.eevee, k, v)+ if samples:+ sc.eevee.taa_render_samples = samples+ if res:+ r.resolution_x, r.resolution_y = res+ r.resolution_percentage = percent or pr["percent"]+ r.film_transparent = pr.get("transparent", False) if transparent is None else transparent+ if view:+ bx.set_enum(sc.view_settings, "view_transform", view)+ if look:+ bx.set_enum(sc.view_settings, "look", look)+ media, fmt, ext = FORMATS[format]+ s = r.image_settings+ s.media_type = media # 5.0+: must precede file_format+ s.file_format = fmt+ if fmt in ("OPEN_EXR", "OPEN_EXR_MULTILAYER"):+ s.color_depth, s.exr_codec = "16", "DWAA"+ elif fmt == "PNG":+ s.color_mode = "RGBA" if r.film_transparent else "RGB"+ if media == "VIDEO":+ r.ffmpeg.format = "MPEG4" if format == "MP4" else "WEBM"+ r.ffmpeg.codec = "H264" if format == "MP4" else "AV1"+ r.ffmpeg.constant_rate_factor = "HIGH"+ if r.film_transparent and fmt == "JPEG":+ info["warning"] = "JPEG has no alpha; use PNG/EXR for transparent renders"+ cams = [bpy.data.objects[c] for c in cameras] if cameras else [sc.camera]+ if cams[0] is None:+ raise ValueError("scene has no camera (see blender-lighting-lookdev)")+ base = bpy.path.abspath(out)+ os.makedirs(os.path.dirname(base) or ".", exist_ok=True)+ files, times = [], []+ for cam in cams:+ sc.camera = cam+ stem = base.replace("####", "") if len(cams) == 1 else f"{base.replace('####', '')}{cam.name}_"+ if media == "VIDEO":+ fr = _frames(frames, sc)+ sc.frame_start, sc.frame_end = fr[0], fr[-1]+ r.filepath = stem+ t = time.time()+ bpy.ops.render.render(animation=True)+ times.append(time.time() - t)+ files.append(stem + ext)+ continue+ for f in _frames(frames, sc):+ sc.frame_set(f)+ path = f"{stem}{f:04d}{ext}"+ r.filepath = path+ t = time.time()+ bpy.ops.render.render(write_still=True)+ times.append(time.time() - t)+ files.append(path)+ info.update({"ok": all(os.path.exists(f) for f in files) or media == "VIDEO", "files": files,+ "sec_per_image": round(sum(times) / max(len(times), 1), 2),+ "res": [r.resolution_x * r.resolution_percentage // 100,+ r.resolution_y * r.resolution_percentage // 100],+ "view": sc.view_settings.view_transform})+ return info+++if __name__ == "__main__":+ p = bx.parser(__doc__)+ p.add_argument("--engine", default=None)+ p.add_argument("--preset", default="preview", choices=list(PRESETS))+ p.add_argument("--res", nargs=2, type=int, default=None)+ p.add_argument("--percent", type=int, default=None)+ p.add_argument("--samples", type=int, default=None)+ p.add_argument("--out", default="//render/####")+ p.add_argument("--format", default="PNG", choices=list(FORMATS))+ p.add_argument("--frames", default=None)+ p.add_argument("--cameras", nargs="*", default=None)+ p.add_argument("--view", default=None)+ p.add_argument("--look", default=None)+ p.add_argument("--transparent", action="store_true", default=None)+ p.add_argument("--device", default="GPU", choices=["GPU", "CPU"])+ bx.cli(run, p)diff --git a/skills/blender-retopology-uv/SKILL.md b/skills/blender-retopology-uv/SKILL.mdnew file mode 100644index 0000000..12b3637--- /dev/null+++ b/skills/blender-retopology-uv/SKILL.md@@ -0,0 +1,61 @@+---+name: blender-retopology-uv+description: Retopology and UVs in Blender 5.2 - auto retopo (Quadriflow, Decimate, planar), deformation edge flow, seams, unwrap (Angle Based, Minimum Stretch, Smart), pixel-margin packing, texel density measure/set, lightmap UV2, UDIMs, mirrored UVs. Use to turn sculpts/scans/AI meshes into game meshes or prep UVs for texturing/baking.+license: MIT+metadata:+ author: blender-agent-skills+ version: "0.1.0"+---++# Retopology & UVs++The execution model is in `blender-core`.++## Retopology+**Automatic** (`scripts/auto_retopo.py -- --objects Sculpt --tris 8000 --method ...`) makes `<name>_low` and leaves the source hidden:+| Method | Use for | Notes |+|---|---|---|+| `quadriflow` | organic props, static characters, scans | clean quads. Voxel-remeshes first so the input is manifold; UVs are lost (re-unwrap) |+| `decimate` | background props, LODs, AI-generated meshes | keeps UVs/shape, gives triangles. Fast |+| `planar` | hard-surface CAD/boolean results | dissolves flat areas; keeps seams/sharp/material/UV borders |++**Manual** (hero characters, anything that deforms). Set up a new mesh object with a Shrinkwrap modifier (`PROJECT`, target = sculpt), snapping to `FACE_PROJECT` + `use_snap_project`, and the source in a different viewport color/x-ray. Auto retopo isn't good enough for deforming hero meshes, because the edge flow below matters.++### Edge flow rules for deforming meshes+- Concentric loops around the eyes and mouth (≥3 rings). The nasolabial loop flows from the nose wing to the mouth corner.+- **3 loops** at every bending joint (elbow, knee, finger knuckles), plus a loop on each side to keep volume. The shoulder needs extra loops for raising the arm.+- Keep poles (3/5-edge verts) out of bending areas. Put them on flat, stiff regions (chest, back of skull).+- Distribute quads evenly, with density where deformation and silhouette need it. Use triangles only in hidden, non-deforming spots.+- Character tri budgets in 2026: mobile 5–15k, Roblox body ≤ 10.7k total, console/PC third-person 30–80k, hero/cinematic 100k+. Check the target in `blender-game-optimization`.++## UVs+1. **Seams**: hide them (under arms, inner legs, back of the head, under parts), follow hard edges, cut cylinders on the back side. Rule for game meshes: every hard edge (>~60°, `sharp_edge`) **must** be a UV seam, or the normal map shows artifacts. `scripts/uv_pack.py --seams-from-sharp 60` does this.+2. **Unwrap**: `--method seams` (Angle Based with marked seams), `--method min_stretch` (SLIM, 4.3+, least distortion on organics), `--method smart` (hard-surface/auto, `--angle 66`).+3. **Straighten** rectangular islands (Follow Active Quads, live only) so trims and pixel grids line up.+4. **Average island scale + pack** with margin in pixels: 2k → 8 px, 4k → 16 px, mobile 1k → 4 px. `--shape CONCAVE` gives the tightest pack (slow headless). The default `AABB` is instant.+5. **Texel density** (`scripts/texel_density.py --res 2048`): keep `spread` ≤ 1.3 within an asset. Set it with `--set <px/m>`; if `fits_0_1` is false, change res or density.+6. QA: `blender-asset-qa` reports zero-area UV faces and overlap %.++### Texel density targets (px/m; studio baselines, not laws)+| Context | px/m |+|---|---|+| First-person hero / weapons | 1024–2048 |+| First-person environment | 512–1024 |+| Third-person games | 512 (console/PC), 256 (mobile) |+| Top-down / strategy | 128–256 |+| Roblox | ~256–512 per texture: 5×5 studs → 256², 10×10 → 512², 20×20 → 1024² |+Everything in the same scene should share one density. The exception is hero assets, kept within 2x.++## Special cases+- **Mirrored/stacked UVs** save space but break unique bakes. Move the duplicate islands exactly +1 U (outside 0–1) during baking, then move them back. Their normal maps must be mirror-safe (tangent space handles it in engines with MikkTSpace).+- **Lightmap UV2** (`--lightmap`, gives `UVMap_Lightmap`): no overlaps, every island inside 0–1, generous margin. Unreal/Unity can generate their own; ship one only if the engine pipeline wants it. Keep UV0 active for texturing.+- **UDIMs** (film/hero): islands in tiles 1001+ (U offset 1 per tile). Texture node image `source="TILED"`. Game engines mostly don't support UDIMs.+- **Trim sheets**: unwrap the strips, then scale/move the islands onto the trim rows (V positions from the trim layout). Islands may exceed 0–1 in U for tiling.+- **Roblox**: exactly one UV set, all inside 0–1. Overlaps are allowed.++## Gotchas+- 5.0+: UV selection is shared across UV maps (`.uv_select_*` attributes). Old `BMLoopUV.select` code fails.+- `uv.*` operators run in Edit Mode and act on selected faces. Select everything first (scripts handle this).+- Headless `uv.pack_islands` with `CONCAVE`/`CONVEX` + rotation can take 2–25 s even on tiny meshes. Use `AABB` while iterating.+- Unwrap warning "failed to solve island": the island has no seams (closed shape). Add seams.+- Apply scale before measuring texel density, or the density reads wrong (the scripts use world space and already account for scale).diff --git a/skills/blender-retopology-uv/scripts/_bpyx.py b/skills/blender-retopology-uv/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-retopology-uv/scripts/_bpyx.py@@ -0,0 +1,136 @@+"""_bpyx - tiny shared helpers for blender-agent-skills scripts (Blender 5.2+).++Source of truth: shared/_bpyx.py. Copies in skills/*/scripts/ are synced by+tools/sync_shared.py - never edit a copy.++Every skill script follows one contract:+ run(**kwargs) -> dict # call from MCP / Python (import the module)+ blender -b f.blend -P x.py -- --arg v # CLI: prints one line "@@JSON@@{...}"+"""+import argparse+import json+import sys++import bpy++MARK = "@@JSON@@"+++def argv():+ """Arguments after '--' (Blender ignores them)."""+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def _default(o):+ if hasattr(o, "__len__") and not isinstance(o, str):+ try:+ return [round(v, 5) if isinstance(v, float) else v for v in o]+ except TypeError:+ pass+ if isinstance(o, (set, frozenset)):+ return sorted(o)+ return str(o)+++def emit(data):+ """Print compact JSON on one marked line (parsed by run_in_blender.py)."""+ print(MARK + json.dumps(data, separators=(",", ":"), default=_default), flush=True)+ return data+++def parser(doc):+ """ArgumentParser whose help is the script docstring's first line."""+ return argparse.ArgumentParser(description=(doc or "").strip().splitlines()[0])+++def cli(run, p):+ """CLI entry: parse args after '--', run, emit JSON. Exit 1 on failure."""+ args = p.parse_args(argv())+ try:+ result = run(**vars(args))+ save = getattr(args, "save", None)+ if save:+ bpy.ops.wm.save_as_mainfile(filepath=bpy.path.abspath(save))+ result["saved"] = save+ emit(result)+ except Exception as e: # report, don't dump a traceback into agent context+ emit({"ok": False, "error": f"{type(e).__name__}: {e}"})+ if bpy.app.background:+ sys.exit(1)+++def add_common(p, save=True):+ """--objects / --save flags shared by most scripts."""+ p.add_argument("--objects", nargs="*", default=None,+ help="object names (default: selected, else all meshes)")+ if save:+ p.add_argument("--save", default=None, help="save .blend to this path after run")+ return p+++def objects(names=None, types=("MESH",)):+ """Resolve names -> objects. No names: selected of `types`, else all visible of `types`."""+ if names:+ missing = [n for n in names if n not in bpy.data.objects]+ if missing:+ raise KeyError(f"objects not found: {missing}")+ return [bpy.data.objects[n] for n in names]+ pool = [o for o in bpy.context.scene.objects if not types or o.type in types]+ sel = [o for o in pool if o.select_get()]+ return sel or [o for o in pool if o.visible_get()]+++def object_mode():+ """Leave edit/sculpt/pose modes; most data API work needs OBJECT mode."""+ ob = bpy.context.view_layer.objects.active+ if ob and ob.mode != "OBJECT":+ bpy.ops.object.mode_set(mode="OBJECT")+++def select_only(objs, active=None):+ """Select exactly `objs` and make `active` (default first) active."""+ for o in bpy.context.view_layer.objects:+ o.select_set(False)+ for o in objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = active or (objs[0] if objs else None)+++def node(tree, type_):+ """First node of `type_` (e.g. 'BSDF_PRINCIPLED'). Names are localized - never look up by name."""+ return next((n for n in tree.nodes if n.type == type_), None)+++def enum_ids(owner, prop):+ """Valid identifiers of an enum property (works on types or instances)."""+ return [i.identifier for i in owner.bl_rna.properties[prop].enum_items]+++def set_enum(owner, prop, value):+ """Assign an enum; on failure raise listing valid values (dynamic enums under-report)."""+ try:+ setattr(owner, prop, value)+ except TypeError as e:+ raise ValueError(f"{prop}={value!r} invalid: {e}") from None+++def mesh_tris(ob, evaluated=True):+ """Triangle count (evaluated = with modifiers)."""+ if evaluated:+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ try:+ me.calc_loop_triangles()+ return len(me.loop_triangles)+ finally:+ eo.to_mesh_clear()+ me = ob.data+ me.calc_loop_triangles()+ return len(me.loop_triangles)+++def r(v, n=4):+ """Round a float or a vector for compact JSON."""+ if isinstance(v, float):+ return round(v, n)+ return [round(x, n) for x in v]diff --git a/skills/blender-retopology-uv/scripts/auto_retopo.py b/skills/blender-retopology-uv/scripts/auto_retopo.pynew file mode 100644index 0000000..6d12fd2--- /dev/null+++ b/skills/blender-retopology-uv/scripts/auto_retopo.py@@ -0,0 +1,90 @@+"""Make a low-poly retopo copy of a dense mesh (sculpt/scan/AI-generated) at a triangle budget.++Methods: quadriflow (clean quads; needs manifold input - auto voxel-remesh first),+decimate (fast, keeps UVs/shape; triangles), planar (hard-surface: dissolve flat areas).+The result is shrinkwrapped back onto the source and named <source>_low.+Usage:+ blender -b f.blend -P auto_retopo.py -- --objects Sculpt [--method quadriflow|decimate|planar]+ [--tris 10000] [--voxel 0] [--symmetry] [--save out.blend]+ MCP: import auto_retopo; print(auto_retopo.run(objects=["Sculpt"], tris=8000))+--tris is the triangle budget (quadriflow targets tris/2 quads).+"""+import math+import os+import sys++import bpy++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402+++def _ctx(ob):+ return bpy.context.temp_override(object=ob, active_object=ob, selected_objects=[ob],+ selected_editable_objects=[ob])+++def _apply_all(ob):+ for name in [m.name for m in ob.modifiers]: # names: applied modifiers are freed+ with _ctx(ob):+ bpy.ops.object.modifier_apply(modifier=name)+++def run(objects=None, method="quadriflow", tris=10000, voxel=0.0, symmetry=False, **_):+ bx.object_mode()+ out = {}+ for src in bx.objects(objects):+ low = src.copy()+ low.data = src.data.copy()+ low.name = low.data.name = f"{src.name}_low"+ for c in src.users_collection:+ c.objects.link(low)+ _apply_all(low)+ before = len(low.data.polygons)+ tris_before = bx.mesh_tris(low, evaluated=False)+ faces = max(tris // 2, 4)+ if method == "quadriflow":+ # Quadriflow needs a closed manifold: voxel remesh first (size from target density)+ area = sum(p.area for p in low.data.polygons) * max(low.scale) ** 2+ low.data.remesh_voxel_size = voxel or max(math.sqrt(area / max(faces * 4, 1)), 1e-4)+ with _ctx(low):+ bpy.ops.object.voxel_remesh()+ res = bpy.ops.object.quadriflow_remesh(mode="FACES", target_faces=faces,+ use_mesh_symmetry=symmetry,+ use_preserve_sharp=True, seed=0)+ if res != {"FINISHED"}:+ raise RuntimeError("quadriflow failed (non-manifold after voxel remesh?)")+ elif method == "decimate":+ d = low.modifiers.new("Decimate", "DECIMATE")+ d.decimate_type = "COLLAPSE"+ d.ratio = min(1.0, tris / max(tris_before, 1))+ d.use_symmetry = symmetry+ d.use_collapse_triangulate = False+ _apply_all(low)+ elif method == "planar":+ d = low.modifiers.new("Decimate", "DECIMATE")+ d.decimate_type = "DISSOLVE"+ d.angle_limit = math.radians(5)+ d.delimit = {"SEAM", "SHARP", "MATERIAL", "UV"}+ _apply_all(low)+ if method != "planar":+ sw = low.modifiers.new("Shrinkwrap", "SHRINKWRAP")+ sw.target, sw.wrap_method, sw.wrap_mode = src, "PROJECT", "ON_SURFACE"+ sw.use_negative_direction = sw.use_positive_direction = True+ _apply_all(low)+ src.hide_set(True)+ src.hide_render = True+ out[src.name] = {"low": low.name, "faces_before": before, "faces_after": len(low.data.polygons),+ "tris_after": bx.mesh_tris(low, evaluated=False),+ "uvs_kept": bool(low.data.uv_layers) and method != "quadriflow"}+ return {"ok": True, "method": method, "objects": out,+ "next": "check edge flow (look wireframe), unwrap (uv_pack.py), bake (blender-texture-baking)"}+++if __name__ == "__main__":+ p = bx.add_common(bx.parser(__doc__))+ p.add_argument("--method", default="quadriflow", choices=["quadriflow", "decimate", "planar"])+ p.add_argument("--tris", type=int, default=10000)+ p.add_argument("--voxel", type=float, default=0.0)+ p.add_argument("--symmetry", action="store_true")+ bx.cli(run, p)diff --git a/skills/blender-retopology-uv/scripts/texel_density.py b/skills/blender-retopology-uv/scripts/texel_density.pynew file mode 100644index 0000000..bf9056e--- /dev/null+++ b/skills/blender-retopology-uv/scripts/texel_density.py@@ -0,0 +1,123 @@+"""Measure (and optionally set) texel density in px/m for objects' active UV map.++Reports per-object area-weighted mean, min/max over islands, and spread (max/min).+--set scales every island to the target density (about its UV centre) then repacks+without rescaling; reports overflow if it no longer fits in 0-1.+Usage:+ blender -b f.blend -P texel_density.py -- [--objects A B] [--res 2048] [--set 512] [--margin-px 8] [--save out.blend]+ MCP: import texel_density; print(texel_density.run(objects=["SM_Crate"], res=2048))+"""+import math+import os+import sys++import bmesh+import bpy++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402+++def _islands(bm, uv):+ """UV islands as lists of faces (connected through shared UV coords)."""+ seen, out = set(), []+ for f in bm.faces:+ if f.index in seen:+ continue+ stack, isl = [f], []+ seen.add(f.index)+ while stack:+ cur = stack.pop()+ isl.append(cur)+ for l in cur.loops:+ rad = l.link_loop_radial_next+ nf = rad.face+ if nf.index in seen or rad == l:+ continue+ # same UV on both sides of the edge -> connected+ a1, a2 = l[uv].uv, l.link_loop_next[uv].uv+ b1, b2 = rad.link_loop_next[uv].uv, rad[uv].uv+ if (a1 - b1).length < 1e-5 and (a2 - b2).length < 1e-5:+ seen.add(nf.index)+ stack.append(nf)+ out.append(isl)+ return out+++def _uv_area(f, uv):+ pts = [l[uv].uv for l in f.loops]+ return abs(sum(pts[i].x * pts[i - 1].y - pts[i - 1].x * pts[i].y for i in range(len(pts)))) / 2+++def _measure(ob, res):+ bm = bmesh.new()+ bm.from_mesh(ob.data)+ bm.transform(ob.matrix_world)+ uv = bm.loops.layers.uv.active+ if uv is None:+ bm.free()+ return None, None, None+ bm.faces.ensure_lookup_table()+ isl_d = []+ tot_w = tot_uv = 0.0+ for isl in _islands(bm, uv):+ wa = sum(f.calc_area() for f in isl)+ ua = sum(_uv_area(f, uv) for f in isl)+ tot_w, tot_uv = tot_w + wa, tot_uv + ua+ if wa > 1e-10:+ isl_d.append((math.sqrt(ua / wa) * res, [f.index for f in isl]))+ mean = math.sqrt(tot_uv / tot_w) * res if tot_w > 1e-10 else 0.0+ return bm, mean, isl_d+++def run(objects=None, res=2048, set=None, margin_px=8, **_): # noqa: A002 (CLI name)+ bx.object_mode()+ out = {}+ for ob in bx.objects(objects):+ bm, mean, isl = _measure(ob, res)+ if bm is None:+ out[ob.name] = {"error": "no UV map"}+ continue+ bm.free()+ dens = [d for d, _ in isl] or [0]+ rec = {"px_per_m": round(mean, 1), "island_min": round(min(dens), 1),+ "island_max": round(max(dens), 1), "islands": len(isl),+ "spread": round(max(dens) / max(min(dens), 1e-6), 2)}+ if set:+ bm = bmesh.new()+ bm.from_mesh(ob.data)+ uv = bm.loops.layers.uv.active+ bm.faces.ensure_lookup_table()+ for d, faces in isl:+ k = set / max(d, 1e-6)+ loops = [l for i in faces for l in bm.faces[i].loops]+ c = sum((l[uv].uv for l in loops), loops[0][uv].uv * 0) / len(loops)+ for l in loops:+ l[uv].uv = c + (l[uv].uv - c) * k+ bm.to_mesh(ob.data)+ bm.free()+ bx.select_only([ob])+ bpy.ops.object.mode_set(mode="EDIT")+ bpy.ops.mesh.select_all(action="SELECT")+ bpy.ops.uv.select_all(action="SELECT")+ bpy.ops.uv.pack_islands(scale=False, rotate=True, shape_method="AABB", margin_method="FRACTION",+ margin=margin_px / res)+ bpy.ops.object.mode_set(mode="OBJECT")+ bm, mean2, isl2 = _measure(ob, res)+ uvl = ob.data.uv_layers.active.data+ co = [d.uv for d in uvl]+ over = any(u.x > 1.0001 or u.y > 1.0001 or u.x < -1e-4 or u.y < -1e-4 for u in co)+ bm.free()+ rec["after"] = {"px_per_m": round(mean2, 1), "fits_0_1": not over}+ if over:+ rec["after"]["hint"] = "lower density, raise --res, or split into more texture sets/UDIMs"+ out[ob.name] = rec+ return {"ok": True, "res": res, "objects": out}+++if __name__ == "__main__":+ p = bx.add_common(bx.parser(__doc__))+ p.add_argument("--res", type=int, default=2048)+ p.add_argument("--set", type=float, default=None, help="target px/m")+ p.add_argument("--margin-px", type=int, default=8)+ bx.cli(run, p)diff --git a/skills/blender-retopology-uv/scripts/uv_pack.py b/skills/blender-retopology-uv/scripts/uv_pack.pynew file mode 100644index 0000000..b48e6c2--- /dev/null+++ b/skills/blender-retopology-uv/scripts/uv_pack.py@@ -0,0 +1,109 @@+"""Unwrap + pack UVs with production defaults; optional seams-from-sharp and lightmap UV2.++Methods: smart (auto seams by angle), seams (use marked seams; --seams-from-sharp marks+hard edges first), min_stretch (SLIM, marked seams), lightmap (non-overlapping UV2 only).+Margins are given in pixels at --res so padding survives mip-mapping.+Usage:+ blender -b f.blend -P uv_pack.py -- [--objects A B] [--method smart|seams|min_stretch]+ [--angle 66] [--seams-from-sharp 60] [--res 2048] [--margin-px 8] [--lightmap]+ [--shape AABB|CONVEX|CONCAVE] [--save out.blend]+ MCP: import uv_pack; print(uv_pack.run(objects=["SM_Crate"], method="seams", seams_from_sharp=60))+"""+import math+import os+import sys++import bmesh+import bpy++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402+++def _seams_from_sharp(ob, angle):+ bm = bmesh.new()+ bm.from_mesh(ob.data)+ n = 0+ for e in bm.edges:+ if len(e.link_faces) == 2 and e.calc_face_angle(0) > math.radians(angle):+ e.seam = True+ n += 1+ elif len(e.link_faces) == 1:+ e.seam = True+ bm.to_mesh(ob.data)+ bm.free()+ return n+++def _collapsed_ratio(ob):+ """Fraction of faces whose UV area is ~0 (failed unwrap)."""+ uv = ob.data.uv_layers.active.data+ bad = 0+ for p in ob.data.polygons:+ pts = [uv[i].uv for i in p.loop_indices]+ a = sum(pts[i].x * pts[i - 1].y - pts[i - 1].x * pts[i].y for i in range(len(pts)))+ bad += abs(a) < 1e-10+ return bad / max(len(ob.data.polygons), 1)+++def run(objects=None, method="smart", angle=66.0, seams_from_sharp=None, res=2048, margin_px=8,+ lightmap=False, shape="AABB", **_):+ bx.object_mode()+ obs = bx.objects(objects)+ margin = margin_px / res+ rep = {}+ for ob in obs:+ if seams_from_sharp:+ rep.setdefault(ob.name, {})["seams_marked"] = _seams_from_sharp(ob, seams_from_sharp)+ if not ob.data.uv_layers:+ ob.data.uv_layers.new(name="UVMap")+ bx.select_only(obs)+ bpy.ops.object.mode_set(mode="EDIT")+ bpy.ops.mesh.select_all(action="SELECT")+ if method == "smart":+ bpy.ops.uv.smart_project(angle_limit=math.radians(angle), island_margin=margin,+ area_weight=0.0, correct_aspect=True, scale_to_bounds=False)+ else:+ bpy.ops.uv.unwrap(method="MINIMUM_STRETCH" if method == "min_stretch" else "ANGLE_BASED",+ fill_holes=True, correct_aspect=True, margin_method="FRACTION", margin=margin)+ bpy.ops.object.mode_set(mode="OBJECT")+ bad = [ob.name for ob in obs if _collapsed_ratio(ob) > 0.2] # closed island without seams+ bpy.ops.object.mode_set(mode="EDIT")+ if bad:+ bpy.ops.uv.smart_project(angle_limit=math.radians(angle), island_margin=margin,+ area_weight=0.0, correct_aspect=True, scale_to_bounds=False)+ for n in bad:+ rep.setdefault(n, {})["fallback"] = "smart (unwrap collapsed: add seams for control)"+ bpy.ops.uv.select_all(action="SELECT")+ bpy.ops.uv.average_islands_scale()+ bpy.ops.uv.pack_islands(rotate=True, rotate_method="ANY", scale=True, shape_method=shape,+ margin_method="FRACTION", margin=margin)+ bpy.ops.object.mode_set(mode="OBJECT")+ if lightmap:+ for ob in obs:+ uvs = ob.data.uv_layers+ lm = uvs.get("UVMap_Lightmap") or uvs.new(name="UVMap_Lightmap")+ uvs.active = lm+ bpy.ops.object.mode_set(mode="EDIT")+ bpy.ops.mesh.select_all(action="SELECT")+ bpy.ops.uv.lightmap_pack(PREF_CONTEXT="ALL_FACES", PREF_PACK_IN_ONE=False,+ PREF_MARGIN_DIV=max(0.05, margin_px / 4))+ bpy.ops.object.mode_set(mode="OBJECT")+ for ob in obs:+ ob.data.uv_layers.active = ob.data.uv_layers[0] # keep UV0 active for texturing+ for ob in obs:+ rep.setdefault(ob.name, {})["uv_maps"] = [u.name for u in ob.data.uv_layers]+ return {"ok": True, "method": method, "margin_fraction": round(margin, 5), "objects": rep}+++if __name__ == "__main__":+ p = bx.add_common(bx.parser(__doc__))+ p.add_argument("--method", default="smart", choices=["smart", "seams", "min_stretch"])+ p.add_argument("--angle", type=float, default=66.0)+ p.add_argument("--seams-from-sharp", type=float, default=None)+ p.add_argument("--res", type=int, default=2048)+ p.add_argument("--margin-px", type=int, default=8)+ p.add_argument("--lightmap", action="store_true")+ p.add_argument("--shape", default="AABB", choices=["AABB", "CONVEX", "CONCAVE"],+ help="AABB fast; CONCAVE tightest but 2-25s headless even on small meshes")+ bx.cli(run, p)diff --git a/skills/blender-scene-setup/SKILL.md b/skills/blender-scene-setup/SKILL.mdnew file mode 100644index 0000000..e0bf836--- /dev/null+++ b/skills/blender-scene-setup/SKILL.md@@ -0,0 +1,73 @@+---+name: blender-scene-setup+description: Set up and audit Blender scenes the way studios do - units and real-world scale, collection layout, naming conventions (SM_/SK_/T_/M_), origins, linking vs appending, library overrides, asset libraries and catalogs, collection exporters, orphan/path cleanup. Use when starting a project, organizing a .blend, or before handoff/export.+license: MIT+metadata:+ author: blender-agent-skills+ version: "0.1.0"+---++# Scene Setup & Hygiene++The execution model and verification steps are in `blender-core`.++## Procedure+1. Run `scripts/scene_audit.py` (add `--fix purge scale paths` only on files you own). It reports units, unapplied/negative scale, default names, objects in the scene root, missing images, orphans and far-off origins.+2. Set units: Metric, Unit Scale **1.0**, Length meters. Keep 1.0 even for Unreal/Roblox, because exporters handle the conversion (see `blender-export-pipelines`).+3. Build the collection layout (below). Every object must be in a named collection, never the scene root.+4. Name everything with the conventions below. Rename after every duplicate or join so no `.001` suffixes remain.+5. Set origins: props at the bottom-center (they sit on the ground at Z=0), characters at world origin between the feet, doors/hinges at the pivot.+6. Apply rotation and scale on meshes (Ctrl+A). Keep location unless the asset should export at the origin.+7. Re-run the audit. It's done when `issues` is empty or every remaining issue is intentional and explained.++## Collection layout (one asset per .blend, or one collection per asset)+```+ASSET_Crate+├── Crate_high # sculpt / subdiv source (exclude from export)+├── Crate_low # game mesh(es) SM_Crate, SM_Crate_LOD1..+├── Crate_bake # cages, bake helpers+├── Crate_collision # UCX_SM_Crate_00 (UE) / Crate-col (Godot)+└── Crate_ref # reference images/blockout (hide_render)+```+Use **Collection Exporters** (4.2+) to define the export once per collection, then re-export with one call:+```python+with bpy.context.temp_override(collection=col):+ bpy.ops.collection.exporter_add(name="IO_FH_gltf2")+ex = col.exporters[-1]; ex.export_properties.filepath = "//export/SM_Crate.glb"+with bpy.context.temp_override(collection=col):+ bpy.ops.collection.exporter_export(index=len(col.exporters) - 1)+```+`bpy.ops.wm.collection_export_all()` re-runs every collection exporter.++## Naming conventions (Unreal-style, accepted by all engines)+| Type | Pattern | Example |+|---|---|---|+| Static mesh | `SM_<Name>[_LOD#]` | `SM_Crate_LOD1` |+| Skeletal mesh / rig | `SK_<Name>` / `RIG_<Name>` (armature object `Armature` or `root`) | `SK_Hero` |+| Material | `M_<Name>` / instance `MI_<Name>` | `M_Wood_Oak` |+| Texture | `T_<Name>_<Suffix>`: `_BC` base color, `_N` normal, `_ORM` (R=AO G=Rough B=Metal), `_E` emissive, `_M` mask | `T_Crate_ORM` |+| Collision | UE `UCX_<Mesh>_##`, Godot suffix `-col`/`-colonly`/`-convcolonly` | `UCX_SM_Crate_00` |+| Bones/sides | `.L`/`.R` suffix (Blender mirror tools depend on it) | `upper_arm.L` |+| Actions | `<Rig>_<Clip>` | `Hero_Run` |+Use ASCII only, no spaces, and PascalCase or snake_case consistently across the project.++## Real-world scale reference (meters)+Door 2.0–2.1 × 0.9 · ceiling 2.4–2.7 · table 0.75 · chair seat 0.45 · counter 0.9 · stair rise 0.18 / tread 0.28 · adult human 1.7–1.8 (eyes 1.6) · car 4.5 × 1.8 × 1.5. Roblox: 1 stud ≈ 0.28 m; default character ≈ 5 studs tall. Wrong scale breaks physics, lighting falloff, DOF and texel density, so check `ob.dimensions` first.++## Linking, appending, overrides+- **Append** (`libraries.load(link=False)`) makes a local copy. Use it for one-off reuse.+- **Link** (`link=True`) is read-only, updates from the source and is what pipelines use. To edit a linked collection, add a library override: `ob.override_hierarchy_create(scene, view_layer, do_fully_editable=False)`. Only overridable properties (transforms, pose, and anything marked overridable) can change.+- Keep library paths relative (`//`). Check `bpy.data.libraries` for broken paths.++## Asset libraries+- Mark: `ob.asset_mark(); ob.asset_generate_preview()`. Metadata goes in `ob.asset_data` (`author`, `description`, `license`, `tags.new("wood")`, `catalog_id`).+- Catalogs live in `blender_assets.cats.txt` at the library root, one line per catalog: `UUID:Path/Sub:Simple Name`.+- Register a library with `prefs.filepaths.asset_libraries.new(name=..., directory=...)`. 5.2+: remote libraries via `use_remote_url` + `remote_url`. In 5.2 `active_asset_library` indices are offset by 2 ("All", "Essentials").+- Import method per library: `LINK`, `APPEND`, `APPEND_REUSE` (default; reuses already-appended data).++## Hygiene rules+- Purge orphans before shipping (`bpy.data.orphans_purge(do_recursive=True)`). Use fake users only on purpose.+- Image paths: relative (`file.make_paths_relative`), or pack for single-file delivery (`file.pack_all`).+- Never ship multi-user mesh data that has an unapplied per-object scale. Instances are fine, but bake scale before export.+- Hide helpers with `hide_render=True` **and** exclude them from export collections; viewport hiding alone isn't enough.+- One active scene per file for delivery. Extra scenes confuse exporters (`use_active_scene`).diff --git a/skills/blender-scene-setup/scripts/_bpyx.py b/skills/blender-scene-setup/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-scene-setup/scripts/_bpyx.py@@ -0,0 +1,136 @@+"""_bpyx - tiny shared helpers for blender-agent-skills scripts (Blender 5.2+).++Source of truth: shared/_bpyx.py. Copies in skills/*/scripts/ are synced by+tools/sync_shared.py - never edit a copy.++Every skill script follows one contract:+ run(**kwargs) -> dict # call from MCP / Python (import the module)+ blender -b f.blend -P x.py -- --arg v # CLI: prints one line "@@JSON@@{...}"+"""+import argparse+import json+import sys++import bpy++MARK = "@@JSON@@"+++def argv():+ """Arguments after '--' (Blender ignores them)."""+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def _default(o):+ if hasattr(o, "__len__") and not isinstance(o, str):+ try:+ return [round(v, 5) if isinstance(v, float) else v for v in o]+ except TypeError:+ pass+ if isinstance(o, (set, frozenset)):+ return sorted(o)+ return str(o)+++def emit(data):+ """Print compact JSON on one marked line (parsed by run_in_blender.py)."""+ print(MARK + json.dumps(data, separators=(",", ":"), default=_default), flush=True)+ return data+++def parser(doc):+ """ArgumentParser whose help is the script docstring's first line."""+ return argparse.ArgumentParser(description=(doc or "").strip().splitlines()[0])+++def cli(run, p):+ """CLI entry: parse args after '--', run, emit JSON. Exit 1 on failure."""+ args = p.parse_args(argv())+ try:+ result = run(**vars(args))+ save = getattr(args, "save", None)+ if save:+ bpy.ops.wm.save_as_mainfile(filepath=bpy.path.abspath(save))+ result["saved"] = save+ emit(result)+ except Exception as e: # report, don't dump a traceback into agent context+ emit({"ok": False, "error": f"{type(e).__name__}: {e}"})+ if bpy.app.background:+ sys.exit(1)+++def add_common(p, save=True):+ """--objects / --save flags shared by most scripts."""+ p.add_argument("--objects", nargs="*", default=None,+ help="object names (default: selected, else all meshes)")+ if save:+ p.add_argument("--save", default=None, help="save .blend to this path after run")+ return p+++def objects(names=None, types=("MESH",)):+ """Resolve names -> objects. No names: selected of `types`, else all visible of `types`."""+ if names:+ missing = [n for n in names if n not in bpy.data.objects]+ if missing:+ raise KeyError(f"objects not found: {missing}")+ return [bpy.data.objects[n] for n in names]+ pool = [o for o in bpy.context.scene.objects if not types or o.type in types]+ sel = [o for o in pool if o.select_get()]+ return sel or [o for o in pool if o.visible_get()]+++def object_mode():+ """Leave edit/sculpt/pose modes; most data API work needs OBJECT mode."""+ ob = bpy.context.view_layer.objects.active+ if ob and ob.mode != "OBJECT":+ bpy.ops.object.mode_set(mode="OBJECT")+++def select_only(objs, active=None):+ """Select exactly `objs` and make `active` (default first) active."""+ for o in bpy.context.view_layer.objects:+ o.select_set(False)+ for o in objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = active or (objs[0] if objs else None)+++def node(tree, type_):+ """First node of `type_` (e.g. 'BSDF_PRINCIPLED'). Names are localized - never look up by name."""+ return next((n for n in tree.nodes if n.type == type_), None)+++def enum_ids(owner, prop):+ """Valid identifiers of an enum property (works on types or instances)."""+ return [i.identifier for i in owner.bl_rna.properties[prop].enum_items]+++def set_enum(owner, prop, value):+ """Assign an enum; on failure raise listing valid values (dynamic enums under-report)."""+ try:+ setattr(owner, prop, value)+ except TypeError as e:+ raise ValueError(f"{prop}={value!r} invalid: {e}") from None+++def mesh_tris(ob, evaluated=True):+ """Triangle count (evaluated = with modifiers)."""+ if evaluated:+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ try:+ me.calc_loop_triangles()+ return len(me.loop_triangles)+ finally:+ eo.to_mesh_clear()+ me = ob.data+ me.calc_loop_triangles()+ return len(me.loop_triangles)+++def r(v, n=4):+ """Round a float or a vector for compact JSON."""+ if isinstance(v, float):+ return round(v, n)+ return [round(x, n) for x in v]diff --git a/skills/blender-scene-setup/scripts/scene_audit.py b/skills/blender-scene-setup/scripts/scene_audit.pynew file mode 100644index 0000000..b4c3d90--- /dev/null+++ b/skills/blender-scene-setup/scripts/scene_audit.py@@ -0,0 +1,117 @@+"""Audit scene hygiene: units, transforms, naming, collections, materials, images, orphans.++Optional safe fixes: purge orphans, apply rot/scale on single-user meshes, make paths relative.+Usage:+ blender -b f.blend -P scene_audit.py -- [--objects A B] [--fix purge scale paths] [--save out.blend]+ MCP: import scene_audit; print(scene_audit.run(fix=["purge"]))+"""+import os+import re+import sys++import bpy+from mathutils import Matrix, Vector++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++DEFAULT_NAME = re.compile(r"^(Cube|Plane|Sphere|Cylinder|Cone|Torus|Suzanne|Circle|Icosphere|"+ r"Mesh|Empty|Armature|Camera|Light|Material|Object|BezierCurve|Text)"+ r"(\.\d{3})?$")+EPS = 1e-4+++def _apply_rot_scale(ob):+ if ob.type != "MESH" or ob.data.users > 1:+ return False+ loc, rot, sca = ob.matrix_basis.decompose()+ ob.data.transform(Matrix.LocRotScale(None, rot, sca))+ ob.matrix_basis = Matrix.Translation(loc)+ for c in ob.children: # keep children in place+ c.matrix_parent_inverse = Matrix.LocRotScale(None, rot, sca) @ c.matrix_parent_inverse+ return True+++def run(objects=None, fix=None, **_):+ bx.object_mode()+ fix = set(fix or [])+ sc = bpy.context.scene+ us = sc.unit_settings+ obs = bx.objects(objects, types=None)+ issues = {k: [] for k in ("unapplied_scale", "negative_scale", "rotated", "default_names",+ "duplicate_suffix", "in_scene_root", "no_material",+ "empty_material_slots", "multi_user_mesh", "origin_far")}+ for ob in obs:+ if ob.type in {"MESH", "CURVE", "ARMATURE", "FONT", "SURFACE"}:+ s = ob.scale+ if any(abs(v - 1) > EPS for v in s):+ issues["unapplied_scale"].append(ob.name)+ if s.x * s.y * s.z < 0:+ issues["negative_scale"].append(ob.name)+ if ob.type == "MESH" and any(abs(v) > EPS for v in ob.rotation_euler):+ issues["rotated"].append(ob.name)+ if DEFAULT_NAME.match(ob.name):+ issues["default_names"].append(ob.name)+ elif re.search(r"\.\d{3}$", ob.name):+ issues["duplicate_suffix"].append(ob.name)+ if ob.name in sc.collection.objects and ob.type not in {"CAMERA", "LIGHT"}:+ issues["in_scene_root"].append(ob.name)+ if ob.type == "MESH":+ if not ob.material_slots:+ issues["no_material"].append(ob.name)+ elif any(s.material is None for s in ob.material_slots):+ issues["empty_material_slots"].append(ob.name)+ if ob.data.users > 1:+ issues["multi_user_mesh"].append(ob.name)+ if ob.data.vertices:+ # origin farther from the bbox centre than 2x the object's size -> pivot problems+ local_c = sum((Vector(c) for c in ob.bound_box), Vector()) / 8+ if local_c.length * max(ob.scale) > 2 * (max(ob.dimensions) or 1):+ issues["origin_far"].append(ob.name)++ images = {"missing": [], "packed": 0, "absolute_paths": []}+ for im in bpy.data.images:+ if im.source != "FILE":+ continue+ if im.packed_file:+ images["packed"] += 1+ continue+ if not os.path.exists(bpy.path.abspath(im.filepath)):+ images["missing"].append(im.name)+ elif not im.filepath.startswith("//") and bpy.data.filepath:+ images["absolute_paths"].append(im.name)++ orphans = sum(1 for c in ("meshes", "materials", "images", "node_groups", "actions", "textures")+ for d in getattr(bpy.data, c) if d.users == 0)+ done = []+ if "purge" in fix:+ n = bpy.data.orphans_purge(do_recursive=True)+ done.append(f"purged {n} orphan blocks")+ if "scale" in fix:+ applied = [ob.name for ob in obs if (ob.name in issues["unapplied_scale"] or+ ob.name in issues["rotated"]) and _apply_rot_scale(ob)]+ bpy.context.view_layer.update()+ done.append(f"applied rot/scale on {len(applied)} meshes")+ if "paths" in fix and bpy.data.filepath:+ bpy.ops.file.make_paths_relative()+ done.append("paths made relative")++ issues = {k: v for k, v in issues.items() if v}+ return {+ "ok": True,+ "units": {"system": us.system, "scale_length": us.scale_length, "length": us.length_unit,+ "warn": None if (us.system == "METRIC" and abs(us.scale_length - 1) < EPS)+ else "non-default units: confirm target engine expects this"},+ "objects": len(obs),+ "issues": issues,+ "images": images,+ "orphans": orphans,+ "linked_libraries": [lib.filepath for lib in bpy.data.libraries],+ "fixed": done,+ }+++if __name__ == "__main__":+ p = bx.add_common(bx.parser(__doc__))+ p.add_argument("--fix", nargs="*", choices=["purge", "scale", "paths"], default=[])+ bx.cli(run, p)diff --git a/skills/blender-sculpting/SKILL.md b/skills/blender-sculpting/SKILL.mdnew file mode 100644index 0000000..4ea4174--- /dev/null+++ b/skills/blender-sculpting/SKILL.md@@ -0,0 +1,51 @@+---+name: blender-sculpting+description: Sculpting in Blender 5.2 - base-to-detail workflow, voxel remesh, dyntopo, multires, 5.x brush types, masks/face sets, symmetry, plus headless-safe procedural ops for agents (remesh, symmetrize, multires, inflate, noise detail, smooth) and the sculpt-to-game handoff. Use for organic models, characters, creatures, rocks and bake sources.+license: MIT+metadata:+ author: blender-agent-skills+ version: "0.1.0"+---++# Sculpting++The execution model is in `blender-core`. The handoff goes to `blender-retopology-uv` → `blender-texture-baking`.++## Agents: what you can and can't do+- **Sculpt Mode operators crash Blender in background mode** (`-b`), including `mesh_filter`. Never enter Sculpt Mode headless.+- Headless or MCP: use `scripts/sculpt_ops.py` for object-level ops: `remesh=SIZE`, `symmetrize=+X`, `multires=N`, `inflate=D`, `detail=STR,SCALE`, `smooth=N`, `apply`. Combine these with Geometry Nodes (`blender-geometry-nodes`: SDF grid booleans/fillets, noise displacement) and shape modeling for procedural organic forms.+- Live sessions with a UI: brush strokes via `bpy.ops.sculpt.brush_stroke(stroke=[...])` need a 3D View region override and are fragile. Prefer procedural ops, then show the user with `look`. Hand detailed brushwork to the human.++## Professional workflow+1. **Base mesh / blockout**: primitives, metaballs, Skin modifier, or a low-poly base at real scale. Proportions first: compare with references and check against a human 1.75 m.+2. **Unify**: voxel remesh (`remesh=0.02` for a 2 m character, smaller for detail) fuses parts and gives even density. Repeat it while the big forms change.+3. **Primary forms** at low resolution (Grab, Snake Hook, Clay Strips, Inflate, Smooth). **Secondary** (muscle groups, folds) at medium resolution. **Tertiary** (pores, scratches, fabric weave) with Multires levels 4–6, or as normal/displacement maps.+4. **Dynamic topology** (`sculpt.dynamic_topology_toggle`): adds detail where you stroke. Good for concept sculpting, bad for final topology and multires (it destroys UVs/multires). Use voxel remesh + multires for production.+5. **Multires**: subdivide (`multires_subdivide`, Catmull-Clark) on a clean quad base (after retopo) to sculpt high detail that bakes back to the base level (`blender-texture-baking`, multires bake or high→low).+6. **Handoff**: export the high (or keep it in-file), retopo to `_low`, UV, bake normal/AO/curvature, then texture.++## Brushes (5.x: brushes are assets in the Essentials library)+| Purpose | `sculpt_brush_type` |+|---|---|+| Build volume | `CLAY_STRIPS`, `CLAY`, `CLAY_THUMB`, `LAYER`, `INFLATE`, `BLOB` |+| Shape / move | `GRAB`, `SNAKE_HOOK`, `ELASTIC_DEFORM`, `POSE`, `BOUNDARY`, `CLOTH`, `NUDGE`, `ROTATE`, `THUMB` |+| Details / edges | `DRAW`, `DRAW_SHARP`, `CREASE`, `PINCH` |+| Flatten / hard surface | `PLANE` (flatten/fill/scrape), `MULTIPLANE_SCRAPE` |+| Clean up | `SMOOTH`, `SIMPLIFY` (dyntopo), `DISPLACEMENT_ERASER`/`SMEAR` (multires) |+| Masking / grouping | `MASK`, `DRAW_FACE_SETS`; Expand (`sculpt.expand`), mask from cavity |+5.0 renamed `brush.sculpt_tool` → `sculpt_brush_type`. 5.1 folded the stroke options into `brush.stroke_method` (`DOTS`, `DRAG_DOT`, `SPACE`, `AIRBRUSH`, `ANCHORED`, `LINE`, `CURVE`). 5.2 moved automasking to `brush.mesh_automasking_settings` / `paint.mesh_automasking_settings`.++## Rules of thumb+- Sculpt at **real scale**, with scale applied. Brush radius is in screen space but strength and remesh sizes depend on scale.+- Use symmetry (`mesh.use_mirror_x`, radial: `mesh.radial_symmetry`) on characters until the asymmetry pass at the end.+- Face Sets organise parts (head, torso, hands). Hide them and mask by face set to isolate.+- Watch density: a 2 m character at voxel 0.005 is already millions of polys. Keep viewport FPS usable and work up in levels.+- Silhouette first. Check from several angles in flat matcap (`look` shading `solid`) before adding detail.+- Floaters/kitbash for hard-surface details on organic models: separate objects, combined at bake time.+- Before baking, run `blender-asset-qa` on the high (no inverted parts, no huge self-intersections in the bake range).++## Gotchas+- `voxel_remesh` destroys UVs, vertex groups (unless preserve attributes) and multires levels. Do it before UVs/rigging.+- Multires + topology changes don't mix: never edit the base topology after subdividing (apply the base or rebuild).+- `symmetrize` on a non-centered object mirrors across the **object's local axis**. Center the origin on the symmetry plane first.+- Sculpting on shape keys: enable `use_shape_key_edit_mode` and sculpt on the active key (facial work, `blender-facial-shapekeys`).diff --git a/skills/blender-sculpting/scripts/_bpyx.py b/skills/blender-sculpting/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-sculpting/scripts/_bpyx.py@@ -0,0 +1,136 @@+"""_bpyx - tiny shared helpers for blender-agent-skills scripts (Blender 5.2+).++Source of truth: shared/_bpyx.py. Copies in skills/*/scripts/ are synced by+tools/sync_shared.py - never edit a copy.++Every skill script follows one contract:+ run(**kwargs) -> dict # call from MCP / Python (import the module)+ blender -b f.blend -P x.py -- --arg v # CLI: prints one line "@@JSON@@{...}"+"""+import argparse+import json+import sys++import bpy++MARK = "@@JSON@@"+++def argv():+ """Arguments after '--' (Blender ignores them)."""+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def _default(o):+ if hasattr(o, "__len__") and not isinstance(o, str):+ try:+ return [round(v, 5) if isinstance(v, float) else v for v in o]+ except TypeError:+ pass+ if isinstance(o, (set, frozenset)):+ return sorted(o)+ return str(o)+++def emit(data):+ """Print compact JSON on one marked line (parsed by run_in_blender.py)."""+ print(MARK + json.dumps(data, separators=(",", ":"), default=_default), flush=True)+ return data+++def parser(doc):+ """ArgumentParser whose help is the script docstring's first line."""+ return argparse.ArgumentParser(description=(doc or "").strip().splitlines()[0])+++def cli(run, p):+ """CLI entry: parse args after '--', run, emit JSON. Exit 1 on failure."""+ args = p.parse_args(argv())+ try:+ result = run(**vars(args))+ save = getattr(args, "save", None)+ if save:+ bpy.ops.wm.save_as_mainfile(filepath=bpy.path.abspath(save))+ result["saved"] = save+ emit(result)+ except Exception as e: # report, don't dump a traceback into agent context+ emit({"ok": False, "error": f"{type(e).__name__}: {e}"})+ if bpy.app.background:+ sys.exit(1)+++def add_common(p, save=True):+ """--objects / --save flags shared by most scripts."""+ p.add_argument("--objects", nargs="*", default=None,+ help="object names (default: selected, else all meshes)")+ if save:+ p.add_argument("--save", default=None, help="save .blend to this path after run")+ return p+++def objects(names=None, types=("MESH",)):+ """Resolve names -> objects. No names: selected of `types`, else all visible of `types`."""+ if names:+ missing = [n for n in names if n not in bpy.data.objects]+ if missing:+ raise KeyError(f"objects not found: {missing}")+ return [bpy.data.objects[n] for n in names]+ pool = [o for o in bpy.context.scene.objects if not types or o.type in types]+ sel = [o for o in pool if o.select_get()]+ return sel or [o for o in pool if o.visible_get()]+++def object_mode():+ """Leave edit/sculpt/pose modes; most data API work needs OBJECT mode."""+ ob = bpy.context.view_layer.objects.active+ if ob and ob.mode != "OBJECT":+ bpy.ops.object.mode_set(mode="OBJECT")+++def select_only(objs, active=None):+ """Select exactly `objs` and make `active` (default first) active."""+ for o in bpy.context.view_layer.objects:+ o.select_set(False)+ for o in objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = active or (objs[0] if objs else None)+++def node(tree, type_):+ """First node of `type_` (e.g. 'BSDF_PRINCIPLED'). Names are localized - never look up by name."""+ return next((n for n in tree.nodes if n.type == type_), None)+++def enum_ids(owner, prop):+ """Valid identifiers of an enum property (works on types or instances)."""+ return [i.identifier for i in owner.bl_rna.properties[prop].enum_items]+++def set_enum(owner, prop, value):+ """Assign an enum; on failure raise listing valid values (dynamic enums under-report)."""+ try:+ setattr(owner, prop, value)+ except TypeError as e:+ raise ValueError(f"{prop}={value!r} invalid: {e}") from None+++def mesh_tris(ob, evaluated=True):+ """Triangle count (evaluated = with modifiers)."""+ if evaluated:+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ try:+ me.calc_loop_triangles()+ return len(me.loop_triangles)+ finally:+ eo.to_mesh_clear()+ me = ob.data+ me.calc_loop_triangles()+ return len(me.loop_triangles)+++def r(v, n=4):+ """Round a float or a vector for compact JSON."""+ if isinstance(v, float):+ return round(v, n)+ return [round(x, n) for x in v]diff --git a/skills/blender-sculpting/scripts/sculpt_ops.py b/skills/blender-sculpting/scripts/sculpt_ops.pynew file mode 100644index 0000000..0640d62--- /dev/null+++ b/skills/blender-sculpting/scripts/sculpt_ops.py@@ -0,0 +1,91 @@+"""Headless-safe sculpt preparation and procedural "sculpt" ops (no Sculpt Mode - it crashes in -b).++Ops run in the order given:+ remesh=SIZE voxel remesh (uniform topology, fuses parts) e.g. remesh=0.01+ symmetrize=+X mirror one side onto the other (+X|-X|+Y|-Y|+Z|-Z)+ multires=LEVELS add Multires and subdivide (Catmull-Clark) LEVELS times+ inflate=DIST push surface along normals (m)+ detail=STR,SCALE noise displacement (organic surface breakup), e.g. detail=0.01,0.05+ smooth=ITER volume-preserving Laplacian smooth+ apply apply all modifiers except Multires+Usage:+ blender -b f.blend -P sculpt_ops.py -- --objects Blob --ops remesh=0.02 symmetrize=+X multires=3 [--save out.blend]+ MCP: import sculpt_ops; print(sculpt_ops.run(objects=["Blob"], ops=["remesh=0.02", "smooth=5"]))+"""+import os+import sys++import bpy++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402+++def _ctx(ob):+ return bpy.context.temp_override(object=ob, active_object=ob, selected_objects=[ob],+ selected_editable_objects=[ob])+++def _apply(ob, keep_multires=True):+ names = [m.name for m in ob.modifiers if not (keep_multires and m.type == "MULTIRES")]+ for name in names: # names: applied modifiers are freed+ with _ctx(ob):+ bpy.ops.object.modifier_apply(modifier=name)+++def run(objects=None, ops=None, **_):+ bx.object_mode()+ out = {}+ for ob in bx.objects(objects):+ log = []+ for op in ops or []:+ k, _, v = op.partition("=")+ if k == "remesh":+ _apply(ob, keep_multires=False)+ ob.data.remesh_voxel_size = float(v)+ ob.data.use_remesh_preserve_volume = True+ with _ctx(ob):+ bpy.ops.object.voxel_remesh()+ elif k == "symmetrize":+ axis = {"+X": "POSITIVE_X", "-X": "NEGATIVE_X", "+Y": "POSITIVE_Y", "-Y": "NEGATIVE_Y",+ "+Z": "POSITIVE_Z", "-Z": "NEGATIVE_Z"}[v or "+X"]+ bx.select_only([ob])+ bpy.ops.object.mode_set(mode="EDIT")+ bpy.ops.mesh.select_all(action="SELECT")+ bpy.ops.mesh.symmetrize(direction=axis)+ bpy.ops.object.mode_set(mode="OBJECT")+ elif k == "multires":+ m = next((m for m in ob.modifiers if m.type == "MULTIRES"), None) or ob.modifiers.new("Multires", "MULTIRES")+ for _ in range(int(v)):+ with _ctx(ob):+ bpy.ops.object.multires_subdivide(modifier=m.name, mode="CATMULL_CLARK")+ m.levels = m.sculpt_levels = m.render_levels = m.total_levels+ elif k == "inflate":+ d = ob.modifiers.new("Inflate", "DISPLACE")+ d.mid_level, d.strength = 0.0, float(v)+ elif k == "detail":+ strength, scale = (float(x) for x in v.split(","))+ tex = bpy.data.textures.new(f"{ob.name}_detail", "CLOUDS")+ tex.noise_scale, tex.noise_depth = scale, 4+ d = ob.modifiers.new("Detail", "DISPLACE")+ d.texture, d.strength, d.texture_coords = tex, strength, "LOCAL"+ elif k == "smooth":+ s = ob.modifiers.new("Smooth", "LAPLACIANSMOOTH")+ s.iterations, s.lambda_factor, s.use_volume_preserve = int(v), 0.5, True+ elif k == "apply":+ _apply(ob)+ else:+ raise ValueError(f"unknown op {op}")+ log.append(op)+ bpy.context.view_layer.update()+ mr = next((m for m in ob.modifiers if m.type == "MULTIRES"), None)+ out[ob.name] = {"ops": log, "base_faces": len(ob.data.polygons),+ "evaluated_tris": bx.mesh_tris(ob), "multires_levels": mr.total_levels if mr else 0,+ "stack": [m.name for m in ob.modifiers]}+ return {"ok": True, "objects": out}+++if __name__ == "__main__":+ p = bx.add_common(bx.parser(__doc__))+ p.add_argument("--ops", nargs="*", default=[])+ bx.cli(run, p)diff --git a/skills/blender-simulation/SKILL.md b/skills/blender-simulation/SKILL.mdnew file mode 100644index 0000000..55cda89--- /dev/null+++ b/skills/blender-simulation/SKILL.md@@ -0,0 +1,67 @@+---+name: blender-simulation+description: Physics in Blender 5.2 - rigid bodies (density mass, shapes, bake to keys), classic cloth presets and pinning, new node-based Cloth/Hair Dynamics (XPBD, Collider, effectors), Mantaflow fluids, hair curves, GN simulation zones, headless baking. Use for destruction, drapes, flags, falling objects, liquids, smoke, hair motion.+license: MIT+metadata:+ author: blender-agent-skills+ version: "0.1.0"+---++# Simulation++The execution model is in `blender-core`. Procedural sim zones are in `blender-geometry-nodes`.++## One call+```+scripts/sim_setup.py -- --rigid --active Crate1 Crate2 --passive Floor --density 500 --frames 1 120 --bake --to-keys+scripts/sim_setup.py -- --cloth Flag --preset cotton --pin Pin --colliders Pole --bake+scripts/sim_setup.py -- --gn-cloth Sheet --colliders Table --set Bendiness=0.5 Stretchiness=0.1 --bake+```+`--bake` steps through every frame in order (this works headless for point caches **and** GN simulation zones) and reports final positions and `min_z`, so you can verify contact. `--to-keys` turns rigid-body motion into keyframes for engines.++## Choose the solver+| Need | Use |+|---|---|+| Falling/stacking/destruction | Rigid Body (Bullet). Pre-fracture with Cell Fracture (extension) or GN Voronoi |+| Clothing, flags, drapes (production-proven) | Classic **Cloth** modifier + Collision modifiers |+| New node-based cloth/hair, custom forces, procedural setups | **Cloth Dynamics (Experimental)** / **Hair Dynamics** assets (5.2, XPBD) |+| Liquids, smoke, fire | Mantaflow fluid domain + flow/effector (`fluid.bake_all`) |+| Hair grooms | Curves objects + hair node assets (`procedural_hair_node_assets`), Hair Dynamics for motion |+| Growth, trails, custom per-frame logic | GN Simulation zone |+| Soft jiggle for games | bones with spring/jiggle in-engine, or Wiggle-style constraints baked to keys |++## Rigid bodies+- Real scale and real mass matter: mass = volume × density (wood 500–700, concrete 2400, steel 7850, plastic 950 kg/m³). The script computes it.+- Collision shape: `CONVEX_HULL` for dynamic objects (fast, stable), `MESH` only for **passive** concave colliders, and primitives (`BOX`, `SPHERE`, `CAPSULE`) when they fit.+- Stability: substeps 10 and iterations 10 (set by the script). Use a small collision margin (1 mm). Avoid objects starting interpenetrated.+- Export: bake to keyframes (`--to-keys`; the built-in `rigidbody.bake_to_keyframes` needs a UI, so the script samples `matrix_world` itself), then export the actions (`blender-export-pipelines`).++## Classic cloth+- Presets (from Blender's): cotton, denim, leather, rubber, silk. The mesh needs even quad density (2–5 cm edges for clothing). Use a subdivided plane or retopologized garment, never ngons.+- **Pinning**: vertex group with weight 1 = pinned (`settings.vertex_group_mass`). Animate pinned verts with hooks/armature.+- Collisions: colliders get a `COLLISION` modifier (thickness 1–5 mm), plus self-collision for folds. Raise `quality` (steps) for fast motion.+- Apply cloth as a shape (`modifier_apply_as_shapekey`) or bake to an Alembic/point cache for render. Games: bake to bones, or apply a static drape.++## Node-based dynamics (5.2, experimental)+- Assets live in `datafiles/assets/nodes/geometry_nodes_dynamics_assets.blend`: `Cloth Dynamics (Experimental)`, `Hair Dynamics`, `Collider`, `Set Effector`, `Custom Force`, `Custom Effector`. The script appends them.+- Cloth inputs include `Pin Group` (attribute), `Stretchiness`, `Bendiness`, `Substeps` (5), `Constraint Steps` (15), `Mass`, `Friction`, `Collision Radius`, `Linear Damping`, `Gravity`, `Tearing` (+ mode/threshold), `Effectors Collection`, `Effectors` (bundle).+- Colliders: put a `Collider` modifier on each collider object and add those objects to the collection fed into `Effectors Collection` (the script does both).+- Hair: Add → Empty Hair sets up the surface + `Capture Rest Geometry`. Hair Dynamics reads the rest/deformed surface through geometry bundles.+- Limits (5.2): no self-collision yet, no built-in wind/turbulence (build a `Custom Force`). Interfaces may change, so pin the Blender version in production.+- The solver itself (`GeometryNodeXPBDSolver`) takes a `World` bundle, `Delta Time`, `Substeps`, `Constraint Iterations`. Building directly on it is advanced; start from the assets.++## Fluids (Mantaflow) quick setup+Domain object (`FLUID` modifier `fluid_type="DOMAIN"`, `domain_type="LIQUID"|"GAS"`), resolution 64 preview / 128–256 final, cache directory set and `cache_type="ALL"` for headless; flow objects `fluid_type="FLOW"` (`flow_type` LIQUID/SMOKE/FIRE, `flow_behavior` INFLOW/GEOMETRY); obstacles `EFFECTOR`. Bake with `bpy.ops.fluid.bake_all()` under a context override with the domain active. This is slow. Test at low resolution first.++## Rules+- Simulations are frame-rate and scale dependent. Set `scene.render.fps` and the scale before tuning.+- Always bake before rendering/exporting, and never rely on viewport playback order.+- GN simulation zones: bake per modifier (`mod.bakes`, `object.geometry_node_bake_single`), or step frames sequentially (script) in background.+- Point caches in background: stepping frames from `frame_start` fills the cache. `ptcache.bake_all(bake=True)` needs a valid context.+- Verify with `look(mode="frames")` plus the numbers (`min_z` ≈ the collider top = contact, no tunnelling).++## Gotchas+- Objects tunnelling through colliders: thin colliders, too few substeps, or too-fast motion. Thicken, raise substeps/quality, or use a bigger collision distance.+- Exploding cloth at frame 1: starting interpenetration or a zero-area face. Run `blender-asset-qa`, offset the start.+- Rigid body world cache ranges are separate from the scene range (the script syncs them).+- Changing anything (frame range, settings) invalidates caches. Re-bake.diff --git a/skills/blender-simulation/scripts/_bpyx.py b/skills/blender-simulation/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-simulation/scripts/_bpyx.py@@ -0,0 +1,136 @@+"""_bpyx - tiny shared helpers for blender-agent-skills scripts (Blender 5.2+).++Source of truth: shared/_bpyx.py. Copies in skills/*/scripts/ are synced by+tools/sync_shared.py - never edit a copy.++Every skill script follows one contract:+ run(**kwargs) -> dict # call from MCP / Python (import the module)+ blender -b f.blend -P x.py -- --arg v # CLI: prints one line "@@JSON@@{...}"+"""+import argparse+import json+import sys++import bpy++MARK = "@@JSON@@"+++def argv():+ """Arguments after '--' (Blender ignores them)."""+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def _default(o):+ if hasattr(o, "__len__") and not isinstance(o, str):+ try:+ return [round(v, 5) if isinstance(v, float) else v for v in o]+ except TypeError:+ pass+ if isinstance(o, (set, frozenset)):+ return sorted(o)+ return str(o)+++def emit(data):+ """Print compact JSON on one marked line (parsed by run_in_blender.py)."""+ print(MARK + json.dumps(data, separators=(",", ":"), default=_default), flush=True)+ return data+++def parser(doc):+ """ArgumentParser whose help is the script docstring's first line."""+ return argparse.ArgumentParser(description=(doc or "").strip().splitlines()[0])+++def cli(run, p):+ """CLI entry: parse args after '--', run, emit JSON. Exit 1 on failure."""+ args = p.parse_args(argv())+ try:+ result = run(**vars(args))+ save = getattr(args, "save", None)+ if save:+ bpy.ops.wm.save_as_mainfile(filepath=bpy.path.abspath(save))+ result["saved"] = save+ emit(result)+ except Exception as e: # report, don't dump a traceback into agent context+ emit({"ok": False, "error": f"{type(e).__name__}: {e}"})+ if bpy.app.background:+ sys.exit(1)+++def add_common(p, save=True):+ """--objects / --save flags shared by most scripts."""+ p.add_argument("--objects", nargs="*", default=None,+ help="object names (default: selected, else all meshes)")+ if save:+ p.add_argument("--save", default=None, help="save .blend to this path after run")+ return p+++def objects(names=None, types=("MESH",)):+ """Resolve names -> objects. No names: selected of `types`, else all visible of `types`."""+ if names:+ missing = [n for n in names if n not in bpy.data.objects]+ if missing:+ raise KeyError(f"objects not found: {missing}")+ return [bpy.data.objects[n] for n in names]+ pool = [o for o in bpy.context.scene.objects if not types or o.type in types]+ sel = [o for o in pool if o.select_get()]+ return sel or [o for o in pool if o.visible_get()]+++def object_mode():+ """Leave edit/sculpt/pose modes; most data API work needs OBJECT mode."""+ ob = bpy.context.view_layer.objects.active+ if ob and ob.mode != "OBJECT":+ bpy.ops.object.mode_set(mode="OBJECT")+++def select_only(objs, active=None):+ """Select exactly `objs` and make `active` (default first) active."""+ for o in bpy.context.view_layer.objects:+ o.select_set(False)+ for o in objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = active or (objs[0] if objs else None)+++def node(tree, type_):+ """First node of `type_` (e.g. 'BSDF_PRINCIPLED'). Names are localized - never look up by name."""+ return next((n for n in tree.nodes if n.type == type_), None)+++def enum_ids(owner, prop):+ """Valid identifiers of an enum property (works on types or instances)."""+ return [i.identifier for i in owner.bl_rna.properties[prop].enum_items]+++def set_enum(owner, prop, value):+ """Assign an enum; on failure raise listing valid values (dynamic enums under-report)."""+ try:+ setattr(owner, prop, value)+ except TypeError as e:+ raise ValueError(f"{prop}={value!r} invalid: {e}") from None+++def mesh_tris(ob, evaluated=True):+ """Triangle count (evaluated = with modifiers)."""+ if evaluated:+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ try:+ me.calc_loop_triangles()+ return len(me.loop_triangles)+ finally:+ eo.to_mesh_clear()+ me = ob.data+ me.calc_loop_triangles()+ return len(me.loop_triangles)+++def r(v, n=4):+ """Round a float or a vector for compact JSON."""+ if isinstance(v, float):+ return round(v, n)+ return [round(x, n) for x in v]diff --git a/skills/blender-simulation/scripts/sim_setup.py b/skills/blender-simulation/scripts/sim_setup.pynew file mode 100644index 0000000..3b0abc8--- /dev/null+++ b/skills/blender-simulation/scripts/sim_setup.py@@ -0,0 +1,204 @@+"""Set up and bake simulations: rigid bodies, classic cloth (presets), 5.2 node-based cloth+(experimental Cloth Dynamics asset + Collider assets), then bake / bake-to-keyframes.++Usage:+ blender -b f.blend -P sim_setup.py -- --rigid --active Crate1 Crate2 --passive Floor [--shape CONVEX_HULL]+ [--density 500] [--frames 1 120] [--bake] [--to-keys] [--save out.blend]+ blender -b f.blend -P sim_setup.py -- --cloth Flag --preset cotton --pin PinGroup --colliders Pole [--bake]+ blender -b f.blend -P sim_setup.py -- --gn-cloth Sheet --colliders Table --set Bendiness=0.5 [--bake]+ MCP: import sim_setup as s; print(s.run(rigid=True, active=["Crate"], passive=["Floor"], bake=True))+Returns per-object settings and, after baking, the final world positions / evaluated bounds.+"""+import os+import sys++import bmesh+import bpy++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++CLOTH = { # Blender's built-in presets (scripts/presets/cloth)+ "cotton": dict(quality=5, mass=0.3, tension_stiffness=15, compression_stiffness=15, shear_stiffness=15,+ bending_stiffness=0.5, tension_damping=5, air_damping=1),+ "denim": dict(quality=12, mass=1, tension_stiffness=40, compression_stiffness=40, shear_stiffness=40,+ bending_stiffness=10, tension_damping=25, air_damping=1),+ "leather": dict(quality=15, mass=0.4, tension_stiffness=80, compression_stiffness=80, shear_stiffness=80,+ bending_stiffness=150, tension_damping=25, air_damping=1),+ "rubber": dict(quality=7, mass=3, tension_stiffness=15, compression_stiffness=15, shear_stiffness=15,+ bending_stiffness=25, tension_damping=25, air_damping=1),+ "silk": dict(quality=5, mass=0.15, tension_stiffness=5, compression_stiffness=5, shear_stiffness=5,+ bending_stiffness=0.05, tension_damping=0, air_damping=1),+}+DYN_BLEND = "geometry_nodes_dynamics_assets.blend"+++def _ctx(ob):+ return bpy.context.temp_override(object=ob, active_object=ob, selected_objects=[ob],+ selected_editable_objects=[ob])+++def _volume(ob):+ bm = bmesh.new()+ bm.from_object(ob, bpy.context.evaluated_depsgraph_get())+ bm.transform(ob.matrix_world)+ v = abs(bm.calc_volume(signed=False))+ bm.free()+ return v+++def _asset_group(name_prefix):+ ng = next((g for g in bpy.data.node_groups if g.name.startswith(name_prefix)), None)+ if ng:+ return ng+ path = os.path.join(bpy.utils.system_resource("DATAFILES"), "assets", "nodes", DYN_BLEND)+ with bpy.data.libraries.load(path, link=False) as (src, dst):+ dst.node_groups = [n for n in src.node_groups if n.startswith(name_prefix)][:1]+ if not dst.node_groups:+ raise RuntimeError(f"asset '{name_prefix}' not found in {DYN_BLEND} (needs Blender 5.2+)")+ return dst.node_groups[0]+++def _set_inputs(mod, values):+ items = {i.name: i.identifier for i in mod.node_group.interface.items_tree if getattr(i, "in_out", "") == "INPUT"}+ for k, v in values.items():+ it = getattr(mod.properties.inputs, items[k])+ if isinstance(v, str) and v.startswith("@"):+ it.type, it.attribute_name = "ATTRIBUTE", v[1:]+ else:+ it.value = v+++def _num(s):+ try:+ return int(s)+ except ValueError:+ try:+ return float(s)+ except ValueError:+ return {"true": True, "false": False}.get(s.lower(), s)+++def run(rigid=False, active=None, passive=None, shape="CONVEX_HULL", density=500.0, friction=0.5,+ bounce=0.1, cloth=None, preset="cotton", pin=None, colliders=None, gn_cloth=None, set=None, # noqa: A002+ frames=None, bake=False, to_keys=False, **_):+ bx.object_mode()+ sc = bpy.context.scene+ if frames:+ sc.frame_start, sc.frame_end = frames+ out = {"ok": True}+ if rigid:+ if sc.rigidbody_world is None:+ with bpy.context.temp_override(scene=sc):+ bpy.ops.rigidbody.world_add()+ rbw = sc.rigidbody_world+ if rbw.collection is None:+ rbw.collection = bpy.data.collections.new("RigidBodyWorld")+ rbw.point_cache.frame_start, rbw.point_cache.frame_end = sc.frame_start, sc.frame_end+ rbw.substeps_per_frame, rbw.solver_iterations = 10, 10+ rec = {}+ for kind, names in (("ACTIVE", active or []), ("PASSIVE", passive or [])):+ for ob in bx.objects(names):+ if ob.rigid_body is None:+ with _ctx(ob):+ bpy.ops.rigidbody.object_add(type=kind)+ rb = ob.rigid_body+ rb.type = kind+ rb.collision_shape = "MESH" if kind == "PASSIVE" and shape == "CONVEX_HULL" and len(+ ob.data.polygons) > 6 else shape+ rb.friction, rb.restitution = friction, bounce+ rb.use_margin, rb.collision_margin = True, 0.001+ if kind == "ACTIVE":+ rb.mass = max(_volume(ob) * density, 0.01)+ rec[ob.name] = {"type": kind, "shape": rb.collision_shape, "mass": round(rb.mass, 3)}+ out["rigid"] = rec+ if cloth:+ ob = bpy.data.objects[cloth]+ m = next((m for m in ob.modifiers if m.type == "CLOTH"), None) or ob.modifiers.new("Cloth", "CLOTH")+ for k, v in CLOTH[preset].items():+ setattr(m.settings, k, v)+ m.collision_settings.use_collision = True+ m.collision_settings.use_self_collision = True+ m.collision_settings.distance_min = 0.005+ if pin:+ m.settings.vertex_group_mass = pin+ m.point_cache.frame_start, m.point_cache.frame_end = sc.frame_start, sc.frame_end+ out["cloth"] = {"object": ob.name, "preset": preset, "pin": pin}+ if gn_cloth:+ ob = bpy.data.objects[gn_cloth]+ ng = _asset_group("Cloth Dynamics")+ mod = next((m for m in ob.modifiers if m.type == "NODES" and m.node_group == ng), None) \+ or ob.modifiers.new("Cloth Dynamics", "NODES")+ mod.node_group = ng+ vals = {k: _num(v) for k, v in (kv.split("=", 1) for kv in set or [])}+ if pin:+ vals["Pin Group"] = f"@{pin}"+ if colliders:+ col = bpy.data.collections.get("Effectors") or bpy.data.collections.new("Effectors")+ if col.name not in sc.collection.children:+ sc.collection.children.link(col)+ vals["Effectors Collection"] = col+ _set_inputs(mod, vals)+ out["gn_cloth"] = {"object": ob.name, "group": ng.name, "inputs": {k: str(v) for k, v in vals.items()}}+ if colliders:+ cg = _asset_group("Collider") if gn_cloth else None+ for c in bx.objects(colliders):+ if gn_cloth:+ if not any(m.type == "NODES" and m.node_group == cg for m in c.modifiers):+ c.modifiers.new("Collider", "NODES").node_group = cg+ col = bpy.data.collections["Effectors"]+ if c.name not in col.objects:+ col.objects.link(c)+ if (cloth or not gn_cloth) and not any(m.type == "COLLISION" for m in c.modifiers):+ c.modifiers.new("Collision", "COLLISION")+ out["colliders"] = colliders+ if bake:+ # step through frames in order: works for point caches AND GN simulation zones headless+ keyed = [bpy.data.objects[n] for n, r in out.get("rigid", {}).items() if r["type"] == "ACTIVE"] if rigid and to_keys else []+ mats = {o: [] for o in keyed}+ for f in range(sc.frame_start, sc.frame_end + 1):+ sc.frame_set(f)+ for o in keyed:+ mats[o].append((f, o.matrix_world.copy()))+ if keyed: # rigidbody.bake_to_keyframes needs a UI context; do it by hand+ for o, samples in mats.items():+ with _ctx(o):+ bpy.ops.rigidbody.object_remove()+ o.rotation_mode = "QUATERNION"+ for f, m in samples:+ o.matrix_world = m+ o.keyframe_insert("location", frame=f)+ o.keyframe_insert("rotation_quaternion", frame=f)+ out["baked_to_keyframes"] = [o.name for o in keyed]+ res = {}+ for n in list(out.get("rigid", {})) + [x for x in (cloth, gn_cloth) if x]:+ ob = bpy.data.objects[n]+ ev = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ zs = [(ev.matrix_world @ v.co).z for v in ev.data.vertices] if ev.type == "MESH" else [0]+ res[n] = {"loc": bx.r(tuple(ev.matrix_world.translation), 3), "min_z": round(min(zs), 3)}+ out["final_frame"] = sc.frame_end+ out["result"] = res+ return out+++if __name__ == "__main__":+ p = bx.parser(__doc__)+ p.add_argument("--rigid", action="store_true")+ p.add_argument("--active", nargs="*", default=None)+ p.add_argument("--passive", nargs="*", default=None)+ p.add_argument("--shape", default="CONVEX_HULL", choices=["CONVEX_HULL", "MESH", "BOX", "SPHERE", "CAPSULE",+ "CYLINDER", "CONE", "COMPOUND"])+ p.add_argument("--density", type=float, default=500.0, help="kg/m3 (wood 500, concrete 2400, steel 7850)")+ p.add_argument("--friction", type=float, default=0.5)+ p.add_argument("--bounce", type=float, default=0.1)+ p.add_argument("--cloth", default=None)+ p.add_argument("--preset", default="cotton", choices=list(CLOTH))+ p.add_argument("--pin", default=None, help="vertex group (pinned = weight 1)")+ p.add_argument("--colliders", nargs="*", default=None)+ p.add_argument("--gn-cloth", default=None)+ p.add_argument("--set", nargs="*", default=None, help="GN cloth inputs Name=value")+ p.add_argument("--frames", nargs=2, type=int, default=None)+ p.add_argument("--bake", action="store_true")+ p.add_argument("--to-keys", action="store_true", help="rigid bodies -> keyframes (for export)")+ p.add_argument("--save", default=None)+ bx.cli(run, p)diff --git a/skills/blender-texture-baking/SKILL.md b/skills/blender-texture-baking/SKILL.mdnew file mode 100644index 0000000..acc47ca--- /dev/null+++ b/skills/blender-texture-baking/SKILL.md@@ -0,0 +1,69 @@+---+name: blender-texture-baking+description: Bake texture maps in Blender 5.2 Cycles - high-to-low normal maps with cage/extrusion, AO, curvature, ID, thickness, base color/roughness/metallic from procedurals, ORM packing, OpenGL vs DirectX, margins, GPU baking, fixing skewing/waviness/seams. Use when transferring sculpt or high-poly detail to game meshes or converting procedural materials to textures.+license: MIT+metadata:+ author: blender-agent-skills+ version: "0.1.0"+---++# Texture Baking (Cycles)++The execution model is in `blender-core`. UVs come from `blender-retopology-uv` and materials from `blender-pbr-materials`.++## One call+```+scripts/bake_maps.py -- --low SM_Crate --high Crate_high Crate_bolts --maps normal ao curvature id \+ --res 2048 --samples 64 --margin-px 16 --pack-orm --out //textures+```+Self-bake (procedural → textures, no `--high`): `--low SM_Crate --maps basecolor roughness metallic normal --pack-orm`.+The script picks the GPU (OptiX/CUDA/HIP/Metal/oneAPI) and falls back to CPU, creates the target images with correct color spaces, cleans up its temporary nodes, and saves `T_<name>_<N|AO|CURV|BC|R|M|ORM...>.png`.++## Preparation checklist (most bake bugs come from this list)+1. **Low poly**: UVs unwrapped, no overlaps (stacked/mirrored islands moved +1 U), padding ≥ 8 px at the bake resolution, scale applied.+2. **Hard edges = UV seams** on the low poly. Use either smooth shading with the bake handling gradients, or hard edges split at seams. Never put a hard edge inside a UV island.+3. **Triangulate the low poly the same way the engine will**, or export the triangulated mesh. Mismatched triangulation shows as shading seams.+4. **High poly** covers the low completely and pokes out of it only a little. Floaters (bolts, panel details) can hover just above the surface, but must stay within the extrusion distance.+5. **Names**: `X_low` / `X_high` pairs. Bake per part, or explode the parts apart (move each pair along an axis) so neighbouring parts don't project onto each other, then put them back.+6. Apply modifiers on the high poly as needed (multires and subd are evaluated automatically).++## Rays: extrusion vs cage+- `--extrusion` (meters) pushes the ray origin outward from the low surface. It must be **greater than the farthest distance the high poly sticks out** of the low. The default is 2% of the low's diagonal; `max_ray_distance` is 2 × extrusion.+- **Cage** (`--cage Crate_cage`): a copy of the low with the same topology, inflated (Displace/"Push"). Use it when uniform extrusion fails (sharp concave corners, thin parts). Edit the cage locally where rays miss.+- Too small: holes or missing details. Too large: other parts of the mesh project in (intersections, "ghosting").++## Map guide+| Map | Space | Notes |+|---|---|---|+| normal | Non-Color, tangent, OpenGL (`--directx` for Unreal) | 16-sample AA is plenty; 8-bit PNG is fine for games |+| ao | Non-Color | 64–256 samples; bake with the high only (no ground) unless contact AO is wanted |+| curvature | Non-Color, 0.5 = flat | derived from the baked normal (convex white / concave dark); drives edge wear |+| id | sRGB | one flat color per high-poly **material**; use materials as masks |+| thickness | Non-Color | AO with inside rays; dark = thin; for SSS/translucency masks |+| basecolor/metallic/opacity | via emission override | reads the Principled inputs of the source materials (also procedural chains) |+| roughness, emit, combined | native Cycles passes | combined = lit result (lightmaps, stylized) |+| position | float | gradient masks |+ORM = R:AO G:Roughness B:Metallic, the glTF/Unreal standard. Unity uses a different packing (`blender-pbr-materials`).++## Fixing common artifacts+| Symptom | Cause | Fix |+|---|---|---|+| Wavy lines on cylinders | low poly too low, smoothing gradients | add segments, use a cage, or more support on the low |+| Skewed details (bolts lean) | ray direction follows the averaged low normals | hard edges + seams, a cage, or bake the floater separately |+| Black/garbage areas | rays miss or hit the back faces | raise extrusion, fix flipped normals (`blender-asset-qa`), check high coverage |+| Seams visible in engine | margin too small, hard edge without a seam, different tangents | margin ≥ 16 px @2k, seams at hard edges, export tangents (MikkTSpace) |+| Details from a neighbouring part | parts too close | explode the bake, or bake per object pair |+| Inverted green look in engine | OpenGL/DirectX mismatch | `--directx` for Unreal, or flip G in the texture importer |+| Stepping/banding | 8-bit with large flat gradients | bake to 16-bit (`float_buffer`) and dither on export |++## Baking non-PBR data+- **Vertex colors**: `bake.target = "VERTEX_COLORS"` with an active color attribute (useful for mobile and Roblox-free shading).+- **Lightmaps**: bake `combined` onto UV2 (`--uv-layer UVMap_Lightmap`) with the scene lights.+- **Multires** (no separate high object): `bake.use_multires=True`, `bake.type="NORMALS"|"DISPLACEMENT"|"VECTOR_DISPLACEMENT"`, `bake.use_lores_mesh=True`, then `bpy.ops.object.bake_image()`. The viewport level is the low, the sculpt level is the high.++## Gotchas+- The target image must be the **active** Image Texture node in **every** material of the low object (the script handles this).+- Baking in Cycles uses the active UV map (`--uv-layer` to pick).+- Images aren't saved automatically: `img.save()` or `save_render`. Packed or internal images disappear on reload.+- 5.2: the Cycles texture cache (`.tx`) is for render memory and doesn't affect bake results.+- Run `blender-asset-qa` on low + high first, because flipped normals and floating chunks produce most bake garbage.diff --git a/skills/blender-texture-baking/scripts/_bpyx.py b/skills/blender-texture-baking/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-texture-baking/scripts/_bpyx.py@@ -0,0 +1,136 @@+"""_bpyx - tiny shared helpers for blender-agent-skills scripts (Blender 5.2+).++Source of truth: shared/_bpyx.py. Copies in skills/*/scripts/ are synced by+tools/sync_shared.py - never edit a copy.++Every skill script follows one contract:+ run(**kwargs) -> dict # call from MCP / Python (import the module)+ blender -b f.blend -P x.py -- --arg v # CLI: prints one line "@@JSON@@{...}"+"""+import argparse+import json+import sys++import bpy++MARK = "@@JSON@@"+++def argv():+ """Arguments after '--' (Blender ignores them)."""+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def _default(o):+ if hasattr(o, "__len__") and not isinstance(o, str):+ try:+ return [round(v, 5) if isinstance(v, float) else v for v in o]+ except TypeError:+ pass+ if isinstance(o, (set, frozenset)):+ return sorted(o)+ return str(o)+++def emit(data):+ """Print compact JSON on one marked line (parsed by run_in_blender.py)."""+ print(MARK + json.dumps(data, separators=(",", ":"), default=_default), flush=True)+ return data+++def parser(doc):+ """ArgumentParser whose help is the script docstring's first line."""+ return argparse.ArgumentParser(description=(doc or "").strip().splitlines()[0])+++def cli(run, p):+ """CLI entry: parse args after '--', run, emit JSON. Exit 1 on failure."""+ args = p.parse_args(argv())+ try:+ result = run(**vars(args))+ save = getattr(args, "save", None)+ if save:+ bpy.ops.wm.save_as_mainfile(filepath=bpy.path.abspath(save))+ result["saved"] = save+ emit(result)+ except Exception as e: # report, don't dump a traceback into agent context+ emit({"ok": False, "error": f"{type(e).__name__}: {e}"})+ if bpy.app.background:+ sys.exit(1)+++def add_common(p, save=True):+ """--objects / --save flags shared by most scripts."""+ p.add_argument("--objects", nargs="*", default=None,+ help="object names (default: selected, else all meshes)")+ if save:+ p.add_argument("--save", default=None, help="save .blend to this path after run")+ return p+++def objects(names=None, types=("MESH",)):+ """Resolve names -> objects. No names: selected of `types`, else all visible of `types`."""+ if names:+ missing = [n for n in names if n not in bpy.data.objects]+ if missing:+ raise KeyError(f"objects not found: {missing}")+ return [bpy.data.objects[n] for n in names]+ pool = [o for o in bpy.context.scene.objects if not types or o.type in types]+ sel = [o for o in pool if o.select_get()]+ return sel or [o for o in pool if o.visible_get()]+++def object_mode():+ """Leave edit/sculpt/pose modes; most data API work needs OBJECT mode."""+ ob = bpy.context.view_layer.objects.active+ if ob and ob.mode != "OBJECT":+ bpy.ops.object.mode_set(mode="OBJECT")+++def select_only(objs, active=None):+ """Select exactly `objs` and make `active` (default first) active."""+ for o in bpy.context.view_layer.objects:+ o.select_set(False)+ for o in objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = active or (objs[0] if objs else None)+++def node(tree, type_):+ """First node of `type_` (e.g. 'BSDF_PRINCIPLED'). Names are localized - never look up by name."""+ return next((n for n in tree.nodes if n.type == type_), None)+++def enum_ids(owner, prop):+ """Valid identifiers of an enum property (works on types or instances)."""+ return [i.identifier for i in owner.bl_rna.properties[prop].enum_items]+++def set_enum(owner, prop, value):+ """Assign an enum; on failure raise listing valid values (dynamic enums under-report)."""+ try:+ setattr(owner, prop, value)+ except TypeError as e:+ raise ValueError(f"{prop}={value!r} invalid: {e}") from None+++def mesh_tris(ob, evaluated=True):+ """Triangle count (evaluated = with modifiers)."""+ if evaluated:+ eo = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())+ me = eo.to_mesh()+ try:+ me.calc_loop_triangles()+ return len(me.loop_triangles)+ finally:+ eo.to_mesh_clear()+ me = ob.data+ me.calc_loop_triangles()+ return len(me.loop_triangles)+++def r(v, n=4):+ """Round a float or a vector for compact JSON."""+ if isinstance(v, float):+ return round(v, n)+ return [round(x, n) for x in v]diff --git a/skills/blender-texture-baking/scripts/bake_maps.py b/skills/blender-texture-baking/scripts/bake_maps.pynew file mode 100644index 0000000..b96d63d--- /dev/null+++ b/skills/blender-texture-baking/scripts/bake_maps.py@@ -0,0 +1,267 @@+"""Bake texture maps with Cycles: high->low (selected-to-active) or self-bake procedural materials.++Maps: normal, ao, roughness, basecolor, metallic, opacity, emit, id, thickness, curvature+(curvature is derived from the baked tangent normal map), combined.+--pack-orm writes T_<name>_ORM (R=AO, G=Roughness, B=Metallic) from the baked maps.+Usage:+ blender -b f.blend -P bake_maps.py -- --low SM_Crate --high Crate_high [Crate_bolts]+ [--maps normal ao curvature] [--res 2048] [--samples 64] [--margin-px 16]+ [--extrusion 0.02] [--cage Crate_cage] [--directx] [--out //textures] [--name Crate]+ [--pack-orm] [--device GPU|CPU] [--save out.blend]+ Self-bake (no --high): bakes the low object's own materials (procedurals -> textures).+ MCP: import bake_maps; print(bake_maps.run(low="SM_Crate", high=["Crate_high"], maps=["normal","ao"]))+"""+import hashlib+import os+import sys++import bpy+import numpy as np++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++NATIVE = {"normal": "NORMAL", "ao": "AO", "roughness": "ROUGHNESS", "emit": "EMIT",+ "combined": "COMBINED", "position": "POSITION"}+OVERRIDE = {"basecolor": "Base Color", "metallic": "Metallic", "opacity": "Alpha"}+SUFFIX = {"normal": "N", "ao": "AO", "roughness": "R", "basecolor": "BC", "metallic": "M",+ "opacity": "A", "emit": "E", "id": "ID", "thickness": "TH", "curvature": "CURV",+ "combined": "C", "position": "POS"}+++def _set_device(sc, device):+ sc.cycles.device = "CPU"+ if device == "CPU":+ return "CPU"+ try:+ prefs = bpy.context.preferences.addons["cycles"].preferences+ for backend in ("OPTIX", "CUDA", "HIP", "METAL", "ONEAPI"):+ try:+ prefs.compute_device_type = backend+ except TypeError:+ continue+ prefs.refresh_devices()+ gpus = [d for d in prefs.devices if d.type != "CPU"]+ if gpus:+ for d in prefs.devices:+ d.use = d.type != "CPU"+ sc.cycles.device = "GPU"+ return backend+ except Exception:+ pass+ return "CPU"+++def _signal_override(mats, key):+ """Route a per-material signal into an Emission shader. Returns an undo list."""+ undo = []+ for mat in mats:+ nt = mat.node_tree+ out = next((n for n in nt.nodes if n.type == "OUTPUT_MATERIAL" and n.is_active_output), None) \+ or bx.node(nt, "OUTPUT_MATERIAL")+ if out is None:+ continue+ prev = out.inputs["Surface"].links[0].from_socket if out.inputs["Surface"].is_linked else None+ em = nt.nodes.new("ShaderNodeEmission")+ em.inputs["Strength"].default_value = 1.0+ bsdf = bx.node(nt, "BSDF_PRINCIPLED")+ col = em.inputs["Color"]+ if key in OVERRIDE and bsdf:+ s = bsdf.inputs[OVERRIDE[key]]+ if s.is_linked:+ nt.links.new(s.links[0].from_socket, col)+ else:+ v = s.default_value+ col.default_value = tuple(v) if hasattr(v, "__len__") else (v, v, v, 1)+ elif key == "id":+ h = hashlib.md5(mat.name.encode()).digest()+ col.default_value = (h[0] / 255, h[1] / 255, h[2] / 255, 1)+ elif key == "thickness":+ ao = nt.nodes.new("ShaderNodeAmbientOcclusion")+ ao.inside, ao.samples = True, 16+ ao.inputs["Distance"].default_value = _thick_dist+ nt.links.new(ao.outputs["AO"], col)+ undo.append((nt, ao, None, None))+ nt.links.new(em.outputs["Emission"], out.inputs["Surface"])+ undo.append((nt, em, out, prev))+ return undo+++def _restore(undo):+ for nt, node, out, prev in reversed(undo):+ nt.nodes.remove(node)+ if out is not None and prev is not None:+ nt.links.new(prev, out.inputs["Surface"])+++def _target_node(low, img):+ """Ensure every low material has an active Image node pointing at img."""+ nodes = []+ if not low.data.materials:+ low.data.materials.append(bpy.data.materials.new(f"M_{low.name}"))+ for slot in low.material_slots:+ if slot.material is None:+ slot.material = bpy.data.materials.new(f"M_{low.name}")+ nt = slot.material.node_tree+ n = nt.nodes.new("ShaderNodeTexImage")+ n.image, n.label = img, "BAKE_TARGET"+ for o in nt.nodes:+ o.select = False+ n.select = True+ nt.nodes.active = n+ nodes.append((nt, n))+ return nodes+++def _blur(x, r):+ for axis in (0, 1):+ x = sum(np.roll(x, k, axis=axis) for k in range(-r, r + 1)) / (2 * r + 1)+ return x+++def _curvature_from_normal(img_n, res, strength=1.5):+ """Divergence of the tangent normal field: convex > 0.5 (white), concave < 0.5 (dark)."""+ a = np.empty(res * res * 4, dtype=np.float32)+ img_n.pixels.foreach_get(a)+ a = a.reshape(res, res, 4)+ r = max(1, res // 512) # smooth 8-bit stepping; scale with resolution+ nx, ny = _blur(a[..., 0] * 2 - 1, r), _blur(a[..., 1] * 2 - 1, r)+ dx = np.roll(nx, -1, axis=1) - np.roll(nx, 1, axis=1)+ dy = np.roll(ny, -1, axis=0) - np.roll(ny, 1, axis=0)+ c = np.clip(0.5 + _blur(dx + dy, r) * strength * res / 512, 0, 1)+ out = np.stack([c, c, c, np.ones_like(c)], -1)+ return out.ravel()+++_thick_dist = 0.1+++def run(low=None, high=None, maps=None, res=2048, samples=64, margin_px=16, extrusion=None,+ cage=None, directx=False, out="//textures", name=None, pack_orm=False, device="GPU",+ uv_layer=None, **_):+ global _thick_dist+ bx.object_mode()+ if not low:+ raise ValueError("--low is required")+ lo = bpy.data.objects[low]+ his = [bpy.data.objects[h] for h in (high or [])]+ if not lo.data.uv_layers:+ raise ValueError(f"{low} has no UVs (see blender-retopology-uv)")+ maps = maps or (["normal", "ao"] if his else ["basecolor", "roughness", "metallic", "normal"])+ if "curvature" in maps and "normal" not in maps:+ maps = ["normal"] + maps+ name = name or low.removeprefix("SM_")+ out_dir = bpy.path.abspath(out)+ os.makedirs(out_dir, exist_ok=True)+ sc = bpy.context.scene+ prev_engine = sc.render.engine+ sc.render.engine = "CYCLES"+ backend = _set_device(sc, device)+ sc.cycles.samples = samples+ sc.cycles.use_denoising = False+ bake = sc.render.bake+ bpy.context.view_layer.update()+ diag = max(lo.dimensions.length, 1e-3)+ _thick_dist = diag * 0.1+ ext = extrusion if extrusion is not None else diag * 0.02+ bake.margin, bake.margin_type = margin_px, "EXTEND"+ bake.use_selected_to_active = bool(his)+ bake.cage_extrusion = ext+ bake.max_ray_distance = ext * 2 if his else 0.0+ bake.use_cage = bool(cage)+ if cage:+ bake.cage_object = bpy.data.objects[cage]+ bake.normal_space = "TANGENT"+ bake.normal_r, bake.normal_g, bake.normal_b = "POS_X", ("NEG_Y" if directx else "POS_Y"), "POS_Z"+ bake.target = "IMAGE_TEXTURES"+ bake.use_clear = True+ if uv_layer:+ lo.data.uv_layers.active = lo.data.uv_layers[uv_layer]+ src_objs = his or [lo]+ src_mats = {s.material for o in src_objs for s in o.material_slots if s.material}+ bx.select_only(his + [lo], active=lo)+ results, images = {}, {}+ try:+ for key in maps:+ if key == "curvature":+ continue+ data = key not in ("basecolor", "emit", "combined", "id")+ img = bpy.data.images.new(f"T_{name}_{SUFFIX[key]}", res, res, alpha=False,+ float_buffer=key in ("position",), is_data=data)+ img.colorspace_settings.name = "Non-Color" if data else "sRGB"+ if key == "normal":+ img.generated_color = (0.5, 0.5, 1, 1)+ targets = _target_node(lo, img)+ undo = []+ try:+ if key in NATIVE:+ btype, pf = NATIVE[key], set()+ else:+ undo = _signal_override(src_mats, key)+ btype = "EMIT"+ pf = set()+ kw = {"type": btype}+ if pf:+ kw["pass_filter"] = pf+ r = bpy.ops.object.bake(**kw)+ if r != {"FINISHED"}:+ raise RuntimeError(f"bake {key} failed")+ finally:+ _restore(undo)+ for nt, n in targets:+ nt.nodes.remove(n)+ path = os.path.join(out_dir, f"{img.name}.png")+ img.filepath_raw, img.file_format = path, "PNG"+ img.save()+ images[key] = img+ results[key] = path+ if "curvature" in maps:+ img = bpy.data.images.new(f"T_{name}_CURV", res, res, alpha=False, is_data=True)+ img.colorspace_settings.name = "Non-Color"+ img.pixels.foreach_set(_curvature_from_normal(images["normal"], res))+ path = os.path.join(out_dir, f"{img.name}.png")+ img.filepath_raw, img.file_format = path, "PNG"+ img.save()+ results["curvature"] = path+ if pack_orm:+ chans = []+ for k, default in (("ao", 1.0), ("roughness", 0.5), ("metallic", 0.0)):+ if k in images:+ a = np.empty(res * res * 4, dtype=np.float32)+ images[k].pixels.foreach_get(a)+ chans.append(a.reshape(-1, 4)[:, 0])+ else:+ chans.append(np.full(res * res, default, dtype=np.float32))+ orm = np.stack(chans + [np.ones(res * res, dtype=np.float32)], -1).ravel()+ img = bpy.data.images.new(f"T_{name}_ORM", res, res, alpha=False, is_data=True)+ img.colorspace_settings.name = "Non-Color"+ img.pixels.foreach_set(orm)+ path = os.path.join(out_dir, f"{img.name}.png")+ img.filepath_raw, img.file_format = path, "PNG"+ img.save()+ results["orm"] = path+ finally:+ sc.render.engine = prev_engine+ return {"ok": True, "device": backend, "extrusion": round(ext, 5), "res": res,+ "maps": {k: bpy.path.relpath(v) if bpy.data.filepath else v for k, v in results.items()}}+++if __name__ == "__main__":+ p = bx.parser(__doc__)+ p.add_argument("--low", required=True)+ p.add_argument("--high", nargs="*", default=None)+ p.add_argument("--maps", nargs="*", default=None,+ choices=sorted(set(NATIVE) | set(OVERRIDE) | {"id", "thickness", "curvature"}))+ p.add_argument("--res", type=int, default=2048)+ p.add_argument("--samples", type=int, default=64)+ p.add_argument("--margin-px", type=int, default=16)+ p.add_argument("--extrusion", type=float, default=None)+ p.add_argument("--cage", default=None)+ p.add_argument("--directx", action="store_true")+ p.add_argument("--out", default="//textures")+ p.add_argument("--name", default=None)+ p.add_argument("--pack-orm", action="store_true")+ p.add_argument("--device", default="GPU", choices=["GPU", "CPU"])+ p.add_argument("--uv-layer", default=None)+ p.add_argument("--save", default=None)+ bx.cli(run, p)diff --git a/skills/blender-workflow-recipes/SKILL.md b/skills/blender-workflow-recipes/SKILL.mdnew file mode 100644index 0000000..4fc3e8b--- /dev/null+++ b/skills/blender-workflow-recipes/SKILL.md@@ -0,0 +1,68 @@+---+name: blender-workflow-recipes+description: End-to-end Blender 5.2 playbooks chaining the blender-* skills with QA gates - game props (mid-poly, high-to-low), game characters (sculpt/AI mesh to rigged, animated export), Roblox props/accessories/avatars, AI or downloaded asset cleanup, procedural environments, web/AR assets, product turntables. Use for complete multi-stage asset requests.+license: MIT+metadata:+ author: blender-agent-skills+ version: "0.1.0"+---++# Workflow Recipes++`S` = the skills folder. Every `.py` runs headless via `python S/blender-core/scripts/run_in_blender.py --blend F.blend S/<skill>/scripts/<x>.py -- ...`, or live via MCP import + `run()` (see `blender-core`). **Gate** = stop and fix before continuing. Save after every stage (`--save`).++## 1. Game prop, mid-poly (fast, no bake)+1. Blockout at real scale (`blender-hardsurface-modeling`). Gate: `ob.dimensions` vs reference.+2. UV the blockout **before** beveling (the Bevel/Boolean modifiers carry UVs): `uv_pack.py --objects SM_X --method seams --seams-from-sharp 60` → `texel_density.py --res 2048 --set 512`+3. `apply_stack.py --objects SM_X --preset midpoly [--cutters ...]` (keep it live; `--apply --triangulate` only on the export copy)+4. Materials: `build_pbr_material.py --preset ...` or tiling/trim textures.+5. Gate: `qa_check.py --objects SM_X --profile game` passes, plus `look` (angles, material + wireframe).+6. `mesh_stats.py --budget <platform>` → `make_lods.py --objects SM_X --rename`+7. `export_asset.py --preset <engine> --objects SM_X_LOD0 SM_X_LOD1 ...` Gate: re-import dims / GLB summary.++## 2. Game prop, high → low baked (hero quality)+1. High poly: hardsurface `--preset subd` or sculpt (`sculpt_ops.py`), named `X_high`.+2. Low: `auto_retopo.py --objects X_high --tris N --method planar|decimate|quadriflow`, or manual. Rename it `SM_X`.+3. `uv_pack.py --objects SM_X --method seams --seams-from-sharp 60 --margin-px 16`+4. Gate: `qa_check.py` on `SM_X` (game) **and** `X_high` (render profile, no inverted parts).+5. `bake_maps.py --low SM_X --high X_high --maps normal ao curvature id --pack-orm [--directx for Unreal]`+6. `build_pbr_material.py --name M_X --textures //textures --objects SM_X` (+ basecolor/roughness from texturing).+7. Gate: `look` in material shading (no seams/waviness), then steps 6–7 of recipe 1.++## 3. Game character (sculpt or AI mesh → animated export)+1. Source mesh (sculpt / `generate_3d` / scan) at real height, facing -Y, feet on Z=0. Run `qa_check.py --profile render`.+2. `auto_retopo.py --method quadriflow --tris 20000` (or manual retopo for heroes, keeping the edge flow rules). `uv_pack.py --method min_stretch`.+3. `bake_maps.py --low Body --high Body_src --maps normal ao basecolor` (basecolor via emission override if the source has colors/materials).+4. `rigify_build.py --add basic_human --fit Body` → place joints (look xray) → `--metarig META_Body --generate`+5. `bind_mesh.py --armature RIG_Body --meshes Body` → `stress_poses.py --armature RIG_Body` → `look(mode="frames")`. Gate: no collapse at the elbows/knees/shoulders. Fix weights.+6. `rigify_build.py --rig RIG_Body --game-skeleton` → `rig_check.py --armature GAME_RIG_Body --profile unity|unreal`+7. Animate on RIG_Body (`blender-animation`) → `bake_action.py --source RIG_Body --target GAME_RIG_Body [--root-motion xy --hips spine]`+8. `export_asset.py --preset unity_skeletal|unreal_skeletal --objects GAME_RIG_Body` (meshes are included as children). Gate: GLB/FBX summary shows skins + all clips. Engine scale check.++## 4. Roblox+- **MeshPart prop**: recipe 1 with `--profile roblox` in QA (≤20k tris, watertight, no n-gons, single UV 0–1), separate grayscale maps (no ORM), `export_asset.py --preset roblox` (FBX) or `roblox_gltf`. Textures 1024² (PBR).+- **Rigid accessory**: ≤4k tris, an attachment point empty matching an R15 `_Att` name, `--preset roblox`.+- **Layered clothing**: start from Roblox's official cage templates. Build `<Name>_InnerCage`/`_OuterCage` (never change cage vertex count/order/UVs), skin to R15 bones, ≤4 influences, no weights on Root. Validate in Studio's Accessory Fitting Tool.+- **Avatar body**: 15 `_Geo` parts, R15 skeleton, attachments, outer cages, 10,742 tri budget. Read `blender-export-pipelines/references/roblox.md` first.+- Upload: Studio `AssetService:CreateAssetAsync` for batches.++## 5. Cleaning AI-generated / downloaded assets+1. Import (`import_asset` / `generate_3d` / file). Scale to real size (`world_bounding_box`), origin to the bottom, ground at z=0, `transform_apply`.+2. `scene_audit.py --fix purge scale` → `qa_check.py --profile game`. Typical findings: non-manifold, duplicate verts, inverted islands, floating debris, z-fighting shells.+3. Fix: `make_lods.py --cleanup` (merge/degenerate/loose), recalc normals, delete floating debris (or `remesh` via `sculpt_ops.py` for garbage topology), then `auto_retopo.py --method decimate` to budget.+4. Re-UV if the UVs are fragmented (`uv_pack.py`) and re-bake from the original (`bake_maps.py --high original`).+5. Gate: QA passes + `look`. Never ship generated meshes unreviewed.++## 6. Procedural environment+1. Terrain/ground mesh, then a scatter tree with `gn_builder.py --spec scatter.json --apply Ground --set Density=... Seed=...` (recipes in `blender-geometry-nodes/references/recipes.md`).+2. Assets to scatter: optimized props with LODs (recipe 1). Keep instances (don't realize) for engines that support instancing (`export_gpu_instances`).+3. Gate: `mesh_stats.py` on the evaluated result, plus `look` from the gameplay camera height.++## 7. Web / AR asset+Recipe 1 or 2 with budgets `--budget web` (≤30k tris, 1–2 materials, 2k textures) → `export_asset.py --preset web` (meshopt + WebP) → optional `gltf-transform optimize --texture-compress ktx2`. USDZ for iOS AR: `--preset usd --out x.usdz`. Gate: GLB summary (size < 5 MB) and Khronos PBR Neutral look-dev match.++## 8. Product shot / turntable+1. Materials with measured values (`build_pbr_material.py --preset`), and QA for z-fighting/floating parts (very visible in close-ups).+2. Set the render resolution, then `turntable.py --objects Product --rig studio --backdrop --frames 120 --lens 85`+3. `render_batch.py --preset preview --frames 1` → review → `--preset product --frames 1-120 --format PNG` → encode, or `--format MP4`.+4. Gate: no fireflies or clipped highlights (AgX / Khronos PBR Neutral), and the product sits on the backdrop (contact shadow).diff --git a/tests/fixtures.py b/tests/fixtures.pynew file mode 100644index 0000000..8256308--- /dev/null+++ b/tests/fixtures.py@@ -0,0 +1,100 @@+"""Procedural test fixtures (no binary .blend files in the repo)."""+import bmesh+import bpy+from mathutils import Matrix+++def mesh_object(name, build, location=(0, 0, 0)):+ me = bpy.data.meshes.new(name)+ bm = bmesh.new()+ build(bm)+ bm.to_mesh(me)+ bm.free()+ ob = bpy.data.objects.new(name, me)+ ob.location = location+ bpy.context.scene.collection.objects.link(ob)+ return ob+++def cube(name="Cube", size=2.0, location=(0, 0, 0)):+ return mesh_object(name, lambda bm: bmesh.ops.create_cube(bm, size=size), location)+++def uv_sphere(name="Sphere", radius=1.0, segs=32, rings=16, location=(0, 0, 0)):+ return mesh_object(name, lambda bm: bmesh.ops.create_uvsphere(+ bm, u_segments=segs, v_segments=rings, radius=radius), location)+++def plane(name="Plane", size=2.0, location=(0, 0, 0)):+ return mesh_object(name, lambda bm: bmesh.ops.create_grid(+ bm, x_segments=1, y_segments=1, size=size / 2), location)+++def zfight_pair():+ """Two coplanar overlapping planes in different objects + one inside a single mesh."""+ a = plane("ZF_A")+ b = plane("ZF_B", location=(0.5, 0, 0))++ def two_layers(bm):+ bmesh.ops.create_grid(bm, x_segments=1, y_segments=1, size=1)+ bmesh.ops.create_grid(bm, x_segments=1, y_segments=1, size=0.5,+ matrix=Matrix.Translation((0.2, 0, 0)))+ c = mesh_object("ZF_Self", two_layers, location=(5, 0, 0))+ return a, b, c+++def detached_part():+ """A body with a floating island and a separate floating object."""+ def build(bm):+ bmesh.ops.create_cube(bm, size=2)+ bmesh.ops.create_cube(bm, size=0.3, matrix=Matrix.Translation((0, 0, 1.6)))+ body = mesh_object("Body", build)+ floater = cube("Floater", size=0.3, location=(3, 0, 3))+ return body, floater+++def unwrap(ob):+ """Smart-project UVs so bake/texel tests have a UV map."""+ from _bpyx import select_only+ select_only([ob])+ bpy.ops.object.mode_set(mode="EDIT")+ bpy.ops.mesh.select_all(action="SELECT")+ bpy.ops.uv.smart_project(island_margin=0.02)+ bpy.ops.object.mode_set(mode="OBJECT")+ return ob+++def simple_character():+ """Capsule-ish mesh + 3-bone chain armature, auto-weighted. Returns (mesh, armature)."""+ def build(bm):+ bmesh.ops.create_cone(bm, cap_ends=True, segments=12, radius1=0.3, radius2=0.3,+ depth=2.0, matrix=Matrix.Translation((0, 0, 1)))+ body = mesh_object("Char", build)+ me = body.data+ bpy.context.view_layer.objects.active = body+ body.select_set(True)+ bpy.ops.object.mode_set(mode="EDIT")+ bpy.ops.mesh.select_all(action="SELECT")+ bpy.ops.mesh.subdivide(number_cuts=8)+ bpy.ops.object.mode_set(mode="OBJECT")+ arm_data = bpy.data.armatures.new("CharRig")+ arm = bpy.data.objects.new("CharRig", arm_data)+ bpy.context.scene.collection.objects.link(arm)+ bpy.context.view_layer.objects.active = arm+ bpy.ops.object.mode_set(mode="EDIT")+ prev = None+ for i, nm in enumerate(("root", "spine", "chest")):+ b = arm_data.edit_bones.new(nm)+ b.head, b.tail = (0, 0, i * 0.66), (0, 0, (i + 1) * 0.66)+ if prev: # spine (hips) unconnected from root so it can translate; chest connected+ b.parent, b.use_connect = prev, nm == "chest"+ prev = b+ bpy.ops.object.mode_set(mode="OBJECT")+ for o in bpy.context.view_layer.objects:+ o.select_set(False)+ body.select_set(True)+ arm.select_set(True)+ bpy.context.view_layer.objects.active = arm+ bpy.ops.object.parent_set(type="ARMATURE_AUTO")+ assert me.vertices+ return body, armdiff --git a/tests/run_all.py b/tests/run_all.pynew file mode 100644index 0000000..b4cc19c--- /dev/null+++ b/tests/run_all.py@@ -0,0 +1,79 @@+"""In-Blender test runner. Discovers tests/test_*.py, runs each test_* on a fresh empty scene.++Usage: blender -b --factory-startup --python-exit-code 1 -P tests/run_all.py -- [name-filter]+ (or: python tools/run_tests.py [name-filter])+"""+import importlib.util+import os+import pathlib+import sys+import tempfile+import time+import traceback++import bpy++HERE = pathlib.Path(__file__).resolve().parent+ROOT = HERE.parent+sys.path.insert(0, str(HERE))+sys.path.insert(0, str(ROOT / "shared"))+++def skill_module(skill, script):+ """Import skills/<skill>/scripts/<script>.py fresh (tests call run() directly)."""+ path = ROOT / "skills" / skill / "scripts" / f"{script}.py"+ sys.path.insert(0, str(path.parent))+ spec = importlib.util.spec_from_file_location(f"{skill}.{script}", path)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++def fresh():+ bpy.ops.wm.read_factory_settings(use_empty=True)+++TMP = pathlib.Path(tempfile.mkdtemp(prefix="bas_tests_"))+++class Skip(Exception):+ pass+++def requires_gpu():+ """Skip when BAS_SKIP_GPU=1 (CI runners without GPU/EGL: EEVEE, Workbench renders)."""+ if os.environ.get("BAS_SKIP_GPU") == "1":+ raise Skip("needs GPU context")+++def main():+ flt = sys.argv[sys.argv.index("--") + 1] if "--" in sys.argv and sys.argv[-1] != "--" else ""+ passed, failed, skipped = 0, [], 0+ for f in sorted(HERE.glob("test_*.py")):+ spec = importlib.util.spec_from_file_location(f.stem, f)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ for name in sorted(n for n in dir(mod) if n.startswith("test_")):+ full = f"{f.stem}::{name}"+ if flt and flt not in full:+ continue+ fresh()+ t = time.time()+ try:+ getattr(mod, name)()+ passed += 1+ print(f"PASS {full} ({time.time() - t:.1f}s)")+ except Exception as e:+ if type(e).__name__ == "Skip": # tests import run_all as a 2nd module: match by name+ skipped += 1+ print(f"SKIP {full} ({e})")+ continue+ failed.append(full)+ print(f"FAIL {full}\n{traceback.format_exc(limit=4)}")+ print(f"\n{passed} passed, {len(failed)} failed, {skipped} skipped")+ if failed:+ sys.exit(1)+++if __name__ == "__main__":+ main()diff --git a/tests/test_addon.py b/tests/test_addon.pynew file mode 100644index 0000000..039dd67--- /dev/null+++ b/tests/test_addon.py@@ -0,0 +1,39 @@+import os+import shutil+import subprocess+import sys++import bpy+import fixtures as fx+from run_all import ROOT, TMP+++def test_template_validates_builds_and_registers():+ src = ROOT / "skills/blender-addon-development/assets/addon_template"+ exe = bpy.app.binary_path+ r = subprocess.run([exe, "--factory-startup", "--command", "extension", "validate", str(src)],+ capture_output=True, text=True)+ assert r.returncode == 0, r.stdout + r.stderr+ out = TMP / "ext_build"+ out.mkdir(exist_ok=True)+ r = subprocess.run([exe, "--factory-startup", "--command", "extension", "build", "--source-dir", str(src),+ "--output-dir", str(out)], capture_output=True, text=True)+ assert r.returncode == 0 and any(p.suffix == ".zip" for p in out.iterdir()), r.stdout + r.stderr+ # register as a package in-process (what Blender does for an installed extension)+ pkg = TMP / "pkgs" / "my_tool"+ shutil.rmtree(pkg, ignore_errors=True)+ shutil.copytree(src, pkg)+ sys.path.insert(0, str(pkg.parent))+ import my_tool+ my_tool.register()+ try:+ ob = fx.cube("C")+ ob.select_set(True)+ bpy.context.view_layer.objects.active = ob+ with bpy.context.temp_override(selected_objects=[ob], object=ob, active_object=ob):+ assert bpy.ops.my_tool.offset_selected(distance=2.0, axis="X") == {"FINISHED"}+ assert ob.location.x == 2.0+ assert abs(bpy.context.scene.my_tool.distance - 0.1) < 1e-6+ finally:+ my_tool.unregister()+ assert os.path.isdir(pkg)diff --git a/tests/test_animation.py b/tests/test_animation.pynew file mode 100644index 0000000..7f6ac45--- /dev/null+++ b/tests/test_animation.py@@ -0,0 +1,57 @@+import bpy+import fixtures as fx+from run_all import TMP, skill_module+++def _walk(rig, name, dist):+ """Keyframe the hips ('spine', child of root) moving dist metres toward -Y over 24 frames."""+ from mathutils import Matrix+ act = bpy.data.actions.new(name)+ act.use_fake_user = True+ rig.animation_data_create()+ rig.animation_data.action = act+ pb = rig.pose.bones["spine"]+ rest = rig.data.bones["spine"].matrix_local.copy()+ for f, d in ((1, 0.0), (24, dist)):+ bpy.context.scene.frame_set(f)+ pb.matrix = Matrix.Translation((0, -d, 0)) @ rest+ bpy.context.view_layer.update()+ pb.keyframe_insert("location", frame=f)+ return act+++def test_bake_to_copy_with_root_motion_and_export():+ body, rig = fx.simple_character() # CharRig: root > spine > chest+ tgt_data = rig.data.copy()+ tgt = bpy.data.objects.new("GAME_CharRig", tgt_data)+ bpy.context.scene.collection.objects.link(tgt)+ bpy.context.view_layer.update()+ for b in tgt.pose.bones:+ c = b.constraints.new("COPY_TRANSFORMS")+ c.target, c.subtarget = rig, b.name+ _walk(rig, "Walk", 1.0)+ _walk(rig, "Run", 2.0)+ ba = skill_module("blender-animation", "bake_action")+ lst = ba.run(list=True)["actions"]+ assert {"Walk", "Run"} <= {a["name"] for a in lst}+ r = ba.run(source="CharRig", target="GAME_CharRig", actions=["Walk", "Run"], root_motion="xy", hips="spine")+ assert [b["action"] for b in r["baked"]] == ["GAME_CharRig|Walk", "GAME_CharRig|Run"], r+ assert all("carries" in b["root_motion"] for b in r["baked"]), r+ tracks = [t.name for t in tgt.animation_data.nla_tracks]+ assert tracks == ["CLIP_Walk", "CLIP_Run"]+ # constraints muted -> target plays its own baked action; root moved, spine world pos preserved+ tgt.animation_data.action = bpy.data.actions["GAME_CharRig|Run"]+ sc = bpy.context.scene+ sc.frame_set(24)+ bpy.context.view_layer.update()+ root_moved = tgt.pose.bones["root"].matrix.translation.length+ rig.animation_data.action = bpy.data.actions["Run"]+ sc.frame_set(24)+ bpy.context.view_layer.update()+ src_spine = rig.pose.bones["spine"].matrix.translation+ assert root_moved > 1.5, root_moved+ assert (tgt.pose.bones["spine"].matrix.translation - src_spine).length < 1e-3+ ex = skill_module("blender-export-pipelines", "export_asset")+ e = ex.run(preset="gltf", objects=["GAME_CharRig"], out=str(TMP / "anim.glb"))+ names = e["files"][0]["summary"]["animation_names"]+ assert len(names) >= 2, ediff --git a/tests/test_baking.py b/tests/test_baking.pynew file mode 100644index 0000000..0a8588f--- /dev/null+++ b/tests/test_baking.py@@ -0,0 +1,50 @@+import os++import bpy+import fixtures as fx+import numpy as np+from run_all import TMP, skill_module+++def _pixels(path):+ im = bpy.data.images.load(path)+ a = np.empty(len(im.pixels), dtype=np.float32)+ im.pixels.foreach_get(a)+ return a.reshape(-1, 4)+++def test_high_to_low_bake_normal_ao_curv_orm_basecolor():+ hi = fx.uv_sphere("Ball_high", radius=1, segs=64, rings=32)+ hi.modifiers.new("D", "DISPLACE").strength = 0.05+ tex = bpy.data.textures.new("N", "CLOUDS")+ tex.noise_scale = 0.2+ hi.modifiers["D"].texture = tex+ mat = bpy.data.materials.new("M_Red")+ next(n for n in mat.node_tree.nodes if n.type == "BSDF_PRINCIPLED").inputs["Base Color"].default_value = (1, 0, 0, 1)+ hi.data.materials.append(mat)+ lo = fx.uv_sphere("SM_Ball", radius=1, segs=16, rings=8)+ fx.unwrap(lo)+ bake = skill_module("blender-texture-baking", "bake_maps")+ r = bake.run(low="SM_Ball", high=["Ball_high"], maps=["normal", "ao", "basecolor", "curvature"],+ res=128, samples=4, device="CPU", out=str(TMP / "bake"), pack_orm=True)+ for k in ("normal", "ao", "basecolor", "curvature", "orm"):+ assert os.path.getsize(r["maps"][k]) > 0, k+ n = _pixels(r["maps"]["normal"])+ assert n[:, 2].mean() > 0.6 and n[:, 0].std() > 0.01 # tangent normal, with detail+ bc = _pixels(r["maps"]["basecolor"])+ assert bc[:, 0].max() > 0.9 and bc[:, 1].max() < 0.1 # red came through+ assert not any(n.label == "BAKE_TARGET" for m in bpy.data.materials if m.node_tree for n in m.node_tree.nodes)+ out = next(n for n in mat.node_tree.nodes if n.type == "OUTPUT_MATERIAL")+ assert out.inputs["Surface"].links[0].from_node.type == "BSDF_PRINCIPLED" # restored+++def test_self_bake_procedural_roughness():+ lo = fx.cube("SM_Box")+ fx.unwrap(lo)+ mat = bpy.data.materials.new("M_Box")+ next(n for n in mat.node_tree.nodes if n.type == "BSDF_PRINCIPLED").inputs["Roughness"].default_value = 0.25+ lo.data.materials.append(mat)+ r = skill_module("blender-texture-baking", "bake_maps").run(+ low="SM_Box", maps=["roughness", "metallic"], res=64, samples=1, device="CPU", out=str(TMP / "bake2"))+ px = _pixels(r["maps"]["roughness"])+ assert abs(np.median(px[:, 0]) - 0.25) < 0.02diff --git a/tests/test_core.py b/tests/test_core.pynew file mode 100644index 0000000..44b0565--- /dev/null+++ b/tests/test_core.py@@ -0,0 +1,44 @@+import os+import pathlib+import re++import bpy+from run_all import ROOT, fresh, skill_module++FENCE = re.compile(r"```python\n(.*?)```", re.S)+++def _run_md_blocks(md):+ """Execute every ```python block of a reference doc on a fresh scene."""+ blocks = FENCE.findall(pathlib.Path(md).read_text("utf-8"))+ assert blocks, f"no python blocks in {md}"+ for i, code in enumerate(blocks):+ if "render.render(" in code and os.environ.get("BAS_SKIP_GPU") == "1":+ continue # needs a GPU context (CI without GPU)+ fresh()+ try:+ exec(compile(code, f"{pathlib.Path(md).name}[{i}]", "exec"), {"__name__": "__snippet__"})+ except Exception as e:+ raise AssertionError(f"{md} block {i} failed: {e}\n{code}") from e+++def test_bpy_patterns_snippets_run():+ _run_md_blocks(ROOT / "skills/blender-core/references/bpy-patterns.md")+++def test_env_report():+ r = skill_module("blender-core", "env_report").run()+ assert r["ok"] and r["blender"].startswith(("5.", "6."))+ assert "CYCLES" in r["engines"] and "BLENDER_EEVEE" in r["engines"]+++def test_snippet_docs_across_skills():+ """Any reference doc tagged '(runs standalone)' must execute cleanly."""+ for md in sorted((ROOT / "skills").glob("*/references/*.md")):+ if "bpy-patterns" in md.name:+ continue+ head = md.read_text("utf-8").splitlines()[0]+ if "runs standalone" in head:+ _run_md_blocks(md)+ fresh()+ assert bpy.data.filepath == ""diff --git a/tests/test_export.py b/tests/test_export.pynew file mode 100644index 0000000..90348b6--- /dev/null+++ b/tests/test_export.py@@ -0,0 +1,48 @@+import os++import bpy+import fixtures as fx+from run_all import TMP, fresh, skill_module+++def _reimport_dims(path):+ fresh()+ if path.endswith(".fbx"):+ bpy.ops.import_scene.fbx(filepath=path)+ elif path.endswith(".glb"):+ bpy.ops.import_scene.gltf(filepath=path)+ else:+ bpy.ops.wm.usd_import(filepath=path)+ bpy.context.view_layer.update()+ meshes = [o for o in bpy.data.objects if o.type == "MESH"]+ return {o.name: tuple(round(d, 3) for d in o.dimensions) for o in meshes}, \+ {o.name: tuple(round(s, 3) for s in o.scale) for o in bpy.data.objects if o.type == "ARMATURE"}+++def test_all_presets_roundtrip_scale():+ ex = skill_module("blender-export-pipelines", "export_asset")+ for preset in ex.PRESETS:+ fresh()+ fx.cube("SM_Box", size=2, location=(0, 0, 1))+ body, arm = fx.simple_character()+ r = ex.run(preset=preset, objects=["SM_Box", "Char"], out=str(TMP / "exp" / f"{preset}{ex.EXT[ex.PRESETS[preset][0]]}"))+ assert r["ok"], (preset, r)+ f = r["files"][0]+ assert f["kb"] > 0+ if "summary" in f:+ assert f["summary"]["meshes"] == 2 and f["summary"]["skins"] == 1, (preset, f["summary"])+ dims, arm_scales = _reimport_dims(f["file"])+ box = next(v for k, v in dims.items() if k.startswith("SM_Box"))+ assert all(abs(d - 2) < 0.01 for d in box), (preset, dims)+ for s in arm_scales.values(): # no 100x armature scale (Unreal/Roblox symptom)+ assert all(abs(x - 1) < 0.01 or abs(x - 0.01) < 1e-4 for x in s), (preset, s)+++def test_batch_export_at_origin():+ ex = skill_module("blender-export-pipelines", "export_asset")+ fx.cube("SM_A", location=(5, 0, 0))+ fx.cube("SM_B", location=(-5, 0, 0))+ r = ex.run(preset="gltf", objects=["SM_A", "SM_B"], out=str(TMP / "batch" / "x.glb"), batch=True)+ names = sorted(os.path.basename(f["file"]) for f in r["files"])+ assert names == ["SM_A.glb", "SM_B.glb"]+ assert tuple(bpy.data.objects["SM_A"].location) == (5, 0, 0) # restoreddiff --git a/tests/test_facial.py b/tests/test_facial.pynew file mode 100644index 0000000..6a69cb9--- /dev/null+++ b/tests/test_facial.py@@ -0,0 +1,33 @@+import bpy+import fixtures as fx+from run_all import skill_module+++def test_arkit_split_mirror_drivers_report():+ sk = skill_module("blender-facial-shapekeys", "shapekeys")+ head = fx.uv_sphere("Head", segs=32, rings=16)+ r = sk.run(mesh="Head", create="arkit")+ assert r["created"] == 52 and len(sk.ARKIT) == 52 == len(set(sk.ARKIT))+ # sculpt a symmetric "eyeBlink" (move all verts up) and split it+ kb = head.shape_key_add(name="eyeBlink", from_mix=False)+ for d in kb.data:+ d.co.z += 0.1+ r = sk.run(mesh="Head", split="eyeBlink")+ kbs = head.data.shape_keys.key_blocks+ left, basis = kbs["eyeBlinkLeft"], kbs["Basis"]+ i_pos = max(range(len(basis.data)), key=lambda i: basis.data[i].co.x)+ i_neg = min(range(len(basis.data)), key=lambda i: basis.data[i].co.x)+ assert abs(left.data[i_pos].co.z - basis.data[i_pos].co.z - 0.1) < 1e-5+ assert abs(left.data[i_neg].co.z - basis.data[i_neg].co.z) < 1e-5+ r = sk.run(mesh="Head", mirror="eyeBlinkLeft")+ assert r["mirrored"]["to"] == "eyeBlinkRight" and "FINISHED" in r["mirrored"]["op"]+ right = kbs["eyeBlinkRight"]+ assert abs(right.data[i_neg].co.z - basis.data[i_neg].co.z - 0.1) < 1e-3+ r = sk.run(mesh="Head", drivers="FaceCtrl")+ assert r["drivers"]["count"] == 53 # 52 ARKit + the symmetric source key+ ctrl = bpy.data.objects["FaceCtrl"]+ ctrl["jawOpen"] = 0.7+ bpy.context.view_layer.update()+ bpy.context.evaluated_depsgraph_get().update()+ r = sk.run(mesh="Head", report=True)+ assert "jawOpen" in r["unsculpted"] and "eyeBlinkLeft" in r["max_offset"] and r["arkit_missing"] == []diff --git a/tests/test_geonodes.py b/tests/test_geonodes.pynew file mode 100644index 0000000..f585b09--- /dev/null+++ b/tests/test_geonodes.py@@ -0,0 +1,89 @@+import bpy+import fixtures as fx+from run_all import skill_module++SCATTER = {+ "name": "GN_Scatter",+ "inputs": [["Geometry", "GEOMETRY"], ["Density", "FLOAT", 10.0, {"min": 0}], ["Scale", "FLOAT", 0.1]],+ "outputs": [["Geometry", "GEOMETRY"]],+ "nodes": {+ "dist": ["GeometryNodeDistributePointsOnFaces", {"distribute_method": "RANDOM"}],+ "cube": ["GeometryNodeMeshCube"],+ "inst": ["GeometryNodeInstanceOnPoints"],+ "real": ["GeometryNodeRealizeInstances"],+ "join": ["GeometryNodeJoinGeometry"],+ },+ "links": [["in.Geometry", "dist.Mesh"], ["in.Density", "dist.Density"], ["dist.Points", "inst.Points"],+ ["cube.Mesh", "inst.Instance"], ["in.Scale", "inst.Scale"], ["inst.Instances", "real.Geometry"],+ ["real.Geometry", "join.Geometry"], ["in.Geometry", "join.Geometry"], ["join.Geometry", "out.Geometry"]],+}++REPEAT = {+ "name": "GN_Repeat",+ "inputs": [["Geometry", "GEOMETRY"], ["Count", "INT", 3]],+ "outputs": [["Geometry", "GEOMETRY"]],+ "nodes": {+ "rin": ["GeometryNodeRepeatInput"],+ "rout": ["GeometryNodeRepeatOutput"],+ "sub": ["GeometryNodeSubdivideMesh", {}, {"Level": 1}],+ },+ "pairs": [["rin", "rout"]],+ "links": [["in.Count", "rin.Iterations"], ["in.Geometry", "rin.Geometry"], ["rin.Geometry", "sub.Mesh"],+ ["sub.Mesh", "rout.Geometry"], ["rout.Geometry", "out.Geometry"]],+}+++def test_build_apply_set_inputs():+ g = skill_module("blender-geometry-nodes", "gn_builder")+ fx.plane("Ground", size=4)+ r = g.run(spec=SCATTER, apply_to="Ground", set=["Density=5"])+ assert r["evaluated"]["verts"] > 4 * 8, r+ r2 = g.run(spec=SCATTER, apply_to="Ground", set=["Density=50"])+ assert r2["evaluated"]["verts"] > r["evaluated"]["verts"]+ mod = bpy.data.objects["Ground"].modifiers["GN_Scatter"]+ ident = next(i.identifier for i in mod.node_group.interface.items_tree if getattr(i, "name", "") == "Density")+ assert getattr(mod.properties.inputs, ident).value == 50+++def test_repeat_zone():+ g = skill_module("blender-geometry-nodes", "gn_builder")+ fx.plane("P", size=1)+ r = g.run(spec=REPEAT, apply_to="P", set=["Count=2"])+ assert r["evaluated"]["faces"] == 16, r+++def test_describe():+ g = skill_module("blender-geometry-nodes", "gn_builder")+ d = g.run(describe_types=["GeometryNodeDistributePointsOnFaces", "ShaderNodeMath", "GeometryNodeMeshBevel"])+ dist = d["nodes"]["GeometryNodeDistributePointsOnFaces"]+ assert any(s[0] == "Density" for s in dist["inputs"]) and "distribute_method" in dist["props"]+ assert "operation" in d["nodes"]["ShaderNodeMath"]["props"]+++def test_reference_recipes_build_and_evaluate():+ import json+ import re+ from run_all import ROOT+ g = skill_module("blender-geometry-nodes", "gn_builder")+ text = (ROOT / "skills/blender-geometry-nodes/references/recipes.md").read_text("utf-8")+ specs = [json.loads(b) for b in re.findall(r"```json\n(.*?)```", text, re.S)]+ assert len(specs) == 5+ fx.plane("Ground", size=4)+ fx.cube("Rock", size=0.2, location=(10, 0, 0))+ cu = bpy.data.curves.new("Path", "CURVE")+ sp = cu.splines.new("POLY")+ sp.points.add(2)+ for i, p in enumerate(sp.points):+ p.co = (i, 0, 0, 1)+ bpy.context.scene.collection.objects.link(bpy.data.objects.new("Path", cu))+ targets = {"GN_Scatter": ("Ground", ["Instance=Rock", "Density=3"]), "GN_Pipe": ("Path", []),+ "GN_Repeat": ("Ground", ["Count=1"]), "GN_HeightMask": ("Ground", [])}+ for spec in specs:+ if spec.get("tree") == "shader":+ r = g.run(spec=spec)+ assert r["links"] == 3+ continue+ obj, sets = targets[spec["name"]]+ r = g.run(spec=spec, apply_to=obj, set=sets)+ assert r["evaluated"] and r["evaluated"]["verts"] > 0 and not r.get("node_warnings"), (spec["name"], r)+ bpy.data.objects[obj].modifiers.clear()diff --git a/tests/test_materials.py b/tests/test_materials.pynew file mode 100644index 0000000..0ccce7a--- /dev/null+++ b/tests/test_materials.py@@ -0,0 +1,41 @@+import bpy+import fixtures as fx+from run_all import TMP, skill_module+++def _img(name, color, colorspace="sRGB"):+ im = bpy.data.images.new(name, 8, 8)+ im.pixels.foreach_set(list(color) * 64)+ im.filepath_raw = str(TMP / "tex" / f"{name}.png")+ im.file_format = "PNG"+ (TMP / "tex").mkdir(exist_ok=True)+ im.save()+ bpy.data.images.remove(im)+++def test_texture_set_autowire_orm_dx_normal():+ _img("T_Crate_BC", (0.5, 0.3, 0.2, 1))+ _img("T_Crate_ORM", (1, 0.6, 0, 1))+ _img("T_Crate_nor_dx", (0.5, 0.5, 1, 1))+ _img("T_Crate_Height", (0.5, 0.5, 0.5, 1))+ fx.cube("SM_Crate")+ m = skill_module("blender-pbr-materials", "build_pbr_material")+ r = m.run(name="M_Crate", textures=str(TMP / "tex"), objects=["SM_Crate"])+ assert set(r["maps"]) >= {"basecolor", "orm", "normal", "height", "normal_flipped_from_dx"}, r+ mat = bpy.data.materials["M_Crate"]+ imgs = {n.label: n.image for n in mat.node_tree.nodes if n.type == "TEX_IMAGE"}+ assert imgs["basecolor"].colorspace_settings.name == "sRGB"+ assert imgs["orm"].colorspace_settings.name == "Non-Color"+ assert any(n.type == "GROUP" and n.node_tree.name == "glTF Material Output" for n in mat.node_tree.nodes)+ assert bpy.data.objects["SM_Crate"].active_material == mat+++def test_presets_and_srgb_color_override():+ m = skill_module("blender-pbr-materials", "build_pbr_material")+ fx.cube("Ring")+ r = m.run(name="M_Gold", preset="gold", objects=["Ring"])+ bsdf = next(n for n in bpy.data.materials["M_Gold"].node_tree.nodes if n.type == "BSDF_PRINCIPLED")+ assert bsdf.inputs["Metallic"].default_value == 1 and r["assigned"] == ["Ring"]+ r = m.run(name="M_Red", preset="plastic", color=(1, 0, 0))+ bsdf = next(n for n in bpy.data.materials["M_Red"].node_tree.nodes if n.type == "BSDF_PRINCIPLED")+ assert abs(bsdf.inputs["Base Color"].default_value[0] - 1) < 1e-6diff --git a/tests/test_modeling.py b/tests/test_modeling.pynew file mode 100644index 0000000..e85c8c1--- /dev/null+++ b/tests/test_modeling.py@@ -0,0 +1,35 @@+import bpy+import fixtures as fx+from run_all import skill_module+++def test_midpoly_stack_with_boolean_and_apply():+ m = skill_module("blender-hardsurface-modeling", "apply_stack")+ fx.cube("Body", size=2, location=(0, 0, 1))+ fx.cube("Cut", size=0.6, location=(0, -1, 1.2))+ r = m.run(objects=["Body"], cutters=["Cut"], preset="midpoly")+ o = r["objects"]["Body"]+ assert o["tris_final"] > o["tris_base"] and o["stack"][:3] == ["HS_Bool_Cut", "HS_Bevel", "HS_WeightedNormal"]+ assert bpy.data.objects["Cut"].hide_render+ r = m.run(objects=["Body"], cutters=["Cut"], preset="midpoly", triangulate=True, apply=True)+ assert not bpy.data.objects["Body"].modifiers and all("FAILED" not in a for a in r["objects"]["Body"]["applied"])+ assert bpy.data.objects["Body"].data.has_custom_normals+++def test_subd_preset_adds_smooth_by_angle():+ m = skill_module("blender-hardsurface-modeling", "apply_stack")+ fx.cube("Box")+ r = m.run(objects=["Box"], preset="subd", solver="MANIFOLD")+ assert "HS_SmoothByAngle" in r["objects"]["Box"]["stack"]+++def test_hardsurface_snippet_attributes():+ ob = fx.cube("Attr")+ me = ob.data+ bw = me.attributes.get("bevel_weight_edge") or me.attributes.new("bevel_weight_edge", "FLOAT", "EDGE")+ sh = me.attributes.get("sharp_edge") or me.attributes.new("sharp_edge", "BOOLEAN", "EDGE")+ bw.data[0].value = 1.0+ sh.data[0].value = True+ mod = ob.modifiers.new("B", "BEVEL")+ mod.limit_method = "WEIGHT"+ assert bpy.context.evaluated_depsgraph_get() and len(me.edges) == 12diff --git a/tests/test_optimization.py b/tests/test_optimization.pynew file mode 100644index 0000000..7af9d8e--- /dev/null+++ b/tests/test_optimization.py@@ -0,0 +1,20 @@+import bpy+import fixtures as fx+from run_all import skill_module+++def test_lods_halve_and_cleanup():+ fx.uv_sphere("SM_Rock", segs=64, rings=32)+ r = skill_module("blender-game-optimization", "make_lods").run(objects=["SM_Rock"], do_cleanup=True, rename=True)+ lods = r["lods"]["SM_Rock_LOD0"]+ assert lods["LOD1"] < lods["LOD0"] * 0.6 and lods["LOD3"] < lods["LOD0"] * 0.2, lods+ assert {"SM_Rock_LOD1", "SM_Rock_LOD2", "SM_Rock_LOD3"} <= set(bpy.data.objects.keys())+++def test_mesh_stats_budget():+ ob = fx.uv_sphere("SM_Ball", segs=128, rings=64)+ for i in range(3):+ ob.data.materials.append(bpy.data.materials.new(f"M{i}"))+ r = skill_module("blender-game-optimization", "mesh_stats").run(objects=["SM_Ball"], budget="mobile")+ assert not r["budget"]["pass"] and any("tris" in o for o in r["budget"]["over"])+ assert any("materials" in o for o in r["budget"]["over"])diff --git a/tests/test_pipeline.py b/tests/test_pipeline.pynew file mode 100644index 0000000..3d37a64--- /dev/null+++ b/tests/test_pipeline.py@@ -0,0 +1,30 @@+import os++import bpy+import fixtures as fx+from run_all import ROOT, TMP, fresh, skill_module+++def test_batch_convert_report_script_shard():+ src = TMP / "batch_src"+ src.mkdir(exist_ok=True)+ for i, ext in enumerate(("fbx", "glb", "blend")):+ fresh()+ fx.cube(f"SM_Item{i}")+ p = str(src / f"item{i}.{ext}")+ if ext == "fbx":+ bpy.ops.export_scene.fbx(filepath=p)+ elif ext == "glb":+ bpy.ops.export_scene.gltf(filepath=p, export_format="GLB")+ else:+ bpy.ops.wm.save_as_mainfile(filepath=p)+ bp = skill_module("blender-pipeline-automation", "batch_process")+ assert len(bp.gather(str(src))) == 3+ r = bp.run(inp=str(src), op="convert", to="obj", out=str(TMP / "batch_out"))+ assert r["ok"] and r["files"] == 3, r+ assert {"item0.obj", "item1.obj", "item2.obj"} <= set(os.listdir(TMP / "batch_out"))+ r = bp.run(inp=str(src / "*.glb"), op="report")+ assert r["results"][0]["tris"] == 12+ qa = str(ROOT / "skills/blender-asset-qa/scripts/qa_check.py")+ r = bp.run(inp=str(src), op="script", script=qa, kwargs={"uv": False}, shard="0/2")+ assert r["files"] == 2 and all("pass" in x["result"] for x in r["results"]), rdiff --git a/tests/test_qa.py b/tests/test_qa.pynew file mode 100644index 0000000..f268db4--- /dev/null+++ b/tests/test_qa.py@@ -0,0 +1,99 @@+import os++import bmesh+import bpy+import fixtures as fx+from run_all import TMP, requires_gpu, skill_module+++def _qa():+ return skill_module("blender-asset-qa", "qa_check")+++def test_clean_cube_passes():+ c = fx.cube("SM_Box", location=(0, 0, 1))+ fx.unwrap(c)+ c.data.materials.append(bpy.data.materials.new("M_Box"))+ r = _qa().run(objects=["SM_Box"])+ assert r["pass"], r+ assert r["objects"]["SM_Box"]["tris"] == 12 and r["ground_z"] == 0+++def test_detects_zfighting_between_objects_and_within_mesh():+ fx.zfight_pair()+ r = _qa().run(objects=["ZF_A", "ZF_B"], uv=False)+ assert any("ZF_A<->ZF_B" in z["where"] for z in r["zfighting"]), r["zfighting"]+ r = _qa().run(objects=["ZF_Self"], uv=False)+ assert any(z["where"] == "ZF_Self" for z in r["zfighting"]), r+ assert not r["pass"]+++def test_slightly_offset_coplanar_is_zfighting_but_far_is_not():+ fx.plane("P1")+ fx.plane("P2", location=(0.3, 0, 0.0004))+ fx.plane("P3", location=(0, 0, 0.05))+ r = _qa().run(objects=["P1", "P2"], uv=False)+ assert r["zfighting"], r+ r = _qa().run(objects=["P1", "P3"], uv=False)+ assert not r["zfighting"], r+++def test_detects_floating_parts_and_objects():+ fx.detached_part()+ r = _qa().run(objects=["Body", "Floater"], uv=False)+ objs = sorted(f["object"] for f in r["floating"])+ assert objs == ["Body", "Floater"], r["floating"]+++def test_touching_parts_are_not_floating():+ fx.cube("Base", size=2, location=(0, 0, 1))+ fx.cube("Top", size=1, location=(0, 0, 2.5)) # rests exactly on Base+ fx.cube("Pierce", size=0.5, location=(1, 0, 1)) # intersects Base+ r = _qa().run(objects=["Base", "Top", "Pierce"], uv=False)+ assert not r["floating"], r["floating"]+++def test_enclosed_part_is_not_floating():+ fx.uv_sphere("Head", radius=1, location=(0, 0, 1))+ fx.uv_sphere("Eye", radius=0.2, location=(0, -0.6, 1.2))+ r = _qa().run(objects=["Head", "Eye"], uv=False)+ assert not r["floating"] and r["enclosed"], r+++def test_detects_inverted_and_inconsistent_normals_and_back_to_back():+ c = fx.cube("Inv", location=(0, 0, 1))+ bm = bmesh.new()+ bm.from_mesh(c.data)+ bmesh.ops.reverse_faces(bm, faces=bm.faces[:])+ bm.to_mesh(c.data)+ bm.free()+ r = _qa().run(objects=["Inv"], uv=False)+ assert r["objects"]["Inv"]["inside_out_islands"] == 1+ d = fx.cube("Inc", location=(4, 0, 1))+ bm = bmesh.new()+ bm.from_mesh(d.data)+ bmesh.ops.reverse_faces(bm, faces=bm.faces[:1])+ bm.to_mesh(d.data)+ bm.free()+ r = _qa().run(objects=["Inc"], uv=False)+ assert r["objects"]["Inc"]["inconsistent_normals_edges"] == 4+ fx.cube("BB1", size=1, location=(10, 0, 0.5))+ fx.cube("BB2", size=1, location=(11, 0, 0.5))+ r = _qa().run(objects=["BB1", "BB2"], uv=False)+ assert r["back_to_back"] and not r["zfighting"], r+++def test_roblox_profile_flags_open_mesh_and_ngons():+ p = fx.plane("Flat")+ r = _qa().run(objects=["Flat"], profile="roblox", uv=False)+ assert r["objects"]["Flat"]["boundary_edges"] == 4+ assert any("watertight" in w for w in r["warnings"])+ assert p+++def test_review_shots_renders_sheet():+ requires_gpu()+ fx.cube("SM_Box", location=(0, 0, 1))+ r = skill_module("blender-asset-qa", "review_shots").run(out=str(TMP / "qa.png"), res=128, mode="wire")+ assert os.path.getsize(r["sheet"]) > 1000 and len(r["views"]) == 4+ assert "QA_Cam" not in bpy.data.objects and len(bpy.data.objects) == 1diff --git a/tests/test_rendering.py b/tests/test_rendering.pynew file mode 100644index 0000000..a9bf1f2--- /dev/null+++ b/tests/test_rendering.py@@ -0,0 +1,40 @@+import os++import bpy+import fixtures as fx+from run_all import TMP, requires_gpu, skill_module+++def _camera():+ cam = bpy.data.objects.new("Cam", bpy.data.cameras.new("Cam"))+ bpy.context.scene.collection.objects.link(cam)+ cam.location, cam.rotation_euler = (0, -6, 1), (1.5708, 0, 0)+ bpy.context.scene.camera = cam+ return cam+++def test_render_stills_cycles_eevee_workbench():+ requires_gpu()+ fx.cube("Box")+ _camera()+ rb = skill_module("blender-rendering", "render_batch")+ r = rb.run(engine="CYCLES", preset="preview", res=(64, 64), samples=4, device="CPU",+ out=str(TMP / "r" / "c_####"), frames="1,2", view="Khronos PBR Neutral")+ assert r["ok"] and len(r["files"]) == 2 and r["view"] == "Khronos PBR Neutral", r+ r = rb.run(engine="BLENDER_WORKBENCH", res=(64, 64), out=str(TMP / "r" / "w_####"), format="EXR")+ assert r["ok"] and r["files"][0].endswith(".exr")+ r = rb.run(engine="BLENDER_EEVEE", res=(64, 64), samples=1, out=str(TMP / "r" / "e_####"), transparent=True)+ assert r["ok"] and os.path.getsize(r["files"][0]) > 0+++def test_lookdev_turntable_and_studio():+ requires_gpu()+ fx.uv_sphere("Hero", radius=0.5, location=(0, 0, 0.5))+ lk = skill_module("blender-lighting-lookdev", "turntable")+ r = lk.run(objects=["Hero"], rig="studio", frames=24, hdri=None)+ assert r["camera"] in bpy.data.objects and r["lights"] >= 3, r+ cam = bpy.data.objects[r["camera"]]+ assert bpy.context.scene.frame_end == 24 and cam.parent is not None+ rb = skill_module("blender-rendering", "render_batch")+ out = rb.run(engine="BLENDER_WORKBENCH", res=(48, 48), out=str(TMP / "tt" / "t_####"), frames="1,12")+ assert len(out["files"]) == 2diff --git a/tests/test_retopo_uv.py b/tests/test_retopo_uv.pynew file mode 100644index 0000000..b2c32be--- /dev/null+++ b/tests/test_retopo_uv.py@@ -0,0 +1,31 @@+import bpy+import fixtures as fx+from run_all import skill_module+++def test_uv_pack_and_texel_density_set():+ fx.cube("SM_Crate", size=1)+ up = skill_module("blender-retopology-uv", "uv_pack")+ r = up.run(objects=["SM_Crate"], method="seams", seams_from_sharp=60, lightmap=True)+ assert r["objects"]["SM_Crate"]["seams_marked"] == 12+ assert r["objects"]["SM_Crate"]["uv_maps"] == ["UVMap", "UVMap_Lightmap"]+ td = skill_module("blender-retopology-uv", "texel_density")+ m = td.run(objects=["SM_Crate"], res=1024)["objects"]["SM_Crate"]+ assert m["px_per_m"] > 0 and m["spread"] < 1.3, m+ s = td.run(objects=["SM_Crate"], res=1024, set=200)["objects"]["SM_Crate"]+ assert abs(s["after"]["px_per_m"] - 200) < 5 and s["after"]["fits_0_1"], s+ s = td.run(objects=["SM_Crate"], res=1024, set=5000)["objects"]["SM_Crate"]+ assert not s["after"]["fits_0_1"]+++def test_auto_retopo_methods():+ rt = skill_module("blender-retopology-uv", "auto_retopo")+ fx.uv_sphere("Dense", segs=96, rings=48)+ r = rt.run(objects=["Dense"], method="decimate", tris=1600)+ o = r["objects"]["Dense"]+ assert o["tris_after"] <= 1700 and "Dense_low" in bpy.data.objects+ bpy.data.objects.remove(bpy.data.objects["Dense_low"])+ bpy.data.objects["Dense"].hide_set(False)+ r = rt.run(objects=["Dense"], method="quadriflow", tris=1200)+ o = r["objects"]["Dense"]+ assert 300 < o["faces_after"] < 1200, odiff --git a/tests/test_rigging.py b/tests/test_rigging.pynew file mode 100644index 0000000..74045d6--- /dev/null+++ b/tests/test_rigging.py@@ -0,0 +1,51 @@+import bmesh+import bpy+import fixtures as fx+from mathutils import Matrix+from run_all import skill_module+++def _humanoid_mesh():+ """Crude closed humanoid (torso, head, arms in T, legs) ~1.8 m, union of boxes (non-manifold joins)."""+ def build(bm):+ for size, loc in (((0.4, 0.25, 0.6), (0, 0, 1.2)), ((0.25, 0.25, 0.25), (0, 0, 1.68)),+ ((0.7, 0.12, 0.12), (0.55, 0, 1.42)), ((0.7, 0.12, 0.12), (-0.55, 0, 1.42)),+ ((0.15, 0.15, 0.9), (0.11, 0, 0.45)), ((0.15, 0.15, 0.9), (-0.11, 0, 0.45))):+ r = bmesh.ops.create_cube(bm, size=1, matrix=Matrix.Translation(loc) @ Matrix.Diagonal((*size, 1)))+ bmesh.ops.subdivide_edges(bm, edges=list({e for v in r["verts"] for e in v.link_edges}), cuts=4,+ use_grid_fill=True)+ return fx.mesh_object("Body", build)+++def test_rigify_pipeline_bind_check_stress():+ rb = skill_module("blender-character-rigging", "rigify_build")+ body = _humanoid_mesh()+ r = rb.run(add="basic_human", fit="Body", generate=True)+ assert r["rig"] == "RIG_Body" and r["deform_bones"] > 20, r+ bind = skill_module("blender-character-rigging", "bind_mesh")+ b = bind.run(armature="RIG_Body", meshes=["Body"], method="auto")["meshes"]["Body"]+ assert b["unweighted_verts"] == 0 and b["max_influences"] <= 4, b+ g = rb.run(rig="RIG_Body", game_skel=True)["game_skeleton"]+ gs = bpy.data.objects[g["name"]]+ assert "root" in gs.data.bones and "spine" in gs.data.bones and "thigh.L" in gs.data.bones+ assert gs.data.bones["thigh.L"].parent.name.startswith("spine")+ assert body.modifiers["Armature"].object == gs and "spine" in body.vertex_groups+ chk = skill_module("blender-character-rigging", "rig_check").run(armature=gs.name, profile="unity")+ assert not [e for e in chk["errors"] if "unweighted" in e or "influences" in e], chk+ assert chk["profile"]["humanoid_map"]["LeftUpperLeg"] == "thigh.L", chk["profile"]+ st = skill_module("blender-character-rigging", "stress_poses").run(armature="RIG_Body")+ assert not st["missing_roles"], st+ assert st["bones_used"]["upper_arm.L"] == "upper_arm_fk.L"+ # the posed control rig must move the game skeleton (constraints)+ bpy.context.scene.frame_set(30)+ bpy.context.view_layer.update()+ assert (gs.pose.bones["shin.L"].tail - gs.data.bones["shin.L"].tail_local).length > 0.1+++def test_proxy_bind_and_fix():+ body, arm = fx.simple_character()+ bind = skill_module("blender-character-rigging", "bind_mesh")+ r = bind.run(armature="CharRig", meshes=["Char"], method="proxy")["meshes"]["Char"]+ assert r["method"] == "proxy" and r["unweighted_verts"] == 0, r+ chk = skill_module("blender-character-rigging", "rig_check").run(armature="CharRig", fix=True)+ assert chk["skin"]["Char"]["over_4"] == 0diff --git a/tests/test_scene.py b/tests/test_scene.pynew file mode 100644index 0000000..589380c--- /dev/null+++ b/tests/test_scene.py@@ -0,0 +1,38 @@+import os++import bpy+import fixtures as fx+from run_all import TMP, skill_module+++def test_scene_audit_flags_and_fixes():+ m = skill_module("blender-scene-setup", "scene_audit")+ a = fx.cube("Cube")+ a.scale = (2, 2, 2)+ b = fx.cube("SM_Crate.001", location=(3, 0, 0))+ b.rotation_euler = (0.3, 0, 0)+ bpy.data.materials.new("Orphan")+ r = m.run()+ assert "Cube" in r["issues"]["default_names"]+ assert "SM_Crate.001" in r["issues"]["duplicate_suffix"]+ assert "Cube" in r["issues"]["unapplied_scale"] and "SM_Crate.001" in r["issues"]["rotated"]+ assert r["orphans"] >= 1+ bpy.context.view_layer.update()+ dims = tuple(a.dimensions)+ r = m.run(fix=["purge", "scale"])+ assert tuple(a.scale) == (1, 1, 1) and all(abs(x - y) < 1e-5 for x, y in zip(a.dimensions, dims))+ assert "Orphan" not in bpy.data.materials+++def test_collection_exporter_snippet():+ col = bpy.data.collections.new("Export")+ bpy.context.scene.collection.children.link(col)+ col.objects.link(fx.cube("SM_Crate"))+ with bpy.context.temp_override(collection=col):+ bpy.ops.collection.exporter_add(name="IO_FH_gltf2")+ ex = col.exporters[-1]+ out = str(TMP / "SM_Crate.glb")+ ex.export_properties.filepath = out+ with bpy.context.temp_override(collection=col):+ assert bpy.ops.collection.exporter_export(index=len(col.exporters) - 1) == {"FINISHED"}+ assert os.path.getsize(out) > 0diff --git a/tests/test_sculpt.py b/tests/test_sculpt.pynew file mode 100644index 0000000..45fcaf4--- /dev/null+++ b/tests/test_sculpt.py@@ -0,0 +1,12 @@+import fixtures as fx+from run_all import skill_module+++def test_sculpt_ops_chain():+ fx.cube("Blob", size=1)+ s = skill_module("blender-sculpting", "sculpt_ops")+ r = s.run(objects=["Blob"], ops=["remesh=0.05", "symmetrize=+X", "inflate=0.02", "detail=0.01,0.2",+ "smooth=3", "apply", "multires=2"])+ o = r["objects"]["Blob"]+ assert o["multires_levels"] == 2 and o["evaluated_tris"] > o["base_faces"] * 2 * 10, o+ assert o["stack"] == ["Multires"]diff --git a/tests/test_simulation.py b/tests/test_simulation.pynew file mode 100644index 0000000..6655559--- /dev/null+++ b/tests/test_simulation.py@@ -0,0 +1,37 @@+import bmesh+import bpy+import fixtures as fx+from run_all import skill_module+++def _grid(name, size=2.0, cuts=20, z=2.0):+ return fx.mesh_object(name, lambda bm: bmesh.ops.create_grid(bm, x_segments=cuts, y_segments=cuts,+ size=size / 2), location=(0, 0, z))+++def test_rigid_body_drop_and_keys():+ fx.cube("Floor", size=1, location=(0, 0, -0.5)).scale = (10, 10, 1)+ fx.cube("Crate", size=0.5, location=(0, 0, 3))+ s = skill_module("blender-simulation", "sim_setup")+ r = s.run(rigid=True, active=["Crate"], passive=["Floor"], frames=(1, 60), bake=True, to_keys=True)+ assert abs(r["rigid"]["Crate"]["mass"] - 0.125 * 500) < 1, r+ assert abs(r["result"]["Crate"]["min_z"]) < 0.05, r["result"] # resting on the floor+ assert bpy.data.objects["Crate"].animation_data.action is not None+++def test_classic_cloth_drapes_on_collider():+ fx.cube("Table", size=1, location=(0, 0, 0.5))+ _grid("Cloth", z=1.5)+ s = skill_module("blender-simulation", "sim_setup")+ r = s.run(cloth="Cloth", preset="cotton", colliders=["Table"], frames=(1, 40), bake=True)+ z = r["result"]["Cloth"]["min_z"]+ assert z < 1.0, r["result"] # fell and draped over the edges+++def test_gn_cloth_52_asset():+ fx.cube("Table", size=1, location=(0, 0, 0.5))+ _grid("Sheet", z=1.5, cuts=16)+ s = skill_module("blender-simulation", "sim_setup")+ r = s.run(gn_cloth="Sheet", colliders=["Table"], frames=(1, 40), bake=True)+ assert r["gn_cloth"]["group"].startswith("Cloth Dynamics")+ assert r["result"]["Sheet"]["min_z"] < 1.4, r["result"]diff --git a/tools/run_tests.py b/tools/run_tests.pynew file mode 100644index 0000000..8883e7d--- /dev/null+++ b/tools/run_tests.py@@ -0,0 +1,34 @@+#!/usr/bin/env python3+"""Run the headless Blender test suite.++Usage: python tools/run_tests.py [name-filter] (BLENDER_EXE overrides discovery)+"""+import pathlib+import subprocess+import sys++ROOT = pathlib.Path(__file__).resolve().parent.parent+sys.path.insert(0, str(ROOT / "skills" / "blender-core" / "scripts"))+from run_in_blender import find_blender # noqa: E402+++def main():+ exe = find_blender()+ if not exe:+ print("Blender not found; set BLENDER_EXE")+ return 2+ cmd = [exe, "-b", "--factory-startup", "--python-exit-code", "1",+ "-P", str(ROOT / "tests" / "run_all.py"), "--", *sys.argv[1:]]+ p = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace")+ out = p.stdout.splitlines()+ start = next((i for i, ln in enumerate(out) if ln.startswith(("PASS", "FAIL", "SKIP"))), len(out))+ keep = ("PASS", "FAIL", "SKIP", "Traceback", " ", "AssertionError", "KeyError", "ValueError", "RuntimeError")+ lines = [ln for ln in out[start:] if ln.startswith(keep) or " passed, " in ln]+ print("\n".join(lines))+ if p.returncode and not lines:+ print(p.stderr[-3000:])+ return p.returncode+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/sync_shared.py b/tools/sync_shared.pynew file mode 100644index 0000000..03d4f66--- /dev/null+++ b/tools/sync_shared.py@@ -0,0 +1,34 @@+#!/usr/bin/env python3+"""Copy shared/_bpyx.py into every skills/*/scripts/ folder that has Blender scripts.++Usage: python tools/sync_shared.py [--check] (--check: exit 1 if any copy is stale)+"""+import pathlib+import re+import sys++ROOT = pathlib.Path(__file__).resolve().parent.parent+SRC = ROOT / "shared" / "_bpyx.py"+++def targets():+ for d in sorted((ROOT / "skills").glob("*/scripts")):+ if any(p.name != "_bpyx.py" and re.search(r"^import bpy", p.read_text("utf-8"), re.M) for p in d.glob("*.py")):+ yield d / "_bpyx.py"+++def main():+ src = SRC.read_bytes()+ stale = [t for t in targets() if not t.exists() or t.read_bytes() != src]+ if "--check" in sys.argv:+ for t in stale:+ print(f"stale: {t.relative_to(ROOT)}")+ return 1 if stale else 0+ for t in stale:+ t.write_bytes(src)+ print(f"synced {t.relative_to(ROOT)}")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/trigger_check.py b/tools/trigger_check.pynew file mode 100644index 0000000..817b947--- /dev/null+++ b/tools/trigger_check.py@@ -0,0 +1,67 @@+#!/usr/bin/env python3+"""Heuristic trigger check: do skill descriptions win for prompts they should own?++Scores each prompt against every description (token overlap, IDF weighted) and checks that the+expected skill is in the top 2. A cheap regression guard when editing descriptions; real agents+use richer matching.+Usage: python tools/trigger_check.py+"""+import math+import pathlib+import re+import sys++ROOT = pathlib.Path(__file__).resolve().parent.parent+CASES = [+ ("rig my character with rigify and fix the weight painting", "blender-character-rigging"),+ ("bake a normal map from the high poly sculpt onto the low poly", "blender-texture-baking"),+ ("export this skeletal mesh to unreal engine", "blender-export-pipelines"),+ ("my model has z-fighting and floating parts, review it", "blender-asset-qa"),+ ("make LODs and reduce draw calls for mobile", "blender-game-optimization"),+ ("unwrap the uvs and set texel density to 512 px/m", "blender-retopology-uv"),+ ("set up a PBR material from these texture maps, metal roughness", "blender-pbr-materials"),+ ("scatter rocks on the terrain procedurally with geometry nodes", "blender-geometry-nodes"),+ ("create ARKit blendshapes for lip-sync visemes", "blender-facial-shapekeys"),+ ("bake the walk cycle with root motion and export clips", "blender-animation"),+ ("render a turntable with studio lighting and an HDRI", "blender-lighting-lookdev"),+ ("render the animation with cycles on the GPU and denoise", "blender-rendering"),+ ("cloth draping over a table and rigid body crates falling", "blender-simulation"),+ ("write a blender add-on with an operator and a panel", "blender-addon-development"),+ ("batch convert a folder of fbx files to glb headless", "blender-pipeline-automation"),+ ("bevel and boolean a hard-surface weapon with weighted normals", "blender-hardsurface-modeling"),+ ("sculpt a creature with multires and voxel remesh", "blender-sculpting"),+ ("organize collections, naming conventions and asset library", "blender-scene-setup"),+ ("make a complete game-ready character from an AI generated mesh", "blender-workflow-recipes"),+ ("run bpy code in blender headless via the cli", "blender-core"),+ ("roblox layered clothing cage and R15 export", "blender-export-pipelines"),+]+++def toks(s):+ return [t for t in re.findall(r"[a-z0-9]+", s.lower()) if len(t) > 2]+++def main():+ descs = {}+ for md in sorted((ROOT / "skills").glob("*/SKILL.md")):+ m = re.search(r"^description: (.*)$", md.read_text("utf-8"), re.M)+ descs[md.parent.name] = set(toks(m.group(1)) + toks(md.parent.name))+ n = len(descs)+ idf = {}+ for d in descs.values():+ for t in d:+ idf[t] = idf.get(t, 0) + 1+ idf = {t: math.log(n / c) + 0.1 for t, c in idf.items()}+ fails = 0+ for prompt, want in CASES:+ q = set(toks(prompt))+ ranked = sorted(descs, key=lambda k: -sum(idf.get(t, 0) for t in q & descs[k]))+ ok = want in ranked[:2]+ fails += not ok+ print(f"{'ok ' if ok else 'MISS'} {want:<30} top: {ranked[0]}, {ranked[1]} <- {prompt}")+ print(f"{len(CASES) - fails}/{len(CASES)} in top-2")+ return 1 if fails > len(CASES) // 10 else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/validate_skills.py b/tools/validate_skills.pynew file mode 100644index 0000000..7c221b6--- /dev/null+++ b/tools/validate_skills.py@@ -0,0 +1,122 @@+#!/usr/bin/env python3+"""Lint skills against the Agent Skills spec + this repo's token budgets.++Checks: frontmatter (name/description rules, name == dir), SKILL.md <= 500 lines and+token budget, relative links resolve, scripts compile, Blender scripts expose run()+and a Usage docstring, _bpyx copies in sync.+Usage: python tools/validate_skills.py [--strict] (--strict: warnings fail too)+"""+import ast+import pathlib+import re+import sys++ROOT = pathlib.Path(__file__).resolve().parent.parent+NAME_RE = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$")+DESC_TARGET, DESC_MAX = 400, 1024+TOK_WARN, TOK_MAX, LINES_MAX = 3000, 5000, 500+LINK_RE = re.compile(r"\]\(([^)#\s]+)(?:#[^)]*)?\)")+++def tokens(text):+ return len(text) // 4 # rough, model-agnostic+++def frontmatter(text):+ if not text.startswith("---\n"):+ return None, text+ end = text.find("\n---", 4)+ if end < 0:+ return None, text+ fm, body = {}, text[end + 4:].lstrip("\n")+ key = None+ for line in text[4:end].splitlines():+ m = re.match(r"^([A-Za-z_-]+):\s*(.*)$", line)+ if m and not line.startswith(" "):+ key, val = m.group(1), m.group(2).strip()+ fm[key] = val.strip("\"'") if val not in (">", "|", ">-", "|-") else ""+ elif key and line.startswith(" ") and fm.get(key) is not None and key != "metadata":+ fm[key] = (fm[key] + " " + line.strip()).strip()+ return fm, body+++def check_skill(d, errs, warns):+ rel = d.relative_to(ROOT)+ md = d / "SKILL.md"+ if not md.exists():+ errs.append(f"{rel}: missing SKILL.md")+ return+ text = md.read_text("utf-8")+ fm, body = frontmatter(text)+ if fm is None:+ errs.append(f"{rel}: no YAML frontmatter")+ return+ name, desc = fm.get("name", ""), fm.get("description", "")+ if not NAME_RE.match(name) or len(name) > 64:+ errs.append(f"{rel}: invalid name {name!r}")+ if name != d.name:+ errs.append(f"{rel}: name {name!r} != dir {d.name!r}")+ raw = next((ln for ln in text.splitlines() if ln.startswith("description:")), "")+ if ": " in raw[len("description: "):] or " #" in raw:+ errs.append(f"{rel}: description has ': ' or ' #' (breaks YAML plain scalars; quote it)")+ if not 1 <= len(desc) <= DESC_MAX:+ errs.append(f"{rel}: description length {len(desc)} (1-{DESC_MAX})")+ elif len(desc) > DESC_TARGET:+ warns.append(f"{rel}: description {len(desc)} chars > target {DESC_TARGET}")+ n_lines, n_tok = body.count("\n") + 1, tokens(body)+ if n_lines > LINES_MAX:+ errs.append(f"{rel}: SKILL.md body {n_lines} lines > {LINES_MAX}")+ if n_tok > TOK_MAX:+ errs.append(f"{rel}: SKILL.md ~{n_tok} tokens > {TOK_MAX}")+ elif n_tok > TOK_WARN:+ warns.append(f"{rel}: SKILL.md ~{n_tok} tokens > {TOK_WARN}")+ for f in [md, *d.glob("references/*.md")]:+ for link in LINK_RE.findall(f.read_text("utf-8")):+ if "://" in link or link.startswith("mailto:"):+ continue+ if not (f.parent / link).resolve().exists():+ errs.append(f"{f.relative_to(ROOT)}: broken link {link}")+ for py in d.glob("scripts/*.py"):+ src = py.read_text("utf-8")+ try:+ tree = ast.parse(src)+ except SyntaxError as e:+ errs.append(f"{py.relative_to(ROOT)}: syntax error {e}")+ continue+ if py.name == "_bpyx.py":+ continue+ doc = ast.get_docstring(tree) or ""+ if "Usage" not in doc:+ errs.append(f"{py.relative_to(ROOT)}: docstring lacks 'Usage'")+ imports_bpy = any(isinstance(n, ast.Import) and any(a.name == "bpy" for a in n.names)+ for n in tree.body)+ if imports_bpy and not any(+ isinstance(n, ast.FunctionDef) and n.name == "run" for n in tree.body):+ errs.append(f"{py.relative_to(ROOT)}: Blender script without run()")+ return n_tok+++def main():+ errs, warns, rows = [], [], []+ skills = sorted(p for p in (ROOT / "skills").iterdir() if p.is_dir())+ for d in skills:+ rows.append((d.name, check_skill(d, errs, warns)))+ shared = (ROOT / "shared" / "_bpyx.py").read_bytes()+ for c in (ROOT / "skills").glob("*/scripts/_bpyx.py"):+ if c.read_bytes() != shared:+ errs.append(f"{c.relative_to(ROOT)}: out of sync (run tools/sync_shared.py)")+ total = sum(t or 0 for _, t in rows)+ print(f"{len(skills)} skills, SKILL.md bodies ~{total} tokens total")+ for n, t in rows:+ print(f" {n:<32} ~{t} tok")+ for w in warns:+ print("WARN ", w)+ for e in errs:+ print("ERROR", e)+ fail = errs or ("--strict" in sys.argv and warns)+ print("FAIL" if fail else "OK")+ return 1 if fail else 0+++if __name__ == "__main__":+ sys.exit(main())