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
Release 1.2.0: six new skills, retargeting, QA texture checks
EL4CTEOfb92cfb4cc5a
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex d380929..8cf5929 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -6,7 +6,7 @@{"name": "blender-agent-skills","source": "./",- "description": "22 tested Blender skills: model, UV, texture, bake, rig, animate, optimize, export, render, time of day, weather, QA"+ "description": "28 tested Blender skills: model, UV, texture, bake, rig, animate, clothe, groom, build environments, toon, optimize, export, render, edit video, weather, QA"}]}diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 768ef08..65a48ed 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,10 +1,10 @@{"name": "blender-agent-skills",- "version": "1.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, time of day, weather, simulation, QA.",+ "version": "1.2.0",+ "description": "Professional Blender 5.2 workflows for AI agents: modeling, retopo/UV, PBR, texturing, baking, rigging, animation, clothing, hair, environments, toon/NPR, optimization, export (Roblox/Unity/Unreal/Godot/web), rendering, video, time of day, weather, 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"]+ "keywords": ["blender", "bpy", "3d", "game-assets", "rigging", "pbr", "texturing", "hair", "terrain", "toon", "roblox", "unity", "unreal", "godot"]}diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 2b7587b..f8bf50a 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -21,7 +21,7 @@ jobs:blender-tests:runs-on: ubuntu-latestenv:- BLENDER_VERSION: "5.2.2"+ BLENDER_VERSION: "5.2.3"BAS_SKIP_GPU: "1" # no GPU on hosted runners: render tests are skippedsteps:- uses: actions/checkout@v4diff --git a/AGENTS.md b/AGENTS.mdindex 79cf72a..34bb3c3 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -16,15 +16,21 @@ This repo contains Agent Skills (`skills/<name>/SKILL.md`, agentskills.io format| 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-texturing | wear/grime/dust layers, decals, trims, painting || 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-animation | actions/slots, NLA, mocap retarget, loops, bake, root motion |+| blender-clothing | garments, weights, body masking, morphs, poke check |+| blender-hair-grooming | hair curves, node assets, hair cards || 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-stylized-npr | toon shading, outlines, Line Art, Grease Pencil |+| blender-environment-kits | terrain, scatter, modular kit checks |+| blender-video-editing | VSE edits, motion tracking || blender-simulation | rigid body, cloth (classic + 5.2 nodes), fluids || blender-time-of-day | sky/sun/moon by time, night, fog, moods || blender-weather-fx | rain, snow, wetness, puddles, lightning |diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0cfafec..7d5bd79 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,13 @@# Changelog+## [1.2.0] - 2026-10-30+- New skills: `blender-texturing` (wear/grime/dust, decals), `blender-stylized-npr` (toon shading, outlines), `blender-hair-grooming` (hair, fur, hair cards), `blender-environment-kits` (terrain, scatter, modular kits), `blender-clothing` (garments, no clipping), `blender-video-editing` (VSE edits, camera tracking).+- Animation: mocap retargeting with auto bone maps (`retarget.py`), loop pop/hitch checker (`loop_check.py`).+- Asset QA: catches faces on empty material slots, missing textures, and data maps set to sRGB.+- Sculpting: proportions, hard-surface and bake-source reference.+- Fix: re-running `surface_weather.py` no longer disconnects the weather layer.+- Validator flags script names that don't exist. Verified on Blender 5.2.3.+## [1.1.0] - 2026-10-16- New `blender-time-of-day`: sky + sun measured from Blender's sky model, night with moon/stars, fog from visibility, moods (cyberpunk, horror, underwater, desert).- New `blender-weather-fx`: looping rain/snow/dust/embers, wet surfaces, puddles with ripples, snow cover, lightning.diff --git a/README.md b/README.mdindex 093ce81..79bfe73 100644--- a/README.md+++ b/README.md@@ -4,7 +4,7 @@Professional Blender workflows packaged as **Agent Skills** for AI coding agents: Claude Code, Codex, OpenCode, Gemini CLI, GitHub Copilot and Cursor.-There are 22 skills covering the full 3D pipeline (modeling, UVs, PBR, baking, rigging, animation, optimization, export, rendering, time of day, weather, simulation and QA), built for **Blender 5.2 LTS+**. Every script is tested in a real Blender.+There are 28 skills covering the full 3D pipeline (modeling, UVs, texturing, baking, rigging, animation, clothing, hair, environments, stylized looks, optimization, export, rendering, video, weather, simulation and QA), built for **Blender 5.2 LTS+**. Every script is tested in a real Blender.## Install@@ -34,21 +34,27 @@ The default installs into `~/.claude/skills` and `~/.agents/skills`. `.agents/sk| `blender-sculpting` | Organic sculpting workflow || `blender-retopology-uv` | Retopology, UVs, texel density || `blender-pbr-materials` | Correct PBR materials from textures |+| `blender-texturing` | Edge wear, grime, dust, decals, trim sheets || `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-animation` | Actions, mocap retargeting, loop checks, root motion |+| `blender-clothing` | Clothes that follow the body without clipping |+| `blender-hair-grooming` | Hair, fur and game hair cards || `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-stylized-npr` | Toon/anime shading and outlines |+| `blender-environment-kits` | Terrain, forests, modular level kits |+| `blender-video-editing` | Edit videos, track cameras || `blender-simulation` | Rigid bodies, cloth, fluids || `blender-time-of-day` | Golden hour, night, fog and mood lighting || `blender-weather-fx` | Rain, snow, wet streets, puddles, lightning || `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-asset-qa` | Catches z-fighting, floating parts, bad normals, weights and textures || `blender-workflow-recipes` | Complete asset playbooks |## With vs without skills@@ -63,12 +69,13 @@ Same model, same prompts, outputs with the skills vs without them: **[see the co> "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."> "Make this street a rainy night with puddles and lightning."+> "Give my character a shirt and hair cards, then retarget this Mixamo run onto it."## Development```bashpython tools/validate_skills.py # spec + token budget checks-python tools/run_tests.py # 50 headless Blender tests (BLENDER_EXE to override)+python tools/run_tests.py # 67 headless Blender tests (BLENDER_EXE to override)```MIT Licensediff --git a/skills/blender-addon-development/SKILL.md b/skills/blender-addon-development/SKILL.mdindex e89ad6d..d57413f 100644--- a/skills/blender-addon-development/SKILL.md+++ b/skills/blender-addon-development/SKILL.md@@ -4,7 +4,7 @@ description: Write Blender 5.2 add-ons as extensions - blender_manifest.toml, oplicense: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Add-on (Extension) Developmentdiff --git a/skills/blender-animation/SKILL.md b/skills/blender-animation/SKILL.mdindex 2afcd11..63204ed 100644--- a/skills/blender-animation/SKILL.md+++ b/skills/blender-animation/SKILL.md@@ -1,10 +1,10 @@---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.+description: Animation in Blender 5.2 - slotted/layered actions and the channelbag API, Python keyframing, F-curves, game loops with pop/hitch checks, NLA clips, pose library, mocap/BVH/Mixamo retargeting with auto bone maps, baking control rigs to export skeletons, root motion, per-clip export. Use for any keyframe, action, NLA, mocap, or animation-export task.license: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Animation@@ -26,7 +26,7 @@ The execution model is in `blender-core` (its `references/bpy-patterns.md` has v## 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.+- **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. Verify with `scripts/loop_check.py -- --object RIG --action Walk [--root-motion root] [--fix]`: it reports pose **pops** (last ≠ first, per bone, in deg/m) and speed **hitches** across the seam, and `--fix` keys the first-frame values on the last frame (root travel is kept).- **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.@@ -41,7 +41,9 @@ This gives one baked action per clip (`GAME_RIG_Body|Walk`), cleaned, with fake## 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.+- Retarget: `scripts/retarget.py -- --source Mocap --target GAME_RIG [--map auto|map.json] [--in-place] [--name Walk]`. Each target bone gets the source bone's **world rotation change from rest** on its own rest orientation, so rolls, bone axes, Y-up/cm FBX object transforms and proportions don't matter. The hips travel is scaled by the hips-height ratio. Keys go straight into a new `TARGET|Name` action (quaternion, linear, fake user). Measured on a Mixamo-style rig (Y-up, 0.01 scale, rolled) → Rigify-named rig with 15% longer legs: 17 bones, < 0.1° error.+- The auto map understands Mixamo (`mixamorig:LeftUpLeg`), Rigify `DEF-`/`ORG-`, UE/Unity/BVH-style names, and spine chains of different lengths. Check it first with `--show-map` (`unmapped_key_parts` must be empty), and pass a JSON `{target: source}` for anything custom (fingers, props).+- **Rest poses must match** (T vs A matters most): pose the target's rest like the source's first. Then clean, add root motion, and export with `bake_action.py`.- 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).diff --git a/skills/blender-animation/scripts/loop_check.py b/skills/blender-animation/scripts/loop_check.pynew file mode 100644index 0000000..0e2ea7e--- /dev/null+++ b/skills/blender-animation/scripts/loop_check.py@@ -0,0 +1,109 @@+"""Check that a cycle loops: the pose at the last frame equals the first (no pop), and the motion+across the seam keeps its speed (no hitch). --fix keys every F-curve's first-frame value onto the+last frame. Root-motion clips: --root-motion BONE ignores that bone's X/Y travel.++Compares evaluated poses (constraints, drivers included) per bone in armature space; works on+plain objects too (object transform). Engines drop the duplicate last frame on import ("loop pose").+Usage:+ blender -b f.blend -P loop_check.py -- --object GAME_RIG [--action Walk] [--frames 1 25]+ [--tol-deg 0.5] [--tol-m 0.001] [--root-motion root] [--fix] [--save out.blend]+ MCP: import loop_check; print(loop_check.run(object="GAME_RIG", action="Walk", fix=True))+"""+import math+import os+import sys++import bpy+from bpy_extras import anim_utils+from mathutils import Matrix++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402+++def _poses(ob, f, root=None):+ bpy.context.scene.frame_set(f)+ if ob.type != "ARMATURE":+ return {"<object>": ob.matrix_world.copy()}+ pose = {pb.name: pb.matrix.copy() for pb in ob.pose.bones}+ if root in pose: # remove the root's ground travel from it and its children (they inherit it)+ t = pose[root].translation.copy()+ t.z = 0.0+ off = Matrix.Translation(-t)+ moved = {root, *(c.name for c in ob.pose.bones[root].children_recursive)}+ pose = {k: (off @ m if k in moved else m) for k, m in pose.items()}+ return pose+++def _diff(a, b):+ rot = math.degrees(a.to_quaternion().rotation_difference(b.to_quaternion()).angle)+ return min(rot, 360.0 - rot), (a.translation - b.translation).length+++def _check(ob, f0, f1, tol_deg, tol_m, root):+ p0, p1 = _poses(ob, f0, root), _poses(ob, f1, root)+ n0, n1 = _poses(ob, f0 + 1, root), _poses(ob, f1 - 1, root)+ pops, hitch = [], []+ for k in p0:+ r, t = _diff(p0[k], p1[k])+ if r > tol_deg or t > tol_m:+ pops.append({"bone": k, "rot_deg": round(r, 3), "loc_m": round(t, 5)})+ v_in, v_out = _diff(p1[k], n1[k])[0], _diff(n0[k], p0[k])[0] # deg/frame arriving vs leaving+ dv = abs(v_in - v_out)+ if dv > tol_deg and dv > 0.25 * max(v_in, v_out):+ hitch.append({"bone": k, "deg_per_frame_in": round(v_in, 3), "deg_per_frame_out": round(v_out, 3)})+ pops.sort(key=lambda x: -x["rot_deg"] - 100 * x["loc_m"])+ hitch.sort(key=lambda x: -abs(x["deg_per_frame_in"] - x["deg_per_frame_out"]))+ return pops, hitch+++def run(object=None, action=None, frames=None, tol_deg=0.5, tol_m=0.001, root_motion=None, fix=False, **_):+ if not object:+ raise ValueError("--object is required")+ ob = bpy.data.objects[object]+ ad = ob.animation_data+ if action:+ ob.animation_data_create()+ ob.animation_data.action = bpy.data.actions[action]+ ad = ob.animation_data+ if ad.action_slot is None:+ ad.action_slot = next(iter(ad.action_suitable_slots), None)+ if ad is None or ad.action is None:+ raise ValueError(f"{object} has no action")+ act = ad.action+ f0, f1 = (int(frames[0]), int(frames[1])) if frames else (int(round(v)) for v in act.frame_range)+ pops, hitch = _check(ob, f0, f1, tol_deg, tol_m, root_motion)+ res = {"ok": True, "object": ob.name, "action": act.name, "frames": [f0, f1], "loops": not pops,+ "pops": pops[:10], "hitches": hitch[:10]}+ if fix and pops:+ cb = anim_utils.action_get_channelbag_for_slot(act, ad.action_slot)+ ground = set()+ if root_motion and ob.type == "ARMATURE": # local location axes that point along the ground+ ml = ob.data.bones[root_motion].matrix_local.to_3x3()+ ground = {i for i in range(3) if abs(ml.col[i].normalized().z) < 0.5}+ n = 0+ for fc in cb.fcurves:+ if fc.data_path == f'pose.bones["{root_motion}"].location' and fc.array_index in ground:+ continue # root travel is the point of a root-motion clip+ fc.keyframe_points.insert(f1, fc.evaluate(f0), options={"REPLACE", "FAST"})+ fc.update()+ n += 1+ pops2, hitch2 = _check(ob, f0, f1, tol_deg, tol_m, root_motion)+ res.update(fixed_curves=n, loops=not pops2, pops=pops2[:10], hitches=hitch2[:10])+ if res["hitches"]:+ res["note"] = "speed changes across the seam: match the tangents (Graph Editor, auto-clamped/cyclic) or re-pose frame 2/N-1"+ bpy.context.scene.frame_set(f0)+ return res+++if __name__ == "__main__":+ p = bx.parser(__doc__)+ p.add_argument("--object", required=True)+ p.add_argument("--action", default=None)+ p.add_argument("--frames", type=int, nargs=2, default=None)+ p.add_argument("--tol-deg", type=float, default=0.5)+ p.add_argument("--tol-m", type=float, default=0.001)+ p.add_argument("--root-motion", default=None, help="bone whose X/Y travel is ignored")+ p.add_argument("--fix", action="store_true")+ p.add_argument("--save", default=None)+ bx.cli(run, p)diff --git a/skills/blender-animation/scripts/retarget.py b/skills/blender-animation/scripts/retarget.pynew file mode 100644index 0000000..a7199cb--- /dev/null+++ b/skills/blender-animation/scripts/retarget.py@@ -0,0 +1,201 @@+"""Retarget an animated skeleton (mocap/BVH/Mixamo/any rig) onto another rig, constraint-free.++Each mapped target bone gets the source bone's world-space rotation *change from rest* applied to its+own rest orientation (so different rolls, axes, object rotation/scale don't matter); the hips also+get the source hips' translation scaled by the hips-height ratio. Keys are written straight into a+new slotted action (quaternions, linear) on the target. Rest poses must match in spirit (T vs A pose+matters most): pose the target's rest to the source's first, or use a source rest-pose frame.+Bone map: auto (Mixamo, Rigify DEF-/ORG-, UE/Unity-style names, BVH) or a JSON {target: source}.+Usage:+ blender -b f.blend -P retarget.py -- --source Mocap --target GAME_RIG [--map auto|map.json]+ [--frames 1 120] [--in-place] [--name Walk] [--save out.blend]+ blender -b f.blend -P retarget.py -- --source Mocap --target GAME_RIG --show-map+ MCP: import retarget; print(retarget.run(source="Armature", target="GAME_RIG", name="Walk"))+"""+import json+import math+import os+import re+import sys++import bpy+from bpy_extras import anim_utils+from mathutils import Matrix, Quaternion, Vector++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++CANON = { # normalized core name -> canonical body part+ "hips": "hips", "pelvis": "hips", "root": None, "neck": "neck", "head": "head",+ "shoulder": "shoulder", "clavicle": "shoulder", "collar": "shoulder",+ "upperarm": "upperarm", "arm": "upperarm", "uparm": "upperarm",+ "forearm": "forearm", "lowerarm": "forearm", "elbow": "forearm",+ "hand": "hand", "wrist": "hand",+ "thigh": "thigh", "upleg": "thigh", "upperleg": "thigh", "hip": "thigh",+ "shin": "shin", "leg": "shin", "calf": "shin", "lowerleg": "shin", "knee": "shin",+ "foot": "foot", "ankle": "foot", "toe": "toe", "toebase": "toe", "toes": "toe", "ball": "toe",+}+SPINE = re.compile(r"^(spine\d*|chest|upperchest|torso|abdomen|back)$")+++def _split(name):+ """'mixamorig:LeftUpLeg' -> ('upleg', 'L'); 'DEF-upper_arm.L' -> ('upperarm', 'L')."""+ n = re.sub(r"^(mixamorig\d*:|def[-_]|org[-_]|cc_base_|bip0?1[ _]?|b_|bn_)", "", name.lower())+ side = ""+ for pat, s in ((r"(^left|left$|^l[_.]|[_.]l$|\.l\.|_l_)", "L"), (r"(^right|right$|^r[_.]|[_.]r$|\.r\.|_r_)", "R")):+ if re.search(pat, n):+ side = s+ n = re.sub(pat, "", n)+ break+ n = n.replace("left", "").replace("right", "")+ core = re.sub(r"[^a-z0-9]", "", n)+ core = re.sub(r"0+(\d)", r"\1", core) # spine.001 -> spine1+ return core, side+++def _parts(arm):+ """{(part, side): bone}, plus the spine chain (hips -> neck order)."""+ out, spine = {}, []+ for b in arm.data.bones:+ core, side = _split(b.name)+ if SPINE.match(core):+ spine.append(b)+ continue+ part = CANON.get(core) or CANON.get(re.sub(r"\d+$", "", core))+ if part and (part, side) not in out:+ out[(part, side)] = b.name+ spine.sort(key=lambda b: len(b.parent_recursive))+ return out, [b.name for b in spine]+++def auto_map(src, tgt):+ sp, ss = _parts(src)+ tp, ts = _parts(tgt)+ m = {tb: sp[k] for k, tb in tp.items() if k in sp}+ for i, tb in enumerate(ts): # spine chains of different lengths map proportionally+ if ss:+ m[tb] = ss[round(i * (len(ss) - 1) / max(1, len(ts) - 1))]+ sn = {_split(b.name): b.name for b in src.data.bones}+ for b in tgt.data.bones: # same normalized name (fingers, extras) maps directly+ if b.name not in m and _split(b.name) in sn:+ m[b.name] = sn[_split(b.name)]+ hips = tp.get(("hips", ""))+ return m, hips+++def _rot(mat):+ return mat.to_3x3().normalized().to_quaternion()+++def run(source=None, target=None, map="auto", frames=None, in_place=False, name=None, show_map=False, **_):+ bx.object_mode()+ if not source or not target:+ raise ValueError("--source and --target are required")+ src, tgt = bpy.data.objects[source], bpy.data.objects[target]+ if map == "auto":+ bmap, hips = auto_map(src, tgt)+ else:+ with open(bpy.path.abspath(map), encoding="utf-8") as f:+ bmap = json.load(f)+ hips = auto_map(src, tgt)[1]+ hips = hips if hips in bmap else None+ bmap = {t: s for t, s in bmap.items() if t in tgt.data.bones and s in src.data.bones}+ key_parts = ("hips", "upperarm", "forearm", "thigh", "shin", "head")+ tparts = _parts(tgt)[0]+ missing = sorted(f"{p}{'.' + sd if sd else ''}" for (p, sd), b in tparts.items() if p in key_parts and b not in bmap)+ if show_map:+ return {"ok": True, "map": bmap, "hips": hips, "unmapped_key_parts": missing}+ if not bmap:+ raise ValueError("no bones mapped: pass --map map.json {target_bone: source_bone}")+ act_src = src.animation_data.action if src.animation_data else None+ if frames:+ f0, f1 = int(frames[0]), int(frames[1])+ elif act_src:+ f0, f1 = (int(round(v)) for v in act_src.frame_range)+ else:+ raise ValueError("source has no action: pass --frames")+ tw_rot = _rot(tgt.matrix_world)+ order = sorted(tgt.data.bones, key=lambda b: len(b.parent_recursive)) # parents first+ rest_rel = {b.name: (b.parent.matrix_local.inverted() @ b.matrix_local if b.parent else b.matrix_local.copy())+ for b in order}+ t_rest_w = {b: _rot(tgt.matrix_world @ tgt.data.bones[b].matrix_local) for b in bmap}+ sc = bpy.context.scene+ sc.frame_set(f0)+ s_rest_w = {s: _rot(src.matrix_world @ src.data.bones[s].matrix_local) for s in bmap.values()}+ ratio = 1.0+ if hips:+ sh = (src.matrix_world @ src.data.bones[bmap[hips]].head_local).z+ th = (tgt.matrix_world @ tgt.data.bones[hips].head_local).z+ ratio = th / sh if abs(sh) > 1e-6 else 1.0+ s_hips_rest = src.matrix_world @ src.data.bones[bmap[hips]].head_local+ t_hips_rest = tgt.matrix_world @ tgt.data.bones[hips].head_local+ keys = {b: [] for b in bmap}+ locs = []+ err = 0.0+ for f in range(f0, f1 + 1):+ sc.frame_set(f)+ pose = {}+ for b in order:+ M_parent = pose.get(b.parent.name, Matrix.Identity(4)) if b.parent else Matrix.Identity(4)+ base = M_parent @ rest_rel[b.name]+ if b.name not in bmap:+ pose[b.name] = base+ continue+ s = bmap[b.name]+ sw = _rot(src.matrix_world @ src.pose.bones[s].matrix)+ dw = sw @ s_rest_w[s].inverted() @ t_rest_w[b.name] # source's change from rest, on our rest+ da = tw_rot.inverted() @ dw+ lq = _rot(base).inverted() @ da+ prev = keys[b.name][-1][1] if keys[b.name] else None+ if prev is not None and lq.dot(prev) < 0:+ lq.negate() # keep quaternions continuous for linear interpolation+ loc = Vector()+ if b.name == hips and not in_place:+ hs = src.matrix_world @ src.pose.bones[s].head+ want_w = t_hips_rest + (hs - s_hips_rest) * ratio+ want_a = tgt.matrix_world.inverted() @ want_w+ loc = base.to_3x3().inverted() @ (want_a - base.translation)+ locs.append((f, loc.copy()))+ pose[b.name] = base @ Matrix.Translation(loc) @ lq.to_matrix().to_4x4()+ keys[b.name].append((f, lq))+ got = tw_rot @ _rot(pose[b.name])+ a = (got @ t_rest_w[b.name].inverted()).rotation_difference(sw @ s_rest_w[s].inverted()).angle+ err = max(err, math.degrees(min(a, 2 * math.pi - a))) # q and -q are the same rotation+ name = name or (act_src.name if act_src else "Retarget")+ act = bpy.data.actions.new(f"{tgt.name}|{name}")+ act.use_fake_user = True+ tgt.animation_data_create()+ tgt.animation_data.action = act+ slot = tgt.animation_data.action_slot or act.slots.new(id_type="OBJECT", name=tgt.name)+ tgt.animation_data.action_slot = slot+ cb = anim_utils.action_ensure_channelbag_for_slot(act, slot)++ def write(path, idx, group, pts):+ fc = cb.fcurves.ensure(path, index=idx, group_name=group)+ fc.keyframe_points.add(len(pts))+ fc.keyframe_points.foreach_set("co", [v for p in pts for v in p])+ fc.keyframe_points.foreach_set("interpolation", [bpy.types.Keyframe.bl_rna.properties["interpolation"].enum_items["LINEAR"].value] * len(pts))+ fc.update()+ for b, ks in keys.items():+ tgt.pose.bones[b].rotation_mode = "QUATERNION"+ for i in range(4):+ write(f'pose.bones["{b}"].rotation_quaternion', i, b, [(f, q[i]) for f, q in ks])+ if locs:+ for i in range(3):+ write(f'pose.bones["{hips}"].location', i, hips, [(f, v[i]) for f, v in locs])+ sc.frame_set(f0)+ return {"ok": True, "action": act.name, "frames": [f0, f1], "mapped": len(bmap), "hips": hips,+ "hips_scale": round(ratio, 4), "unmapped_key_parts": missing, "max_error_deg": round(err, 3)}+++if __name__ == "__main__":+ p = bx.parser(__doc__)+ p.add_argument("--source", required=True)+ p.add_argument("--target", required=True)+ p.add_argument("--map", default="auto", help="auto or JSON file {target_bone: source_bone}")+ p.add_argument("--frames", type=int, nargs=2, default=None)+ p.add_argument("--in-place", action="store_true", help="no hips translation")+ p.add_argument("--name", default=None)+ p.add_argument("--show-map", 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.mdindex b0b9073..992ea8e 100644--- a/skills/blender-asset-qa/SKILL.md+++ b/skills/blender-asset-qa/SKILL.md@@ -1,10 +1,10 @@---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.+description: Mandatory review gate for any mesh or asset created or edited in Blender. Detects z-fighting, floating/detached parts, inverted or inconsistent normals, non-manifold/open geometry, degenerate faces, duplicate verts, n-gons, unapplied scale, UV problems, bad skin weights, material/texture errors, and renders multi-angle review sheets. Use before calling any modeling, export or delivery task done.license: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Asset QA (review gate)@@ -37,8 +37,12 @@ Never assume a generated or edited mesh is correct. Check it with numbers, then| `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`) |+| unweighted / >4 influences | skinning | `blender-character-rigging` (`rig_check.py`) || `ground_z` ≠ 0 | asset floats or sinks | move the origin to the bottom and set z = 0 (props) |+| faces on empty/missing slot | material removed or index out of range | assign a material; engines show grey/magenta |+| `feeds [...] but is sRGB` | normal/roughness/metal/AO map tagged as color | `image.colorspace_settings.is_data = True` (Non-Color) |+| missing texture file | broken path, unpacked | relink (`blender-scene-setup` path cleanup) or pack |+| unused slot / Non-Color base color | leftovers, wrong tag | remove the slot; base color and emission are sRGB |## 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`).@@ -46,7 +50,7 @@ Never assume a generated or edited mesh is correct. Check it with numbers, then- **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.+- **Material assignment**: slots and color spaces are checked automatically. Still look at whether each part got the *intended* material.## 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.diff --git a/skills/blender-asset-qa/scripts/qa_check.py b/skills/blender-asset-qa/scripts/qa_check.pyindex 8f14bb0..e6d7a5b 100644--- a/skills/blender-asset-qa/scripts/qa_check.py+++ b/skills/blender-asset-qa/scripts/qa_check.py@@ -1,4 +1,5 @@-"""Mesh/asset QA: z-fighting, detached parts, normals, topology, transforms, UVs, weights.+"""Mesh/asset QA: z-fighting, detached parts, normals, topology, transforms, UVs, weights, materials+(faces on empty slots, unused slots, missing texture files, data maps set to sRGB).Pass the objects of ONE asset (they are checked together: islands far from all others = floating).Usage:@@ -23,15 +24,69 @@ 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"),+ # zfight floating inverted inconsist nonmanif boundary degen dupes ngons scale uv weights materials+ "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", mt="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", mt="e"),+ "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, mt=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", mt="e"),}TRI_LIMIT = {"roblox": 20000}+DATA_INPUTS = {"Roughness", "Metallic", "Normal", "Alpha", "Specular IOR Level", "Coat Weight", "Coat Roughness",+ "Transmission Weight", "Subsurface Weight", "Anisotropic", "Sheen Weight", "IOR"}+DATA_NODES = {"NORMAL_MAP", "BUMP", "DISPLACEMENT", "VECTOR_DISPLACEMENT"}+++def _feeds(sock, depth=4):+ """(node type, input name) pairs a socket reaches through up to `depth` nodes."""+ out = set()+ for lk in sock.links:+ n = lk.to_node+ out.add((n.type, lk.to_socket.name))+ if depth and n.type not in DATA_NODES and n.type != "BSDF_PRINCIPLED":+ for o in n.outputs:+ out |= _feeds(o, depth - 1)+ return out+++def _material_issues(ob):+ """[(severity_is_error, message)] for slots, faces and image textures."""+ me, slots, out = ob.data, ob.material_slots, []+ idx = [0] * len(me.polygons)+ me.polygons.foreach_get("material_index", idx)+ used = set(idx)+ bad = sorted(i for i in used if i >= len(slots) or slots[i].material is None)+ if bad or not slots:+ out.append((True, f"{ob.name}: faces use empty/missing material slot(s) {bad or [0]} (grey in engines)"))+ unused = [s.name or str(i) for i, s in enumerate(slots) if i not in used]+ if unused:+ out.append((False, f"{ob.name}: unused material slot(s) {unused} (extra draw calls in some exporters)"))+ for i in sorted(used):+ mat = slots[i].material if i < len(slots) else None+ if mat is None or not mat.node_tree:+ continue+ for n in mat.node_tree.nodes:+ if n.type != "TEX_IMAGE":+ continue+ img = n.image+ if img is None:+ if n.outputs["Color"].is_linked or n.outputs["Alpha"].is_linked:+ out.append((False, f"{mat.name}: image node {n.name!r} has no image"))+ continue+ if img.source == "FILE" and not img.packed_file and not os.path.exists(bpy.path.abspath(img.filepath)):+ out.append((True, f"{mat.name}: missing texture file {img.filepath!r}"))+ reach = _feeds(n.outputs["Color"])+ data_use = sorted({s for t, s in reach if t == "BSDF_PRINCIPLED" and s in DATA_INPUTS}+ | {t.lower() for t, _s in reach if t in DATA_NODES})+ if data_use and not img.colorspace_settings.is_data:+ out.append((True, f"{mat.name}: {img.name} feeds {data_use} but is {img.colorspace_settings.name} "+ "(must be Non-Color)"))+ if img.colorspace_settings.is_data and ("BSDF_PRINCIPLED", "Base Color") in reach:+ out.append((False, f"{mat.name}: {img.name} is Non-Color but drives Base Color (looks washed out)"))+ return out++def _mesh_world(ob, use_mods):"""bmesh of the (evaluated) object in world space, triangulated copy kept separately."""bm = bmesh.new()@@ -193,8 +248,11 @@ def run(objects=None, profile="game", eps=0.001, tol=0.002, no_modifiers=False,errors.append(f"{ob.name}: negative scale (flips normals on export)")# materialsm["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")+ for is_err, msg in _material_issues(ob):+ if is_err:+ flag("mt", msg)+ else:+ warnings.append(msg)# weightsarm_mod = next((md for md in ob.modifiers if md.type == "ARMATURE" and md.object), None)if arm_mod and ob.vertex_groups:diff --git a/skills/blender-character-rigging/SKILL.md b/skills/blender-character-rigging/SKILL.mdindex e7c4fea..a3d3277 100644--- a/skills/blender-character-rigging/SKILL.md+++ b/skills/blender-character-rigging/SKILL.md@@ -4,7 +4,7 @@ description: Character rigging in Blender 5.2 - Rigify metarig fit/generate, bonlicense: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Character Riggingdiff --git a/skills/blender-clothing/SKILL.md b/skills/blender-clothing/SKILL.mdnew file mode 100644index 0000000..6f1f3a8--- /dev/null+++ b/skills/blender-clothing/SKILL.md@@ -0,0 +1,47 @@+---+name: blender-clothing+description: Game clothing in Blender 5.2 - garments from body regions (ease offset, thickness), skin-weight transfer, hiding covered body faces, cloth-sim draping for folds, body-morph shape keys on garments, layered clothing, pose-aware poke-through checks, sim-to-game-mesh cleanup. Use for shirts, pants, armor, outfits, layered or swappable clothing.+license: MIT+metadata:+ author: blender-agent-skills+ version: "1.2.0"+---++# Clothing++The execution model is in `blender-core`. The rig and weights are in `blender-character-rigging`, classic cloth settings in `blender-simulation`, and Roblox layered clothing cages in `blender-export-pipelines` (references/roblox.md).++## One call each+```+scripts/garment.py -- --body Body --group Torso --name Shirt --hide-body+scripts/garment.py -- --body Body --zmin 0.45 --zmax 1.05 --name Pants --offset 0.01 --drape 40 --morphs+scripts/garment.py -- --body Body --group Torso --name Armor --offset 0.02 --thickness 0.008+scripts/garment.py -- --check Shirt --body Body # pose the rig first: checks the current pose+```++## How pros build game clothing+1. **Shape**: start from the body (extract + offset) for fitted clothes, or from flat patterns sewn by cloth sim (Marvelous Designer or Blender cloth with sewing springs) for loose ones. Simulate on the body in its **rest pose** (A/T).+2. **Game mesh**: retopo the high/sim result to clean, even quads with loops at the joints (elbows, knees, shoulders get 3 loops), then UV it. Bake folds into normal maps (`blender-texture-baking`) so the low mesh stays light.+3. **Skin**: copy weights from the body (same bones, same influences), clean them (limit 4, normalize, drop < 0.001), then blend toward smoother weights only on loose parts (skirts, coats) and add extra bones for those.+4. **Hide what's covered**: delete body faces under the garment (save tris, stop poke-through) or mask them per outfit. Keep one ring of skin under cuffs and collars.+5. **Verify in motion**: stress poses (`blender-character-rigging` `stress_poses.py`), then `--check` in each. Fix by easing (offset), smoothing the body there, weight tweaks, or hiding.++## garment.py+- Region: `--group` (body vertex group, weight > 0.5) or a world `--zmin/--zmax` band. The faces are copied in world space and pushed out along the vertex normals by `--offset` (ease: 5–10 mm fitted cotton, 10–20 mm jackets, 15–30 mm armor). Then `Solidify` adds `--thickness` (2–4 mm fabric, 5–10 mm leather/armor), growing outward. UVs carry over from the body.+- Weights: Data Transfer (`POLYINTERP_NEAREST`, all groups by name), applied, limited to `--max-influences`, normalized and cleaned. The body's Armature modifier is added and parented to the rig.+- `--hide-body`: `Hidden_<name>` vertex group (the region shrunk by one ring) + an inverted Mask modifier on the body. Swappable outfits toggle masks. For export, delete those faces on a body copy instead.+- `--drape N`: classic cloth (cotton-ish: mass 0.15, tension 15, bending 0.5, quality 8). The top 8% is pinned, the body collides at 3 mm, it settles N frames, then the result is applied. That gives gravity folds on loose areas. Use 30–60 frames.+- `--morphs`: for each body shape key, a same-named garment shape key, via Surface Deform bound in the rest pose and applied as a shape key per morph. Engines drive body and garment keys together (fat/thin, muscle, breathing). Measured: a 30% body morph pokes through 346 verts. With the matching garment key, 0.+- **Poke check** (also run at the end of every build): casts along each body vertex normal. If the garment is hit inward before outward (or sits < 0.5 mm away), it's poke-through. Verts that hit no garment within 0.1 m aren't covered and are ignored. It reports `covered_verts`, `poke_verts` and `poke_max_m`, uses the **evaluated** pose, and respects the body masks.++## Layered clothing+- Order from the skin out: underwear/base → shirt → vest → jacket → armor. Each layer offsets from the one below (run `garment.py --body Shirt` for a vest over the shirt) and copies weights from the body, not from the layer below.+- Interpenetration between layers in motion usually comes from mismatched weights. Copying all layers from the same body keeps them moving together.+- Roblox layered clothing needs `<Name>_InnerCage` + `<Name>_OuterCage` built from Roblox's template cages (same vert order/UVs). Other engines (UE Mutable/Unity) blend shape keys or use body-hiding masks. Same principle.++## Gotchas+- `shape_key_add()` creates keys at value 1.0 (measured). Set `.value = 0` when authoring morphs from Python.+- Surface Deform for **morphs only**: if left live together with an Armature modifier, the pose is applied twice. `--morphs` removes it after baking the keys.+- Apply the body's scale before building. Offsets and thickness are in meters.+- Cloth sims need the body's collision mesh at a modest resolution. Decimate a proxy for the collision if the body is > 50k verts.+- Run `blender-asset-qa` on the final garment (z-fighting with the body, floating parts, normals) and check its tris against `blender-game-optimization` budgets.diff --git a/skills/blender-clothing/scripts/_bpyx.py b/skills/blender-clothing/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-clothing/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-clothing/scripts/garment.py b/skills/blender-clothing/scripts/garment.pynew file mode 100644index 0000000..b18d846--- /dev/null+++ b/skills/blender-clothing/scripts/garment.py@@ -0,0 +1,260 @@+"""Game clothing from a body: extract a region as a garment shell (ease offset + thickness), copy the+body's skin weights so it deforms with the rig, mask the body faces it hides, optionally drape it with+a cloth sim for folds, copy body shape keys as matching garment keys (--morphs), and measure body poke-through in the current pose.++Region: a body vertex group (--group) or a world Z band (--zmin/--zmax). Weights: Data Transfer+(nearest face, interpolated) from the body, limited to --max-influences and normalized, plus the+body's Armature modifier. --hide-body adds a Mask modifier that hides covered body faces (delete them+on export for games). --check measures penetration: body verts in front of the garment's inner+surface, evaluated in the current pose (pose the rig, then check).+Usage:+ blender -b f.blend -P garment.py -- --body Body (--group Torso | --zmin 1.0 --zmax 1.5) [--name Shirt]+ [--offset 0.008] [--thickness 0.003] [--subdiv 0] [--max-influences 4] [--hide-body]+ [--drape 0] [--morphs] [--save out.blend]+ blender -b f.blend -P garment.py -- --check Shirt --body Body+ MCP: import garment; print(garment.run(body="Body", zmin=1.0, zmax=1.5, name="Shirt", hide_body=True))+"""+import os+import sys++import bmesh+import bpy+import numpy as np+from mathutils import Vector++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402+++def _region(body, group, zmin, zmax):+ me = body.data+ if group:+ if group not in body.vertex_groups:+ raise KeyError(f"vertex group {group!r} not on {body.name}")+ gi = body.vertex_groups[group].index+ return {v.index for v in me.vertices if any(g.group == gi and g.weight > 0.5 for g in v.groups)}+ if zmin is None or zmax is None:+ raise ValueError("give --group or both --zmin and --zmax")+ mw = body.matrix_world+ return {v.index for v in me.vertices if zmin <= (mw @ v.co).z <= zmax}+++def _shell(body, verts, name, offset):+ """Copy the region's faces in world space and push them out along the vertex normals."""+ bm = bmesh.new()+ bm.from_mesh(body.data)+ bm.transform(body.matrix_world)+ bm.normal_update()+ drop = [f for f in bm.faces if not all(v.index in verts for v in f.verts)]+ bmesh.ops.delete(bm, geom=drop, context="FACES")+ for v in bm.verts:+ v.co += v.normal * offset+ me = bpy.data.meshes.new(name)+ bm.to_mesh(me)+ bm.free()+ ob = bpy.data.objects.get(name)+ if ob is None:+ ob = bpy.data.objects.new(name, me)+ bpy.context.scene.collection.objects.link(ob)+ else:+ ob.data = me+ ob.matrix_world.identity()+ return ob+++def _transfer_weights(garment, body, max_inf):+ for vg in body.vertex_groups:+ if vg.name not in garment.vertex_groups:+ garment.vertex_groups.new(name=vg.name)+ dt = garment.modifiers.new("Weights", "DATA_TRANSFER")+ dt.object, dt.use_object_transform = body, True+ dt.use_vert_data, dt.data_types_verts = True, {"VGROUP_WEIGHTS"}+ dt.vert_mapping = "POLYINTERP_NEAREST"+ dt.layers_vgroup_select_src, dt.layers_vgroup_select_dst = "ALL", "NAME"+ bx.select_only([garment])+ with bpy.context.temp_override(object=garment, active_object=garment):+ bpy.ops.object.modifier_move_to_index(modifier=dt.name, index=0)+ bpy.ops.object.modifier_apply(modifier=dt.name)+ bpy.ops.object.vertex_group_limit_total(group_select_mode="ALL", limit=max_inf)+ bpy.ops.object.vertex_group_normalize_all(group_select_mode="ALL", lock_active=False)+ bpy.ops.object.vertex_group_clean(group_select_mode="ALL", limit=0.001)+++def _hide_body(body, verts, name, inset=1):+ """Vertex group of body verts strictly inside the covered region (shrunk `inset` rings) + Mask."""+ me = body.data+ keep = set(verts)+ for _ in range(inset): # don't hide the border ring: avoids gaps at cuffs/collars+ border = {v for e in me.edges for v in e.vertices if (e.vertices[0] in keep) != (e.vertices[1] in keep)}+ keep -= border+ gname = f"Hidden_{name}"+ vg = body.vertex_groups.get(gname) or body.vertex_groups.new(name=gname)+ vg.remove(range(len(me.vertices)))+ vg.add(sorted(keep), 1.0, "REPLACE")+ md = body.modifiers.get(gname) or body.modifiers.new(gname, "MASK")+ md.vertex_group, md.invert_vertex_group = gname, True+ return gname, len(keep)+++def _drape(garment, body, frames, pin_frac=0.08):+ """Classic cloth: pin the top band, collide with the body, settle `frames`, apply the result."""+ me = garment.data+ zs = np.array([(garment.matrix_world @ v.co).z for v in me.vertices])+ top = zs.max() - (zs.max() - zs.min()) * pin_frac+ pin = garment.vertex_groups.get("Pin") or garment.vertex_groups.new(name="Pin")+ pin.add([i for i, z in enumerate(zs) if z >= top], 1.0, "REPLACE")+ cl = garment.modifiers.new("Drape", "CLOTH")+ s = cl.settings+ s.quality, s.mass, s.tension_stiffness, s.bending_stiffness = 8, 0.15, 15.0, 0.5 # cotton-ish+ s.vertex_group_mass = "Pin"+ cl.collision_settings.distance_min = 0.003+ cl.collision_settings.use_self_collision = False+ added = body.collision is None or not any(m.type == "COLLISION" for m in body.modifiers)+ if added:+ body.modifiers.new("Collision", "COLLISION")+ body.collision.thickness_outer = 0.003+ sc = bpy.context.scene+ cl.point_cache.frame_start, cl.point_cache.frame_end = sc.frame_current, sc.frame_current + frames+ f0 = sc.frame_current+ for f in range(f0, f0 + frames + 1):+ sc.frame_set(f)+ bx.select_only([garment])+ with bpy.context.temp_override(object=garment, active_object=garment):+ bpy.ops.object.modifier_apply(modifier=cl.name)+ sc.frame_set(f0)+ if added:+ body.modifiers.remove(body.modifiers["Collision"])+ if "Pin" in garment.vertex_groups: # re-fetch: modifier_apply invalidates the old reference+ garment.vertex_groups.remove(garment.vertex_groups["Pin"])+++def transfer_morphs(garment, body):+ """Same-named garment shape key for every body shape key (Surface Deform bound at rest, applied as+ shape key per morph), so engines drive body and garment morphs together."""+ keys = body.data.shape_keys+ if keys is None or len(keys.key_blocks) < 2:+ return []+ arm = next((m.object for m in body.modifiers if m.type == "ARMATURE" and m.object), None)+ prev_pos = arm.data.pose_position if arm else None+ if arm:+ arm.data.pose_position = "REST"+ vals = {kb.name: kb.value for kb in keys.key_blocks}+ for kb in keys.key_blocks:+ kb.value = 0.0+ sd = garment.modifiers.new("FollowBody", "SURFACE_DEFORM")+ sd.target = body+ bx.select_only([garment])+ done = []+ with bpy.context.temp_override(object=garment, active_object=garment):+ bpy.ops.object.modifier_move_to_index(modifier=sd.name, index=0)+ bpy.context.view_layer.update()+ bpy.ops.object.surfacedeform_bind(modifier=sd.name)+ if garment.data.shape_keys is None:+ garment.shape_key_add(name="Basis", from_mix=False)+ for kb in keys.key_blocks[1:]:+ kb.value = 1.0+ bpy.context.view_layer.update()+ bpy.ops.object.modifier_apply_as_shapekey(modifier=sd.name, keep_modifier=True)+ gk = garment.data.shape_keys.key_blocks[-1]+ gk.name, gk.value = kb.name, 0.0 # applied keys come in at 1+ kb.value = 0.0+ done.append(kb.name)+ bpy.ops.object.modifier_remove(modifier=sd.name)+ for kb in keys.key_blocks:+ kb.value = vals[kb.name]+ if arm:+ arm.data.pose_position = prev_pos+ return done+++def penetration(garment, body, tol=0.0005, reach=0.1):+ """Body verts (evaluated pose) poking through: casting along the body normal, the garment is hit+ inward (behind the skin) before outward, or sits closer than tol. Verts that hit nothing within+ reach either way aren't covered by this garment (head, hands, legs) and are ignored."""+ dg = bpy.context.evaluated_depsgraph_get()+ ge, be = garment.evaluated_get(dg), body.evaluated_get(dg)+ bme = be.to_mesh()+ try:+ ginv, bmw = garment.matrix_world.inverted(), body.matrix_world+ gdir, nmat = ginv.to_3x3(), bmw.to_3x3().inverted().transposed()+ n_in, worst, covered = 0, 0.0, 0+ for v in bme.vertices:+ p = ginv @ (bmw @ v.co)+ n = (gdir @ (nmat @ v.normal)).normalized()+ hit_o, loc_o, _n, _i = ge.ray_cast(p, n, distance=reach)+ hit_i, loc_i, _n, _i = ge.ray_cast(p, -n, distance=reach)+ d_o = (loc_o - p).length if hit_o else None+ d_i = (loc_i - p).length if hit_i else None+ if d_o is None and d_i is None:+ continue+ covered += 1+ if d_i is not None and (d_o is None or d_i < d_o):+ n_in += 1+ worst = max(worst, d_i)+ elif d_o < tol:+ n_in += 1+ return {"covered_verts": covered, "poke_verts": n_in, "poke_max_m": round(worst, 5)}+ finally:+ be.to_mesh_clear()+++def run(body=None, group=None, zmin=None, zmax=None, name="Garment", offset=0.008, thickness=0.003, subdiv=0,+ max_influences=4, hide_body=False, drape=0, morphs=False, check=None, **_):+ bx.object_mode()+ if not body:+ raise ValueError("--body is required")+ bod = bpy.data.objects[body]+ if check:+ return {"ok": True, "garment": check, **penetration(bpy.data.objects[check], bod)}+ verts = _region(bod, group, zmin, zmax)+ if not verts:+ raise ValueError("region is empty")+ g = _shell(bod, verts, name, offset)+ res = {"ok": True, "garment": g.name, "region_verts": len(verts), "offset_m": offset, "thickness_m": thickness}+ arm = next((m.object for m in bod.modifiers if m.type == "ARMATURE" and m.object), None)+ if bod.vertex_groups:+ _transfer_weights(g, bod, max_influences)+ res["vertex_groups"] = len(g.vertex_groups)+ if subdiv:+ sd = g.modifiers.new("Subdiv", "SUBSURF")+ sd.levels = sd.render_levels = subdiv+ if drape:+ _drape(g, bod, int(drape))+ res["draped_frames"] = int(drape)+ if morphs:+ res["morphs"] = transfer_morphs(g, bod)+ if thickness > 0:+ so = g.modifiers.new("Thickness", "SOLIDIFY")+ so.thickness, so.offset, so.use_even_offset, so.use_quality_normals = thickness, 1.0, True, True+ if arm is not None:+ am = g.modifiers.new("Armature", "ARMATURE")+ am.object = arm+ g.parent = arm+ g.matrix_parent_inverse = arm.matrix_world.inverted()+ res["armature"] = arm.name+ if hide_body:+ res["hidden_group"], res["hidden_verts"] = _hide_body(bod, verts, name)+ bpy.context.view_layer.update()+ res.update(penetration(g, bod))+ if res["poke_verts"]:+ res["warning"] = "body pokes through: raise --offset, smooth the body there, or --hide-body"+ return res+++if __name__ == "__main__":+ p = bx.parser(__doc__)+ p.add_argument("--body", required=True)+ p.add_argument("--group", default=None)+ p.add_argument("--zmin", type=float, default=None)+ p.add_argument("--zmax", type=float, default=None)+ p.add_argument("--name", default="Garment")+ p.add_argument("--offset", type=float, default=0.008, help="ease: gap to the skin (m)")+ p.add_argument("--thickness", type=float, default=0.003, help="cloth thickness (m)")+ p.add_argument("--subdiv", type=int, default=0)+ p.add_argument("--max-influences", type=int, default=4)+ p.add_argument("--hide-body", action="store_true")+ p.add_argument("--drape", type=int, default=0, help="cloth-sim frames to settle folds (0 = off)")+ p.add_argument("--morphs", action="store_true", help="copy body shape keys as garment shape keys")+ p.add_argument("--check", default=None, help="garment to measure against --body")+ p.add_argument("--save", default=None)+ bx.cli(run, p)diff --git a/skills/blender-core/SKILL.md b/skills/blender-core/SKILL.mdindex 44128f8..9aeacc3 100644--- a/skills/blender-core/SKILL.md+++ b/skills/blender-core/SKILL.md@@ -5,7 +5,7 @@ license: MITcompatibility: Blender 5.2 LTS or newer. Optional blender-mcp server for live sessions.metadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Blender Core (5.2 LTS+)@@ -18,15 +18,21 @@ metadata:| Sculpting, multires, remesh | `blender-sculpting` || Retopology, UV unwrap, texel density | `blender-retopology-uv` || PBR materials, color spaces, texture sets | `blender-pbr-materials` |+| Wear, grime, dust, decals, trim sheets, texture painting | `blender-texturing` || 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` |+| Keyframes, actions, NLA, mocap retarget, loops, root motion | `blender-animation` |+| Garments, layered clothing, body poke-through | `blender-clothing` |+| Hair, fur, grooming, hair cards | `blender-hair-grooming` || 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` |+| Toon/cel/anime shading, outlines, Line Art, Grease Pencil | `blender-stylized-npr` |+| Terrain, biome scatter, modular kits | `blender-environment-kits` |+| Video editing (VSE), motion tracking, camera solve | `blender-video-editing` || Time of day, night, sunset, fog, mood (cyberpunk, horror...) | `blender-time-of-day` || Rain, snow, wet surfaces, puddles, lightning, dust/embers | `blender-weather-fx` || Cloth, rigid body, fluids, hair, GN physics | `blender-simulation` |diff --git a/skills/blender-core/references/api-changes-5x.md b/skills/blender-core/references/api-changes-5x.mdindex dd6df3b..1df3a97 100644--- a/skills/blender-core/references/api-changes-5x.md+++ b/skills/blender-core/references/api-changes-5x.md@@ -1,6 +1,6 @@# 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).+Each row was verified against Blender 5.2.3. Format: **old → new** (version).## Core / properties| Old | New |diff --git a/skills/blender-environment-kits/SKILL.md b/skills/blender-environment-kits/SKILL.mdnew file mode 100644index 0000000..1e04149--- /dev/null+++ b/skills/blender-environment-kits/SKILL.md@@ -0,0 +1,47 @@+---+name: blender-environment-kits+description: Game environments in Blender 5.2 - terrain from noise or heightmaps (erosion, terraces, play areas, slope/height materials, 16-bit heightmaps + splat maps for UE/Unity), biome scatter by slope/height/mask with Poisson spacing, modular kit metrics and validation (grid, pivots, seams, texel density). Use for levels, landscapes, forests, modular buildings, dungeons.+license: MIT+metadata:+ author: blender-agent-skills+ version: "1.2.0"+---++# Environment kits++The execution model is in `blender-core`. Custom GN tools are in `blender-geometry-nodes`, materials in `blender-texturing` (trims, vertex blends), and mood/weather in `blender-time-of-day`/`blender-weather-fx`.++## One call each+```+scripts/terrain.py -- --size 400 --res 513 --height 60 --type ridged --erosion 30 --flatten 0 0 40 --material+scripts/terrain.py -- --heightmap //hm.png --size 1000 --res 1009 --height 120 --export-splat //T_Splat.png+scripts/scatter.py -- --target Terrain --collection Trees --density 0.02 --min-distance 5 --max-slope 25 --height-max 45+scripts/scatter.py -- --target Terrain --collection Rocks --density 0.05 --max-slope 70 --align 0.8 --name ENV_Rocks+scripts/kit_check.py -- --objects SM_Wall_4m SM_Floor_4m SM_Door_4m --grid 0.5 --fix+```++## Terrain (terrain.py)+- Grid of `--res`² verts over `--size` m. Use **2^n + 1** for Unity (513/1025/2049, `.raw` 16-bit LE) and UE Landscape's recommended sizes (505/1009/2017/4033, 16-bit PNG). Above 1025, tile it.+- `--type fbm` (rolling), `ridged` (mountains), `hills` (hetero terrain). `--scale` = feature size m. `--erosion N` = thermal erosion steps (talus 33°): slopes relax and debris fills valleys. `--terrace` m = stepped flats. `--flatten X Y R` = a level play/build area blended back with a smoothstep.+- Writes `ENV_Slope` (deg/90) and `ENV_Height` (0–1) point attributes. `--material` builds grass/rock/snow from them: rock above 35°, snow above 75% height on slopes below ~40°, with noise-broken edges.+- Engines: `--export-heightmap` (PNG = 16-bit gray, `.raw` = 16-bit little-endian, row 0 = −Y edge; flip vertically in Unity if mirrored) plus `heightmap_z_scale_m` for the import Z scale. `--export-splat` = 16-bit RGBA weights (R grass, G rock, B snow, sum 1) for terrain layers. Both are written Raw (no display transform): measured round-trip error < 0.001.++## Scatter (scatter.py)+- One GN modifier per layer: Poisson disk (`--density` per m² max, `--min-distance` m), kept where the **interpolated surface normal** is within `--max-slope` and Z is inside `--height-min/max` (object space). `--mask` = vertex group or float attribute as density factor (paint it, or use `ENV_Height`).+- Collection children are instanced at their own origins with random yaw, `--scale` range, and `--align` (0 = upright trees, 0.6–1 = rocks hugging the slope). The source collection is excluded from the view layer.+- The result checks every instance against the real surface (`slope_max_deg`, `height_range`) and counts per source. Instances stay instances. `--realize` only when an exporter or boolean needs real mesh.+- Densities: forest trees 0.01–0.05/m² (min distance 4–8 m), bushes 0.05–0.2, rocks 0.01–0.1, grass clumps 2–20/m² (near camera only). Layer big → small: trees, then bushes masked away from trunks, then grass.+- Engines: glTF `export_gpu_instances=True` (EXT_mesh_gpu_instancing), or `--export-points file.json` (world transforms, Z-up m, wxyz quats) for UE foliage/PCG or Unity instancing scripts. FBX needs realized geometry or one object per instance.++## Modular kits (kit_check.py)+- **Metrics first**: pick a grid (0.5 m snap, 1/2/4 m modules) and keep it everywhere. Walls 3–4 m tall interior (player ~1.8 m eye 1.6 m, doors ≥ 1 × 2.2 m), floors 4 × 4 m, stairs 0.18 m rise / 0.28 m run. UE works in cm (×100 on import), Unity in m.+- **Pivot** convention (`--pivot corner` default, `bottom-center`, `center`) so pieces snap by increments. Footprint lengths are multiples of the grid. Thinner-than-a-cell dims (wall thickness, trims) may be off-grid.+- Open edges only on the piece's outer faces (seams); holes inside are errors. Seam verts must be on the grid so neighbours weld visually. Texel density within 25% of the kit median (`--texture` px). `SM_` names (`--prefix`).+- `--fix` applies rotation/scale and moves each origin to the pivot without moving geometry. Linked duplicates share mesh data, so fix the source once.+- Break repetition with trims and decals (`blender-texturing`), vertex-color blends, and rotated/mirrored variants (mirrors flip normals, so check with `blender-asset-qa`). Hide seams with trim pieces over joints.++## Gotchas+- Apply terrain/kit scale before scattering. Densities and slopes are world-based.+- Scatter height is in the target's object space. Keep terrains at the origin or offset `--height-*`.+- Huge Poisson counts are slow. Scatter per tile/area, or lower the density in the viewport and raise it for renders.+- Validate terrain + scatter with `blender-asset-qa` (floating instances on cliffs, z-fighting decals) and `blender-game-optimization` (instances, LODs, draw calls).diff --git a/skills/blender-environment-kits/scripts/_bpyx.py b/skills/blender-environment-kits/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-environment-kits/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-environment-kits/scripts/kit_check.py b/skills/blender-environment-kits/scripts/kit_check.pynew file mode 100644index 0000000..f03da57--- /dev/null+++ b/skills/blender-environment-kits/scripts/kit_check.py@@ -0,0 +1,138 @@+"""Validate modular kit pieces so they snap together: applied transforms, footprint on the grid,+pivot convention, open edges only on the piece's outer faces (seams), consistent texel density,+naming. --fix applies rotation/scale and moves each origin to the pivot convention.++Pivot conventions: corner = bounding-box min (x, y, z), the usual kit/Roblox choice;+bottom-center = center of the bottom face; center = bounding-box center.+Usage:+ blender -b f.blend -P kit_check.py -- [--objects SM_Wall_4m SM_Floor_4m] [--grid 0.5]+ [--pivot corner|bottom-center|center] [--texture 2048] [--tol 0.001] [--prefix SM_] [--fix]+ [--save out.blend]+ MCP: import kit_check; print(kit_check.run(objects=["SM_Wall_4m"], grid=0.5, fix=True))+"""+import math+import os+import sys++import bmesh+import bpy+import numpy as np+from mathutils import Matrix, Vector++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402+++def _on_grid(v, grid, tol):+ return abs(v / grid - round(v / grid)) * grid <= tol+++def _pivot_target(lo, hi, pivot):+ if pivot == "corner":+ return Vector(lo)+ c = (Vector(lo) + Vector(hi)) / 2+ return Vector((c.x, c.y, lo[2])) if pivot == "bottom-center" else c+++def _texel_density(ob, texture):+ me = ob.data+ if not me.uv_layers:+ return None+ me.calc_loop_triangles()+ uv = me.uv_layers.active.uv+ mw = ob.matrix_world+ a3 = a2 = 0.0+ for t in me.loop_triangles:+ p = [mw @ me.vertices[v].co for v in t.vertices]+ q = [Vector((*uv[li].vector, 0)) for li in t.loops]+ a3 += (p[1] - p[0]).cross(p[2] - p[0]).length / 2+ a2 += (q[1] - q[0]).cross(q[2] - q[0]).length / 2+ return math.sqrt(a2 / a3) * texture if a3 > 0 and a2 > 0 else None+++def _fix(ob, pivot):+ """Apply rotation+scale, then move the origin to the pivot without moving the geometry."""+ me = ob.data+ loc, rot, scl = ob.matrix_world.decompose()+ me.transform(Matrix.LocRotScale(None, rot, scl))+ ob.matrix_world = Matrix.Translation(loc)+ co = np.empty(len(me.vertices) * 3, np.float32)+ me.vertices.foreach_get("co", co)+ co = co.reshape(-1, 3)+ off = _pivot_target(co.min(0), co.max(0), pivot)+ me.transform(Matrix.Translation(-off))+ ob.location = loc + off+ me.update()+++def run(objects=None, grid=0.5, pivot="corner", texture=2048, tol=0.001, prefix="SM_", fix=False, **_):+ bx.object_mode()+ if pivot not in ("corner", "bottom-center", "center"):+ raise ValueError("--pivot must be corner, bottom-center or center")+ obs = [o for o in bx.objects(objects) if o.type == "MESH"]+ pieces, tds = {}, {}+ for ob in obs:+ if fix:+ _fix(ob, pivot)+ e, w = [], []+ loc, rot, scl = ob.matrix_world.decompose()+ if any(abs(s - 1) > 1e-4 for s in scl):+ e.append(f"unapplied scale {bx.r(list(scl), 3)}")+ if rot.angle > 1e-4:+ e.append(f"unapplied rotation {round(math.degrees(rot.angle), 2)} deg")+ me = ob.data+ co = np.empty(len(me.vertices) * 3, np.float32)+ me.vertices.foreach_get("co", co)+ co = co.reshape(-1, 3)+ lo, hi = co.min(0), co.max(0)+ dims = hi - lo+ # lengths must tile; anything thinner than one cell is a thickness (walls, trims) and may be off-grid+ bad_dims = [round(float(d), 4) for d in dims[:2] if d >= grid - tol and not _on_grid(float(d), grid, tol)]+ if bad_dims:+ e.append(f"footprint {bx.r(dims.tolist(), 4)} m is not a multiple of the {grid} m grid")+ if not _on_grid(float(dims[2]), grid, tol):+ w.append(f"height {round(float(dims[2]), 4)} m is off-grid (fine for props, not for walls)")+ tgt = _pivot_target(lo, hi, pivot)+ if tgt.length > tol:+ e.append(f"pivot is not at the {pivot}: offset {bx.r(list(tgt), 4)} m (--fix)")+ if not all(_on_grid(float(c), grid, tol) for c in loc[:2]):+ w.append(f"placed off-grid at {bx.r(list(loc), 4)}")+ bm = bmesh.new()+ bm.from_mesh(me)+ open_v = {v for ed in bm.edges if ed.is_boundary for v in ed.verts}+ axes = [i for i in range(3) if dims[i] > tol] # a flat tile's Z faces would contain every vertex+ inner = [v for v in open_v if not any(abs(v.co[i] - b[i]) <= tol for b in (lo, hi) for i in axes)]+ seam = [v.co.copy() for v in open_v if v not in set(inner)]+ bm.free()+ if inner:+ e.append(f"{len(inner)} open-edge verts inside the piece (holes; seams must lie on its outer faces)")+ if seam and not all(_on_grid(float(c[i]), grid, tol) for c in seam for i in range(2)+ if abs(c[i] - lo[i]) > tol and abs(c[i] - hi[i]) > tol):+ w.append("seam verts off the grid: neighbours won't weld")+ if prefix and not ob.name.startswith(prefix):+ w.append(f"name lacks {prefix!r} prefix")+ td = _texel_density(ob, texture)+ if td is None:+ w.append("no UVs")+ else:+ tds[ob.name] = td+ pieces[ob.name] = {"dims_m": bx.r(dims.tolist(), 4), "tris": bx.mesh_tris(ob, False),+ "texel_px_per_m": round(td, 1) if td else None, "errors": e, "warnings": w}+ if len(tds) > 1:+ med = float(np.median(list(tds.values())))+ for n, td in tds.items():+ if abs(td - med) / med > 0.25:+ pieces[n]["warnings"].append(f"texel density {round(td)} px/m vs kit median {round(med)} (>25% off)")+ ok = not any(p["errors"] for p in pieces.values())+ return {"ok": True, "pass": ok, "grid_m": grid, "pivot": pivot, "fixed": fix, "pieces": pieces}+++if __name__ == "__main__":+ p = bx.add_common(bx.parser(__doc__))+ p.add_argument("--grid", type=float, default=0.5)+ p.add_argument("--pivot", default="corner", choices=("corner", "bottom-center", "center"))+ p.add_argument("--texture", type=int, default=2048, help="texture px for texel density")+ p.add_argument("--tol", type=float, default=0.001)+ p.add_argument("--prefix", default="SM_")+ p.add_argument("--fix", action="store_true")+ bx.cli(run, p)diff --git a/skills/blender-environment-kits/scripts/scatter.py b/skills/blender-environment-kits/scripts/scatter.pynew file mode 100644index 0000000..645bcef--- /dev/null+++ b/skills/blender-environment-kits/scripts/scatter.py@@ -0,0 +1,255 @@+"""Biome scatter with Geometry Nodes: Poisson-disk instances of a collection on a surface, filtered by+max slope, height band and an optional density mask, with random yaw/scale and partial normal+alignment. Instances stay instances (cheap, GPU-instanced in glTF) unless --realize.++One modifier per layer (--name), e.g. trees on gentle slopes, rocks on steep ones, grass in a mask.+Height is in the target's object space. The result counts the instances and checks every one+against the slope and height limits.+Usage:+ blender -b f.blend -P scatter.py -- --target Terrain --collection Trees [--density 0.02]+ [--min-distance 4] [--max-slope 25] [--height-min -1e9] [--height-max 1e9] [--mask VG|ATTR]+ [--scale 0.8 1.2] [--align 0.0] [--seed 0] [--realize] [--name ENV_Trees]+ [--export-points //trees.json] [--save out.blend]+ MCP: import scatter; print(scatter.run(target="Terrain", collection="Rocks", density=0.1, max_slope=60))+"""+import json+import math+import os+import sys++import bpy+from mathutils import Vector, geometry++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++TREE = "ENV_Scatter"+++def _on(socks, name):+ """Enabled socket by name: Random Value keeps one hidden Min/Max/Value per data type (5.2 renamed ids)."""+ return next(s for s in socks if s.enabled and s.name == name)+++def build_tree():+ ng = bpy.data.node_groups.get(TREE)+ if ng is not None:+ return ng+ ng = bpy.data.node_groups.new(TREE, "GeometryNodeTree")+ ng.is_modifier = True+ for nm, kind, d in (("Geometry", "Geometry", None), ("Collection", "Collection", None),+ ("Density", "Float", 0.1), ("Distance Min", "Float", 1.0), ("Max Slope", "Float", 30.0),+ ("Height Min", "Float", -1e9), ("Height Max", "Float", 1e9), ("Mask", "Float", 1.0),+ ("Scale Min", "Float", 0.8), ("Scale Max", "Float", 1.2), ("Align", "Float", 0.0),+ ("Seed", "Int", 0), ("Realize", "Bool", False)):+ s = ng.interface.new_socket(nm, in_out="INPUT", socket_type=f"NodeSocket{kind}")+ if d is not None:+ s.default_value = d+ ng.interface.new_socket("Geometry", in_out="OUTPUT", socket_type="NodeSocketGeometry")+ L = ng.links.new++ def N(type_, **props):+ node = ng.nodes.new(type_)+ for k, v in props.items():+ setattr(node, k, v)+ return node+ gi, go = N("NodeGroupInput"), N("NodeGroupOutput")+ I = gi.outputs # noqa: E741+ dist = N("GeometryNodeDistributePointsOnFaces", distribute_method="POISSON")+ L(I["Geometry"], dist.inputs["Mesh"])+ L(I["Density"], dist.inputs["Density Max"])+ L(I["Distance Min"], dist.inputs["Distance Min"])+ L(I["Mask"], dist.inputs["Density Factor"])+ L(I["Seed"], dist.inputs["Seed"])+ # keep points whose surface normal is within Max Slope of up and whose height is inside the band+ sep_n = N("ShaderNodeSeparateXYZ")+ L(dist.outputs["Normal"], sep_n.inputs[0])+ cosmax = N("ShaderNodeMath", operation="COSINE")+ rad = N("ShaderNodeMath", operation="RADIANS")+ L(I["Max Slope"], rad.inputs[0])+ L(rad.outputs[0], cosmax.inputs[0])+ flat = N("FunctionNodeCompare", data_type="FLOAT", operation="GREATER_EQUAL")+ L(sep_n.outputs["Z"], _on(flat.inputs, "A"))+ L(cosmax.outputs[0], _on(flat.inputs, "B"))+ sep_p = N("ShaderNodeSeparateXYZ")+ L(N("GeometryNodeInputPosition").outputs[0], sep_p.inputs[0])+ above = N("FunctionNodeCompare", data_type="FLOAT", operation="GREATER_EQUAL")+ L(sep_p.outputs["Z"], _on(above.inputs, "A"))+ L(I["Height Min"], _on(above.inputs, "B"))+ below = N("FunctionNodeCompare", data_type="FLOAT", operation="LESS_EQUAL")+ L(sep_p.outputs["Z"], _on(below.inputs, "A"))+ L(I["Height Max"], _on(below.inputs, "B"))+ a1 = N("FunctionNodeBooleanMath", operation="AND")+ L(flat.outputs[0], a1.inputs[0])+ L(above.outputs[0], a1.inputs[1])+ keep = N("FunctionNodeBooleanMath", operation="AND")+ L(a1.outputs[0], keep.inputs[0])+ L(below.outputs[0], keep.inputs[1])+ # rotation: lean Z toward the surface normal by Align, then a random yaw about the local Z+ yaw = N("FunctionNodeRandomValue", data_type="FLOAT")+ _on(yaw.inputs, "Max").default_value = 2 * math.pi+ L(I["Seed"], _on(yaw.inputs, "Seed"))+ eul = N("ShaderNodeCombineXYZ")+ L(_on(yaw.outputs, "Value"), eul.inputs["Z"])+ e2r = N("FunctionNodeEulerToRotation")+ L(eul.outputs[0], e2r.inputs[0])+ align = N("FunctionNodeAlignRotationToVector")+ align.axis = "Z"+ L(I["Align"], align.inputs["Factor"])+ L(dist.outputs["Normal"], align.inputs["Vector"])+ rot = N("FunctionNodeRotateRotation")+ rot.rotation_space = "LOCAL"+ L(align.outputs[0], rot.inputs["Rotation"])+ L(e2r.outputs[0], rot.inputs["Rotate By"])+ scl = N("FunctionNodeRandomValue", data_type="FLOAT")+ L(I["Scale Min"], _on(scl.inputs, "Min"))+ L(I["Scale Max"], _on(scl.inputs, "Max"))+ sd = N("ShaderNodeMath", operation="ADD")+ L(I["Seed"], sd.inputs[0])+ sd.inputs[1].default_value = 7+ L(sd.outputs[0], _on(scl.inputs, "Seed"))+ col = N("GeometryNodeCollectionInfo")+ col.transform_space = "ORIGINAL"+ L(I["Collection"], col.inputs["Collection"])+ col.inputs["Separate Children"].default_value = True+ col.inputs["Reset Children"].default_value = True # each child instanced at its own origin+ inst = N("GeometryNodeInstanceOnPoints")+ L(dist.outputs["Points"], inst.inputs["Points"])+ L(keep.outputs[0], inst.inputs["Selection"])+ L(col.outputs[0], inst.inputs["Instance"])+ inst.inputs["Pick Instance"].default_value = True+ pick = N("FunctionNodeRandomValue", data_type="INT")+ _on(pick.inputs, "Min").default_value, _on(pick.inputs, "Max").default_value = 0, 1 << 20+ L(I["Seed"], _on(pick.inputs, "Seed"))+ L(_on(pick.outputs, "Value"), inst.inputs["Instance Index"])+ L(rot.outputs[0], inst.inputs["Rotation"])+ L(_on(scl.outputs, "Value"), inst.inputs["Scale"])+ real = N("GeometryNodeRealizeInstances")+ L(inst.outputs[0], real.inputs["Geometry"])+ sw = N("GeometryNodeSwitch", input_type="GEOMETRY")+ L(I["Realize"], sw.inputs["Switch"])+ L(inst.outputs[0], sw.inputs["False"])+ L(real.outputs[0], sw.inputs["True"])+ join = N("GeometryNodeJoinGeometry")+ L(sw.outputs[0], join.inputs[0])+ L(I["Geometry"], join.inputs[0])+ L(join.outputs[0], go.inputs[0])+ return ng+++def _instances(target):+ dg = bpy.context.evaluated_depsgraph_get()+ return [(i.matrix_world.copy(), i.object.original.name) for i in dg.object_instances+ if i.is_instance and i.parent and i.parent.original == target]+++def run(target=None, collection=None, density=0.1, min_distance=1.0, max_slope=30.0, height_min=-1e9,+ height_max=1e9, mask=None, scale=(0.8, 1.2), align=0.0, seed=0, realize=False, name=None,+ export_points=None, **_):+ bx.object_mode()+ if not target or not collection:+ raise ValueError("--target and --collection are required")+ tgt, coll = bpy.data.objects[target], bpy.data.collections[collection]+ if not coll.all_objects:+ raise ValueError(f"collection {collection!r} is empty")+ name = name or f"ENV_{collection}"+ ng = build_tree()+ md = tgt.modifiers.get(name) or tgt.modifiers.new(name, "NODES")+ md.node_group = ng+ ids = {i.name: i.identifier for i in ng.interface.items_tree if getattr(i, "in_out", "") == "INPUT"}+ ins = md.properties.inputs+ for k, v in (("Collection", coll), ("Density", density), ("Distance Min", min_distance), ("Max Slope", max_slope),+ ("Height Min", height_min), ("Height Max", height_max), ("Scale Min", scale[0]),+ ("Scale Max", scale[1]), ("Align", align), ("Seed", seed), ("Realize", realize)):+ getattr(ins, ids[k]).value = v+ m = getattr(ins, ids["Mask"])+ if mask:+ m.type, m.attribute_name = "ATTRIBUTE", mask+ else:+ m.type, m.value = "VALUE", 1.0+ for c in (coll,): # the source collection shouldn't render at the origin+ lc = _layer_coll(bpy.context.view_layer.layer_collection, c.name)+ if lc is not None:+ lc.exclude = True+ res = {"ok": True, "target": target, "modifier": name, "collection": collection}+ if realize:+ me = tgt.evaluated_get(bpy.context.evaluated_depsgraph_get()).to_mesh()+ res["tris_total"] = sum(len(p.vertices) - 2 for p in me.polygons)+ tgt.evaluated_get(bpy.context.evaluated_depsgraph_get()).to_mesh_clear()+ return res+ inst = _instances(tgt)+ res["instances"] = len(inst)+ res["by_source"] = {}+ for _m, src in inst:+ res["by_source"][src] = res["by_source"].get(src, 0) + 1+ if inst: # verify the filters on the surface under each instance, with GN's interpolated normal+ surf = tgt.evaluated_get(bpy.context.evaluated_depsgraph_get()) # instances aren't in its mesh+ me = surf.to_mesh()+ me.calc_loop_triangles()+ cn = me.corner_normals+ by_poly = {}+ for t in me.loop_triangles:+ by_poly.setdefault(t.polygon_index, []).append(t)+ tinv = tgt.matrix_world.inverted()+ worst, zs = 0.0, []+ for mw, _src in inst[:: max(1, len(inst) // 500)]:+ p = tinv @ mw.translation+ ok, loc, _n, fi = surf.closest_point_on_mesh(p)+ if not ok:+ continue+ best = None+ for t in by_poly.get(fi, []):+ a, b, c = (me.vertices[v].co for v in t.vertices)+ w = geometry.barycentric_transform(loc, a, b, c, Vector((1, 0, 0)), Vector((0, 1, 0)), Vector((0, 0, 1)))+ if best is None or min(w) > min(best[1]):+ best = (t, w)+ t, w = best+ n = sum((cn[li].vector * wi for li, wi in zip(t.loops, w)), Vector()).normalized()+ worst = max(worst, math.degrees(math.acos(max(-1.0, min(1.0, n.z)))))+ zs.append(p.z)+ surf.to_mesh_clear()+ res["slope_max_deg"] = round(worst, 2)+ res["height_range"] = [round(min(zs), 3), round(max(zs), 3)]+ area = sum(pl.area for pl in tgt.data.polygons) * abs(tgt.matrix_world.determinant()) ** (2 / 3)+ res["per_m2"] = round(len(inst) / max(area, 1e-9), 5)+ else:+ res["warning"] = "no instances: density too low, or slope/height/mask filters exclude everything"+ if export_points and inst: # world transforms for engine foliage/instancing tools (Z-up, meters)+ path = bpy.path.abspath(export_points)+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)+ rows = []+ for mw, src in inst:+ loc, rot, scl = mw.decompose()+ rows.append({"source": src, "location": [round(v, 4) for v in loc],+ "rotation_quat_wxyz": [round(v, 5) for v in rot], "scale": [round(v, 4) for v in scl]})+ with open(path, "w", encoding="utf-8") as f:+ json.dump({"up": "Z", "units": "m", "instances": rows}, f)+ res["points_file"] = path+ return res+++def _layer_coll(lc, name):+ if lc.collection.name == name:+ return lc+ for ch in lc.children:+ f = _layer_coll(ch, name)+ if f is not None:+ return f+ return None+++if __name__ == "__main__":+ p = bx.parser(__doc__)+ p.add_argument("--target", required=True)+ p.add_argument("--collection", required=True)+ for k, d in (("density", 0.1), ("min-distance", 1.0), ("max-slope", 30.0), ("height-min", -1e9),+ ("height-max", 1e9), ("align", 0.0)):+ p.add_argument(f"--{k}", type=float, default=d)+ p.add_argument("--mask", default=None, help="vertex group / float attribute = density factor")+ p.add_argument("--scale", type=float, nargs=2, default=(0.8, 1.2))+ p.add_argument("--seed", type=int, default=0)+ p.add_argument("--realize", action="store_true")+ p.add_argument("--name", default=None)+ p.add_argument("--export-points", default=None, help="JSON of instance world transforms")+ p.add_argument("--save", default=None)+ bx.cli(run, p)diff --git a/skills/blender-environment-kits/scripts/terrain.py b/skills/blender-environment-kits/scripts/terrain.pynew file mode 100644index 0000000..d0e5e21--- /dev/null+++ b/skills/blender-environment-kits/scripts/terrain.py@@ -0,0 +1,245 @@+"""Game-ready terrain: noise (fbm, ridged mountains, rolling hills) or a heightmap image on a grid,+thermal erosion, terraces, flattened play areas, slope/height attributes, an auto slope/height+material, and engine exports (16-bit heightmap + RGBA splat map, same grid).++Grid --res is vertices per side: use 2^n + 1 (129, 257, 513, 1025) so heightmaps import 1:1 into+Unity Terrain / UE Landscape. Attributes ENV_Slope (deg / 90) and ENV_Height (0-1) drive the material+and blender-environment-kits scatter.py.+Usage:+ blender -b f.blend -P terrain.py -- [--size 200] [--res 257] [--height 30] [--type fbm|ridged|hills]+ [--scale 80] [--octaves 6] [--seed 0] [--heightmap hm.png] [--erosion 20] [--terrace 0]+ [--flatten 0 0 15] [--material] [--export-heightmap //T_Height.png|.raw] [--export-splat //T_Splat.png]+ [--name Terrain] [--save out.blend]+ MCP: import terrain; print(terrain.run(size=200, height=30, type="ridged", erosion=20, material=True))+"""+import math+import os+import sys++import bpy+import numpy as np+from mathutils import Vector, noise++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++ROCK_DEG, SNOW_H = 35.0, 0.75 # rock above 35 deg, snow above 75% height on gentler slopes+++def _noise_field(res, size, kind, scale, octaves, seed):+ off = Vector((seed * 31.7, seed * 17.3, seed * 7.1))+ xs = np.linspace(-size / 2, size / 2, res)+ h = np.empty((res, res), np.float64)+ basis = "PERLIN_ORIGINAL"+ for j, y in enumerate(xs):+ for i, x in enumerate(xs):+ p = Vector((x / scale, y / scale, 0.0)) + off+ if kind == "ridged":+ h[j, i] = noise.ridged_multi_fractal(p, 1.0, 2.0, octaves, 1.0, 2.0, noise_basis=basis)+ elif kind == "hills":+ h[j, i] = noise.hetero_terrain(p, 1.0, 2.0, min(octaves, 4), 0.5, noise_basis=basis)+ else:+ h[j, i] = noise.fractal(p, 1.0, 2.0, octaves, noise_basis=basis)+ return h+++def _heightmap(path, res):+ img = bpy.data.images.load(bpy.path.abspath(path), check_existing=True)+ img.colorspace_settings.is_data = True+ w, hgt = img.size+ a = np.empty(w * hgt * 4, np.float32)+ img.pixels.foreach_get(a)+ a = a.reshape(hgt, w, 4)[..., 0]+ yi = np.linspace(0, hgt - 1, res).round().astype(int)+ xi = np.linspace(0, w - 1, res).round().astype(int)+ return a[np.ix_(yi, xi)].astype(np.float64)+++def _erode(h, cell, steps, talus_deg=33.0, rate=0.25):+ """Thermal erosion: material above the talus angle slides to lower neighbours (4-neighbourhood)."""+ talus = math.tan(math.radians(talus_deg)) * cell+ for _ in range(steps):+ move = np.zeros_like(h)+ for ax, sh in ((0, 1), (0, -1), (1, 1), (1, -1)):+ nb = np.roll(h, sh, axis=ax)+ d = h - nb - talus+ d[d < 0] = 0+ if ax == 0:+ d[0 if sh == 1 else -1, :] = 0 # no wrap-around at the borders+ else:+ d[:, 0 if sh == 1 else -1] = 0+ m = d * rate * 0.25+ move -= m+ move += np.roll(m, -sh, axis=ax)+ h = h + move+ return h+++def _slope_deg(h, cell):+ gy, gx = np.gradient(h, cell)+ return np.degrees(np.arctan(np.hypot(gx, gy)))+++def _material(name):+ mat = bpy.data.materials.get(name) or bpy.data.materials.new(name)+ nt = mat.node_tree+ bsdf = bx.node(nt, "BSDF_PRINCIPLED")+ for n in [n for n in nt.nodes if n.name.startswith("ENV_T_")]:+ nt.nodes.remove(n)++ def nn(t, **kw):+ n = nt.nodes.new(t)+ n.name = "ENV_T_" + n.name+ for k, v in kw.items():+ setattr(n, k, v)+ return n+ sl = nn("ShaderNodeAttribute", attribute_type="GEOMETRY", attribute_name="ENV_Slope")+ ht = nn("ShaderNodeAttribute", attribute_type="GEOMETRY", attribute_name="ENV_Height")+ tc = nn("ShaderNodeTexCoord")+ nz = nn("ShaderNodeTexNoise")+ nt.links.new(tc.outputs["Object"], nz.inputs["Vector"])+ nz.inputs["Scale"].default_value = 0.15+ nz.inputs["Detail"].default_value = 6.0++ def ramp(src, lo, hi):+ m = nn("ShaderNodeMapRange", clamp=True)+ add = nn("ShaderNodeMath", operation="MULTIPLY_ADD")+ nt.links.new(nz.outputs["Factor"], add.inputs[0])+ add.inputs[1].default_value = 0.12+ nt.links.new(src, add.inputs[2])+ nt.links.new(add.outputs[0], m.inputs[0])+ m.inputs[1].default_value, m.inputs[2].default_value = lo, hi+ return m.outputs[0]+ rock = ramp(sl.outputs["Fac"], ROCK_DEG / 90 - 0.03, ROCK_DEG / 90 + 0.03)+ snow = ramp(ht.outputs["Fac"], SNOW_H - 0.03, SNOW_H + 0.03)+ snow_ok = nn("ShaderNodeMath", operation="MULTIPLY")+ nt.links.new(snow, snow_ok.inputs[0])+ nt.links.new(ramp(sl.outputs["Fac"], 0.5, 0.42), snow_ok.inputs[1]) # snow slides off > ~40 deg++ def mix(fac, a, b):+ m = nn("ShaderNodeMix", data_type="RGBA")+ nt.links.new(fac, m.inputs[0])+ for i, v in ((6, a), (7, b)):+ if isinstance(v, bpy.types.NodeSocket):+ nt.links.new(v, m.inputs[i])+ else:+ m.inputs[i].default_value = v+ return m.outputs[2]+ grass = mix(nz.outputs["Factor"], (0.045, 0.075, 0.02, 1), (0.08, 0.1, 0.03, 1)) # measured-range grass albedo+ col = mix(snow_ok.outputs[0], mix(rock, grass, (0.2, 0.18, 0.16, 1)), (0.8, 0.82, 0.86, 1))+ nt.links.new(col, bsdf.inputs["Base Color"])+ rough = mix(rock, (0.85, 0.85, 0.85, 1), (0.7, 0.7, 0.7, 1))+ bw = nn("ShaderNodeRGBToBW")+ nt.links.new(rough, bw.inputs[0])+ nt.links.new(bw.outputs[0], bsdf.inputs["Roughness"])+ return mat+++def _save_png16(path, rgba, res, bw):+ img = bpy.data.images.new(os.path.basename(path), res, res, alpha=not bw, float_buffer=True)+ img.colorspace_settings.is_data = True+ img.pixels.foreach_set(rgba.astype(np.float32).ravel())+ sc = bpy.context.scene+ st, vt = sc.render.image_settings, sc.view_settings.view_transform+ prev = (st.file_format, st.color_mode, st.color_depth)+ st.file_format, st.color_mode, st.color_depth = "PNG", "BW" if bw else "RGBA", "16"+ sc.view_settings.view_transform = "Raw" # write data values, not a display transform+ try:+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)+ img.save_render(path, scene=sc)+ finally:+ st.file_format, st.color_mode, st.color_depth = prev+ sc.view_settings.view_transform = vt+ bpy.data.images.remove(img)+ return path+++def run(size=200.0, res=257, height=30.0, type="fbm", scale=80.0, octaves=6, seed=0, heightmap=None,+ erosion=0, terrace=0.0, flatten=None, material=False, export_heightmap=None, export_splat=None,+ name="Terrain", **_):+ bx.object_mode()+ cell = size / (res - 1)+ h = _heightmap(heightmap, res) if heightmap else _noise_field(res, size, type, scale, octaves, seed)+ h = (h - h.min()) / max(np.ptp(h), 1e-9) * height+ if erosion:+ h = _erode(h, cell, int(erosion))+ if terrace > 0:+ frac = (h / terrace) % 1.0+ h = (np.floor(h / terrace) + np.clip((frac - 0.75) / 0.25, 0, 1)) * terrace # flats with short risers+ xs = np.linspace(-size / 2, size / 2, res)+ X, Y = np.meshgrid(xs, xs)+ if flatten:+ cx, cy, rad = flatten+ d = np.hypot(X - cx, Y - cy)+ target = h[np.abs(d) <= rad].mean() if (d <= rad).any() else h.mean()+ w = np.clip((d - rad) / (rad * 0.6), 0, 1)+ w = w * w * (3 - 2 * w) # smoothstep blend back into the terrain+ h = target + (h - target) * w+ slope = _slope_deg(h, cell)+ hn = (h - h.min()) / max(np.ptp(h), 1e-9)+ me = bpy.data.meshes.get(name) or bpy.data.meshes.new(name)+ me.clear_geometry()+ me.vertices.add(res * res)+ me.vertices.foreach_set("co", np.stack([X, Y, h], -1).astype(np.float32).ravel())+ q = np.arange(res * res).reshape(res, res)+ quads = np.stack([q[:-1, :-1], q[:-1, 1:], q[1:, 1:], q[1:, :-1]], -1).reshape(-1, 4)+ me.loops.add(quads.size)+ me.loops.foreach_set("vertex_index", quads.ravel().astype(np.int32))+ me.polygons.add(len(quads))+ me.polygons.foreach_set("loop_start", np.arange(0, quads.size, 4, dtype=np.int32))+ me.update()+ me.validate()+ uv = me.uv_layers.new(name="UVMap")+ uvs = np.stack([(X + size / 2) / size, (Y + size / 2) / size], -1).reshape(-1, 2)+ uv.uv.foreach_set("vector", uvs[quads.ravel()].astype(np.float32).ravel())+ for an, val in (("ENV_Slope", slope / 90.0), ("ENV_Height", hn)):+ at = me.attributes.get(an) or me.attributes.new(an, "FLOAT", "POINT")+ at.data.foreach_set("value", val.astype(np.float32).ravel())+ me.shade_smooth()+ ob = bpy.data.objects.get(name)+ if ob is None:+ ob = bpy.data.objects.new(name, me)+ bpy.context.scene.collection.objects.link(ob)+ res_d = {"ok": True, "object": ob.name, "size_m": size, "res": res, "cell_m": round(cell, 4),+ "tris": int(len(quads) * 2), "height_range_m": [round(float(h.min()), 3), round(float(h.max()), 3)],+ "slope_mean_deg": round(float(slope.mean()), 2), "rock_pct": round(float((slope > ROCK_DEG).mean()) * 100, 1)}+ if material:+ mat = _material("M_" + name)+ me.materials.clear()+ me.materials.append(mat)+ res_d["material"] = mat.name+ if export_heightmap: # row 0 = -Y (south) edge; .raw = 16-bit little-endian (Unity), .png = 16-bit gray (UE)+ path = bpy.path.abspath(export_heightmap)+ if path.lower().endswith(".raw"):+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)+ np.round(hn * 65535).astype("<u2").tofile(path)+ res_d["heightmap"] = path+ else:+ g = np.repeat(hn[..., None], 4, -1)+ g[..., 3] = 1+ res_d["heightmap"] = _save_png16(path, g, res, True)+ res_d["heightmap_z_scale_m"] = round(float(np.ptp(h)), 4)+ if export_splat: # R grass, G rock, B snow, weights sum to 1+ rock = np.clip((slope - ROCK_DEG + 2) / 4, 0, 1)+ snow = np.clip((hn - SNOW_H + 0.03) / 0.06, 0, 1) * np.clip((40 - slope) / 4, 0, 1) * (1 - rock)+ grass = np.clip(1 - rock - snow, 0, 1)+ res_d["splat"] = _save_png16(bpy.path.abspath(export_splat), np.stack([grass, rock, snow, np.ones_like(grass)], -1), res, False)+ if res > 1025:+ res_d["warning"] = "res > 1025: split into tiles/chunks for engines and LODs"+ return res_d+++if __name__ == "__main__":+ p = bx.parser(__doc__)+ for k, t, d in (("size", float, 200.0), ("res", int, 257), ("height", float, 30.0), ("scale", float, 80.0),+ ("octaves", int, 6), ("seed", int, 0), ("erosion", int, 0), ("terrace", float, 0.0)):+ p.add_argument(f"--{k}", type=t, default=d)+ p.add_argument("--type", default="fbm", choices=("fbm", "ridged", "hills"))+ p.add_argument("--heightmap", default=None)+ p.add_argument("--flatten", type=float, nargs=3, default=None, metavar=("X", "Y", "RADIUS"))+ p.add_argument("--material", action="store_true")+ p.add_argument("--export-heightmap", default=None)+ p.add_argument("--export-splat", default=None)+ p.add_argument("--name", default="Terrain")+ p.add_argument("--save", default=None)+ bx.cli(run, p)diff --git a/skills/blender-export-pipelines/SKILL.md b/skills/blender-export-pipelines/SKILL.mdindex 8172db7..be7b380 100644--- a/skills/blender-export-pipelines/SKILL.md+++ b/skills/blender-export-pipelines/SKILL.md@@ -4,7 +4,7 @@ description: Export from Blender 5.2 with verified presets - Roblox (FBX/glTF, clicense: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Export Pipelinesdiff --git a/skills/blender-facial-shapekeys/SKILL.md b/skills/blender-facial-shapekeys/SKILL.mdindex 2c75722..82676d8 100644--- a/skills/blender-facial-shapekeys/SKILL.md+++ b/skills/blender-facial-shapekeys/SKILL.md@@ -4,7 +4,7 @@ description: Facial rigs and shape keys in Blender 5.2 - ARKit 52 blendshapes, vlicense: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Facial Rig & Shape Keysdiff --git a/skills/blender-game-optimization/SKILL.md b/skills/blender-game-optimization/SKILL.mdindex f648df3..9197fe3 100644--- a/skills/blender-game-optimization/SKILL.md+++ b/skills/blender-game-optimization/SKILL.md@@ -4,7 +4,7 @@ description: Optimize Blender assets for real-time engines - triangle/material/tlicense: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Game Optimizationdiff --git a/skills/blender-geometry-nodes/SKILL.md b/skills/blender-geometry-nodes/SKILL.mdindex f3b3fea..16717c1 100644--- a/skills/blender-geometry-nodes/SKILL.md+++ b/skills/blender-geometry-nodes/SKILL.md@@ -4,7 +4,7 @@ description: Geometry Nodes in Blender 5.2 - fields, domains, attributes, instanlicense: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Geometry Nodesdiff --git a/skills/blender-hair-grooming/SKILL.md b/skills/blender-hair-grooming/SKILL.mdnew file mode 100644index 0000000..06811c6--- /dev/null+++ b/skills/blender-hair-grooming/SKILL.md@@ -0,0 +1,58 @@+---+name: blender-hair-grooming+description: Hair and fur in Blender 5.2 - hair curves on a surface, guides + interpolated children with the bundled hair node assets (clump, curl, noise, droop), density masks, Principled Hair BSDF (melanin), Curves Sculpt combing, 5.2 node Hair Dynamics, game hair cards with a rendered strand atlas, Alembic/USD groom export. Use for hair, fur, beards, eyebrows, grass tufts.+license: MIT+metadata:+ author: blender-agent-skills+ version: "1.2.0"+---++# Hair grooming++The execution model is in `blender-core`. Hair physics details are in `blender-simulation`, and look-dev in `blender-lighting-lookdev`.++## One call each+```+scripts/groom.py -- --surface Head --mask Scalp --length 0.15 --children 150000 --clump 0.5+scripts/groom.py -- --surface Head --mask Beard --length 0.02 --droop 0.2 --curl 0.004 --melanin 0.9 --name Beard+scripts/groom.py -- --surface Body --length 0.025 --droop 0.3 --clump 0.3 --name Fur+scripts/groom.py -- --cards Hair --card-count 150 --atlas-res 2048 --out //textures # game hair cards+```++## How pros groom+1. **Surface first**: the scalp is a mesh (or the head itself) with **UVs** (hair attaches by UV) and a **vertex group** painted where hair grows. That group becomes the density mask, so soft edges give a natural hairline.+2. **Guides → children**: a few hundred to a few thousand guides carry the shape, and thousands of interpolated children give the volume. Style the guides, never the children.+3. **Shape in layers**: length, then clump (strands gather into locks), then curl/wave, then frizz/noise, then profile (thin tips). Keep each a separate modifier you can toggle.+4. **Comb by hand** for anything hero: Curves Sculpt mode brushes (`Comb`, `Add`, `Puff`, `Pinch`, `Grow/Shrink`, `Smooth`, `Slide`, `Density`, `Delete`, `Pull Tips`). Procedural droop gives a believable base, not a hairstyle.+5. Look-dev under the final lights. Hair reads mostly from **specular** and depth (clumps catch highlights), not albedo.++## groom.py+- Runs 5.2's Add Empty Hair (`object.curves_empty_hair_add`). It parents to the surface, sets `surface`/`surface_uv_map`, adds **Capture Rest Geometry** to the surface, and adds the node **Hair Dynamics** modifier (pinned last, experimental). Then it stacks the bundled assets: Generate (`--density` guides/m²) → Interpolate (`--children`/m², `--viewport` fraction in the viewport) → Clump → Curl → Displace + Shrinkwrap (`--droop` × length down, kept 2 mm above the surface) → Noise → Set Hair Curve Profile (`--radius`, tip taper).+- **Clump/curl guide distance = 10% of `--length`.** The asset's default 0.1 m collapses a whole head into a few tufts.+- Each asset stays a modifier with live inputs, so tweak there. Inputs by name: `getattr(md.properties.inputs, identifier).value`; vertex-group masks use `.type = "ATTRIBUTE"`, `.attribute_name`.+- It reports curves, mean length, the max root gap to the surface (must be ~0) and the modifier stacks. Evaluated counts in background mode use the viewport amount.++## Numbers+| | Value |+|---|---|+| Human scalp | ~100–150k hairs, ~200/cm². CG: 30k–150k rendered strands, 300–3000 guides |+| Strand radius | real 0.03–0.05 mm. Use 0.05 mm (`--radius 0.00005`), thicker with fewer strands |+| Melanin (Principled Hair, Chiang) | black 1.0 · dark brown 0.8 · brown 0.65 · light brown 0.45 · blond 0.25 · platinum 0.1. Red: 0.5 + redness 0.9. Grey: 0 + tint |+| Roughness | 0.25–0.35 (glossy) … 0.5 (dry). Radial roughness 0.3 |+| Fur | length 1–5 cm, density 200k–2M/m², little clump |+`HUANG` (4.0+) models elliptical cross-sections and is better for close-ups. `CHIANG` is the reference default.++## Game hair cards (`--cards HAIR`)+- Picks `--card-count` well-spread strands (farthest-point sampling) of the evaluated groom and builds a ribbon along each: `--card-width` m, tapering to 30% at the tip, lying flat on the surface (side = tangent × surface normal). UV v runs root 0 → tip 1, one atlas column per card (`--atlas-columns`).+- Renders the atlas with Cycles from flat strand clumps: `T_<name>_BC` (darker roots, coverage in alpha, Standard view), plus `T_<name>_RootTip` and `T_<name>_ID` (Raw, linear data). The card material uses Dithered alpha with no backface culling.+- Pros layer cards from the scalp outward: dense, wide, opaque cards on the scalp to hide skin; mid layers; then thin flyaway cards on top. Budgets: hero 20k–60k tris, NPC 5k–15k. Bend cards in S/C shapes, never flat planes, and check from every angle. Engines use alpha test/dither + depth prepass, root-tip for darkening/AO and ID for per-strand variation. Add a tangent (flow) map along V for anisotropic specular.++## Export grooms+Strand hair for UE Groom/Houdini: Alembic (`wm.alembic_export`) or USD (`wm.usd_export(export_curves=True)`). Both write the evaluated curves (measured: 246/246 curves round-trip). Bake the modifier stack first if the target needs guides only.++## Gotchas+- No UVs on the surface means `Generate` has nothing to attach to. Add UVs before grooming.+- Changing the surface topology after grooming breaks attachment. Groom last, or re-run.+- Scale: apply the head's scale. Lengths and densities are world meters.+- Viewport: keep `--viewport` ≤ 0.2 on full heads. Final strand counts only appear in renders.+- Hair Dynamics simulates on playback. For stills on frame 1 it's a pass-through. Bake it (`blender-simulation`) before animated renders.diff --git a/skills/blender-hair-grooming/scripts/_bpyx.py b/skills/blender-hair-grooming/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-hair-grooming/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-hair-grooming/scripts/groom.py b/skills/blender-hair-grooming/scripts/groom.pynew file mode 100644index 0000000..855c1d4--- /dev/null+++ b/skills/blender-hair-grooming/scripts/groom.py@@ -0,0 +1,330 @@+"""Groom hair curves on a surface with Blender's bundled hair node assets, and turn a groom into+game hair cards with a rendered strand atlas.++Groom: Add Empty Hair (5.2: attaches to --surface, UV, rest geometry, node Hair Dynamics), then+Generate (density per m^2, optional vertex-group mask) -> Clump -> Curl -> Droop (Displace ++Shrinkwrap off the scalp) -> Noise -> Set Profile, plus a+Principled Hair BSDF (melanin). Every asset stays a modifier with live inputs.+Cards: ribbons along --card-count well-spaced strands of the evaluated groom (UV v: root 0 -> tip 1,+one atlas column per card), plus an atlas rendered with Cycles from flat strand clumps:+T_<name>_BC (color + coverage alpha), T_<name>_RootTip, T_<name>_ID.+Usage:+ blender -b f.blend -P groom.py -- --surface Head [--mask Scalp] [--density 2000] [--children 100000] [--viewport 0.2]+ [--length 0.12]+ [--points 12] [--clump 0.5] [--curl 0] [--droop 0.8] [--noise 0.003] [--radius 0.00005] [--melanin 0.65]+ [--redness 0.1] [--roughness 0.3] [--seed 0] [--name Hair] [--save out.blend]+ blender -b f.blend -P groom.py -- --cards Hair [--card-count 120] [--card-width 0.012]+ [--atlas-columns 8] [--atlas-res 1024] [--out //textures] [--save out.blend]+ MCP: import groom; print(groom.run(surface="Head", density=20000, length=0.12))+"""+import os+import random+import sys++import bpy+import numpy as np+from mathutils import Vector++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++ASSETS = ("Generate Hair Curves", "Interpolate Hair Curves", "Clump Hair Curves", "Curl Hair Curves", "Displace Hair Curves",+ "Shrinkwrap Hair Curves", "Hair Curves Noise", "Set Hair Curve Profile")+++def _assets():+ path = os.path.join(bpy.utils.system_resource("DATAFILES"), "assets", "nodes", "procedural_hair_node_assets.blend")+ need = [n for n in ASSETS if n not in bpy.data.node_groups]+ if need:+ with bpy.data.libraries.load(path, link=False) as (src, dst):+ dst.node_groups = need+ return {n: bpy.data.node_groups[n] for n in ASSETS}+++def _modifier(ob, group, vals):+ md = ob.modifiers.get(group.name) or ob.modifiers.new(group.name, "NODES")+ md.node_group = group+ ids = {}+ for i in group.interface.items_tree: # assets reuse names ("Surface" Object + Geometry): "Name:Type" picks one+ if getattr(i, "in_out", "") == "INPUT":+ ids.setdefault(i.name, i.identifier)+ ids[f"{i.name}:{i.socket_type[len('NodeSocket'):]}"] = i.identifier+ for k, v in vals.items():+ sock = getattr(md.properties.inputs, ids[k])+ if isinstance(v, tuple) and v[0] == "ATTR":+ sock.type, sock.attribute_name = "ATTRIBUTE", v[1]+ else:+ sock.value = v+ return md+++def hair_material(name, melanin, redness, roughness):+ mat = bpy.data.materials.get(name) or bpy.data.materials.new(name)+ nt = mat.node_tree+ nt.nodes.clear()+ out = nt.nodes.new("ShaderNodeOutputMaterial")+ h = nt.nodes.new("ShaderNodeBsdfHairPrincipled")+ h.model, h.parametrization = "CHIANG", "MELANIN"+ h.inputs["Melanin"].default_value = melanin+ h.inputs["Melanin Redness"].default_value = redness+ h.inputs["Roughness"].default_value = roughness+ h.inputs["Radial Roughness"].default_value = 0.3+ nt.links.new(h.outputs[0], out.inputs["Surface"])+ return mat+++def groom(surface, mask=None, density=2000.0, children=100000.0, viewport=0.2, length=0.12, points=12, clump=0.5, curl=0.0, droop=0.8,+ noise=0.003, radius=0.00005, melanin=0.65, redness=0.1, roughness=0.3, seed=0, name="Hair"):+ surf = bpy.data.objects[surface]+ if not surf.data.uv_layers:+ raise ValueError(f"{surface} needs a UV map (hair attaches by UV)")+ if mask and mask not in surf.vertex_groups:+ raise KeyError(f"vertex group {mask!r} not on {surface}")+ before = set(bpy.data.objects)+ bx.select_only([surf])+ with bpy.context.temp_override(object=surf, active_object=surf, selected_objects=[surf]):+ bpy.ops.object.curves_empty_hair_add()+ hair = next(o for o in bpy.data.objects if o not in before and o.type == "CURVES")+ hair.name = hair.data.name = name+ g = _assets()+ gen = {"Hair Length": length, "Density": density, "Control Points": points, "Seed": seed}+ if mask:+ gen["Density Mask"] = ("ATTR", mask)+ _modifier(hair, g["Generate Hair Curves"], gen)+ if children > 0: # guides -> interpolated children: the production way to get strand counts+ ch = {"Density": children, "Viewport Amount": viewport, "Interpolation Guides": 4, "Seed": seed}+ if mask:+ ch["Density Mask"] = ("ATTR", mask)+ _modifier(hair, g["Interpolate Hair Curves"], ch)+ guide = max(0.004, length * 0.1) # asset default 0.1 m clumps a whole head into a few tufts+ if clump > 0:+ _modifier(hair, g["Clump Hair Curves"], {"Factor": clump, "Shape": 0.5, "Guide Distance": guide, "Seed": seed})+ if curl > 0:+ _modifier(hair, g["Curl Hair Curves"], {"Factor": 1.0, "Radius": curl, "Frequency": 3.0,+ "Guide Distance": guide, "Seed": seed})+ if droop > 0: # gravity: tips fall by droop x length, then pushed back above the scalp+ _modifier(hair, g["Displace Hair Curves"], {"Displace Vector": (0.0, 0.0, -droop * length), "Shape": 0.35})+ _modifier(hair, g["Shrinkwrap Hair Curves"], {"Surface Input Type": "Object", "Surface:Object": surf,+ "Offset Distance": 0.002, "Lock Roots": True})+ if noise > 0:+ _modifier(hair, g["Hair Curves Noise"], {"Distance": noise, "Seed": seed})+ _modifier(hair, g["Set Hair Curve Profile"], {"Radius": radius, "Shape": 0.5})+ mat = hair_material("M_" + name, melanin, redness, roughness)+ hair.data.materials.clear()+ hair.data.materials.append(mat)+ for md in hair.modifiers: # the material lives on the generated curves, set by the Generate input+ if md.node_group and md.node_group.name == "Generate Hair Curves":+ ids = {i.name: i.identifier for i in md.node_group.interface.items_tree if getattr(i, "in_out", "") == "INPUT"}+ getattr(md.properties.inputs, ids["Hair Material"]).value = mat+ stats = curve_stats(hair, surf)+ return {"ok": True, "hair": hair.name, "surface": surface, "modifiers": [m.name for m in hair.modifiers],+ "surface_modifiers": [m.name for m in surf.modifiers], "material": mat.name, **stats}+++def _evaluated(hair):+ ev = hair.evaluated_get(bpy.context.evaluated_depsgraph_get()).data+ n = len(ev.points)+ pos = np.empty(n * 3, np.float32)+ ev.attributes["position"].data.foreach_get("vector", pos)+ off = np.empty(len(ev.curves) + 1, np.int32)+ ev.curve_offset_data.foreach_get("value", off)+ mw = np.array(hair.matrix_world, np.float32)+ return pos.reshape(-1, 3) @ mw[:3, :3].T + mw[:3, 3], off+++def curve_stats(hair, surf):+ pos, off = _evaluated(hair)+ if len(off) < 2:+ return {"curves": 0}+ roots, tips = pos[off[:-1]], pos[off[1:] - 1]+ seg = np.linalg.norm(np.diff(pos, axis=0), axis=1)+ lens = np.array([seg[a:b - 1].sum() for a, b in zip(off[:-1], off[1:])])+ sinv = surf.matrix_world.inverted()+ sev = surf.evaluated_get(bpy.context.evaluated_depsgraph_get())+ gap = max((surf.matrix_world @ sev.closest_point_on_mesh(sinv @ Vector(r))[1] - Vector(r)).length+ for r in roots[:: max(1, len(roots) // 400)])+ return {"curves": int(len(off) - 1), "points": int(len(pos)), "length_mean_m": round(float(lens.mean()), 4),+ "root_gap_max_m": round(gap, 5), "tip_z_mean": round(float(tips[:, 2].mean()), 4)}+++def _spaced(roots, k, rng):+ """Farthest-point sampling: k well-spread curve indices."""+ k = min(k, len(roots))+ pick = [rng.randrange(len(roots))]+ d = np.linalg.norm(roots - roots[pick[0]], axis=1)+ for _ in range(k - 1):+ i = int(d.argmax())+ pick.append(i)+ d = np.minimum(d, np.linalg.norm(roots - roots[i], axis=1))+ return pick+++def build_cards(hair, count=120, width=0.012, columns=8, seed=0):+ surf = hair.data.surface+ pos, off = _evaluated(hair)+ roots = pos[off[:-1]]+ rng = random.Random(seed)+ idx = _spaced(roots, count, rng)+ sev = surf.evaluated_get(bpy.context.evaluated_depsgraph_get()) if surf else None+ verts, faces, uvs = [], [], []+ for c, ci in enumerate(idx):+ p = pos[off[ci]:off[ci + 1]]+ if len(p) < 2:+ continue+ nrm = Vector((0, 0, 1))+ if sev is not None: # side vector = tangent x surface normal: cards lie flat on the head+ sinv = surf.matrix_world.inverted()+ nrm = (surf.matrix_world.to_3x3() @ sev.closest_point_on_mesh(sinv @ Vector(p[0]))[2]).normalized()+ col = c % columns+ u0, u1 = col / columns, (col + 1) / columns+ base = len(verts)+ n = len(p)+ for j in range(n):+ t = Vector(p[min(j + 1, n - 1)] - p[max(j - 1, 0)]).normalized()+ side = t.cross(nrm)+ if side.length < 1e-6:+ side = t.orthogonal()+ side.normalize()+ w = width * 0.5 * (1.0 - 0.7 * j / (n - 1)) # taper to 30% at the tip+ verts += [Vector(p[j]) - side * w, Vector(p[j]) + side * w]+ v = j / (n - 1)+ uvs += [(u0, v), (u1, v)]+ for j in range(n - 1):+ a = base + 2 * j+ faces.append((a, a + 1, a + 3, a + 2))+ me = bpy.data.meshes.new(hair.name + "_Cards")+ me.from_pydata([tuple(v) for v in verts], [], faces)+ uv = me.uv_layers.new(name="UVMap")+ loop_v = np.empty(len(me.loops), np.int32)+ me.loops.foreach_get("vertex_index", loop_v)+ uv.uv.foreach_set("vector", np.array(uvs, np.float32)[loop_v].ravel())+ ob = bpy.data.objects.get(me.name)+ if ob is None:+ ob = bpy.data.objects.new(me.name, me)+ bpy.context.scene.collection.objects.link(ob)+ else:+ ob.data = me+ return ob, len(idx), len(faces)+++def render_atlas(name, columns=8, res=1024, out="//textures", seed=0, color=(0.12, 0.07, 0.04)):+ """Flat strand clumps (one per column) rendered orthographically: BC+alpha, root-tip, ID."""+ rng = np.random.default_rng(seed)+ src = bpy.context.window.scene if bpy.context.window else bpy.context.scene+ sc = bpy.data.scenes.new("HairAtlas")+ strands, pts = 40, 16+ curves = bpy.data.hair_curves.new("HairAtlas")+ curves.add_curves([pts] * (strands * columns))+ P = np.zeros((strands * columns, pts, 3), np.float32)+ for c in range(columns):+ cx = (c + 0.5) / columns+ for s in range(strands):+ k = c * strands + s+ x0 = cx + rng.uniform(-0.38, 0.38) / columns+ ln = rng.uniform(0.82, 0.98)+ t = np.linspace(0, 1, pts)+ wave = 0.04 / columns * np.sin(t * rng.uniform(4, 9) + rng.uniform(0, 6.28))+ pinch = (cx - x0) * t ** 1.5 * 0.6 # clump toward the column center at the tip+ P[k, :, 0] = x0 + wave + pinch+ P[k, :, 2] = 0.01 + t * ln+ curves.attributes["position"].data.foreach_set("vector", P.ravel())+ rad = curves.attributes.get("radius") or curves.attributes.new("radius", "FLOAT", "POINT")+ rad.data.foreach_set("value", np.full(strands * columns * pts, 0.6 / res, np.float32)) # ~1.2 px wide+ ob = bpy.data.objects.new("HairAtlas", curves)+ sc.collection.objects.link(ob)+ cam = bpy.data.objects.new("AtlasCam", bpy.data.cameras.new("AtlasCam"))+ sc.collection.objects.link(cam)+ cam.data.type, cam.data.ortho_scale = "ORTHO", 1.0+ cam.location, cam.rotation_euler = (0.5, -2.0, 0.5), (np.pi / 2, 0, 0)+ sc.camera = cam+ sc.render.engine = "CYCLES"+ sc.cycles.samples, sc.cycles.device = 16, "CPU"+ sc.render.resolution_x = sc.render.resolution_y = res+ sc.render.film_transparent = True+ sc.render.image_settings.file_format, sc.render.image_settings.color_mode = "PNG", "RGBA"+ mat = bpy.data.materials.new("HairAtlas_Emit")+ nt = mat.node_tree+ nt.nodes.clear()+ o, em, info = (nt.nodes.new(t) for t in ("ShaderNodeOutputMaterial", "ShaderNodeEmission", "ShaderNodeHairInfo"))+ nt.links.new(em.outputs[0], o.inputs["Surface"])+ curves.materials.append(mat)+ out_dir = bpy.path.abspath(out)+ os.makedirs(out_dir, exist_ok=True)+ paths = {}+ for key, setup in (("BC", "color"), ("RootTip", "Intercept"), ("ID", "Random")):+ for lk in list(em.inputs["Color"].links):+ nt.links.remove(lk)+ if setup == "color": # darker roots, the usual card albedo+ mix = nt.nodes.get("rootdark") or nt.nodes.new("ShaderNodeMix")+ mix.name, mix.data_type = "rootdark", "RGBA"+ mix.inputs[6].default_value = tuple(x * 0.45 for x in color) + (1,)+ mix.inputs[7].default_value = (*color, 1)+ nt.links.new(info.outputs["Intercept"], mix.inputs[0])+ nt.links.new(mix.outputs[2], em.inputs["Color"])+ else:+ nt.links.new(info.outputs[setup], em.inputs["Color"])+ sc.view_settings.view_transform = "Standard" if key == "BC" else "Raw" # data maps stay linear+ sc.render.filepath = os.path.join(out_dir, f"T_{name}_{key}.png")+ with bpy.context.temp_override(scene=sc):+ bpy.ops.render.render(write_still=True, scene=sc.name)+ paths[key] = sc.render.filepath+ for d in (ob, cam):+ bpy.data.objects.remove(d)+ bpy.data.scenes.remove(sc)+ if bpy.context.window:+ bpy.context.window.scene = src+ return paths+++def card_material(name, bc_path):+ mat = bpy.data.materials.get("M_" + name) or bpy.data.materials.new("M_" + name)+ nt = mat.node_tree+ bsdf = bx.node(nt, "BSDF_PRINCIPLED")+ tex = bx.node(nt, "TEX_IMAGE") or nt.nodes.new("ShaderNodeTexImage")+ tex.image = bpy.data.images.load(bc_path, check_existing=True)+ tex.location = bsdf.location.x - 320, bsdf.location.y+ nt.links.new(tex.outputs["Color"], bsdf.inputs["Base Color"])+ nt.links.new(tex.outputs["Alpha"], bsdf.inputs["Alpha"])+ bsdf.inputs["Roughness"].default_value = 0.45+ mat.surface_render_method = "DITHERED"+ mat.use_backface_culling = False # cards are seen from both sides+ return mat+++def run(surface=None, cards=None, mask=None, density=2000.0, children=100000.0, viewport=0.2, length=0.12, points=12, clump=0.5, curl=0.0,+ droop=0.8, noise=0.003, radius=0.00005, melanin=0.65, redness=0.1, roughness=0.3, seed=0, name="Hair",+ card_count=120, card_width=0.012, atlas_columns=8, atlas_res=1024, out="//textures", **_):+ bx.object_mode()+ if surface:+ return groom(surface, mask, density, children, viewport, length, points, clump, curl, droop, noise, radius, melanin, redness,+ roughness, seed, name)+ if not cards:+ raise ValueError("give --surface (groom) or --cards HAIR_OBJECT")+ hair = bpy.data.objects[cards]+ ob, n_cards, quads = build_cards(hair, card_count, card_width, atlas_columns, seed)+ paths = render_atlas(cards + "Card", atlas_columns, atlas_res, out, seed)+ mat = card_material(cards + "Card", paths["BC"])+ ob.data.materials.clear()+ ob.data.materials.append(mat)+ if hair.parent:+ ob.parent = hair.parent+ ob.matrix_parent_inverse = hair.parent.matrix_world.inverted()+ return {"ok": True, "cards": ob.name, "card_count": n_cards, "tris": quads * 2, "atlas": paths,+ "material": mat.name}+++if __name__ == "__main__":+ p = bx.parser(__doc__)+ p.add_argument("--surface", default=None)+ p.add_argument("--cards", default=None, help="hair curves object to convert to cards")+ p.add_argument("--mask", default=None, help="surface vertex group = density mask")+ for k, t, d in (("density", float, 2000.0), ("children", float, 100000.0), ("viewport", float, 0.2), ("length", float, 0.12), ("points", int, 12),+ ("clump", float, 0.5), ("curl", float, 0.0), ("droop", float, 0.8), ("noise", float, 0.003), ("radius", float, 0.00005),+ ("melanin", float, 0.65), ("redness", float, 0.1), ("roughness", float, 0.3), ("seed", int, 0),+ ("card-count", int, 120), ("card-width", float, 0.012), ("atlas-columns", int, 8),+ ("atlas-res", int, 1024)):+ p.add_argument(f"--{k}", type=t, default=d)+ p.add_argument("--name", default="Hair")+ p.add_argument("--out", default="//textures")+ 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.mdindex 1838e20..127ff83 100644--- a/skills/blender-hardsurface-modeling/SKILL.md+++ b/skills/blender-hardsurface-modeling/SKILL.md@@ -4,7 +4,7 @@ description: Hard-surface and prop modeling in Blender 5.2 - blockout-to-detaillicense: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Hard-Surface Modelingdiff --git a/skills/blender-lighting-lookdev/SKILL.md b/skills/blender-lighting-lookdev/SKILL.mdindex b0c8447..4087b16 100644--- a/skills/blender-lighting-lookdev/SKILL.md+++ b/skills/blender-lighting-lookdev/SKILL.md@@ -4,7 +4,7 @@ description: Lighting, cameras and look-dev in Blender 5.2 - studio 3-point andlicense: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Lighting & Look-devdiff --git a/skills/blender-pbr-materials/SKILL.md b/skills/blender-pbr-materials/SKILL.mdindex e8604b8..7d701d1 100644--- a/skills/blender-pbr-materials/SKILL.md+++ b/skills/blender-pbr-materials/SKILL.md@@ -4,7 +4,7 @@ description: Physically based materials in Blender 5.2 - metal/roughness rules,license: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# PBR Materialsdiff --git a/skills/blender-pipeline-automation/SKILL.md b/skills/blender-pipeline-automation/SKILL.mdindex 7f9f171..32b5ea7 100644--- a/skills/blender-pipeline-automation/SKILL.md+++ b/skills/blender-pipeline-automation/SKILL.md@@ -4,7 +4,7 @@ description: Automate Blender 5.2 at scale - headless CLI flags, batch convert/ilicense: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Pipeline Automation@@ -57,4 +57,4 @@ Environment variables: `BLENDER_USER_SCRIPTS`, `BLENDER_USER_EXTENSIONS`, `BLEND- 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.+Download the Linux tarball (`https://download.blender.org/release/Blender5.2/blender-5.2.3-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-rendering/SKILL.md b/skills/blender-rendering/SKILL.mdindex 537fb8b..f593ccd 100644--- a/skills/blender-rendering/SKILL.md+++ b/skills/blender-rendering/SKILL.md@@ -4,7 +4,7 @@ description: Render with Blender 5.2 Cycles/EEVEE/Workbench - quality presets, Glicense: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Renderingdiff --git a/skills/blender-retopology-uv/SKILL.md b/skills/blender-retopology-uv/SKILL.mdindex 5372468..c858c55 100644--- a/skills/blender-retopology-uv/SKILL.md+++ b/skills/blender-retopology-uv/SKILL.md@@ -4,7 +4,7 @@ description: Retopology and UVs in Blender 5.2 - auto retopo (Quadriflow, Decimalicense: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Retopology & UVsdiff --git a/skills/blender-scene-setup/SKILL.md b/skills/blender-scene-setup/SKILL.mdindex 15f1c2f..72d1b0f 100644--- a/skills/blender-scene-setup/SKILL.md+++ b/skills/blender-scene-setup/SKILL.md@@ -4,7 +4,7 @@ description: Set up and audit Blender scenes the way studios do - units and reallicense: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Scene Setup & Hygienediff --git a/skills/blender-sculpting/SKILL.md b/skills/blender-sculpting/SKILL.mdindex 301310a..fcbdfad 100644--- a/skills/blender-sculpting/SKILL.md+++ b/skills/blender-sculpting/SKILL.md@@ -4,7 +4,7 @@ description: Sculpting in Blender 5.2 - base-to-detail workflow, voxel remesh, dlicense: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Sculpting@@ -44,6 +44,9 @@ The execution model is in `blender-core`. The handoff goes to `blender-retopolog- 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).+## References+[references/forms-and-bake-sources.md](references/forms-and-bake-sources.md): human proportions in meters and heads, form order (primary → tertiary), hard-surface sculpting (trim gestures, mask extract, face sets, mesh filters), multires rebuild/reshape, and preparing a high-poly bake source (density, cage, naming, exploding). Load it before character, creature or bake-source work.+## 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).diff --git a/skills/blender-sculpting/references/forms-and-bake-sources.md b/skills/blender-sculpting/references/forms-and-bake-sources.mdnew file mode 100644index 0000000..f312855--- /dev/null+++ b/skills/blender-sculpting/references/forms-and-bake-sources.md@@ -0,0 +1,38 @@+# Forms, proportions, hard-surface sculpting, bake sources (operators verified in Blender 5.2.3)++## Human proportions (art canon, real scale in m)+| | Value |+|---|---|+| Height | adult ~1.75 m (male) / ~1.62 m (female). Model at real scale |+| Heads tall | realistic 7.5 · heroic 8–8.5 · stylized 5–7 · anime teen 6.5–7 · chibi 2–4. Head ≈ 0.22–0.23 m |+| Vertical landmarks | half height = pubis/greater trochanter. Nipples ≈ 2 heads from the top, navel ≈ 3, crotch ≈ 4. Knee ≈ halfway hip → sole |+| Arms | span ≈ height. Elbow at the waist, wrist at the crotch, fingertips mid-thigh (arms down) |+| Widths | shoulders ≈ 2 heads (male), 1.75 (female). Hips ≈ 1.5 (male), 1.75–2 (female) |+| Hand / foot | hand ≈ face height (chin → hairline). Foot ≈ forearm length (~0.26 m) |+| Face | eyes at half the head height, one eye-width apart. Nose base halfway brow → chin. Ears from brow to nose base. Mouth corners under the pupils |+Check proportions in an orthographic front/side view against a 1.75 m reference before any detail. Bad primary forms can't be saved by tertiary detail.++## Silhouette and form order+1. **Gesture/primary**: the big masses (ribcage, pelvis, skull as boxes/eggs), tilts and rhythm. They should read at 5% of screen.+2. **Secondary**: muscle groups, fat pads, bony landmarks (clavicle, iliac crest, kneecap, elbow), cloth folds. Work from planes, not blobs: flatten with `PLANE`, then soften.+3. **Tertiary**: skin pores, wrinkles, scratches, weave. Use Multires level 4–6 or (for games) normal/displacement maps from alphas.+Sculpt from reference, check every few minutes in a flat matcap from several angles, and turn the model upside down/mirrored to see errors fresh.++## Hard-surface sculpting (concepts, kitbash, organic-mechanical)+- **Trim gestures** cut or extrude crisp shapes: `sculpt.trim_box_gesture` / `trim_lasso_gesture` / `trim_line_gesture` (`trim_mode` DIFFERENCE/UNION/JOIN, `trim_solver` EXACT/FLOAT/MANIFOLD). `sculpt.project_line_gesture` flattens to a line.+- **Masks to parts**: paint a mask (or `sculpt.mask_from_cavity`), then `mesh.paint_mask_extract` (new shell object with thickness) or `mesh.paint_mask_slice` (split). `sculpt.face_set_extract` does the same per face set. Ideal for armor plates on a body.+- **Panels**: Face Sets (`sculpt.face_sets_init` by loose parts/normals/UV seams) + `sculpt.expand` for clean borders. Then `sculpt.mesh_filter(type="SHARPEN"|"RELAX_FACE_SETS"|"SURFACE_SMOOTH")` to crisp or relax along them.+- **Remesh in between**: `object.voxel_remesh` fuses cuts. 5.2 interpolates color attributes during voxel remesh, which is less scrambling but a bit blurrier.+- For production game props, hard-surface is usually polygon modeling (`blender-hardsurface-modeling`). Sculpt hard-surface for concepts and organic/mechanical blends.++## Multires tricks+- `object.multires_rebuild_subdiv` recovers subdivision levels from an imported dense mesh that came from a subdivided base. `object.multires_unsubdivide` finds a lower base from a dense uniform mesh.+- `object.multires_reshape` moves the detail of one mesh onto another with the same base topology (e.g. after a retopo with identical base).++## Preparing a high-poly bake source (→ `blender-texture-baking`)+- **Watertight where rays land**: no holes, no inverted parts (run `blender-asset-qa` on the high with `--profile render`). Overlapping floaters are fine (they bake as surface detail), interpenetrating thin shells are not (AO and normal leaks).+- **Density**: at least ~1 high-poly face per texel of the target map over the region. A 2k map on a 1 m prop needs about 2–4 M faces at the detail. Decimate the high (`Decimate` collapse 0.2–0.4) before baking to cut memory: normals survive it.+- **Same silhouette**: the low must envelope the high within the cage distance (1–2% of the object size). Bevel or chamfer high-poly edges so normals have something to capture (0.5–2 mm on props).+- **Naming for bake-by-name**: `Crate_high` / `Crate_low`, one pair per exploded part. Explode overlapping parts (move apart) before baking, or use bake groups, so the AO/normal of one part doesn't project onto another.+- Apply symmetry and scale. Keep the high in its own collection, excluded from export.+- External bakers (Marmoset, Substance): export the high as `.ply`/`.fbx` with smooth normals, triangulated low with tangents (`blender-export-pipelines`).diff --git a/skills/blender-simulation/SKILL.md b/skills/blender-simulation/SKILL.mdindex bcb0f0e..082662e 100644--- a/skills/blender-simulation/SKILL.md+++ b/skills/blender-simulation/SKILL.md@@ -4,7 +4,7 @@ description: Physics in Blender 5.2 - rigid bodies (density mass, shapes, bake tlicense: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Simulationdiff --git a/skills/blender-stylized-npr/SKILL.md b/skills/blender-stylized-npr/SKILL.mdnew file mode 100644index 0000000..4364d33--- /dev/null+++ b/skills/blender-stylized-npr/SKILL.md@@ -0,0 +1,62 @@+---+name: blender-stylized-npr+description: Stylized / NPR looks in Blender 5.2 - toon and cel shading (bands, shadow tint, rim, hard specular), anime faces with custom normals, inverted-hull outlines with smoothed outline normals for game engines, Line Art and Freestyle lines, Grease Pencil drawing, unlit export. Use for anime, cartoon, comic, cel-shaded or outlined styles.+license: MIT+metadata:+ author: blender-agent-skills+ version: "1.2.0"+---++# Stylized / NPR++The execution model is in `blender-core`. Base colors still come from `blender-pbr-materials`/`blender-texturing`. This skill replaces how they're lit.++## One call each+```+scripts/toon_setup.py -- --objects Hero Sword --bands 2 --rim 0.4 --outline 0.004+scripts/toon_setup.py -- --objects Hero --bands 3 --spec 0.3 --smooth-normals # + engine outline data+scripts/toon_setup.py -- --objects Hero --lighting scene # EEVEE: all lights + cast shadows+scripts/toon_setup.py -- --line-art --outline 0 # scene-wide Line Art+scripts/toon_setup.py -- --objects Hero Sword --remove --line-art # exact restore+```++## toon_setup.py+- Inserts an `NPR_Toon` emission group between each material's Principled base color and the output, and records the original surface link for `--remove`. Re-running updates values in place.+- **`--lighting key`** (default, Cycles + EEVEE): shading = N·L against one sun (`--light`; `NPR_Key` is created if there's none). Drivers follow the sun's rotation, so rotate the sun to art-direct the shadow shape. This is how engine toon shaders work, and the look matches after export.+- **`--lighting scene`**: Shader to RGB on a white diffuse, so every light and cast shadow shapes the bands. **EEVEE only.** Measured: in Cycles, Shader to RGB returns a constant regardless of light (identical render at 0, 3 and 10 W/m² sun).+- Bands: 2 (lit/shadow, classic anime) or 3 (adds a mid band 0.45 above `--threshold`). `--softness` (0.02) is the half-width of the band edge, so 0 aliases. `--shadow-tint` multiplies the base color: use cool and saturated (0.6, 0.55, 0.75), never grey/black, because grey shadows read as dirty.+- `--rim` (0–1) adds a lit-side rim, and `--spec` (0–1) a hard Blinn highlight disc (0.2–0.4 for hair/metal, 0 for skin).+- Sets **view transform Standard**: AgX/Filmic desaturate and compress flat colors, so the albedo you pick is the pixel you get only under Standard. The original is restored on `--remove`.++## Outlines (pros use several at once)+| Method | Where it works | Notes |+|---|---|---|+| Inverted hull (`--outline`, m) | Cycles, EEVEE, engines | Solidify outward, flipped normals, outline slot, Backfacing→transparent. Width 2–6 mm on a 1.75 m character. `--outline-group` = vertex group for width (taper toward tips, 0 inside the mouth) |+| `--smooth-normals` | engine outline shaders | `NPR_OutlineNormal` corner color = position-welded normal in tangent space (0.5 + 0.5n). Hard edges/UV splits no longer open gaps. Decode `n = TBN·(c·2−1)` |+| Line Art (`--line-art`, Grease Pencil) | renders | contour + crease + intersection from the camera. Needs a scene camera. `--line-radius` (m) |+| Freestyle | renders | `scene.render.use_freestyle = True`, `line_thickness` px. Slowest, most options |+Known hull limits: lines at intersections and inner creases are missing (use Line Art for those in renders), and hard-edged meshes split the hull. In Blender, merge by distance before the Solidify. In engines, use `--smooth-normals`.++## Anime faces and hair+- Face shadows from real normals look blotchy. Transfer **custom normals** from a simple ellipsoid proxy: a Data Transfer modifier with `use_loop_data=True`, `data_types_loops={'CUSTOM_NORMAL'}`, `loop_mapping='POLYINTERP_NEAREST'` (no auto smooth needed since 4.1), masked by a face vertex group. Engines import the custom normals (FBX/glTF export normals).+- For a stylized nose/cheek shadow, many games use an SDF face shadow texture sampled with the light angle in-engine. Author it as a grayscale threshold map, not in the node tree.+- Hair: a strong `--spec` plus a hand-painted highlight band ("angel ring") in the base color texture.++## Grease Pencil (5.x API)+```python+gp = bpy.data.grease_pencils.new("Ink"); ob = bpy.data.objects.new("Ink", gp); scene.collection.objects.link(ob)+mat = bpy.data.materials.new("Ink"); bpy.data.materials.create_gpencil_data(mat); gp.materials.append(mat)+drawing = gp.layers.new("Lines").frames.new(1).drawing+drawing.add_strokes([3]); s = drawing.strokes[0]+for i, p in enumerate(s.points): p.position, p.radius = (i * 0.5, 0, 0), 0.01 # radius in m+```+Strokes expose `cyclic`, `material_index`, `fill_id`, `hide_stroke`. Raw attributes: `drawing.attributes` (`position`, `radius`). `GreasePencilv3`/`grease_pencils_v3` are gone (5.0). 5.2 Line Art can emit fill strokes (`fill_strokes`).++## To game engines+Node toon shading doesn't export. Export the base color textures and rebuild the toon ramp in the engine (UE material/post-process, Unity URP toon shader, Godot `ShaderMaterial`), driven by the same sun direction. Ship the hull as a second material slot (apply the modifier), or as `NPR_OutlineNormal` for a shader outline pass.+For flat, unlit assets in glTF, use a **Background** shader, or Light Path *Is Camera Ray* mixing Transparent→Background: both export as `KHR_materials_unlit`. Emission exports as emissive on a black base, not unlit (measured).++## Gotchas+- Apply scale before `--outline`: Solidify thickness is in object space.+- Bloom and AO fight the flat look. Keep the world dim and uniform, and use one key light plus maybe a rim light.+- `--lighting scene` bands shift with light energy (luminance 0.3 ≈ threshold 0). Raise/lower `--threshold` instead of the light power.diff --git a/skills/blender-stylized-npr/scripts/_bpyx.py b/skills/blender-stylized-npr/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-stylized-npr/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-stylized-npr/scripts/toon_setup.py b/skills/blender-stylized-npr/scripts/toon_setup.pynew file mode 100644index 0000000..f6f2c35--- /dev/null+++ b/skills/blender-stylized-npr/scripts/toon_setup.py@@ -0,0 +1,365 @@+"""Reversible toon/cel look: banded shading, shadow tint, rim, hard specular, inverted-hull outlines,+smoothed outline normals for engine shaders, and an optional Line Art (Grease Pencil) pass.++--lighting key (default): N.L against one sun (--light, created if missing) through drivers. Works in+Cycles and EEVEE and matches engine toon shaders. --lighting scene: EEVEE Shader to RGB, reacting+to every light and cast shadows (Shader to RGB is constant in Cycles). Sets view transform Standard+(AgX desaturates flat colors). --remove restores materials, slots, modifiers and view transform.+Usage:+ blender -b f.blend -P toon_setup.py -- --objects Hero Sword [--bands 2|3] [--shadow-tint 0.6 0.55 0.75]+ [--threshold 0.0] [--softness 0.02] [--rim 0.4] [--spec 0.0] [--lighting key|scene] [--light Sun]+ [--outline 0.004] [--outline-color 0.05 0.04 0.06] [--outline-group LineWidth]+ [--smooth-normals] [--line-art] [--line-radius 0.002] [--save out.blend]+ blender -b f.blend -P toon_setup.py -- --objects Hero Sword --remove+ MCP: import toon_setup as t; print(t.run(objects=["Hero"], bands=3, outline=0.004, rim=0.4))+"""+import json+import os+import sys++import bpy+import numpy as np++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++GROUP, TAG, KEY = "NPR_Toon", "NPR_", "npr_toon"+OUTLINE_MAT, OUTLINE_MOD, NORMAL_ATTR = "NPR_M_Outline", "NPR_Outline", "NPR_OutlineNormal"+LINEART = "NPR_LineArt"+++def _lin(c):+ return tuple(x / 12.92 if x <= 0.04045 else ((x + 0.055) / 1.055) ** 2.4 for x in c[:3]) + (1.0,)+++class _G:+ def __init__(self, nt):+ self.nt = nt++ def link(self, a, b):+ self.nt.links.new(a, b)++ def set(self, sock, v):+ if isinstance(v, bpy.types.NodeSocket):+ self.link(v, sock)+ elif v is not None:+ sock.default_value = v++ def n(self, type_, **props):+ node = self.nt.nodes.new(type_)+ for k, v in props.items():+ setattr(node, k, v)+ return node++ def math(self, op, a, b=0.0, clamp=False):+ m = self.n("ShaderNodeMath", operation=op, use_clamp=clamp)+ self.set(m.inputs[0], a)+ self.set(m.inputs[1], b)+ return m.outputs[0]++ def vmath(self, op, a, b=None):+ m = self.n("ShaderNodeVectorMath", operation=op)+ self.set(m.inputs[0], a)+ self.set(m.inputs[1], b)+ return m.outputs["Value" if op == "DOT_PRODUCT" else "Vector"]++ def step(self, v, edge, soft):+ m = self.n("ShaderNodeMapRange", interpolation_type="SMOOTHSTEP", clamp=True)+ self.set(m.inputs[0], v)+ self.set(m.inputs[1], self.math("SUBTRACT", edge, soft))+ self.set(m.inputs[2], self.math("ADD", edge, soft))+ return m.outputs[0]++ def mix(self, fac, a, b, blend="MIX"):+ m = self.n("ShaderNodeMix", data_type="RGBA", blend_type=blend)+ self.set(m.inputs[0], fac)+ self.set(m.inputs[6], a)+ self.set(m.inputs[7], b)+ return m.outputs[2]+++def build_group():+ ng = bpy.data.node_groups.get(GROUP) or bpy.data.node_groups.new(GROUP, "ShaderNodeTree")+ ng.nodes.clear()+ ng.interface.clear()+ for nm, kind, d in (("Base Color", "Color", (0.8, 0.8, 0.8, 1)), ("Light Direction", "Vector", (0.3, -0.5, 0.8)),+ ("Scene Lighting", "Float", 0.0), ("Bands", "Float", 2.0), ("Threshold", "Float", 0.0),+ ("Softness", "Float", 0.02), ("Shadow Tint", "Color", (0.32, 0.27, 0.52, 1)),+ ("Rim", "Float", 0.0), ("Specular", "Float", 0.0)):+ s = ng.interface.new_socket(nm, in_out="INPUT", socket_type=f"NodeSocket{kind}")+ s.default_value = d+ ng.interface.new_socket("Shader", in_out="OUTPUT", socket_type="NodeSocketShader")+ g = _G(ng)+ gi, go = g.n("NodeGroupInput"), g.n("NodeGroupOutput")+ I = gi.outputs # noqa: E741+ geo = g.n("ShaderNodeNewGeometry")+ N, V = geo.outputs["Normal"], geo.outputs["Incoming"]+ L = g.vmath("NORMALIZE", I["Light Direction"])+ ndl = g.vmath("DOT_PRODUCT", N, L)+ # scene lighting (EEVEE): luminance of a lit white diffuse, remapped to the same -1..1 range+ s2r = g.n("ShaderNodeShaderToRGB")+ g.link(g.n("ShaderNodeBsdfDiffuse").outputs[0], s2r.inputs[0])+ lum = g.n("ShaderNodeRGBToBW")+ g.link(s2r.outputs["Color"], lum.inputs[0])+ scene_v = g.n("ShaderNodeMapRange", clamp=False)+ g.link(lum.outputs[0], scene_v.inputs[0])+ scene_v.inputs[1].default_value, scene_v.inputs[2].default_value = 0.0, 0.6+ scene_v.inputs[3].default_value, scene_v.inputs[4].default_value = -1.0, 1.0+ shade = g.n("ShaderNodeMix", data_type="FLOAT")+ g.link(I["Scene Lighting"], shade.inputs[0])+ g.link(ndl, shade.inputs[2])+ g.link(scene_v.outputs[0], shade.inputs[3])+ s = shade.outputs[0]+ lit = g.step(s, I["Threshold"], I["Softness"])+ # optional mid band (Bands >= 3) halfway between shadow and light, 0.45 above the threshold+ mid = g.math("MULTIPLY", g.step(s, g.math("ADD", I["Threshold"], 0.45), I["Softness"]),+ g.math("GREATER_THAN", I["Bands"], 2.5))+ shadow_col = g.mix(1.0, I["Base Color"], I["Shadow Tint"], "MULTIPLY")+ mid_col = g.mix(0.5, shadow_col, I["Base Color"])+ three = g.math("GREATER_THAN", I["Bands"], 2.5)+ col = g.mix(lit, shadow_col, g.mix(three, I["Base Color"], g.mix(mid, mid_col, I["Base Color"])))+ # hard specular: N.H above 1 - size (Blinn half vector), only on the lit side+ H = g.vmath("NORMALIZE", g.vmath("ADD", L, V))+ spec_on = g.math("GREATER_THAN", I["Specular"], 0.0)+ spec = g.step(g.vmath("DOT_PRODUCT", N, H), g.math("SUBTRACT", 1.0, g.math("MULTIPLY", I["Specular"], 0.03)), 0.002)+ spec = g.math("MULTIPLY", g.math("MULTIPLY", spec, lit), spec_on)+ col = g.mix(spec, col, (1, 1, 1, 1), "SCREEN")+ # rim: grazing angles on the lit side+ lw = g.n("ShaderNodeLayerWeight")+ lw.inputs["Blend"].default_value = 0.5+ rim = g.step(lw.outputs["Facing"], g.math("SUBTRACT", 1.0, g.math("MULTIPLY", I["Rim"], 0.35)), 0.02)+ rim = g.math("MULTIPLY", g.math("MULTIPLY", rim, lit), g.math("GREATER_THAN", I["Rim"], 0.0))+ col = g.mix(g.math("MULTIPLY", rim, 0.6), col, (1, 1, 1, 1), "SCREEN")+ em = g.n("ShaderNodeEmission")+ g.link(col, em.inputs["Color"])+ g.link(em.outputs[0], go.inputs[0])+ return ng+++def _outline_material(color):+ mat = bpy.data.materials.get(OUTLINE_MAT) or bpy.data.materials.new(OUTLINE_MAT)+ nt = mat.node_tree+ nt.nodes.clear()+ out = nt.nodes.new("ShaderNodeOutputMaterial")+ em, tr, mx = (nt.nodes.new(t) for t in ("ShaderNodeEmission", "ShaderNodeBsdfTransparent", "ShaderNodeMixShader"))+ geo = nt.nodes.new("ShaderNodeNewGeometry")+ em.inputs["Color"].default_value = _lin(color)+ nt.links.new(geo.outputs["Backfacing"], mx.inputs[0]) # flipped hull: only its far shell faces us+ nt.links.new(em.outputs[0], mx.inputs[1])+ nt.links.new(tr.outputs[0], mx.inputs[2])+ nt.links.new(mx.outputs[0], out.inputs["Surface"])+ mat.use_backface_culling = True # EEVEE/Workbench; Cycles relies on the Backfacing mix+ mat.surface_render_method = "DITHERED"+ return mat+++def _key_light(name):+ if name:+ return bpy.data.objects[name]+ sun = next((o for o in bpy.context.scene.objects if o.type == "LIGHT" and o.data.type == "SUN"), None)+ if sun is None:+ sun = bpy.data.objects.new("NPR_Key", bpy.data.lights.new("NPR_Key", "SUN"))+ bpy.context.scene.collection.objects.link(sun)+ sun.rotation_euler = (0.7, 0.0, 0.6)+ sun.data.energy = 3.0+ return sun+++def _drive_light(sock, sun):+ """Light Direction = the sun's local +Z in world space (the sun shines along -Z)."""+ for i in range(3):+ fc = sock.driver_add("default_value", i)+ d = fc.driver+ d.type = "SCRIPTED"+ for v in list(d.variables):+ d.variables.remove(v)+ var = d.variables.new()+ var.name, var.type = "m", "SINGLE_PROP"+ var.targets[0].id, var.targets[0].data_path = sun, f"matrix_world[2][{i}]"+ d.expression = "m"+++def _apply_mat(mat, ng, vals, sun):+ nt = mat.node_tree+ out = next((n for n in nt.nodes if n.type == "OUTPUT_MATERIAL" and n.is_active_output), None)+ bsdf = bx.node(nt, "BSDF_PRINCIPLED")+ if out is None:+ return False+ gn = nt.nodes.get(TAG + "toon")+ surf = out.inputs["Surface"]+ if gn is None: # first application: remember the original surface+ rec = {"out": out.name}+ if surf.is_linked:+ rec["from"] = [surf.links[0].from_node.name, surf.links[0].from_socket.identifier]+ mat[KEY] = json.dumps(rec)+ gn = nt.nodes.new("ShaderNodeGroup")+ gn.name, gn.label, gn.node_tree = TAG + "toon", "NPR Toon", ng+ gn.location = out.location.x - 220, out.location.y + 220+ # (re)wire on every run: re-running rebuilds the group, which recreates its sockets and drops links+ if bsdf is not None:+ bc = bsdf.inputs["Base Color"]+ if bc.is_linked:+ nt.links.new(bc.links[0].from_socket, gn.inputs["Base Color"])+ else:+ gn.inputs["Base Color"].default_value = bc.default_value+ nt.links.new(gn.outputs[0], surf)+ for k, v in vals.items():+ gn.inputs[k].default_value = v+ if sun is not None:+ _drive_light(gn.inputs["Light Direction"], sun)+ return True+++def _remove_mat(mat):+ nt = mat.node_tree+ rec = json.loads(mat.get(KEY, "{}"))+ out = nt.nodes.get(rec.get("out", ""))+ for nd in [nd for nd in nt.nodes if nd.name.startswith(TAG)]:+ if nd.inputs.get("Light Direction") is not None:+ nd.inputs["Light Direction"].driver_remove("default_value")+ nt.nodes.remove(nd)+ if out is not None and "from" in rec and rec["from"][0] in nt.nodes:+ nt.links.new(nt.nodes[rec["from"][0]].outputs[rec["from"][1]], out.inputs["Surface"])+ if KEY in mat:+ del mat[KEY]+++def smooth_outline_normals(ob, uv=None):+ """NPR_OutlineNormal corner color: position-averaged normal in tangent space, packed 0.5 + 0.5 n.++ Engine outline shaders extrude along this instead of the split normal, so hard edges don't open+ gaps. Decode: n = TBN * (c * 2 - 1)."""+ me = ob.data+ if not me.uv_layers:+ raise ValueError(f"{ob.name}: --smooth-normals needs a UV map (tangent space)")+ me.calc_tangents(uvmap=uv or me.uv_layers.active.name)+ nl, nv = len(me.loops), len(me.vertices)+ co = np.empty(nv * 3, np.float32)+ me.vertices.foreach_get("co", co)+ key = np.unique(np.round(co.reshape(-1, 3), 5), axis=0, return_inverse=True)[1].ravel()+ vn = np.empty(nv * 3, np.float32)+ me.vertex_normals.foreach_get("vector", vn)+ acc = np.zeros((key.max() + 1, 3))+ np.add.at(acc, key, vn.reshape(-1, 3)) # weld split vertices by position+ acc /= np.maximum(np.linalg.norm(acc, axis=1), 1e-9)[:, None]+ lv = np.empty(nl, np.int32)+ me.loops.foreach_get("vertex_index", lv)+ t, n, sgn = np.empty(nl * 3, np.float32), np.empty(nl * 3, np.float32), np.empty(nl, np.float32)+ me.loops.foreach_get("tangent", t)+ me.loops.foreach_get("normal", n)+ me.loops.foreach_get("bitangent_sign", sgn)+ t, n = t.reshape(-1, 3), n.reshape(-1, 3)+ b = np.cross(n, t) * sgn[:, None]+ s = acc[key[lv]]+ ts = np.stack([(t * s).sum(1), (b * s).sum(1), (n * s).sum(1)], 1)+ me.free_tangents()+ at = me.color_attributes.get(NORMAL_ATTR) or me.color_attributes.new(NORMAL_ATTR, "FLOAT_COLOR", "CORNER")+ at.data.foreach_set("color", np.hstack([ts * 0.5 + 0.5, np.ones((nl, 1))]).astype(np.float32).ravel())+ return float(ts[:, 2].min())+++def _line_art(radius, color):+ ob = bpy.data.objects.get(LINEART)+ if ob is None:+ gp = bpy.data.grease_pencils.new(LINEART)+ gp.layers.new("Lines")+ ob = bpy.data.objects.new(LINEART, gp)+ bpy.context.scene.collection.objects.link(ob)+ gp = ob.data+ mat = bpy.data.materials.get("NPR_M_Line") or bpy.data.materials.new("NPR_M_Line")+ if not mat.is_grease_pencil:+ bpy.data.materials.create_gpencil_data(mat)+ mat.grease_pencil.color = _lin(color)+ if mat.name not in gp.materials:+ gp.materials.append(mat)+ md = ob.modifiers.get("LineArt") or ob.modifiers.new("LineArt", "LINEART")+ md.source_type, md.target_layer, md.target_material = "SCENE", "Lines", mat+ md.use_contour = md.use_crease = md.use_intersection = True+ md.radius = radius+ return ob.name+++def run(objects=None, bands=2, shadow_tint=(0.6, 0.55, 0.75), threshold=0.0, softness=0.02, rim=0.0,+ spec=0.0, lighting="key", light=None, outline=0.004, outline_color=(0.05, 0.04, 0.06),+ outline_group=None, smooth_normals=False, line_art=False, line_radius=0.002, remove=False, **_):+ bx.object_mode()+ sc = bpy.context.scene+ obs = [o for o in bx.objects(objects) if o.type == "MESH"]+ mats = {s.material for o in obs for s in o.material_slots if s.material and s.material.node_tree+ and s.material.name != OUTLINE_MAT}+ if remove:+ for m in mats:+ _remove_mat(m)+ for o in obs:+ md = o.modifiers.get(OUTLINE_MOD)+ if md:+ o.modifiers.remove(md)+ idx = o.data.materials.find(OUTLINE_MAT)+ if idx >= 0:+ o.data.materials.pop(index=idx)+ ca = o.data.color_attributes.get(NORMAL_ATTR)+ if ca:+ o.data.color_attributes.remove(ca)+ if KEY in sc:+ sc.view_settings.view_transform = sc[KEY]+ del sc[KEY]+ la = bpy.data.objects.get(LINEART)+ if la and line_art:+ bpy.data.objects.remove(la)+ return {"ok": True, "removed": sorted(m.name for m in mats), "objects": [o.name for o in obs]}+ if lighting not in ("key", "scene"):+ raise ValueError("--lighting must be key or scene")+ sun = _key_light(light) if lighting == "key" else None+ ng = build_group()+ vals = {"Bands": float(bands), "Threshold": threshold, "Softness": softness, "Shadow Tint": _lin(shadow_tint),+ "Rim": rim, "Specular": spec, "Scene Lighting": 1.0 if lighting == "scene" else 0.0}+ done = [m.name for m in mats if _apply_mat(m, ng, vals, sun)]+ if KEY not in sc:+ sc[KEY] = sc.view_settings.view_transform+ sc.view_settings.view_transform = "Standard"+ res = {"ok": True, "objects": [o.name for o in obs], "materials": sorted(done), "lighting": lighting,+ "view_transform": "Standard"}+ if sun is not None:+ res["key_light"] = sun.name+ if lighting == "scene" and sc.render.engine != "BLENDER_EEVEE":+ res["warning"] = "lighting=scene needs EEVEE (Shader to RGB is constant in Cycles)"+ no_mat = [o.name for o in obs if not any(s.material for s in o.material_slots)]+ if no_mat:+ res["warning"] = f"no material (skipped): {no_mat}"+ if outline > 0:+ omat = _outline_material(outline_color)+ for o in obs:+ if o.data.materials.find(OUTLINE_MAT) < 0:+ o.data.materials.append(omat)+ md = o.modifiers.get(OUTLINE_MOD) or o.modifiers.new(OUTLINE_MOD, "SOLIDIFY")+ md.thickness, md.offset = outline, 1.0 # grow outward only+ md.use_flip_normals, md.use_rim, md.use_quality_normals = True, False, True+ md.material_offset = o.data.materials.find(OUTLINE_MAT) # shell faces use the outline slot+ if outline_group:+ md.vertex_group = outline_group if outline_group in o.vertex_groups else ""+ res["outline"] = {"modifier": OUTLINE_MOD, "thickness_m": outline}+ if smooth_normals:+ res["outline_normals"] = {o.name: {"attribute": NORMAL_ATTR, "min_z": round(smooth_outline_normals(o), 3)}+ for o in obs}+ if line_art:+ res["line_art"] = _line_art(line_radius, outline_color)+ if sc.camera is None:+ res["warning"] = "Line Art needs a scene camera"+ return res+++if __name__ == "__main__":+ p = bx.add_common(bx.parser(__doc__))+ p.add_argument("--bands", type=int, default=2, choices=(2, 3))+ p.add_argument("--shadow-tint", type=float, nargs=3, default=(0.6, 0.55, 0.75), help="sRGB multiplier")+ for k, d in (("threshold", 0.0), ("softness", 0.02), ("rim", 0.0), ("spec", 0.0), ("outline", 0.004),+ ("line-radius", 0.002)):+ p.add_argument(f"--{k}", type=float, default=d)+ p.add_argument("--lighting", default="key", choices=("key", "scene"))+ p.add_argument("--light", default=None, help="sun object for key lighting (default: first sun)")+ p.add_argument("--outline-color", type=float, nargs=3, default=(0.05, 0.04, 0.06), help="sRGB")+ p.add_argument("--outline-group", default=None, help="vertex group scaling outline width")+ p.add_argument("--smooth-normals", action="store_true")+ p.add_argument("--line-art", action="store_true")+ p.add_argument("--remove", action="store_true")+ bx.cli(run, p)diff --git a/skills/blender-texture-baking/SKILL.md b/skills/blender-texture-baking/SKILL.mdindex 1685203..f144e4a 100644--- a/skills/blender-texture-baking/SKILL.md+++ b/skills/blender-texture-baking/SKILL.md@@ -4,7 +4,7 @@ description: Bake texture maps in Blender 5.2 Cycles - high-to-low normal maps wlicense: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Texture Baking (Cycles)diff --git a/skills/blender-texturing/SKILL.md b/skills/blender-texturing/SKILL.mdnew file mode 100644index 0000000..54d544a--- /dev/null+++ b/skills/blender-texturing/SKILL.md@@ -0,0 +1,56 @@+---+name: blender-texturing+description: Texture authoring in Blender 5.2 - smart-material layers (edge wear, cavity grime, dust, rust, roughness breakup) from curvature/AO masks, z-fight-safe decal and sticker placement, trim sheets, tiling + vertex-color blends, texture painting, baking the look to game texture sets. Use when a material needs wear, dirt, a decal, trims or hand painting, not just wiring.+license: MIT+metadata:+ author: blender-agent-skills+ version: "1.2.0"+---++# Texturing++The execution model is in `blender-core`. Material wiring and measured values are in `blender-pbr-materials`, and bakes are in `blender-texture-baking`. This skill authors the *surface story*: where paint chips, where dirt collects, what's printed on it.++## One call each+```+scripts/smart_material.py -- --objects Crate --wear 0.5 --grime 0.4 --dust 0.3+scripts/smart_material.py -- --objects Crate --rust 0.6 --under-color 0.3 0.29 0.28 # rusty iron+scripts/smart_material.py -- --objects SM_Crate --wear 0.5 --curvature-map //tex/T_Crate_CURV.png --ao-map //tex/T_Crate_AO.png+scripts/decal.py -- --target Wall --at 0 -0.1 1.5 --image //decals/hazard.png --size 0.4+scripts/smart_material.py -- --objects Crate --remove # exact restore+```++## How pros layer a material+Start with a clean base (correct albedo/roughness, `blender-pbr-materials`), then stack from the inside out: **base → edge wear → rust → grime → dust**. Each layer has a physical cause:+| Layer | Mask (cause) | Look |+|---|---|---|+| Edge wear | convex curvature (edges get hit) + chip noise | reveals the under-material: bare metal, primer, raw wood |+| Rust | cavities and worn edges + blotch noise | orange-brown, metallic 0, roughness ~0.85 |+| Grime | concave curvature + (1 − AO) (dirt collects where it can't be wiped) | dark, rougher, not metallic |+| Dust | world up-facing normal × patch noise (it settles from above) | light, roughness ~0.9 |+| Breakup | fine noise on roughness (±25%) | the cheapest realism win; never ship a flat roughness value |+Pure curvature looks procedural and even. Always multiply in noise so wear is heavy in some places and absent in others. Less is more: wear 0.2–0.4 reads as "used", and 0.7+ reads as "abandoned".++## smart_material.py+- Inserts one `TX_Layers` group in front of every Principled BSDF (Base Color, Roughness, Metallic) and records the originals, so `--remove` restores links and values exactly. Re-running updates values in place. All layer amounts stay inputs on the group node, so you can tweak them there.+- **Curvature**, live and portable (Cycles + EEVEE, no bake): the `TX_Curvature` point attribute is the mean elevation of the neighbours within `--edge-width` (m, default 0.02). It's density-independent: band ≈ edge width. Set the width to roughly the bevel width (1–3 cm on props, 5–10 cm on buildings). Cost: ~1.5 s per 30k verts.+- It needs **mid-poly density** (bevels/supports). When the median edge is > 4× the edge width, the result carries a `note`: wear would smear across whole faces. On low-poly game meshes, bake from the high (`bake_maps.py --high ... --maps normal ao curvature`) and pass `--curvature-map`/`--ao-map` (loaded as Non-Color, read through `--uv`).+- Noise is in **object space** (`--scale` = feature size in m), so masks stick to the asset when it moves. Mirrored/linked duplicates share the pattern, so vary `--scale` or the object if that shows.+- Colors are sRGB 0–1. Defaults: steel under paint (0.56, 0.57, 0.58, metallic 1, roughness 0.35). For wood under paint, use `--under-color 0.45 0.32 0.2 --under-metallic 0 --under-roughness 0.7`.++## To game engines+Engines don't run Blender node trees. Bake the result into a texture set: `bake_maps.py -- --low SM_Crate --maps basecolor roughness metallic normal --pack-orm` (self-bake, no `--high`). Then `build_pbr_material.py --textures` and export. Check the result with `blender-asset-qa` and a lit `look`.++## Decals (decal.py)+- Places a subdivided plane at the closest surface point to `--at`, oriented to the normal and spun by `--rotation`. A Shrinkwrap (project, above surface) keeps it `--offset` (2 mm) off the surface. It's parented, has no shadow, uses Dithered alpha, and its height follows the image aspect.+- It measures the gap at every triangle like `blender-asset-qa` does, and doubles `--subdiv` (to 128) until flat triangles stop dipping over convex creases. The result reports `gap_min_m`/`gap_max_m`. Never place decals at 0 offset: that's guaranteed z-fighting.+- Games: mesh decals cost a draw call each and need alpha sorting. Merge decals that share an atlas into one mesh, use engine projectors (UE Decal Actor, Unity URP Decal Projector, Godot `Decal`) for dynamic ones, or bake them into the base texture.++## Trim sheets, tiling, painting+Trim sheets, tiling with vertex-color blends, hand/texture painting (5.2 brush assets) and headless pixel writes: [references/trims-tiling-painting.md](references/trims-tiling-painting.md).++## Gotchas+- Mask textures (curvature, AO, roughness, ID) must be **Non-Color**. The script forces it, but hand-made nodes often don't.+- Apply scale before computing curvature or setting `--scale`. Both are world-sized.+- `TX_Curvature` is mesh data. Applying modifiers or remeshing afterward invalidates it, so re-run after topology changes.+- Viewport EEVEE vs Cycles: identical masks (no Bevel/Pointiness/AO shader nodes are used, because those are Cycles-only or screen-space).diff --git a/skills/blender-texturing/references/trims-tiling-painting.md b/skills/blender-texturing/references/trims-tiling-painting.mdnew file mode 100644index 0000000..814cbf9--- /dev/null+++ b/skills/blender-texturing/references/trims-tiling-painting.md@@ -0,0 +1,41 @@+# Trim sheets, tiling blends, texture painting (verified in Blender 5.2.3)++## Trim sheets (environment and hard-surface kits)+- One texture holds horizontal **strips** (trims) that tile in U: panels, edges, bolts, pipes, rails. Many meshes share one material, which means few draw calls, high texel density, and consistent wear.+- Layout: a 2048² or 4096² sheet with strip heights in powers of two (32/64/128/256/512 px), so mips don't bleed. Put the most-used trims tallest. Leave 4–8 px gutters.+- Model with UV-friendly pieces: each face's UVs go into exactly one strip, with U running along the length. Keep the kit's **texel density** fixed (`blender-retopology-uv` `texel_density.py`, e.g. 512 px/m) and let U overrun 0–1 to tile.+- Snap an island to a strip with numpy (`v0`/`v1` are the strip's bounds, 0–1 from the bottom):+```python+uv = me.uv_layers.active.uv; a = np.empty(len(uv) * 2, np.float32); uv.foreach_get("vector", a)+a = a.reshape(-1, 2); sel = ... # loop indices of the island+a[sel, 1] = v0 + (a[sel, 1] - a[sel, 1].min()) / np.ptp(a[sel, 1]) * (v1 - v0)+uv.foreach_set("vector", a.ravel())+```+- Unique hero assets still get unique textures. Trims are for kits, architecture and vehicles' repeated parts.++## Tiling materials + vertex-color blends (large surfaces)+- Tiling textures (concrete, brick, ground) + a **color attribute** that blends a second layer (moss, dirt, wet). This keeps resolution infinite and memory tiny. Paint the mask in Vertex Paint (5.2: spherical falloff draws a surface-aligned cursor), or compute it (`blender-weather-fx` `--vertex-mask`, slope/height masks in `blender-environment-kits`).+- Height-blend instead of a linear fade: `t = clamp((hB − hA + (mask·2 − 1)) · contrast + 0.5)`. The second layer fills the cracks of the first first, which looks natural. The node is `ShaderNodeVertexColor` (`layer_name`).+- Engines get the mask as COLOR_0 (glTF exports the active color attribute, `export_vertex_color`). Rebuild the blend in the engine shader.++## Texture painting (live session with UI)+```python+img = bpy.data.images.new("T_Hand_BC", 2048, 2048) # or load the baked base color+tex = mat.node_tree.nodes.new("ShaderNodeTexImage"); tex.image = img+mat.node_tree.nodes.active = tex # the active image node is the paint target+bpy.ops.object.mode_set(mode="TEXTURE_PAINT")+bpy.ops.brush.asset_activate(asset_library_type="ESSENTIALS",+ relative_asset_identifier="brushes/essentials_brushes-mesh_texture.blend/Brush/Paint Hard")+ts = bpy.context.tool_settings.image_paint; ts.mode = "IMAGE"; ts.canvas = img # or "MATERIAL"+```+- Essentials texture brushes include `Paint Hard`, `Paint Soft`, `Airbrush`, `Blur`, `Smear`, `Clone`, `Fill`, `Mask`, `Erase Hard`, `Paint Pixel Art`.+- Strokes from Python are fragile (`paint.image_paint(stroke=[...])` needs a 3D View region). Agents should set up the canvas and brushes and let the human paint, or write pixels directly.+- **Save images explicitly** (`img.filepath_raw = ...; img.save()`). Painted images live only in memory. 5.2 autosave covers texture paint sessions, but don't rely on it.+- Projection painting from a photo: `paint.project_image(image=...)` projects onto the mesh from the view (UI only). `ts.seam_bleed` (px) hides UV seams, and `ts.use_occlude` stops paint going through.++## Headless pixel writes (masks, IDs, procedural stencils)+```python+a = np.zeros((h, w, 4), np.float32); a[..., 3] = 1; a[y0:y1, x0:x1, 0] = 1 # rows = y from the bottom+img.pixels.foreach_set(a.ravel()); img.update(); img.save()+```+5.2 adds the `imbuf` module (`imbuf.new((w, h))`, `load`, `write`, `with_buffer` for buffer-protocol access, `quality`/`compress`) for file I/O without creating an Image data-block.diff --git a/skills/blender-texturing/scripts/_bpyx.py b/skills/blender-texturing/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-texturing/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-texturing/scripts/decal.py b/skills/blender-texturing/scripts/decal.pynew file mode 100644index 0000000..7dbe999--- /dev/null+++ b/skills/blender-texturing/scripts/decal.py@@ -0,0 +1,133 @@+"""Mesh decal that conforms to a surface without z-fighting: a subdivided plane placed at the+closest surface point, shrinkwrapped a fixed offset above it, parented, alpha material, no shadow.++The offset (default 2 mm) stays above blender-asset-qa's 1 mm z-fight threshold and below what the+eye sees as floating. Size follows the image aspect. The result reports the measured min/max gap.+Usage:+ blender -b f.blend -P decal.py -- --target Wall --at 0 -0.1 1.5 --image //decals/logo.png+ [--size 0.5] [--rotation 0] [--offset 0.002] [--subdiv 16 (auto-doubles to 128)] [--name DC_Logo] [--save out.blend]+ blender -b f.blend -P decal.py -- --target Wall --at 0 -0.1 1.5 --color 0.8 0.1 0.1 --size 0.3+ MCP: import decal; print(decal.run(target="Wall", at=(0, -0.1, 1.5), image="C:/decals/logo.png"))+"""+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+++def _material(name, image, color):+ mat = bpy.data.materials.get(name) or bpy.data.materials.new(name)+ nt = mat.node_tree+ bsdf = bx.node(nt, "BSDF_PRINCIPLED")+ bsdf.inputs["Roughness"].default_value = 0.5+ if image:+ tex = bx.node(nt, "TEX_IMAGE") or nt.nodes.new("ShaderNodeTexImage")+ tex.image = image+ tex.extension = "CLIP" # no smeared border pixels+ tex.location = bsdf.location.x - 320, bsdf.location.y+ nt.links.new(tex.outputs["Color"], bsdf.inputs["Base Color"])+ nt.links.new(tex.outputs["Alpha"], bsdf.inputs["Alpha"])+ else:+ bsdf.inputs["Base Color"].default_value = (*color, 1.0)+ mat.surface_render_method = "DITHERED" # sorts correctly in EEVEE; glTF exports alpha from the Alpha link+ mat.use_backface_culling = True+ return mat+++def _gaps(ob, target):+ """World distance to the target at every evaluated triangle's centroid and corners-towards-centroid+ (where flat triangles over a convex crease dip closest), like blender-asset-qa samples them."""+ dg = bpy.context.evaluated_depsgraph_get()+ eo = ob.evaluated_get(dg)+ me = eo.to_mesh()+ me.calc_loop_triangles()+ tinv, tev = target.matrix_world.inverted(), target.evaluated_get(dg)+ out = []+ for t in me.loop_triangles:+ a, b, c = (ob.matrix_world @ me.vertices[i].co for i in t.vertices)+ cen = (a + b + c) / 3+ for p in (cen, cen.lerp(a, .6), cen.lerp(b, .6), cen.lerp(c, .6), a):+ ok, loc, _n, _i = tev.closest_point_on_mesh(tinv @ p)+ if ok:+ out.append((target.matrix_world @ loc - p).length)+ eo.to_mesh_clear()+ return out+++def _grid(me, subdiv, w, h):+ bm = bmesh.new()+ bm.loops.layers.uv.new("UVMap") # calc_uvs only fills an existing layer+ bmesh.ops.create_grid(bm, x_segments=subdiv, y_segments=subdiv, size=0.5, calc_uvs=True)+ bmesh.ops.scale(bm, vec=(w, h, 1), verts=bm.verts)+ bm.to_mesh(me)+ bm.free()+++def run(target=None, at=None, image=None, color=(0.8, 0.8, 0.8), size=0.5, rotation=0.0, offset=0.002,+ subdiv=16, name=None, **_):+ bx.object_mode()+ if not target or at is None:+ raise ValueError("--target and --at are required")+ tgt = bpy.data.objects[target]+ tev = tgt.evaluated_get(bpy.context.evaluated_depsgraph_get())+ ok, loc, nrm, _i = tev.closest_point_on_mesh(tgt.matrix_world.inverted() @ Vector(at))+ if not ok:+ raise ValueError(f"no surface found on {target}")+ loc = tgt.matrix_world @ loc+ nrm = (tgt.matrix_world.to_3x3().inverted().transposed() @ nrm).normalized()+ img = bpy.data.images.load(bpy.path.abspath(image), check_existing=True) if image else None+ w = h = size+ if img and img.size[0] and img.size[1]:+ h = size * img.size[1] / img.size[0]+ name = name or "DC_" + (os.path.splitext(os.path.basename(image))[0] if image else "Decal")+ me = bpy.data.meshes.new(name)+ _grid(me, subdiv, w, h)+ ob = bpy.data.objects.new(name, me)+ bpy.context.scene.collection.objects.link(ob)+ # orient +Z to the surface normal, spin about it, sit `offset` above the surface+ rot = nrm.to_track_quat("Z", "Y").to_matrix().to_4x4() @ Matrix.Rotation(math.radians(rotation), 4, "Z")+ ob.matrix_world = Matrix.Translation(loc + nrm * offset) @ rot+ sw = ob.modifiers.new("Conform", "SHRINKWRAP")+ sw.target, sw.wrap_method, sw.wrap_mode, sw.offset = tgt, "PROJECT", "ABOVE_SURFACE", offset+ sw.use_project_z, sw.use_negative_direction, sw.use_positive_direction = True, True, True+ sw.project_limit = max(w, h) # don't jump to far faces behind the target+ me.materials.append(_material("M_" + name, img, color))+ ob.visible_shadow = False+ ob.parent = tgt+ ob.matrix_parent_inverse = tgt.matrix_world.inverted()+ bpy.context.view_layer.update()+ gaps = _gaps(ob, tgt)+ while min(gaps, default=offset) < 0.6 * offset and subdiv < 128: # flat tris dip over convex creases+ subdiv *= 2+ _grid(me, subdiv, w, h)+ ob.data.update()+ bpy.context.view_layer.update()+ gaps = _gaps(ob, tgt)+ res = {"ok": True, "decal": name, "target": target, "size_m": bx.r([w, h], 3), "offset_m": offset, "subdiv": subdiv,+ "gap_min_m": round(min(gaps), 5) if gaps else None, "gap_max_m": round(max(gaps), 5) if gaps else None}+ if gaps and max(gaps) > offset * 3:+ res["warning"] = "decal lifts off the surface (gaps > 3x offset): smaller --size, or split it"+ elif gaps and min(gaps) < 0.6 * offset:+ res["warning"] = "decal dips near the surface on sharp creases: raise --offset or move it off the edge"+ return res+++if __name__ == "__main__":+ p = bx.parser(__doc__)+ p.add_argument("--target", required=True)+ p.add_argument("--at", type=float, nargs=3, required=True, help="world point near the surface")+ p.add_argument("--image", default=None)+ p.add_argument("--color", type=float, nargs=3, default=(0.8, 0.8, 0.8), help="linear RGB if no image")+ p.add_argument("--size", type=float, default=0.5, help="width in m (height from image aspect)")+ p.add_argument("--rotation", type=float, default=0.0, help="degrees about the surface normal")+ p.add_argument("--offset", type=float, default=0.002)+ p.add_argument("--subdiv", type=int, default=16)+ p.add_argument("--name", default=None)+ p.add_argument("--save", default=None)+ bx.cli(run, p)diff --git a/skills/blender-texturing/scripts/smart_material.py b/skills/blender-texturing/scripts/smart_material.pynew file mode 100644index 0000000..e09da6b--- /dev/null+++ b/skills/blender-texturing/scripts/smart_material.py@@ -0,0 +1,329 @@+"""Reversible "smart material" layers on existing Principled materials: edge wear (paint chipped to+an under-material), cavity grime, top dust, rust and roughness breakup, driven by curvature.++Curvature comes from a TX_Curvature point attribute computed here (convex > 0.5, concave < 0.5,+needs mid-poly density) or from a baked map (--curvature-map, e.g. bake_maps.py T_<name>_CURV) for+low-poly meshes. --ao-map adds baked AO to the grime mask. Inserts one TX_Layers group node in+front of each Principled BSDF (Base Color, Roughness, Metallic); --remove restores the originals.+Works in Cycles and EEVEE; bake to textures with blender-texture-baking bake_maps.py (no --high).+Usage:+ blender -b f.blend -P smart_material.py -- --objects Crate [--wear 0.5] [--grime 0.4] [--dust 0.3]+ [--rust 0] [--breakup 0.3] [--scale 0.1] [--edge-width 0.02] [--under-color 0.56 0.57 0.58] [--under-metallic 1]+ [--under-roughness 0.35] [--grime-color R G B] [--dust-color R G B] [--curvature-map T_CURV.png]+ [--ao-map T_AO.png] [--uv UVMap] [--save out.blend]+ blender -b f.blend -P smart_material.py -- --objects Crate --remove+ MCP: import smart_material as sm; print(sm.run(objects=["Crate"], wear=0.6, grime=0.4))+"""+import json+import os+import sys++import bpy+import numpy as np+from mathutils.kdtree import KDTree++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++GROUP, TAG, KEY, ATTR = "TX_Layers", "TX_", "tx_layers", "TX_Curvature"+WRAPPED = ("Base Color", "Roughness", "Metallic")+COLORS = ("Under Color", "Grime Color", "Dust Color")+++def _lin(c):+ """sRGB 0-1 -> linear (Blender color sockets are linear)."""+ return tuple(x / 12.92 if x <= 0.04045 else ((x + 0.055) / 1.055) ** 2.4 for x in c[:3]) + (1.0,)+++class _G:+ def __init__(self, nt):+ self.nt = nt++ def link(self, a, b):+ self.nt.links.new(a, b)++ def set(self, sock, v):+ if isinstance(v, bpy.types.NodeSocket):+ self.link(v, sock)+ elif v is not None:+ sock.default_value = v++ def n(self, type_, **props):+ node = self.nt.nodes.new(type_)+ for k, v in props.items():+ setattr(node, k, v)+ return node++ def math(self, op, a, b=0.0, c=None, clamp=False):+ m = self.n("ShaderNodeMath", operation=op, use_clamp=clamp)+ for i, v in enumerate((a, b, c)):+ self.set(m.inputs[i], v)+ return m.outputs[0]++ def mrange(self, v, a, b, lo=0.0, hi=1.0):+ m = self.n("ShaderNodeMapRange", clamp=True)+ for i, x in enumerate((v, a, b, lo, hi)):+ self.set(m.inputs[i], x)+ return m.outputs[0]++ def mix(self, kind, fac, a, b):+ m = self.n("ShaderNodeMix", data_type=kind)+ sock = {"FLOAT": (0, 2, 3, 0), "RGBA": (0, 6, 7, 2)}[kind]+ self.set(m.inputs[sock[0]], fac)+ self.set(m.inputs[sock[1]], a)+ self.set(m.inputs[sock[2]], b)+ return m.outputs[sock[3]]++ def noise(self, vec, scale, detail=4.0, rough=0.6):+ n = self.n("ShaderNodeTexNoise")+ self.set(n.inputs["Vector"], vec)+ self.set(n.inputs["Scale"], scale)+ n.inputs["Detail"].default_value = detail+ n.inputs["Roughness"].default_value = rough+ return n.outputs["Factor"]+++def build_group():+ ng = bpy.data.node_groups.get(GROUP) or bpy.data.node_groups.new(GROUP, "ShaderNodeTree")+ ng.nodes.clear()+ ng.interface.clear()+ for nm, kind, d in (("Base Color", "Color", (0.8, 0.8, 0.8, 1)), ("Roughness", "Float", 0.5),+ ("Metallic", "Float", 0.0), ("Curvature", "Float", 0.5), ("AO", "Float", 1.0),+ ("Wear", "Float", 0.0), ("Grime", "Float", 0.0), ("Dust", "Float", 0.0),+ ("Rust", "Float", 0.0), ("Breakup", "Float", 0.3), ("Scale", "Float", 0.1),+ ("Under Color", "Color", (0.27, 0.28, 0.29, 1)), ("Under Metallic", "Float", 1.0),+ ("Under Roughness", "Float", 0.35), ("Grime Color", "Color", (0.04, 0.03, 0.02, 1)),+ ("Dust Color", "Color", (0.45, 0.4, 0.33, 1))):+ s = ng.interface.new_socket(nm, in_out="INPUT", socket_type=f"NodeSocket{kind}")+ s.default_value = d+ for nm, kind in (("Base Color", "Color"), ("Roughness", "Float"), ("Metallic", "Float"),+ ("Wear Mask", "Float")):+ ng.interface.new_socket(nm, in_out="OUTPUT", socket_type=f"NodeSocket{kind}")+ g = _G(ng)+ gi, go = g.n("NodeGroupInput"), g.n("NodeGroupOutput")+ I = gi.outputs # noqa: E741+ obj = g.n("ShaderNodeTexCoord").outputs["Object"] # object space: masks stick to the asset+ inv = g.math("DIVIDE", 1.0, I["Scale"])+ up = g.n("ShaderNodeSeparateXYZ")+ g.link(g.n("ShaderNodeNewGeometry").outputs["Normal"], up.inputs[0])+ convex = g.mrange(I["Curvature"], 0.5, 1.0)+ concave = g.mrange(I["Curvature"], 0.5, 0.0)+ # edge wear: convexity above 1 - Wear, noise breaks the line into chips+ chips = g.math("SUBTRACT", g.noise(obj, g.math("MULTIPLY", inv, 2.0), 8.0, 0.7), 0.5)+ w_thr = g.math("SUBTRACT", 1.0, I["Wear"])+ wear = g.mrange(g.math("MULTIPLY_ADD", chips, 1.2, convex), w_thr, g.math("ADD", w_thr, 0.08))+ wear = g.math("MULTIPLY", wear, g.math("GREATER_THAN", I["Wear"], 0.0))+ # grime: cavities + (1 - AO), blotchy+ cav = g.math("MAXIMUM", concave, g.math("SUBTRACT", 1.0, I["AO"]))+ blot = g.noise(obj, inv, 4.0, 0.55)+ g_thr = g.math("SUBTRACT", 1.0, I["Grime"])+ grime = g.mrange(g.math("MULTIPLY_ADD", g.math("SUBTRACT", blot, 0.5), 0.8, cav), g_thr, g.math("ADD", g_thr, 0.2))+ grime = g.math("MULTIPLY", grime, g.math("GREATER_THAN", I["Grime"], 0.0))+ # dust: up-facing, in noisy patches whose coverage grows with Dust+ d_thr = g.math("SUBTRACT", 1.0, I["Dust"])+ patches = g.mrange(g.noise(obj, g.math("MULTIPLY", inv, 0.5), 5.0, 0.6), g.math("MULTIPLY", d_thr, 0.75),+ g.math("ADD", g.math("MULTIPLY", d_thr, 0.75), 0.15))+ dust = g.math("MULTIPLY", g.mrange(up.outputs["Z"], 0.45, 0.85), patches)+ dust = g.math("MULTIPLY", dust, g.math("GREATER_THAN", I["Dust"], 0.0))+ # rust: blotches seeded in cavities and on worn edges+ r_n = g.noise(obj, g.math("MULTIPLY", inv, 0.7), 6.0, 0.65)+ r_seed = g.math("ADD", g.math("MAXIMUM", concave, wear), r_n)+ r_thr = g.math("MULTIPLY_ADD", I["Rust"], -0.9, 1.45)+ rust = g.mrange(r_seed, r_thr, g.math("ADD", r_thr, 0.12))+ rust = g.math("MULTIPLY", rust, g.math("GREATER_THAN", I["Rust"], 0.0))+ rust_col = g.mix("RGBA", g.noise(obj, g.math("MULTIPLY", inv, 6.0)), (0.12, 0.03, 0.01, 1), (0.3, 0.1, 0.03, 1))+ # roughness breakup: +-25% fine variation, the cheapest realism win+ br = g.math("MULTIPLY_ADD", g.math("SUBTRACT", g.noise(obj, g.math("MULTIPLY", inv, 4.0), 6.0), 0.5),+ g.math("MULTIPLY", I["Breakup"], 0.5), 1.0)+ # stack: base -> wear (reveals under-material) -> rust -> grime -> dust+ col = g.mix("RGBA", wear, I["Base Color"], I["Under Color"])+ rough = g.mix("FLOAT", wear, I["Roughness"], I["Under Roughness"])+ metal = g.mix("FLOAT", wear, I["Metallic"], I["Under Metallic"])+ col = g.mix("RGBA", rust, col, rust_col)+ rough = g.mix("FLOAT", rust, rough, 0.85)+ metal = g.mix("FLOAT", rust, metal, 0.0)+ col = g.mix("RGBA", g.math("MULTIPLY", grime, 0.85), col, I["Grime Color"])+ rough = g.mix("FLOAT", grime, rough, g.math("MAXIMUM", rough, 0.7))+ metal = g.mix("FLOAT", grime, metal, 0.0)+ col = g.mix("RGBA", dust, col, I["Dust Color"])+ rough = g.mix("FLOAT", dust, rough, 0.9)+ metal = g.mix("FLOAT", dust, metal, 0.0)+ g.link(col, go.inputs["Base Color"])+ g.link(g.math("MULTIPLY", rough, br, clamp=True), go.inputs["Roughness"])+ g.link(metal, go.inputs["Metallic"])+ g.link(wear, go.inputs["Wear Mask"])+ return ng+++def curvature_attribute(ob, width=0.02, gain=1.0):+ """TX_Curvature point attribute: 0.5 flat, -> 1 convex, -> 0 concave.++ Mean elevation of the neighbours within `width` (world m) below/above the vertex tangent plane,+ so the band is ~width wide whatever the mesh density. Vertices with < 3 neighbours in range+ (low-poly) fall back to their 1-ring.+ """+ me = ob.data+ n = len(me.vertices)+ co = np.empty(n * 3, np.float32)+ me.vertices.foreach_get("co", co)+ mw = np.array(ob.matrix_world, np.float32)+ co = co.reshape(n, 3) @ mw[:3, :3].T + mw[:3, 3]+ nr = np.empty(n * 3, np.float32)+ me.vertex_normals.foreach_get("vector", nr)+ nr = nr.reshape(n, 3) @ np.linalg.inv(mw[:3, :3]) # normal matrix = inverse transpose+ nr /= np.maximum(np.linalg.norm(nr, axis=1), 1e-9)[:, None]+ ed = np.empty(len(me.edges) * 2, np.int32)+ me.edges.foreach_get("vertices", ed)+ ring = [[] for _ in range(n)]+ for a, b in zip(ed[0::2].tolist(), ed[1::2].tolist()):+ ring[a].append(b)+ ring[b].append(a)+ kd = KDTree(n)+ for i, p in enumerate(co.tolist()):+ kd.insert(p, i)+ kd.balance()+ c = np.zeros(n)+ for i in range(n):+ idx = [j for _, j, _ in kd.find_range(co[i], width) if j != i]+ if len(idx) < 3:+ idx = ring[i]+ if not idx:+ continue+ d = co[idx] - co[i]+ ln = np.maximum(np.linalg.norm(d, axis=1), 1e-9)+ c[i] = -(d @ nr[i] / ln).mean() # sine of elevation: below the tangent plane = convex+ c = np.clip(0.5 + c * gain * 2.0, 0.0, 1.0).astype(np.float32)+ at = me.attributes.get(ATTR) or me.attributes.new(ATTR, "FLOAT", "POINT")+ at.data.foreach_set("value", c)+ edge = float(np.median(np.linalg.norm(co[ed[0::2]] - co[ed[1::2]], axis=1))) if len(ed) else 0.0+ return c, edge+++def _src(sock):+ if sock.is_linked:+ lk = sock.links[0]+ return {"node": lk.from_node.name, "out": lk.from_socket.identifier}+ v = sock.default_value+ return {"value": list(v) if hasattr(v, "__len__") else v}+++def _image_node(nt, name, path, uv, x, y):+ node = nt.nodes.get(name) or nt.nodes.new("ShaderNodeTexImage")+ node.name, node.location = name, (x, y)+ node.image = bpy.data.images.load(bpy.path.abspath(path), check_existing=True)+ node.image.colorspace_settings.is_data = True # masks are data, never sRGB+ if uv:+ m = nt.nodes.get(name + "_uv") or nt.nodes.new("ShaderNodeUVMap")+ m.name, m.uv_map, m.location = name + "_uv", uv, (x - 200, y)+ nt.links.new(m.outputs["UV"], node.inputs["Vector"])+ return node.outputs["Color"]+++def _apply_mat(mat, ng, vals, curv_map, ao_map, uv):+ nt = mat.node_tree+ record = json.loads(mat.get(KEY, "{}"))+ for bsdf in [n for n in nt.nodes if n.type == "BSDF_PRINCIPLED"]:+ gname = TAG + bsdf.name+ gn = nt.nodes.get(gname)+ x, y = bsdf.location.x - 280, bsdf.location.y+ if gn is None: # first application: remember the originals+ record[bsdf.name] = {k: _src(bsdf.inputs[k]) for k in WRAPPED}+ gn = nt.nodes.new("ShaderNodeGroup")+ gn.name, gn.label, gn.node_tree, gn.location = gname, "TX Layers", ng, (x, y)+ # (re)wire on every run: re-running rebuilds the group, which recreates its sockets and drops links+ for k, src in record[bsdf.name].items():+ if "node" in src and src["node"] in nt.nodes:+ nt.links.new(nt.nodes[src["node"]].outputs[src["out"]], gn.inputs[k])+ else:+ gn.inputs[k].default_value = src["value"]+ nt.links.new(gn.outputs[k], bsdf.inputs[k])+ if curv_map:+ nt.links.new(_image_node(nt, TAG + "curv", curv_map, uv, x - 260, y - 420), gn.inputs["Curvature"])+ else:+ at = nt.nodes.get(TAG + "attr") or nt.nodes.new("ShaderNodeAttribute")+ at.name, at.attribute_type, at.attribute_name = TAG + "attr", "GEOMETRY", ATTR+ at.location = x - 260, y - 420+ nt.links.new(at.outputs["Fac"], gn.inputs["Curvature"])+ if ao_map:+ nt.links.new(_image_node(nt, TAG + "ao", ao_map, uv, x - 260, y - 700), gn.inputs["AO"])+ for k, v in vals.items():+ gn.inputs[k].default_value = v+ mat[KEY] = json.dumps(record)+++def _remove_mat(mat):+ nt = mat.node_tree+ record = json.loads(mat.get(KEY, "{}"))+ for bname, socks in record.items():+ bsdf = nt.nodes.get(bname)+ if bsdf is None:+ continue+ for k, src in socks.items():+ s = bsdf.inputs[k]+ for lk in list(s.links):+ nt.links.remove(lk)+ if "node" in src and src["node"] in nt.nodes:+ nt.links.new(nt.nodes[src["node"]].outputs[src["out"]], s)+ elif "value" in src:+ s.default_value = src["value"]+ for nd in [nd for nd in nt.nodes if nd.name.startswith(TAG)]:+ nt.nodes.remove(nd)+ if KEY in mat:+ del mat[KEY]+++def run(objects=None, wear=0.0, grime=0.0, dust=0.0, rust=0.0, breakup=0.3, scale=0.1,+ under_color=(0.56, 0.57, 0.58), under_metallic=1.0, under_roughness=0.35,+ grime_color=(0.22, 0.19, 0.15), dust_color=(0.71, 0.67, 0.6), curvature_map=None, ao_map=None,+ uv=None, edge_width=0.02, gain=1.0, remove=False, **_):+ bx.object_mode()+ obs = [o for o in bx.objects(objects) if o.type == "MESH"]+ mats = {s.material for o in obs for s in o.material_slots if s.material and s.material.node_tree}+ if remove:+ for m in mats:+ _remove_mat(m)+ for o in obs:+ if ATTR in o.data.attributes:+ o.data.attributes.remove(o.data.attributes[ATTR])+ return {"ok": True, "removed": sorted(m.name for m in mats), "objects": [o.name for o in obs]}+ res = {"ok": True, "objects": [o.name for o in obs], "materials": sorted(m.name for m in mats)}+ no_mat = [o.name for o in obs if not any(s.material for s in o.material_slots)]+ if no_mat:+ res["warning"] = f"no material (skipped): {no_mat}"+ if not curvature_map:+ coarse, stats = [], {}+ for o in obs:+ c, edge = curvature_attribute(o, edge_width, gain)+ stats[o.name] = {"convex_verts_pct": round(float((c > 0.65).mean()) * 100, 1),+ "concave_verts_pct": round(float((c < 0.35).mean()) * 100, 1)}+ if edge > 4 * edge_width:+ coarse.append(o.name)+ res["curvature"] = stats+ if coarse:+ res["note"] = (f"{coarse}: low vertex density, wear spreads over whole faces. Bake a curvature "+ "map (bake_maps.py --maps normal curvature) and pass --curvature-map")+ elif any(not o.data.uv_layers for o in obs):+ raise ValueError("--curvature-map/--ao-map need a UV map")+ ng = build_group()+ vals = {"Wear": wear, "Grime": grime, "Dust": dust, "Rust": rust, "Breakup": breakup, "Scale": scale,+ "Under Color": _lin(under_color), "Under Metallic": under_metallic,+ "Under Roughness": under_roughness, "Grime Color": _lin(grime_color), "Dust Color": _lin(dust_color)}+ for m in mats:+ _apply_mat(m, ng, vals, curvature_map, ao_map, uv)+ res["params"] = {k: v for k, v in vals.items() if k in ("Wear", "Grime", "Dust", "Rust", "Breakup", "Scale")}+ return res+++if __name__ == "__main__":+ p = bx.add_common(bx.parser(__doc__))+ for k, d in (("wear", 0.0), ("grime", 0.0), ("dust", 0.0), ("rust", 0.0), ("breakup", 0.3),+ ("scale", 0.1), ("edge-width", 0.02), ("under-metallic", 1.0), ("under-roughness", 0.35), ("gain", 1.0)):+ p.add_argument(f"--{k}", type=float, default=d)+ p.add_argument("--under-color", type=float, nargs=3, default=(0.56, 0.57, 0.58), help="sRGB 0-1")+ p.add_argument("--grime-color", type=float, nargs=3, default=(0.22, 0.19, 0.15), help="sRGB 0-1")+ p.add_argument("--dust-color", type=float, nargs=3, default=(0.71, 0.67, 0.6), help="sRGB 0-1")+ p.add_argument("--curvature-map", default=None)+ p.add_argument("--ao-map", default=None)+ p.add_argument("--uv", default=None, help="UV map for the mask images (default: active)")+ p.add_argument("--remove", action="store_true")+ bx.cli(run, p)diff --git a/skills/blender-time-of-day/SKILL.md b/skills/blender-time-of-day/SKILL.mdindex d3c1835..47f91bf 100644--- a/skills/blender-time-of-day/SKILL.md+++ b/skills/blender-time-of-day/SKILL.md@@ -4,7 +4,7 @@ description: Time of day and atmosphere in Blender 5.2 - measured sky + sun forlicense: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Time of Day & Atmospherediff --git a/skills/blender-video-editing/SKILL.md b/skills/blender-video-editing/SKILL.mdnew file mode 100644index 0000000..a54f4b8--- /dev/null+++ b/skills/blender-video-editing/SKILL.md@@ -0,0 +1,49 @@+---+name: blender-video-editing+description: Video in Blender 5.2 - Video Sequencer edits from Python (clips, image sequences, crossfades, titles, music fades, proxies, color management, H.264/AAC output) and motion tracking (feature detection, camera solve, scene orientation, tripod and plane tracking, stabilization) for VFX shots. Use to cut renders/footage together or match-move a camera.+license: MIT+metadata:+ author: blender-agent-skills+ version: "1.2.0"+---++# Video editing and tracking++The execution model is in `blender-core`. Rendering the 3D shots and the compositor (5.0 API) are in `blender-rendering`.++## One call each+```+scripts/vse_edit.py -- --clips //renders/sh010/ //renders/sh020/ //logo.png --crossfade 12 --title "Project" --audio //music.wav --out //edit.mp4 --render+scripts/vse_edit.py -- --clips a.mp4 b.mp4 c.mp4 --crossfade 0 --fps 24 --out //review/f_#### --render # hard cuts to PNG+```+```python+import track_camera; print(track_camera.run(clip="C:/shots/sh010.mp4", focal=35, sensor=36)) # live/MCP only+```++## vse_edit.py+- Builds into its own `Edit` scene (`--scene`), so 3D scenes stay untouched. Clips go on alternating channels 1/2, crossfades (`CROSS`) on 3, the title on 4, clip audio on 6/7 (movies get their sound strip), and music on 8 (trimmed to the edit with a `--audio-fade` volume fade-out).+- A clip may be a movie, a still (`--still-seconds`), a folder of frames, or a `####` pattern. Each crossfade overlaps the previous clip by `--crossfade` frames, so the edit gets shorter by that much per cut. Re-running replaces the previous edit.+- Sets **view transform Standard**: footage must pass through untouched (measured: AgX turned pure red into 0.86/0.23/0.13). Grade on purpose with strip modifiers instead.+- Output: `.mp4/.mov/.mkv` = H.264 (CRF high, preset good) + AAC 192k stereo. Any other path = PNG frames. 5.0+ needs `image_settings.media_type = "VIDEO"` **before** `file_format = "FFMPEG"`. It reports the file size, and the test decodes it back (frame count, size).++## Editing rules pros follow+- **Match the frame rate first** (`--fps` = the footage/render rate). Mixed rates drift audio. Re-render or retime (`SPEED` effect) instead.+- Heavy footage: build proxies (`strip.use_proxy = True`, 25/50%, `sequencer.rebuild_proxy`). 5.2 builds only proxies (no `.blen_tc` timecode files anymore).+- Per-strip color: `strip.colorspace_settings.name` (sRGB for 8-bit video, Linear Rec.709 for EXR renders). A dedicated edit scene keeps 3D color settings out of the edit.+- 5.2 API: `strips.new_movie(..., stream=N)` / `new_sound(stream=N)` pick a stream from multi-track files. `strip.connections` lists connected strips. New effect type `COMPOSITOR` (a node-tree effect). Text strips have Subtitles / Main Title / Corner Title presets in the UI. Timing uses `left_handle`/`right_handle`/`duration` (5.1 names). Strip keyframes live on the **scene's** action.++## Motion tracking (track_camera.py, live session)+- The Clip Editor operators need a window, so this borrows the largest area, runs, and restores it. In `-b` it raises. It detects features at the first and last frame, tracks both ways, deletes tracks shorter than `min_frames`, solves (auto keyframes, refines focal only if unknown), deletes tracks above `max_error` px and re-solves, then runs `setup_tracking_scene` (camera + Camera Solver constraint, background footage, frame range).+- Measured on a synthetic 40-frame dolly at 960×540: 56 tracks, **0.19 px** solve error, 35 mm focal kept exactly. Quality bar: < 0.3 px great, < 0.5 good, > 1 px slides.+- Give `focal`/`sensor` whenever known. The solver is far more stable than when refining the focal. Set the sensor before the focal (focal is stored in px).+- Nodal pans (camera only rotates): `tripod=True`. A normal solve fails without parallax.+- Orient the scene after solving (UI, Clip Editor context): select 3 floor tracks → `clip.set_plane(plane="FLOOR")`, 1 track → `clip.set_origin()`, 2 tracks a known distance apart → `clip.set_scale(distance=…)`. Otherwise scale and up are arbitrary.+- Other jobs: screen/sign replacement → `clip.create_plane_track()` on 4+ tracks of a planar surface. Shaky footage → 2D stabilization (`tracking.stabilization.use_2d_stabilization`, add tracks). Points for modeling → `clip.bundles_to_mesh()`.++## Shooting/footage tips that make solves work+Fast shutter (little motion blur), real parallax (move the camera, don't just pan), textured static surfaces at several depths, no rolling-shutter whip pans, and a lens grid shot to calibrate distortion when using wide lenses.++## Gotchas+- `bpy.ops.render.render(animation=True)` renders the sequencer only when `scene.render.use_sequencer` is on and the strips are in the **scene being rendered**. The script renders its own edit scene.+- Removing a clip also removes its effect strips. Collect names before deleting in loops.+- Image sequences must be contiguous. Missing frames show as black.diff --git a/skills/blender-video-editing/scripts/_bpyx.py b/skills/blender-video-editing/scripts/_bpyx.pynew file mode 100644index 0000000..9048f69--- /dev/null+++ b/skills/blender-video-editing/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-video-editing/scripts/track_camera.py b/skills/blender-video-editing/scripts/track_camera.pynew file mode 100644index 0000000..0197593--- /dev/null+++ b/skills/blender-video-editing/scripts/track_camera.py@@ -0,0 +1,103 @@+"""Automatic camera solve from footage: detect features at the start and end of the shot, track them+both ways, drop short tracks, solve (keyframes auto-picked), drop high-error tracks, re-solve, and set+up the 3D scene (camera with Camera Solver, footage as background, frame range).++Motion-tracking operators need a Clip Editor, so this runs in a live session with a window (blender-mcp+or the UI); it borrows the largest area as a Clip Editor and restores it. Background mode (-b) returns+an error. Give the real focal length and sensor width when known: the solve is far more stable.+Usage (live/MCP only):+ import track_camera; print(track_camera.run(clip="C:/shots/sh010.mp4", focal=35, sensor=36))+ track_camera.run(clip=..., tripod=True) # nodal pans: rotation-only solve+ run(clip, focal=None, sensor=None, threshold=0.3, min_distance=60, min_frames=10, max_error=2.0,+ tripod=False, setup_scene=True) -> {"solve_error_px", "tracks", "bundles", ...}+"""+import os+import sys++import bpy++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402+++def _clip_area():+ win = bpy.context.window or (bpy.context.window_manager.windows[0] if bpy.context.window_manager.windows else None)+ if win is None:+ raise RuntimeError("motion tracking needs a window: run in a live session (blender-mcp/UI), not -b")+ area = max(win.screen.areas, key=lambda a: a.width * a.height)+ return win, area+++def _solve(ctx, clip):+ with bpy.context.temp_override(**ctx):+ bpy.ops.clip.solve_camera()+ rec = clip.tracking.objects.active.reconstruction+ return rec.is_valid, rec.average_error+++def run(clip=None, focal=None, sensor=None, threshold=0.3, min_distance=60, min_frames=10, max_error=2.0,+ tripod=False, setup_scene=True, **_):+ if bpy.app.background:+ raise RuntimeError("motion tracking operators need a Clip Editor: run in a live session (blender-mcp)")+ if not clip:+ raise ValueError("clip is required")+ mc = bpy.data.movieclips.load(bpy.path.abspath(clip), check_existing=True)+ sc = bpy.context.scene+ sc.active_clip = mc+ tr = mc.tracking+ if sensor: # sensor first: focal is stored in pixels, so a later sensor change rescales the mm value+ tr.camera.sensor_width = sensor+ if focal:+ tr.camera.focal_length = focal+ st = tr.settings+ st.default_pattern_size, st.default_search_size = 21, 71+ st.default_motion_model, st.use_default_brute, st.use_default_normalization = "Loc", True, True+ st.default_correlation_min = 0.75+ st.use_keyframe_selection, st.use_tripod_solver = not tripod, tripod+ st.refine_intrinsics_focal_length = focal is None+ first, last = mc.frame_start, mc.frame_start + mc.frame_duration - 1+ win, area = _clip_area()+ old = area.ui_type+ area.ui_type = "CLIP_EDITOR"+ try:+ space = area.spaces.active+ space.clip, space.mode = mc, "TRACKING"+ region = next(r for r in area.regions if r.type == "WINDOW")+ ctx = dict(window=win, screen=win.screen, area=area, region=region, space_data=space, edit_movieclip=mc)+ with bpy.context.temp_override(**ctx):+ for frame, backwards in ((first, False), (last, True)): # features entering late get tracked too+ sc.frame_set(frame)+ bpy.ops.clip.select_all(action="DESELECT")+ bpy.ops.clip.detect_features(threshold=threshold, min_distance=min_distance, margin=16)+ bpy.ops.clip.track_markers(backwards=backwards, sequence=True)+ bpy.ops.clip.select_all(action="SELECT")+ bpy.ops.clip.clean_tracks(frames=min_frames, error=0.0, action="DELETE_TRACK")+ ok, err = _solve(ctx, mc)+ removed = 0+ if ok and err > max_error * 0.5: # second pass without the worst tracks+ n0 = len(tr.objects.active.tracks)+ with bpy.context.temp_override(**ctx):+ bpy.ops.clip.select_all(action="SELECT")+ bpy.ops.clip.clean_tracks(frames=0, error=max_error, action="DELETE_TRACK")+ removed = n0 - len(tr.objects.active.tracks)+ ok, err = _solve(ctx, mc)+ res = {"ok": True, "clip": mc.name, "frames": [first, last], "solved": ok, "solve_error_px": round(err, 4),+ "tracks": len(tr.objects.active.tracks), "removed_high_error": removed,+ "bundles": sum(1 for t in tr.objects.active.tracks if t.has_bundle),+ "focal_mm": round(tr.camera.focal_length, 3), "tripod": tripod}+ if ok and setup_scene:+ sc.frame_start, sc.frame_end = first, last+ with bpy.context.temp_override(**ctx):+ bpy.ops.clip.setup_tracking_scene()+ res["camera"] = sc.camera.name if sc.camera else None+ if not ok:+ res["warning"] = "solve failed: give --focal/--sensor, track more frames, or use tripod=True for pans"+ elif err > 1.0:+ res["warning"] = f"solve error {err:.2f} px: > 0.5 px will slide; refine tracks around the keyframes"+ return res+ finally:+ area.ui_type = old+++if __name__ == "__main__":+ bx.emit({"ok": False, "error": "track_camera needs a live session with a window (import it via blender-mcp)"})diff --git a/skills/blender-video-editing/scripts/vse_edit.py b/skills/blender-video-editing/scripts/vse_edit.pynew file mode 100644index 0000000..3f1cad5--- /dev/null+++ b/skills/blender-video-editing/scripts/vse_edit.py@@ -0,0 +1,164 @@+"""Assemble a video edit in the Video Sequencer headless: movies (with their audio), image+sequences and stills in order, crossfades, a title card, a music bed with fade-out, then render+H.264/AAC MP4 or PNG frames.++Builds into its own scene (--scene, default "Edit") so the user's 3D scenes stay untouched. Channels:+1-2 clips (alternating), 3 crossfades, 4 title, 6-7 clip audio, 8 music. Clips+alternate channels 1/2 so each crossfade (channel 3) overlaps the previous clip by --crossfade frames.+A clip may be a movie file, a single image (held --still-seconds), a folder of frames, or a+frame pattern with # (render_####.png).+Usage:+ blender -b -P vse_edit.py -- --clips intro.mp4 //shots/sh010/ //logo.png [--fps 30]+ [--resolution 1920 1080] [--crossfade 12] [--still-seconds 3] [--title "My Film"]+ [--title-seconds 3] [--audio music.wav] [--audio-fade 1.0] [--out //edit.mp4] [--render]+ [--scene Edit] [--save out.blend]+ MCP: import vse_edit; print(vse_edit.run(clips=["a.mp4", "b.mp4"], crossfade=12, out="//edit.mp4", render=True))+"""+import glob+import os+import re+import sys++import bpy++sys.path.insert(0, os.path.dirname(__file__))+import _bpyx as bx # noqa: E402++MOVIE = (".mp4", ".mov", ".mkv", ".avi", ".webm", ".m4v", ".mxf")+IMAGE = (".png", ".jpg", ".jpeg", ".exr", ".tif", ".tiff", ".webp", ".bmp", ".tga")+++def _frames(path):+ """Sorted frame files for a folder or a # pattern, else None."""+ p = bpy.path.abspath(path)+ if os.path.isdir(p):+ files = sorted(f for f in glob.glob(os.path.join(p, "*")) if f.lower().endswith(IMAGE))+ return files or None+ if "#" in p:+ files = sorted(glob.glob(re.sub(r"#+", "*", p)))+ return files or None+ return None+++def _add_clip(sed, path, channel, start, fps, still_seconds):+ p = bpy.path.abspath(path)+ name = os.path.splitext(os.path.basename(p.rstrip("/\\")))[0] or "clip"+ frames = _frames(path)+ sound = None+ if frames:+ st = sed.strips.new_image(name, frames[0], channel, start, fit_method="FIT")+ for f in frames[1:]:+ st.elements.append(os.path.basename(f))+ elif p.lower().endswith(MOVIE):+ st = sed.strips.new_movie(name, p, channel, start, fit_method="FIT")+ try: # a movie's audio is a separate strip; files without audio raise+ sound = sed.strips.new_sound(name + "_audio", p, channel + 5, start) # 6/7+ except RuntimeError:+ sound = None+ elif p.lower().endswith(IMAGE):+ st = sed.strips.new_image(name, p, channel, start, fit_method="FIT")+ st.right_handle = start + max(1, round(still_seconds * fps))+ else:+ raise ValueError(f"unsupported clip: {path}")+ if not os.path.exists(frames[0] if frames else p):+ raise FileNotFoundError(path)+ return st, sound+++def _output(sc, out):+ path = bpy.path.abspath(out)+ st = sc.render.image_settings+ if path.lower().endswith((".mp4", ".mov", ".mkv")):+ st.media_type = "VIDEO" # 5.0+: set the media type before the file format+ st.file_format = "FFMPEG"+ ff = sc.render.ffmpeg+ ff.format = "MPEG4" if path.lower().endswith(".mp4") else ("QUICKTIME" if path.lower().endswith(".mov") else "MKV")+ ff.codec, ff.constant_rate_factor, ff.ffmpeg_preset = "H264", "HIGH", "GOOD"+ ff.audio_codec, ff.audio_bitrate, ff.audio_channels = "AAC", 192, "STEREO"+ else:+ st.media_type, st.file_format = "IMAGE", "PNG"+ sc.render.filepath = path+ return path+++def run(clips=None, fps=30, resolution=(1920, 1080), crossfade=12, still_seconds=3.0, title=None,+ title_seconds=3.0, audio=None, audio_fade=1.0, out=None, render=False, scene="Edit", **_):+ if not clips:+ raise ValueError("--clips is required")+ sc = bpy.data.scenes.get(scene) or bpy.data.scenes.new(scene)+ sc.render.fps, sc.render.fps_base = int(fps), 1.0+ sc.render.resolution_x, sc.render.resolution_y = resolution+ sc.render.resolution_percentage = 100+ sc.render.use_sequencer = True+ sc.view_settings.view_transform = "Standard" # editorial: footage passes through (AgX would grade it)+ sc.view_settings.look = "None"+ sed = sc.sequence_editor_create()+ for nm in [s.name for s in sed.strips]: # removing a clip also removes its crossfade+ if nm in sed.strips:+ sed.strips.remove(sed.strips[nm])+ placed, start, prev = [], 1, None+ for i, c in enumerate(clips):+ ch = 1 + i % 2+ st, snd = _add_clip(sed, c, ch, start, fps, still_seconds)+ info = {"name": st.name, "start": st.left_handle, "end": st.right_handle}+ if prev is not None and crossfade > 0:+ xf = min(crossfade, prev.right_handle - prev.left_handle - 1, st.right_handle - st.left_handle - 1)+ if xf > 0: # slide the new clip back to overlap, then fade across the overlap+ shift = prev.right_handle - xf - st.left_handle+ st.frame_start += shift+ if snd:+ snd.frame_start += shift+ sed.strips.new_effect(f"XF_{i}", "CROSS", 3, st.left_handle, length=xf, input1=prev, input2=st)+ info.update(start=st.left_handle, end=st.right_handle, crossfade=xf)+ placed.append(info)+ prev, start = st, st.right_handle+ end = max(s.right_handle for s in sed.strips) - 1+ sc.frame_start, sc.frame_end = 1, end+ if title:+ t = sed.strips.new_effect("Title", "TEXT", 4, 1, length=max(1, round(title_seconds * fps)))+ t.text, t.font_size = title, max(24, resolution[1] * 0.07)+ t.location, t.alignment_x, t.anchor_x = (0.5, 0.15), "CENTER", "CENTER" # lower third+ t.use_shadow = True+ t.blend_type = "ALPHA_OVER"+ if audio:+ a = sed.strips.new_sound("Music", bpy.path.abspath(audio), 8, 1)+ if a.right_handle > end + 1:+ a.right_handle = end + 1+ fade = max(1, round(audio_fade * fps))+ a.volume = 1.0+ a.keyframe_insert("volume", frame=max(1, end - fade))+ a.volume = 0.0+ a.keyframe_insert("volume", frame=end)+ a.volume = 1.0+ res = {"ok": True, "scene": sc.name, "clips": placed, "frame_end": end, "fps": int(fps),+ "duration_s": round(end / fps, 3), "strips": len(sed.strips)}+ ws = getattr(bpy.context, "workspace", None)+ if ws is not None and hasattr(ws, "sequencer_scene"):+ ws.sequencer_scene = sc # 5.0+: the VSE shows the workspace's sequencer scene+ if out:+ path = _output(sc, out)+ res["out"] = path+ if render:+ with bpy.context.temp_override(scene=sc):+ bpy.ops.render.render(animation=True, scene=sc.name)+ if sc.render.image_settings.media_type == "VIDEO":+ res["bytes"] = os.path.getsize(path) if os.path.exists(path) else 0+ return res+++if __name__ == "__main__":+ p = bx.parser(__doc__)+ p.add_argument("--clips", nargs="+", required=True)+ p.add_argument("--fps", type=int, default=30)+ p.add_argument("--resolution", type=int, nargs=2, default=(1920, 1080))+ p.add_argument("--crossfade", type=int, default=12, help="frames (0 = hard cuts)")+ p.add_argument("--still-seconds", type=float, default=3.0)+ p.add_argument("--title", default=None)+ p.add_argument("--title-seconds", type=float, default=3.0)+ p.add_argument("--audio", default=None)+ p.add_argument("--audio-fade", type=float, default=1.0, help="fade-out seconds")+ p.add_argument("--out", default=None, help=".mp4/.mov/.mkv = H.264 video, else PNG frames path")+ p.add_argument("--render", action="store_true")+ p.add_argument("--scene", default="Edit")+ p.add_argument("--save", default=None)+ bx.cli(run, p)diff --git a/skills/blender-weather-fx/SKILL.md b/skills/blender-weather-fx/SKILL.mdindex a701787..4b2d88b 100644--- a/skills/blender-weather-fx/SKILL.md+++ b/skills/blender-weather-fx/SKILL.md@@ -4,7 +4,7 @@ description: Weather effects in Blender 5.2 - looping Geometry Nodes rain, snow,license: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Weather FXdiff --git a/skills/blender-weather-fx/scripts/surface_weather.py b/skills/blender-weather-fx/scripts/surface_weather.pyindex b1d2e9f..9309eb0 100644--- a/skills/blender-weather-fx/scripts/surface_weather.py+++ b/skills/blender-weather-fx/scripts/surface_weather.py@@ -197,26 +197,26 @@ def _apply_mat(mat, ng, vals):for bsdf in [n for n in nt.nodes if n.type == "BSDF_PRINCIPLED"]:gname = TAG + bsdf.namegn = nt.nodes.get(gname)- if gn is None: # first application: remember and rewire+ if gn is None: # first application: remember the originalsrecord[bsdf.name] = {k: _src(bsdf.inputs[k]) for k in WRAPPED}gn = nt.nodes.new("ShaderNodeGroup")gn.name, gn.label, gn.node_tree = gname, "ENV Weather", nggn.location = bsdf.location.x - 260, bsdf.location.y- for k in ("Base Color", "Roughness", "Coat Weight", "Coat Roughness"):- s = bsdf.inputs[k]- if s.is_linked:- nt.links.new(s.links[0].from_socket, gn.inputs[k])- else:- gn.inputs[k].default_value = s.default_value- if bsdf.inputs["Normal"].is_linked:- nt.links.new(bsdf.inputs["Normal"].links[0].from_socket, gn.inputs["Normal"])- else: # unlinked = shading normal; an unlinked group vector would be (0,0,0)- geo = nt.nodes.new("ShaderNodeNewGeometry")+ # (re)wire on every run: re-running rebuilds the group, which recreates its sockets and drops links+ for k, src in record[bsdf.name].items():+ if k == "Coat Normal": # restore-only; the group derives it+ continue+ if "node" in src and src["node"] in nt.nodes:+ nt.links.new(nt.nodes[src["node"]].outputs[src["out"]], gn.inputs[k])+ elif k == "Normal": # unlinked = shading normal; an unlinked group vector would be (0,0,0)+ geo = nt.nodes.get(TAG + "geo_" + bsdf.name) or nt.nodes.new("ShaderNodeNewGeometry")geo.name = TAG + "geo_" + bsdf.namegeo.location = gn.location.x - 200, gn.location.y - 300nt.links.new(geo.outputs["Normal"], gn.inputs["Normal"])- for k in WRAPPED:- nt.links.new(gn.outputs[k], bsdf.inputs[k])+ else:+ gn.inputs[k].default_value = src["value"]+ for k in WRAPPED:+ nt.links.new(gn.outputs[k], bsdf.inputs[k])for k, v in vals.items():gn.inputs[k].default_value = vmat[KEY] = json.dumps(record)diff --git a/skills/blender-workflow-recipes/SKILL.md b/skills/blender-workflow-recipes/SKILL.mdindex aec155c..1d8ece0 100644--- a/skills/blender-workflow-recipes/SKILL.md+++ b/skills/blender-workflow-recipes/SKILL.md@@ -4,7 +4,7 @@ description: End-to-end Blender 5.2 playbooks chaining the blender-* skills withlicense: MITmetadata:author: blender-agent-skills- version: "1.1.0"+ version: "1.2.0"---# Workflow Recipes@@ -26,7 +26,7 @@ metadata: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).+6. `build_pbr_material.py --name M_X --textures //textures --objects SM_X`. Wear/grime: `smart_material.py --curvature-map //textures/T_X_CURV.png --ao-map //textures/T_X_AO.png --wear 0.4 --grime 0.4`, then self-bake (`bake_maps.py --low SM_X --maps basecolor roughness metallic`) (`blender-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)@@ -36,7 +36,8 @@ metadata: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]`+6b. Clothes and hair: `garment.py --body Body --group Torso --name Shirt --hide-body --morphs` (`blender-clothing`), `groom.py --surface Head --mask Scalp` → `--cards Hair` for engines (`blender-hair-grooming`). Gate: `garment.py --check` in every stress pose.+7. Animate on RIG_Body, or retarget mocap: `retarget.py --source Mocap --target RIG_Body --show-map` → run (`blender-animation`). Then `bake_action.py --source RIG_Body --target GAME_RIG_Body [--root-motion xy --hips spine]` and `loop_check.py --fix` on cycles.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@@ -54,7 +55,7 @@ metadata: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`).+1. `terrain.py --size 400 --res 513 --type ridged --erosion 30 --material` (or `--heightmap`), then one `scatter.py` layer per biome element (trees by slope/height, rocks aligned, grass masked) (`blender-environment-kits`). Custom scatter logic: `gn_builder.py` (recipes in `blender-geometry-nodes/references/recipes.md`). Modular buildings: `kit_check.py --grid 0.5 --fix` on every kit piece.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.diff --git a/tests/test_animation.py b/tests/test_animation.pyindex 7f6ac45..a3a975d 100644--- a/tests/test_animation.py+++ b/tests/test_animation.py@@ -55,3 +55,111 @@ def test_bake_to_copy_with_root_motion_and_export():e = ex.run(preset="gltf", objects=["GAME_CharRig"], out=str(TMP / "anim.glb"))names = e["files"][0]["summary"]["animation_names"]assert len(names) >= 2, e+++HUMANOID = { # canonical -> (head, tail, parent) in world meters, Z-up, facing -Y+ "hips": ((0, 0, 1.0), (0, 0, 1.12), None), "spine": ((0, 0, 1.12), (0, 0, 1.3), "hips"),+ "chest": ((0, 0, 1.3), (0, 0, 1.5), "spine"), "neck": ((0, 0, 1.5), (0, 0, 1.6), "chest"),+ "head": ((0, 0, 1.6), (0, 0, 1.8), "neck"),+ "upperarm.L": ((0.18, 0, 1.45), (0.45, 0, 1.45), "chest"), "forearm.L": ((0.45, 0, 1.45), (0.7, 0, 1.45), "upperarm.L"),+ "hand.L": ((0.7, 0, 1.45), (0.8, 0, 1.45), "forearm.L"),+ "upperarm.R": ((-0.18, 0, 1.45), (-0.45, 0, 1.45), "chest"), "forearm.R": ((-0.45, 0, 1.45), (-0.7, 0, 1.45), "upperarm.R"),+ "hand.R": ((-0.7, 0, 1.45), (-0.8, 0, 1.45), "forearm.R"),+ "thigh.L": ((0.1, 0, 1.0), (0.1, 0, 0.55), "hips"), "shin.L": ((0.1, 0, 0.55), (0.1, 0, 0.1), "thigh.L"),+ "foot.L": ((0.1, 0, 0.1), (0.1, -0.15, 0.0), "shin.L"),+ "thigh.R": ((-0.1, 0, 1.0), (-0.1, 0, 0.55), "hips"), "shin.R": ((-0.1, 0, 0.55), (-0.1, 0, 0.1), "thigh.R"),+ "foot.R": ((-0.1, 0, 0.1), (-0.1, -0.15, 0.0), "shin.R"),+}+MIXAMO = {"hips": "Hips", "spine": "Spine", "chest": "Spine1", "neck": "Neck", "head": "Head",+ "upperarm.L": "LeftArm", "forearm.L": "LeftForeArm", "hand.L": "LeftHand",+ "upperarm.R": "RightArm", "forearm.R": "RightForeArm", "hand.R": "RightHand",+ "thigh.L": "LeftUpLeg", "shin.L": "LeftLeg", "foot.L": "LeftFoot",+ "thigh.R": "RightUpLeg", "shin.R": "RightLeg", "foot.R": "RightFoot"}+++def _rig(name, names, obj_matrix, legs=1.0, roll=0.0):+ from mathutils import Matrix, Vector+ arm = bpy.data.objects.new(name, bpy.data.armatures.new(name))+ bpy.context.scene.collection.objects.link(arm)+ arm.matrix_world = obj_matrix+ bpy.context.view_layer.objects.active = arm+ bpy.ops.object.mode_set(mode="EDIT")+ inv = obj_matrix.inverted()++ def w(p): # stretch legs below the hips to test proportions+ p = Vector(p)+ return Vector((p.x, p.y, p.z * legs if p.z <= 1.0 else p.z - 1.0 + legs))+ for canon, (h, t, par) in HUMANOID.items():+ eb = arm.data.edit_bones.new(names[canon])+ eb.head, eb.tail = inv @ w(h), inv @ w(t)+ eb.roll = roll+ if par:+ eb.parent = arm.data.edit_bones[names[par]]+ eb.use_connect = canon not in ("upperarm.L", "upperarm.R", "thigh.L", "thigh.R")+ bpy.ops.object.mode_set(mode="OBJECT")+ return arm+++def test_retarget_mixamo_to_rigify_names():+ import math as m+ from mathutils import Euler, Matrix+ src = _rig("Mocap", {k: "mixamorig:" + v for k, v in MIXAMO.items()},+ Matrix.Rotation(m.pi / 2, 4, "X") @ Matrix.Scale(0.01, 4), roll=0.7) # Mixamo FBX: Y-up bones, cm+ tgt = _rig("GAME_RIG", {k: ("DEF-" + k.replace("upperarm", "upper_arm")) for k in HUMANOID},+ Matrix.Identity(4), legs=1.15)+ sc = bpy.context.scene+ for f, sp, la, th, hx in ((1, (0, 0, 0), (0, 0, 0), (0, 0, 0), 0.0), (10, (0.4, 0.2, 0), (0, 0.9, 0.5), (-0.8, 0, 0), 5.0),+ (20, (-0.3, 0, 0.3), (0.6, -0.4, 0), (0.5, 0.1, 0), 12.0)):+ for bn, e in (("mixamorig:Spine", sp), ("mixamorig:LeftArm", la), ("mixamorig:RightUpLeg", th)):+ pb = src.pose.bones[bn]+ pb.rotation_mode, pb.rotation_euler = "XYZ", Euler(e)+ pb.keyframe_insert("rotation_euler", frame=f)+ hp = src.pose.bones["mixamorig:Hips"]+ hp.location = (hx, 0, 0) # local units are cm-scaled+ hp.keyframe_insert("location", frame=f)+ rt = skill_module("blender-animation", "retarget")+ shown = rt.run(source="Mocap", target="GAME_RIG", show_map=True)+ assert shown["map"]["DEF-upper_arm.L"] == "mixamorig:LeftArm" and shown["map"]["DEF-shin.R"] == "mixamorig:RightLeg"+ assert shown["hips"] == "DEF-hips" and not shown["unmapped_key_parts"], shown+ r = rt.run(source="Mocap", target="GAME_RIG", name="Walk")+ assert r["mapped"] == 17 and r["frames"] == [1, 20] and abs(r["hips_scale"] - 1.15) < 1e-3, r+ assert r["max_error_deg"] < 0.1, r+ def delta(ob, pb): # world rotation change from rest+ q = lambda mt: mt.to_3x3().normalized().to_quaternion() # noqa: E731+ return q(ob.matrix_world @ pb.matrix) @ q(ob.matrix_world @ pb.bone.matrix_local).inverted()+ moved = 0+ for f in (1, 7, 10, 15, 20): # every bone turns by the same world rotation as its source+ sc.frame_set(f)+ for canon, mx in MIXAMO.items():+ sb, tb = src.pose.bones["mixamorig:" + mx], tgt.pose.bones["DEF-" + canon.replace("upperarm", "upper_arm")]+ ds, dt = delta(src, sb), delta(tgt, tb)+ a = ds.rotation_difference(dt).angle+ a = min(a, 2 * m.pi - a) # q and -q are the same rotation+ assert m.degrees(a) < 0.5, (f, canon, m.degrees(a))+ moved += ds.angle > 0.1+ assert moved > 20 # the clip actually moves several bones (incl. children of rotated parents)+ sh = src.matrix_world @ src.pose.bones["mixamorig:Hips"].head+ th = tgt.matrix_world @ tgt.pose.bones["DEF-hips"].head+ assert abs(th.x - sh.x * 1.15) < 1e-3 # hips travel scaled by the hips-height ratio+ assert tgt.animation_data.action.name == "GAME_RIG|Walk" and tgt.animation_data.action.use_fake_user+++def test_loop_check_pops_fix_and_root_motion():+ _body, arm = fx.simple_character()+ sc = bpy.context.scene+ chest, spine = arm.pose.bones["chest"], arm.pose.bones["spine"]+ chest.rotation_mode = "XYZ"+ for f, rx, y in ((1, 0.0, 0.0), (12, 0.5, 0.5), (24, 0.1, 1.0)): # ends 0.1 rad off; hips travel 1 m+ chest.rotation_euler = (rx, 0, 0)+ chest.keyframe_insert("rotation_euler", frame=f)+ spine.location = (y, 0, 0) # the upright spine's local X lies along the ground+ spine.keyframe_insert("location", frame=f)+ lc = skill_module("blender-animation", "loop_check")+ r = lc.run(object="CharRig")+ assert not r["loops"] and {p["bone"] for p in r["pops"]} >= {"chest", "spine"}, r+ r = lc.run(object="CharRig", root_motion="spine")+ assert not r["loops"] and r["pops"][0]["bone"] == "chest" and abs(r["pops"][0]["rot_deg"] - 5.73) < 0.05, r+ r = lc.run(object="CharRig", root_motion="spine", fix=True)+ assert r["loops"] and r["fixed_curves"] >= 3, r+ sc.frame_set(24)+ assert abs(spine.location.x - 1.0) < 1e-6 # root travel keptdiff --git a/tests/test_clothing.py b/tests/test_clothing.pynew file mode 100644index 0000000..f375aca--- /dev/null+++ b/tests/test_clothing.py@@ -0,0 +1,42 @@+import bpy+import fixtures as fx+from mathutils import Vector+from run_all import skill_module+++def test_garment_weights_mask_and_pose():+ body, arm = fx.simple_character()+ gm = skill_module("blender-clothing", "garment")+ r = gm.run(body="Char", zmin=0.7, zmax=1.6, name="Shirt", hide_body=True)+ assert r["ok"] and r["poke_verts"] == 0 and r["armature"] == "CharRig" and r["vertex_groups"] == 3, r+ sh = bpy.data.objects["Shirt"]+ assert [m.type for m in sh.modifiers] == ["SOLIDIFY", "ARMATURE"] and sh.parent == arm+ assert all(len(v.groups) <= 4 and abs(sum(g.weight for g in v.groups) - 1) < 1e-3 for v in sh.data.vertices)+ assert body.modifiers["Hidden_Shirt"].type == "MASK" and 0 < r["hidden_verts"] < r["region_verts"]+ pb = arm.pose.bones["chest"]+ pb.rotation_mode, pb.rotation_euler = "XYZ", (0.5, 0, 0)+ bpy.context.view_layer.update()+ assert gm.run(body="Char", check="Shirt")["poke_verts"] == 0 # weights follow the pose+ rigid = gm.run(body="Char", zmin=0.7, zmax=1.6, name="Rigid")+ bpy.data.objects["Rigid"].modifiers.remove(bpy.data.objects["Rigid"].modifiers["Armature"])+ bpy.context.view_layer.update()+ assert gm.run(body="Char", check="Rigid")["poke_verts"] > 20 and rigid["ok"] # the check catches poke-through+++def test_garment_morphs_and_drape():+ body, _arm = fx.simple_character()+ body.shape_key_add(name="Basis")+ fat = body.shape_key_add(name="Fat")+ fat.value = 0.0 # shape_key_add creates keys at 1.0+ for i, v in enumerate(body.data.vertices):+ fat.data[i].co = v.co * Vector((1.3, 1.3, 1.0))+ gm = skill_module("blender-clothing", "garment")+ r = gm.run(body="Char", zmin=0.7, zmax=1.6, name="Shirt", morphs=True, drape=20)+ assert r["morphs"] == ["Fat"] and r["draped_frames"] == 20 and r["poke_verts"] == 0, r+ sh = bpy.data.objects["Shirt"]+ fat.value = 1.0+ bpy.context.view_layer.update()+ assert gm.run(body="Char", check="Shirt")["poke_verts"] > 50 # body morph alone pokes through+ sh.data.shape_keys.key_blocks["Fat"].value = 1.0+ bpy.context.view_layer.update()+ assert gm.run(body="Char", check="Shirt")["poke_verts"] == 0 # matching garment key fixes itdiff --git a/tests/test_environment.py b/tests/test_environment.pynew file mode 100644index 0000000..118bae6--- /dev/null+++ b/tests/test_environment.py@@ -0,0 +1,95 @@+import json+import math+import struct++import bmesh+import bpy+import fixtures as fx+import numpy as np+from run_all import TMP, skill_module+++def test_terrain_attributes_flatten_and_engine_maps():+ tr = skill_module("blender-environment-kits", "terrain")+ hm, sp = str(TMP / "T_Height.png"), str(TMP / "T_Splat.png")+ r = tr.run(size=100, res=129, height=20, type="ridged", erosion=10, flatten=(10, -10, 12), material=True,+ export_heightmap=hm, export_splat=sp)+ assert r["ok"] and r["tris"] == 128 * 128 * 2 and r["height_range_m"][1] > 15, r+ me = bpy.data.objects["Terrain"].data+ assert len(me.vertices) == 129 * 129 and {"ENV_Slope", "ENV_Height"} <= set(me.attributes.keys())+ co = np.array([v.co for v in me.vertices])+ inner = np.hypot(co[:, 0] - 10, co[:, 1] + 10) < 10+ assert np.ptp(co[inner, 2]) < 0.05 # the play area is flat+ for path, ctype in ((hm, 0), (sp, 6)): # 16-bit grayscale heightmap, 16-bit RGBA splat+ w, h, depth, ct = struct.unpack(">IIBB", open(path, "rb").read(26)[16:26])+ assert (w, h, depth, ct) == (129, 129, 16, ctype), (path, w, h, depth, ct)+ img = bpy.data.images.load(sp)+ img.colorspace_settings.is_data = True # data maps load as Non-Color, like engines read them+ a = np.array(img.pixels[:]).reshape(-1, 4)+ assert np.allclose(a[:, :3].sum(1), 1.0, atol=0.01) # splat weights sum to 1+ h = bpy.data.images.load(hm)+ h.colorspace_settings.is_data = True+ hv = np.array(h.pixels[:]).reshape(129, 129, 4)[..., 0]+ zs = co[:, 2].reshape(129, 129)+ assert np.abs(hv - (zs - zs.min()) / np.ptp(zs)).max() < 1e-3 # raw 16-bit heights, no display transform+ raw = str(TMP / "T_Height.raw")+ tr.run(size=100, res=129, height=20, type="ridged", erosion=10, flatten=(10, -10, 12), export_heightmap=raw)+ rv = np.fromfile(raw, "<u2").reshape(129, 129) / 65535+ assert np.abs(rv - hv).max() < 2e-3 # .raw and .png carry the same heights+++def _trees():+ col = bpy.data.collections.new("Trees")+ bpy.context.scene.collection.children.link(col)+ for i in range(2):+ me = bpy.data.meshes.new(f"Tree{i}")+ bm = bmesh.new()+ bmesh.ops.create_cone(bm, cap_ends=True, segments=6, radius1=1, radius2=0, depth=4)+ bm.to_mesh(me)+ bm.free()+ col.objects.link(bpy.data.objects.new(f"Tree{i}", me))+ return col+++def test_scatter_respects_slope_height_and_realize():+ skill_module("blender-environment-kits", "terrain").run(size=120, res=129, height=25, scale=50, erosion=10)+ _trees()+ sc = skill_module("blender-environment-kits", "scatter")+ r = sc.run(target="Terrain", collection="Trees", density=0.05, min_distance=3, max_slope=20, height_max=18, seed=1,+ export_points=str(TMP / "trees.json"))+ pts = json.load(open(r["points_file"]))["instances"]+ assert len(pts) == r["instances"] and all(len(p["rotation_quat_wxyz"]) == 4 for p in pts)+ assert r["instances"] > 30 and set(r["by_source"]) == {"Tree0", "Tree1"}, r+ assert r["slope_max_deg"] <= 20.05 and r["height_range"][1] <= 18.0, r+ assert bpy.context.view_layer.layer_collection.children["Trees"].exclude # sources hidden at the origin+ r2 = sc.run(target="Terrain", collection="Trees", density=0.05, min_distance=3, max_slope=20, height_max=18,+ seed=1, realize=True)+ assert r2["tris_total"] > 128 * 128 * 2 + r["instances"] * 6, r2+++def test_kit_check_flags_and_fixes():+ wall = fx.cube("SM_Wall_4m", size=1, location=(0.3, 0.1, 1.5))+ wall.scale = (4, 0.2, 3) # unapplied scale, centered pivot, off-grid placement+ floor = fx.mesh_object("SM_Floor_4m", lambda bm: bmesh.ops.create_grid(bm, x_segments=4, y_segments=4, size=2))+ holed = fx.mesh_object("Floor_Hole", lambda bm: bmesh.ops.create_grid(bm, x_segments=4, y_segments=4, size=2))+ bm = bmesh.new()+ bm.from_mesh(holed.data)+ bm.faces.ensure_lookup_table()+ centre = min(bm.faces, key=lambda f: f.calc_center_median().length)+ bmesh.ops.delete(bm, geom=[centre], context="FACES_ONLY")+ bm.to_mesh(holed.data)+ bm.free()+ for o in (wall, floor, holed):+ fx.unwrap(o)+ kc = skill_module("blender-environment-kits", "kit_check")+ r = kc.run(objects=[wall.name, floor.name, holed.name], grid=0.5)+ p = r["pieces"]+ assert not r["pass"] and any("scale" in e for e in p["SM_Wall_4m"]["errors"]), p["SM_Wall_4m"]+ assert any("pivot" in e for e in p["SM_Floor_4m"]["errors"]), p["SM_Floor_4m"]+ assert any("open-edge" in e for e in p["Floor_Hole"]["errors"]) and any("prefix" in w for w in p["Floor_Hole"]["warnings"])+ r = kc.run(objects=[wall.name, floor.name], grid=0.5, fix=True)+ assert r["pass"], r["pieces"]+ bpy.context.view_layer.update()+ assert np.allclose(wall.scale, 1, atol=1e-5) and math.isclose(wall.dimensions.x, 4, abs_tol=1e-4), (+ tuple(wall.scale), tuple(wall.dimensions))+ assert np.allclose(wall.location, (-1.7, 0.0, 0.0), atol=1e-4) # geometry stayed, origin moved to its min cornerdiff --git a/tests/test_hair.py b/tests/test_hair.pynew file mode 100644index 0000000..ad76401--- /dev/null+++ b/tests/test_hair.py@@ -0,0 +1,45 @@+import bpy+import fixtures as fx+import numpy as np+from run_all import TMP, skill_module+++def _head():+ ob = fx.mesh_object("Head", lambda bm: (bm.loops.layers.uv.new("UVMap"), __import__("bmesh").ops.create_uvsphere(+ bm, u_segments=32, v_segments=16, radius=0.1, calc_uvs=True)), location=(0, 0, 1.6))+ vg = ob.vertex_groups.new(name="Scalp")+ vg.add([v.index for v in ob.data.vertices if v.co.z > 0.02], 1.0, "REPLACE")+ return ob+++def test_groom_attached_masked_with_assets():+ head = _head()+ gr = skill_module("blender-hair-grooming", "groom")+ r = gr.run(surface="Head", mask="Scalp", density=2000, children=60000, viewport=1.0, length=0.12, curl=0.01)+ assert r["ok"] and r["curves"] > 500 and r["root_gap_max_m"] < 1e-3, r+ assert "Capture Rest Geometry" in r["surface_modifiers"] and r["modifiers"][-1] == "Hair Dynamics", r+ assert r["modifiers"][:2] == ["Generate Hair Curves", "Interpolate Hair Curves"]+ hair = bpy.data.objects[r["hair"]]+ assert hair.parent == head and hair.data.surface == head and hair.data.surface_uv_map == "UVMap"+ pos, off = gr._evaluated(hair)+ assert pos[off[:-1], 2].min() - 1.6 > 0.015 # every root inside the Scalp mask (z > 0.02 band)+ assert 0.05 < r["length_mean_m"] < 0.2, r+++def test_hair_cards_and_atlas():+ _head()+ gr = skill_module("blender-hair-grooming", "groom")+ r = gr.run(surface="Head", mask="Scalp", children=20000, viewport=1.0, droop=0)+ c = gr.run(cards=r["hair"], card_count=40, atlas_columns=8, atlas_res=256, out=str(TMP / "hair"))+ assert c["card_count"] == 40 and c["tris"] > 40 * 2 * 4, c+ me = bpy.data.objects[c["cards"]].data+ uv = np.empty(len(me.loops) * 2, np.float32)+ me.uv_layers[0].uv.foreach_get("vector", uv)+ assert uv.min() >= 0 and uv.max() <= 1+ a = np.array(bpy.data.images.load(c["atlas"]["BC"]).pixels[:]).reshape(256, 256, 4)+ assert 0.1 < (a[..., 3] > 0.5).mean() < 0.75 # strands with gaps, not a solid sheet+ rt = np.array(bpy.data.images.load(c["atlas"]["RootTip"]).pixels[:]).reshape(256, 256, 4)+ m = rt[..., 3] > 0.5+ lo, hi = rt[48:56][m[48:56]][:, 0].mean(), rt[200:208][m[200:208]][:, 0].mean()+ assert 0.12 < lo < 0.3 and hi > 0.7, (lo, hi) # linear root->tip gradient+ assert bpy.context.scene.name == "Scene" and len(bpy.data.scenes) == 1 # atlas scene cleaned updiff --git a/tests/test_npr.py b/tests/test_npr.pynew file mode 100644index 0000000..3143c5e--- /dev/null+++ b/tests/test_npr.py@@ -0,0 +1,91 @@+import math++import bpy+import fixtures as fx+import numpy as np+from run_all import TMP, requires_gpu, skill_module+++def _scene():+ ob = fx.unwrap(fx.uv_sphere("Ball", radius=1, segs=32, rings=16))+ for p in ob.data.polygons:+ p.use_smooth = True+ mat = bpy.data.materials.new("M_Skin")+ bsdf = next(n for n in mat.node_tree.nodes if n.type == "BSDF_PRINCIPLED")+ bsdf.inputs["Base Color"].default_value = (0.8, 0.3, 0.2, 1)+ ob.data.materials.append(mat)+ sc = bpy.context.scene+ cam = bpy.data.objects.new("Cam", bpy.data.cameras.new("Cam"))+ sc.collection.objects.link(cam)+ sc.camera, cam.location, cam.rotation_euler = cam, (0, -5, 0), (math.pi / 2, 0, 0)+ return ob, mat, bsdf+++def _clusters(a, tol=0.04, min_frac=0.02):+ """Distinct flat colors (8-bit rounding splits a band into near-identical values)."""+ cols, counts = np.unique(np.round(a, 2), axis=0, return_counts=True)+ centers, sizes = [], []+ for i in np.argsort(-counts):+ k = next((k for k, c in enumerate(centers) if np.abs(cols[i] - c).max() <= tol), None)+ if k is None:+ centers.append(cols[i])+ sizes.append(counts[i])+ else:+ sizes[k] += counts[i]+ return sum(s > min_frac * len(a) for s in sizes)+++def _bands(engine, tag):+ sc = bpy.context.scene+ sc.render.engine = engine+ if engine == "CYCLES":+ sc.cycles.samples, sc.cycles.device = 4, "CPU"+ sc.render.resolution_x = sc.render.resolution_y = 96+ sc.render.film_transparent = True+ sc.render.filepath = str(TMP / f"npr_{tag}.png")+ bpy.ops.render.render(write_still=True)+ a = np.array(bpy.data.images.load(sc.render.filepath).pixels[:]).reshape(-1, 4)+ a = a[a[:, 3] > 0.99, :3] # opaque object pixels only+ return _clusters(a)+++def test_toon_hull_bands_lineart_roundtrip():+ ob, mat, bsdf = _scene()+ nt = mat.node_tree+ out = next(n for n in nt.nodes if n.type == "OUTPUT_MATERIAL")+ ts = skill_module("blender-stylized-npr", "toon_setup")+ r = ts.run(objects=["Ball"], bands=2, outline=0.03, smooth_normals=True, line_art=True)+ assert r["ok"] and r["key_light"] == "NPR_Key" and bpy.context.scene.view_settings.view_transform == "Standard", r+ me = ob.evaluated_get(bpy.context.evaluated_depsgraph_get()).to_mesh()+ body = [p.normal.dot(p.center) for p in me.polygons if p.material_index == 0]+ hull = [(p.normal.dot(p.center), p.center.length) for p in me.polygons if p.material_index == 1]+ ob.evaluated_get(bpy.context.evaluated_depsgraph_get()).to_mesh_clear()+ assert len(hull) == len(body) and min(body) > 0 # body faces outward+ assert max(d for d, _ in hull) < 0 and min(rad for _, rad in hull) > 1.0 # hull outside, facing inward+ sun = bpy.data.objects["NPR_Key"]+ sun.rotation_euler = (0, 0, 0)+ bpy.context.scene.frame_set(2)+ assert tuple(nt.nodes["NPR_toon"].inputs["Light Direction"].default_value) == (0.0, 0.0, 1.0)+ la = bpy.data.objects[r["line_art"]].evaluated_get(bpy.context.evaluated_depsgraph_get())+ assert len(la.data.layers["Lines"].current_frame().drawing.strokes) > 0+ sun.rotation_euler = (0.9, 0, 0.5)+ bpy.context.scene.frame_set(1)+ ts.run(objects=["Ball"], outline=0, rim=0, spec=0) # bands only for the color count+ ob.modifiers["NPR_Outline"].show_render = False+ bpy.data.objects[r["line_art"]].hide_render = True+ assert _bands("CYCLES", "key") == 2+ ts.run(objects=["Ball"], remove=True, line_art=True)+ assert out.inputs["Surface"].links[0].from_node == bsdf and len(ob.material_slots) == 1+ assert not ob.modifiers and "NPR_OutlineNormal" not in ob.data.color_attributes+ assert bpy.context.scene.view_settings.view_transform == "AgX" and "NPR_LineArt" not in bpy.data.objects+++def test_toon_scene_lighting_eevee():+ requires_gpu()+ _scene()+ sun = bpy.data.objects.new("Sun", bpy.data.lights.new("Sun", "SUN"))+ bpy.context.scene.collection.objects.link(sun)+ sun.rotation_euler, sun.data.energy = (0.9, 0, 0.5), 4.0+ ts = skill_module("blender-stylized-npr", "toon_setup")+ ts.run(objects=["Ball"], bands=3, lighting="scene", outline=0)+ assert _bands("BLENDER_EEVEE", "scene") == 3diff --git a/tests/test_qa.py b/tests/test_qa.pyindex f268db4..7bbc2e5 100644--- a/tests/test_qa.py+++ b/tests/test_qa.py@@ -97,3 +97,38 @@ def test_review_shots_renders_sheet():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"]) == 4assert "QA_Cam" not in bpy.data.objects and len(bpy.data.objects) == 1+++def test_material_and_texture_delivery_checks():+ ob = fx.unwrap(fx.cube("Crate"))+ good, bad = bpy.data.materials.new("M_Good"), bpy.data.materials.new("M_Bad")+ ob.data.materials.append(good)+ ob.data.materials.append(bad)+ ob.data.materials.append(None) # unused empty slot+ for p in ob.data.polygons:+ p.material_index = 0 if p.index < 3 else 1+ nt = bad.node_tree+ bsdf = next(n for n in nt.nodes if n.type == "BSDF_PRINCIPLED")+ rough = nt.nodes.new("ShaderNodeTexImage")+ rough.image = bpy.data.images.new("T_Crate_R", 8, 8) # generated image, default sRGB+ nt.links.new(rough.outputs["Color"], bsdf.inputs["Roughness"])+ nrm, nmap = nt.nodes.new("ShaderNodeTexImage"), nt.nodes.new("ShaderNodeNormalMap")+ nrm.image = bpy.data.images.load(__file__) # any existing file, then point it at a missing one+ nrm.image.filepath = "//textures/T_Crate_N_missing.png"+ nrm.image.colorspace_settings.is_data = True+ nt.links.new(nrm.outputs["Color"], nmap.inputs["Color"])+ nt.links.new(nmap.outputs["Normal"], bsdf.inputs["Normal"])+ qa = skill_module("blender-asset-qa", "qa_check")+ r = qa.run(objects=["Crate"])+ errs, warns = " | ".join(r["errors"]), " | ".join(r["warnings"])+ assert "T_Crate_R feeds ['Roughness'] but is sRGB" in errs, errs+ assert "missing texture file" in errs and "unused material slot" in warns, (errs, warns)+ rough.image.colorspace_settings.is_data = True+ nt.nodes.remove(nrm)+ ob.data.materials.pop(index=2)+ r = qa.run(objects=["Crate"])+ assert not any("M_" in e or "slot" in e for e in r["errors"] + r["warnings"]), r+ ob.data.polygons[0].material_index = 1+ ob.data.materials[1] = None+ r = qa.run(objects=["Crate"])+ assert any("empty/missing material slot" in e for e in r["errors"]), r["errors"]diff --git a/tests/test_texturing.py b/tests/test_texturing.pynew file mode 100644index 0000000..ab4cf5c--- /dev/null+++ b/tests/test_texturing.py@@ -0,0 +1,93 @@+import bpy+import fixtures as fx+import numpy as np+from run_all import TMP, skill_module+++def _stepped_block():+ """1 m block with a 0.5 m step on top (convex outer edges + one concave inner edge), beveled 2 cm."""+ base = fx.cube("Block", size=1)+ top = fx.cube("Step", size=1, location=(-0.25, 0, 0.7))+ top.scale = (0.5, 1, 0.5)+ bo = base.modifiers.new("U", "BOOLEAN")+ bo.operation, bo.object = "UNION", top+ bv = base.modifiers.new("B", "BEVEL")+ bv.width, bv.segments, bv.limit_method = 0.02, 3, "ANGLE"+ ss = base.modifiers.new("S", "SUBSURF")+ ss.levels, ss.subdivision_type = 3, "SIMPLE"+ bpy.context.view_layer.objects.active = base+ for m in [m.name for m in base.modifiers]:+ with bpy.context.temp_override(object=base, active_object=base):+ bpy.ops.object.modifier_apply(modifier=m)+ bpy.data.objects.remove(top)+ bpy.context.view_layer.update() # drop the stale view-layer entry+ mat = bpy.data.materials.new("M_Paint")+ bsdf = next(n for n in mat.node_tree.nodes if n.type == "BSDF_PRINCIPLED")+ bsdf.inputs["Base Color"].default_value = (0.5, 0.05, 0.03, 1)+ base.data.materials.clear()+ base.data.materials.append(mat)+ for p in base.data.polygons:+ p.material_index = 0+ return base, mat, bsdf+++def test_smart_material_curvature_and_roundtrip():+ ob, mat, bsdf = _stepped_block()+ nt = mat.node_tree+ tex = nt.nodes.new("ShaderNodeTexNoise")+ nt.links.new(tex.outputs["Color"], bsdf.inputs["Base Color"]) # linked input must survive+ bsdf.inputs["Roughness"].default_value = 0.37+ before = sorted((lk.from_node.name, lk.to_socket.identifier) for lk in nt.links)+ sm = skill_module("blender-texturing", "smart_material")+ r = sm.run(objects=["Block"], wear=0.6, grime=0.5, dust=0.4, rust=0.2)+ assert r["ok"] and "M_Paint" in r["materials"] and "note" not in r, r+ co = np.array([v.co for v in ob.data.vertices])+ c = np.array([d.value for d in ob.data.attributes["TX_Curvature"].data])+ mid = np.abs(co[:, 1]) < 0.4+ outer = mid & (co[:, 0] > 0.49) & (co[:, 2] > 0.49) # bevel of the x+ top edge (convex)+ inner = mid & (np.abs(co[:, 0]) < 0.03) & (np.abs(co[:, 2] - 0.5) < 0.03) # step's inner corner+ flat = (np.abs(co[:, 1] + 0.5) < 1e-4) & (np.abs(co[:, 0] - 0.25) < 0.15) & (np.abs(co[:, 2]) < 0.2)+ assert outer.any() and inner.any() and flat.any(), (outer.sum(), inner.sum(), flat.sum())+ assert c[outer].mean() > 0.75 and c[inner].min() < 0.35 and abs(c[flat].mean() - 0.5) < 0.05, (+ c[outer].mean(), c[inner].min(), c[flat].mean())+ assert bsdf.inputs["Base Color"].links[0].from_node.name.startswith("TX_")+ sm.run(objects=["Block"], wear=0.9) # re-run updates in place, links intact+ assert len([n for n in nt.nodes if n.type == "GROUP" and n.name.startswith("TX_")]) == 1+ gn = bsdf.inputs["Metallic"].links[0].from_node+ assert gn.name.startswith("TX_") and gn.inputs["Base Color"].links[0].from_node == tex+ assert abs(gn.inputs["Wear"].default_value - 0.9) < 1e-6 and gn.inputs["Curvature"].is_linked+ sm.run(objects=["Block"], remove=True)+ after = sorted((lk.from_node.name, lk.to_socket.identifier) for lk in nt.links)+ assert after == before and abs(bsdf.inputs["Roughness"].default_value - 0.37) < 1e-6+ assert "TX_Curvature" not in ob.data.attributes and "tx_layers" not in mat+++def test_smart_material_bakes_to_texture():+ ob, mat, _ = _stepped_block()+ fx.unwrap(ob)+ bake = skill_module("blender-texture-baking", "bake_maps")+ sm = skill_module("blender-texturing", "smart_material")++ def bake_bc(tag):+ r = bake.run(low="Block", maps=["basecolor"], res=64, samples=1, out=str(TMP / tag), name=tag, device="CPU")+ img = bpy.data.images.load(r["maps"]["basecolor"])+ a = np.empty(64 * 64 * 4, np.float32)+ img.pixels.foreach_get(a)+ return a.reshape(-1, 4)[:, :3]+ clean = bake_bc("clean")+ sm.run(objects=["Block"], wear=0.8, grime=0.6)+ worn = bake_bc("worn")+ changed = (np.abs(worn - clean).max(1) > 0.05).mean()+ assert 0.02 < changed < 0.8, changed # wear/grime visible on part of the surface, not everywhere+++def test_decal_conforms_without_zfighting():+ s = fx.uv_sphere("Ball", radius=1, segs=48, rings=24, location=(0, 0, 1))+ dc = skill_module("blender-texturing", "decal")+ r = dc.run(target="Ball", at=(0.2, -1.5, 1.3), color=(0.8, 0.1, 0.1), size=0.6, rotation=15)+ assert r["ok"] and "warning" not in r, r+ assert r["gap_min_m"] >= 0.0012 and r["gap_max_m"] <= 0.0025, r+ ob = bpy.data.objects[r["decal"]]+ assert ob.parent == s and not ob.visible_shadow and abs(ob.dimensions.x - 0.6) < 0.02+ qa = skill_module("blender-asset-qa", "qa_check").run(objects=["Ball", r["decal"]], uv=False)+ assert not any("z-fighting" in e for e in qa["errors"]), qa["errors"]diff --git a/tests/test_video.py b/tests/test_video.pynew file mode 100644index 0000000..4249284--- /dev/null+++ b/tests/test_video.py@@ -0,0 +1,144 @@+import json+import math+import os+import pathlib+import struct+import subprocess+import wave++import bmesh+import bpy+import numpy as np+from run_all import TMP, requires_gpu, skill_module++HERE = pathlib.Path(__file__).resolve().parent+++def _png(path, rgb, w=160, h=90):+ img = bpy.data.images.new("t", w, h)+ a = np.zeros((h, w, 4), np.float32)+ a[...] = (*rgb, 1)+ img.pixels.foreach_set(a.ravel())+ img.filepath_raw, img.file_format = str(path), "PNG"+ img.save()+ bpy.data.images.remove(img)+++def test_vse_edit_crossfade_title_audio_mp4():+ d = TMP / "vse"+ for c, rgb in (("red", (1, 0, 0)), ("blue", (0, 0, 1))):+ (d / c).mkdir(parents=True, exist_ok=True)+ for i in range(12):+ _png(d / c / f"f_{i:04d}.png", rgb)+ _png(d / "green.png", (0, 1, 0))+ with wave.open(str(d / "tone.wav"), "wb") as w:+ w.setnchannels(1), w.setsampwidth(2), w.setframerate(22050)+ w.writeframes(b"".join(struct.pack("<h", int(8000 * math.sin(2 * math.pi * 440 * t / 22050))) for t in range(22050 * 3)))+ ve = skill_module("blender-video-editing", "vse_edit")+ r = ve.run(clips=[str(d / "red"), str(d / "blue" / "f_####.png"), str(d / "green.png")], fps=12,+ resolution=(160, 90), crossfade=4, still_seconds=1, title="Test", audio=str(d / "tone.wav"),+ out=str(d / "frames" / "f_####"), render=True)+ assert r["frame_end"] == 28 and [c.get("crossfade") for c in r["clips"]] == [None, 4, 4], r++ def px(f):+ a = np.array(bpy.data.images.load(str(d / "frames" / f"f_{f:04d}.png")).pixels[:]).reshape(90, 160, 4)+ return np.round(a[45, 20, :3], 2).tolist()+ assert px(1) == [1, 0, 0] and px(11) == [0.5, 0, 0.5] and px(14) == [0, 0, 1] and px(26) == [0, 1, 0]+ edit = bpy.data.scenes["Edit"]+ music = edit.sequence_editor.strips["Music"]+ assert music.right_handle == 29 # trimmed to the edit+ edit.frame_set(10)+ loud = music.volume+ edit.frame_set(28)+ assert loud == 1.0 and music.volume < 0.01 # fade-out keys live on the scene's action+ r = ve.run(clips=[str(d / "red"), str(d / "blue")], fps=12, resolution=(160, 90), crossfade=4,+ audio=str(d / "tone.wav"), out=str(d / "edit.mp4"), render=True) # re-run clears the old edit+ assert r["bytes"] > 1000 and r["strips"] == 4, r+ mc = bpy.data.movieclips.load(r["out"])+ assert mc.frame_duration == r["frame_end"] == 20 and tuple(mc.size) == (160, 90)+++DRIVER = """+import bpy, sys, json+args = sys.argv[sys.argv.index("--") + 1:]+sys.path.insert(0, args[2])+def go():+ try:+ import track_camera+ r = track_camera.run(clip=args[0], focal=35, sensor=36)+ r["constraints"] = [c.type for c in bpy.context.scene.camera.constraints]+ r["area_restored"] = all(a.ui_type != "CLIP_EDITOR" for a in bpy.context.window.screen.areas)+ except Exception as e:+ r = {"ok": False, "error": repr(e)}+ open(args[1], "w").write(json.dumps(r))+ bpy.ops.wm.quit_blender()+bpy.app.timers.register(go, first_interval=2.0)+"""+++def _footage(out):+ """40 frames of a textured set seen by a dollying 35 mm camera (Workbench, textured)."""+ sc = bpy.context.scene+ rng = np.random.default_rng(3)+ img = bpy.data.images.new("noise", 512, 512)+ a = np.kron(rng.random((64, 64)), np.ones((8, 8)))[..., None].repeat(4, -1)+ a[..., 3] = 1+ img.pixels.foreach_set(a.astype(np.float32).ravel())+ mat = bpy.data.materials.new("N")+ t = mat.node_tree.nodes.new("ShaderNodeTexImage")+ t.image = img+ mat.node_tree.links.new(t.outputs[0], next(n for n in mat.node_tree.nodes if n.type == "BSDF_PRINCIPLED").inputs[0])++ def obj(name, build, loc=(0, 0, 0)):+ me, bm = bpy.data.meshes.new(name), bmesh.new()+ uv = bm.loops.layers.uv.new("UVMap")+ build(bm)+ for f in bm.faces:+ for lp in f.loops:+ c = lp.vert.co+ lp[uv].uv = (c.x * 0.13 + c.z * 0.07, c.y * 0.13 + c.z * 0.05)+ bm.to_mesh(me)+ bm.free()+ o = bpy.data.objects.new(name, me)+ o.location = loc+ sc.collection.objects.link(o)+ me.materials.append(mat)+ obj("Ground", lambda bm: bmesh.ops.create_grid(bm, x_segments=1, y_segments=1, size=10))+ for i, (x, y, s) in enumerate(((-2, 2, 1.2), (1.5, 3, 1.6), (3, 0.5, 0.8), (-3, -1, 1.0))):+ obj(f"Box{i}", lambda bm, s=s: bmesh.ops.create_cube(bm, size=s), (x, y, s / 2))+ cam = bpy.data.objects.new("Cam", bpy.data.cameras.new("Cam"))+ sc.collection.objects.link(cam)+ sc.camera, cam.data.lens, cam.data.sensor_width = cam, 35, 36+ for f, x in ((1, -2.0), (40, 2.0)):+ cam.location, cam.rotation_euler = (x, -9, 3.2), (math.radians(75), 0, math.radians(-x * 3))+ cam.keyframe_insert("location", frame=f)+ cam.keyframe_insert("rotation_euler", frame=f)+ sc.frame_start, sc.frame_end = 1, 40+ sc.render.engine = "BLENDER_WORKBENCH"+ sc.display.shading.color_type, sc.display.shading.light = "TEXTURE", "FLAT"+ sc.render.resolution_x, sc.render.resolution_y = 960, 540+ sc.render.filepath, sc.render.image_settings.file_format = str(out / "f_"), "PNG"+ bpy.ops.render.render(animation=True)+++def test_track_camera_solves_in_ui_session():+ requires_gpu() # opens a real Blender window: Clip Editor operators don't run in -b+ out = TMP / "footage"+ out.mkdir(exist_ok=True)+ _footage(out)+ drv, res = TMP / "drive_track.py", TMP / "track.json"+ drv.write_text(DRIVER)+ scripts = HERE.parent / "skills" / "blender-video-editing" / "scripts"+ subprocess.run([bpy.app.binary_path, "--factory-startup", "--no-window-focus", "--window-geometry", "0", "0",+ "1000", "700", "--python", str(drv), "--", str(out / "f_0001.png"), str(res), str(scripts)],+ timeout=300, capture_output=True)+ r = json.loads(res.read_text())+ assert r["ok"] and r["solved"] and r["solve_error_px"] < 0.5 and r["bundles"] >= 20, r+ assert abs(r["focal_mm"] - 35) < 0.01 and r["constraints"] == ["CAMERA_SOLVER"] and r["area_restored"], r+ tc = skill_module("blender-video-editing", "track_camera")+ try:+ tc.run(clip=str(out / "f_0001.png"))+ raise AssertionError("background mode must refuse")+ except RuntimeError as e:+ assert "live session" in str(e)+ assert os.path.exists(out / "f_0040.png")diff --git a/tests/test_weather.py b/tests/test_weather.pyindex 8a23114..229a17a 100644--- a/tests/test_weather.py+++ b/tests/test_weather.py@@ -43,8 +43,11 @@ def test_surface_weather_roundtrip_restores_materials():r = sw.run(objects=names, wetness=0.6, puddles=0.4, ripples=1, streaks=0.5, snow=0.3)assert "M_Ground" in r["materials"], rassert bsdf.inputs["Coat Weight"].is_linked and bsdf.inputs["Base Color"].links[0].from_node.name.startswith("ENV_W_")- sw.run(objects=names, wetness=0.9) # re-run updates in place, no second group+ sw.run(objects=names, wetness=0.9) # re-run updates in place, no second group, links intactassert len([n for n in nt.nodes if n.name.startswith("ENV_W_") and n.type == "GROUP"]) == 1+ gn = bsdf.inputs["Coat Weight"].links[0].from_node+ assert gn.name.startswith("ENV_W_") and gn.inputs["Base Color"].links[0].from_node == tex+ assert abs(gn.inputs["Wetness"].default_value - 0.9) < 1e-6 and gn.inputs["Normal"].is_linkedsw.run(objects=names, remove=True)after = sorted((lk.from_node.name, lk.to_socket.identifier) for lk in nt.links)assert after == before and abs(bsdf.inputs["Roughness"].default_value - 0.42) < 1e-6diff --git a/tools/trigger_check.py b/tools/trigger_check.pyindex df1e90f..0b0e931 100644--- a/tools/trigger_check.py+++ b/tools/trigger_check.py@@ -20,7 +20,8 @@ CASES = [("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"),+ ("scatter rocks on the terrain by slope and height", "blender-environment-kits"),+ ("build a procedural geometry nodes tool with a repeat zone", "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"),@@ -38,6 +39,17 @@ CASES = [("make it a moonlit night scene with stars", "blender-time-of-day"),("rainy street with puddles, wet surfaces and lightning", "blender-weather-fx"),("snow falling and snow cover on the roofs", "blender-weather-fx"),+ ("add edge wear, grime and dust to this crate material", "blender-texturing"),+ ("place a decal sticker on the wall", "blender-texturing"),+ ("anime cel shading with outlines for my character", "blender-stylized-npr"),+ ("groom hair on the head and make hair cards for the game", "blender-hair-grooming"),+ ("generate a mountain terrain heightmap for unreal", "blender-environment-kits"),+ ("check my modular wall kit pieces snap to the grid", "blender-environment-kits"),+ ("make a shirt for my character that doesn't clip through the body", "blender-clothing"),+ ("edit the rendered shots together with crossfades and music into an mp4", "blender-video-editing"),+ ("track the camera from this footage and solve it", "blender-video-editing"),+ ("retarget mixamo mocap onto my rig", "blender-animation"),+ ("check the walk cycle loops without a pop", "blender-animation"),]diff --git a/tools/validate_skills.py b/tools/validate_skills.pyindex 7c221b6..386b372 100644--- a/tools/validate_skills.py+++ b/tools/validate_skills.py@@ -2,7 +2,7 @@"""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()+token budget, relative links and mentioned *.py scripts 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)"""@@ -16,6 +16,9 @@ NAME_RE = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$")DESC_TARGET, DESC_MAX = 400, 1024TOK_WARN, TOK_MAX, LINES_MAX = 3000, 5000, 500LINK_RE = re.compile(r"\]\(([^)#\s]+)(?:#[^)]*)?\)")+SCRIPT_RE = re.compile(r"\b([a-z][a-z0-9_]*\.py)\b")+# file names used as examples (add-on layout, generic CLI placeholders, this repo's test runner)+PLACEHOLDER_PY = {"__init__.py", "operators.py", "ui.py", "script.py", "x.py", "run_all.py"}def tokens(text):@@ -40,6 +43,11 @@ def frontmatter(text):return fm, body+def known_py():+ """Script names a SKILL.md or reference may mention (any skill's scripts, repo tools)."""+ return {p.name for p in (*ROOT.glob("skills/*/scripts/*.py"), *ROOT.glob("tools/*.py"))}++def check_skill(d, errs, warns):rel = d.relative_to(ROOT)md = d / "SKILL.md"@@ -76,6 +84,9 @@ def check_skill(d, errs, warns):continueif not (f.parent / link).resolve().exists():errs.append(f"{f.relative_to(ROOT)}: broken link {link}")+ for name in sorted(set(SCRIPT_RE.findall(f.read_text("utf-8"))) - PLACEHOLDER_PY - known_py()):+ if not name.startswith("test_"):+ errs.append(f"{f.relative_to(ROOT)}: mentions {name}, which no skill ships")for py in d.glob("scripts/*.py"):src = py.read_text("utf-8")try: