Skip to content
Back to search

spine-animation-ai

AI-powered Claude skill for Spine 2D skeletal animation — auto-rig, animate, and preview characters

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/genielabsopensource--spine-animation-ai/badge.svg)](/listings/genielabsopensource--spine-animation-ai)

HTML

<a href="/listings/genielabsopensource--spine-animation-ai"><img src="/api/listings/genielabsopensource--spine-animation-ai/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Option A: Claude Projects (Recommended)

The easiest way — works with any Claude account, no extra software needed.

1. Go to [claude.ai](https://claude.ai) → create a new **Project** 2. Open **Project Knowledge** → **Add content** 3. Copy the full contents of [`SKILL.md`](SKILL.md) and paste it in 4. Save — Claude now has the full skill baked in, **including all scripts embedded inline** 5. Upload your character assets and describe what you want:

"I have separated body part PNGs for my character.
 Create idle and walk animations."

Claude will write the scripts to disk, run the pipeline, and deliver `skeleton.json` + `preview.html`.

> **Why it works:** `SKILL.md` is auto-generated with all 4 Python scripts embedded inside it — Claude extracts and runs them without needing to clone the repo.

---

Option B: Claude Custom Skill (`/mnt/skills/` environments)

For Claude environments that support mounted skill directories:

git clone https://github.com/GenielabsOpenSource/spine-animation-ai.git /mnt/skills/user/spine-animation

Claude will automatically discover and load the skill on next session start.

---

Option C: Manual Pipeline (no Claude needed)

**Step 0: Split a Full Character Into Parts (New!)**

If you only have a single character image (not separated body parts), `split_character.py` uses Google Gemini to generate a deconstructed sprite atlas and then segments it into individual transparent PNGs via OpenCV connected-components analysis.

Prerequisites: - `GEMINI_API_KEY` environment variable — get a free key at https://aistudio.google.com/app/apikey - `pip install google-generativeai`

GEMINI_API_KEY=your_key python3 scripts/split_character.py character.png \
  --output-dir parts/

Skip this step if you already have separated body-part PNGs.

**1. Auto-position parts from a reference image**

python3 scripts/position_parts.py \
  --reference assembled_character.png \
  --parts parts/ \
  --output layout.json \
  --debug debug/

**2. Build the Spine JSON**

python3 scripts/build_spine_json.py \
  --config layout.json \
  --output skeleton.json

**3. Pack a texture atlas**

python3 scripts/make_atlas.py \
  --parts parts/ \
  --output atlas/ \
  --name skeleton

**4. Generate a self-contained HTML preview**

python3 scripts/generate_spine_player.py \
  --skeleton skeleton.json \
  --atlas skeleton.atlas \
  --atlas-image skeleton.png \
  --output preview.html

Open `preview.html` in any browser — no server needed.

---

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 1,995 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. ---
  2. name: spine-animation
  3. description: >
  4. Create Spine 2D skeletal animations from pre-existing character assets (separated body-part PNGs,
  5. atlas spritesheet, or a full character image). Use this skill whenever the user wants to animate
  6. a 2D character, create Spine JSON from existing art assets, rig a character with bones, build
  7. walk/idle/run/attack animations, produce an interactive Spine Web Player preview, or generate
  8. Spine-compatible export files (.json + .atlas + .png). Also trigger when the user mentions
  9. "Spine animation", "2D rigging", "skeletal animation", "bone animation", "cutout animation",
  10. "animate this character", "make this walk", "create walk cycle", or uploads separated character
  11. body parts and wants them animated. This skill handles the full pipeline: asset analysis,
  12. skeleton rigging, animation keyframing, Spine JSON export, and interactive HTML5 preview.
  13. ---
  14. <!-- ⚠️ AUTO-GENERATED FILE — DO NOT EDIT DIRECTLY
  15. Edit SKILL.template.md instead, then push to trigger rebuild.
  16. Scripts are embedded automatically by build_skill.py via GitHub Actions. -->
  17. # Spine Animation Skill
  18. Turn pre-existing 2D character assets into fully animated, interactive Spine animations.
  19. ## Step 0: Set Up Scripts
  20. This skill includes Python scripts that do the heavy lifting. Claude MUST write them to disk
  21. before use. Each script is embedded below — Claude should save them to `/home/claude/spine-scripts/`
  22. at the start of every session.
  23. ```bash
  24. mkdir -p /home/claude/spine-scripts
  25. pip install opencv-python Pillow numpy google-generativeai --break-system-packages -q
  26. ```
  27. ### Embedded Scripts
  28. The following scripts are auto-injected from the repository's `scripts/` directory.
  29. **Claude: read these carefully, then write each one to `/home/claude/spine-scripts/`**
  30. before running the pipeline.
  31. <!-- EMBED:scripts/split_character.py -->
  32. <details>
  33. <summary>📄 <code>scripts/split_character.py</code> (231 lines)</summary>
  34. ```python
  35. #!/usr/bin/env python3
  36. """
  37. split_character.py — Generate a sprite-sheet atlas from a full character image
  38. using Google Gemini image generation, then segment individual body parts via
  39. OpenCV connected-components analysis.
  40. Usage:
  41. python split_character.py <input_image> [--output-dir output_parts]
  42. [--atlas-out atlas.png] [--min-area 500] [--padding 12]
  43. [--bg-threshold 240]
  44. Requires:
  45. pip install google-generativeai opencv-python Pillow numpy
  46. Environment variable GEMINI_API_KEY must be set.
  47. """
  48. import argparse
  49. import os
  50. import sys
  51. import cv2
  52. import numpy as np
  53. from PIL import Image
  54. def get_gemini_client():
  55. """Initialise the Gemini generative-AI client, or exit with a helpful
  56. error if the API key is missing."""
  57. api_key = os.environ.get("GEMINI_API_KEY")
  58. if not api_key:
  59. print(
  60. "ERROR: GEMINI_API_KEY environment variable is not set.\n"
  61. "Get a free API key at: https://aistudio.google.com/app/apikey\n"
  62. "Then run:\n"
  63. " export GEMINI_API_KEY=your_key_here",
  64. file=sys.stderr,
  65. )
  66. sys.exit(1)
  67. from google import genai
  68. client = genai.Client(api_key=api_key)
  69. return client
  70. POSITIVE_PROMPT = (
  71. "A complete 2D game sprite sheet texture atlas for Spine animation of the "
  72. "exact character in the reference image. The character is completely "
  73. "deconstructed into separated, isolated body parts. Separated individual "
  74. "parts laid out flatly: isolated head, isolated torso, isolated upper arms, "
  75. "lower arms, hands, upper legs, lower legs, and feet. Spread out with clear "
  76. "space between every single body part. No overlapping parts. Clean solid "
  77. "white background. CRITICAL: Maintain the exact same art style, exact same "
  78. "shading, exact face, and exact color palette as the reference image. "
  79. "Identical style match, 2D game asset, flat layout, character design sheet."
  80. )
  81. NEGATIVE_PROMPT = (
  82. "3D, realistic, altered style, different art style, different face, "
  83. "redesign, overlapping parts, connected limbs, full body standing, dynamic "
  84. "pose, background scenery, shadows, gradients on background, messy layout, "
  85. "missing limbs, merged layers, text, watermarks."
  86. )
  87. def generate_atlas(client, input_image_path: str, atlas_out: str) -> str:
  88. """Send the reference image to Gemini and save the generated atlas PNG."""
  89. from google.genai import types
  90. ref_image = Image.open(input_image_path)
  91. response = client.models.generate_content(
  92. model="gemini-3.1-flash-image-preview",
  93. contents=[
  94. POSITIVE_PROMPT,
  95. f"Negative prompt: {NEGATIVE_PROMPT}",
  96. ref_image,
  97. ],
  98. config=types.GenerateContentConfig(
  99. response_modalities=["IMAGE", "TEXT"],
  100. ),
  101. )
  102. # Extract the generated image from the response parts
  103. for part in response.candidates[0].content.parts:
  104. if part.inline_data is not None:
  105. image_data = part.inline_data.data
  106. with open(atlas_out, "wb") as f:
  107. f.write(image_data)
  108. return atlas_out
  109. print("ERROR: Gemini did not return an image in its response.", file=sys.stderr)
  110. sys.exit(1)
  111. def segment_parts(
  112. atlas_path: str,
  113. output_dir: str,
  114. min_area: int = 500,
  115. padding: int = 12,
  116. bg_threshold: int = 240,
  117. ) -> list[str]:
  118. """Detect individual parts in the atlas using connected-components analysis.
  119. Returns a list of saved part file paths.
  120. """
  121. img = cv2.imread(atlas_path, cv2.IMREAD_UNCHANGED)
  122. if img is None:
  123. print(f"ERROR: Could not read atlas image: {atlas_path}", file=sys.stderr)
  124. sys.exit(1)
  125. # Convert to RGBA if needed
  126. if img.shape[2] == 3:
  127. img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
  128. # Build a foreground mask: pixels whose RGB channels are all below the
  129. # background threshold are considered foreground.
  130. bgr = img[:, :, :3]
  131. gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
  132. _, mask = cv2.threshold(gray, bg_threshold, 255, cv2.THRESH_BINARY_INV)
  133. # Connected-components analysis (8-connectivity)
  134. num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(
  135. mask, connectivity=8
  136. )
  137. os.makedirs(output_dir, exist_ok=True)
  138. saved: list[str] = []
  139. part_idx = 0
  140. h_img, w_img = img.shape[:2]
  141. for label_id in range(1, num_labels): # skip background (label 0)
  142. area = stats[label_id, cv2.CC_STAT_AREA]
  143. if area < min_area:
  144. continue
  145. x = stats[label_id, cv2.CC_STAT_LEFT]
  146. y = stats[label_id, cv2.CC_STAT_TOP]
  147. w = stats[label_id, cv2.CC_STAT_WIDTH]
  148. h = stats[label_id, cv2.CC_STAT_HEIGHT]
  149. # Apply padding (clamped to image bounds)
  150. x1 = max(x - padding, 0)
  151. y1 = max(y - padding, 0)
  152. x2 = min(x + w + padding, w_img)
  153. y2 = min(y + h + padding, h_img)
  154. # Crop the RGBA region
  155. crop = img[y1:y2, x1:x2].copy()
  156. # Zero-out pixels that don't belong to this component (make transparent)
  157. label_region = labels[y1:y2, x1:x2]
  158. component_mask = label_region == label_id
  159. crop[~component_mask] = [0, 0, 0, 0]
  160. out_path = os.path.join(output_dir, f"part_{part_idx:02d}.png")
  161. cv2.imwrite(out_path, crop)
  162. saved.append(out_path)
  163. part_idx += 1
  164. return saved
  165. def main():
  166. parser = argparse.ArgumentParser(
  167. description="Generate a sprite atlas from a character image using "
  168. "Gemini, then segment into individual body parts."
  169. )
  170. parser.add_argument("input_image", help="Path to the character reference image")
  171. parser.add_argument(
  172. "--output-dir",
  173. default="output_parts",
  174. help="Directory for cropped part PNGs (default: output_parts)",
  175. )
  176. parser.add_argument(
  177. "--atlas-out",
  178. default="atlas.png",
  179. help="Output path for the generated atlas PNG (default: atlas.png)",
  180. )
  181. parser.add_argument(
  182. "--min-area",
  183. type=int,
  184. default=500,
  185. help="Minimum component area in pixels to keep (default: 500)",
  186. )
  187. parser.add_argument(
  188. "--padding",
  189. type=int,
  190. default=12,
  191. help="Padding in pixels around each cropped part (default: 12)",
  192. )
  193. parser.add_argument(
  194. "--bg-threshold",
  195. type=int,
  196. default=240,
  197. help="Grayscale threshold above which pixels are treated as background (default: 240)",
  198. )
  199. args = parser.parse_args()
  200. if not os.path.isfile(args.input_image):
  201. print(f"ERROR: Input image not found: {args.input_image}", file=sys.stderr)
  202. sys.exit(1)
  203. # --- Step 1: Generate atlas ---
  204. print("[1/3] Generating atlas …")
  205. client = get_gemini_client()
  206. generate_atlas(client, args.input_image, args.atlas_out)
  207. print(f" Atlas saved to {args.atlas_out}")
  208. # --- Step 2: Segment parts ---
  209. print("[2/3] Segmenting parts …")
  210. parts = segment_parts(
  211. args.atlas_out,
  212. args.output_dir,
  213. min_area=args.min_area,
  214. padding=args.padding,
  215. bg_threshold=args.bg_threshold,
  216. )
  217. print(f" Found {len(parts)} parts → {args.output_dir}/")
  218. for p in parts:
  219. print(f" • {os.path.basename(p)}")
  220. # --- Step 3: Done ---
  221. print("[3/3] Done ✓")
  222. print(f"\nParts are in: {args.output_dir}/")
  223. print("You can now feed them into position_parts.py (Step 1 of the Spine pipeline).")
  224. if __name__ == "__main__":
  225. main()
  226. ```
  227. </details>
  228. <!-- EMBED:scripts/position_parts.py -->
  229. <details>
  230. <summary>📄 <code>scripts/position_parts.py</code> (492 lines)</summary>
  231. ```python
  232. #!/usr/bin/env python3
  233. """
  234. position_parts.py — Part positioning via SIFT + RANSAC homography, z-order via occlusion.
  235. Given a fully assembled character image and individual body-part PNGs,
  236. determines where each part goes (x, y, scale, rotation) and the draw order.
  237. Algorithm:
  238. Phase 1 — SIFT keypoint matching + RANSAC homography
  239. - Extract SIFT features from each part (alpha-masked) and the reference
  240. - Match descriptors via FLANN (knnMatch + Lowe's ratio test)
  241. - Estimate homography via RANSAC → extract position, scale, rotation
  242. - For small/low-texture parts that fail SIFT: fall back to template matching
  243. Phase 2 — Pairwise occlusion voting for z-order
  244. - Sample overlap pixels, compare to reference → occlusion graph → topo sort
  245. Usage:
  246. python3 position_parts.py \
  247. --reference character.png \
  248. --parts parts_folder/ \
  249. --output layout.json \
  250. [--min-matches 4] \
  251. [--ratio 0.80] \
  252. [--debug debug_folder/]
  253. """
  254. import argparse, json, os, sys, math
  255. from pathlib import Path
  256. from collections import defaultdict
  257. import cv2
  258. import numpy as np
  259. from PIL import Image
  260. def load_rgba(path):
  261. return np.array(Image.open(path).convert("RGBA"))
  262. def create_foreground_mask(rgba, bg_color=(255,255,255), bg_threshold=30):
  263. alpha = rgba[:, :, 3]
  264. is_opaque = alpha > 128
  265. rgb = rgba[:, :, :3].astype(float)
  266. dist = np.sqrt(np.sum((rgb - np.array(bg_color, dtype=float)) ** 2, axis=2))
  267. mask = (is_opaque & (dist > bg_threshold)).astype(np.uint8) * 255
  268. k = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
  269. return cv2.morphologyEx(cv2.morphologyEx(mask, cv2.MORPH_CLOSE, k), cv2.MORPH_OPEN, k)
  270. # ─────────────────────────────────────────────────────────────────
  271. # Phase 1: SIFT + RANSAC
  272. # ─────────────────────────────────────────────────────────────────
  273. def sift_match_part(ref_gray, ref_kp, ref_des, part_rgba,
  274. sift, ratio_thresh=0.80, min_matches=4):
  275. """
  276. Match a part to the reference using SIFT + FLANN + RANSAC affine transform.
  277. Uses estimateAffinePartial2D (4 DOF: translate + scale + rotation) instead
  278. of full homography — much more robust with sparse matches on game art.
  279. Returns dict with position/scale/rotation/score, or None.
  280. """
  281. part_h, part_w = part_rgba.shape[:2]
  282. part_gray = cv2.cvtColor(part_rgba[:, :, :3], cv2.COLOR_RGB2GRAY)
  283. part_mask = (part_rgba[:, :, 3] > 128).astype(np.uint8) * 255
  284. part_kp, part_des = sift.detectAndCompute(part_gray, part_mask)
  285. if part_des is None or len(part_kp) < 2:
  286. return None
  287. # FLANN matching
  288. flann = cv2.FlannBasedMatcher(dict(algorithm=1, trees=5), dict(checks=150))
  289. try:
  290. matches = flann.knnMatch(part_des, ref_des, k=2)
  291. except cv2.error:
  292. return None
  293. # Lowe's ratio test
  294. good = []
  295. for pair in matches:
  296. if len(pair) == 2 and pair[0].distance < ratio_thresh * pair[1].distance:
  297. good.append(pair[0])
  298. if len(good) < min_matches:
  299. return None
  300. src_pts = np.float32([part_kp[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
  301. dst_pts = np.float32([ref_kp[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)
  302. # RANSAC similarity transform (4 DOF: translate + uniform scale + rotation)
  303. # This is much more constrained than homography (8 DOF) and needs only 2 points
  304. M, inliers_mask = cv2.estimateAffinePartial2D(
  305. src_pts, dst_pts, method=cv2.RANSAC, ransacReprojThreshold=5.0)
  306. if M is None or inliers_mask is None:
  307. return None
  308. inliers = int(inliers_mask.sum())
  309. if inliers < min_matches:
  310. return None
  311. # Extract scale and rotation from 2x3 affine matrix
  312. # M = [[s*cos(θ), -s*sin(θ), tx], [s*sin(θ), s*cos(θ), ty]]
  313. scale = np.sqrt(M[0,0]**2 + M[1,0]**2)
  314. rotation = math.degrees(math.atan2(M[1,0], M[0,0]))
  315. # Sanity: game parts should be ~0.5–2.0x scale, ~0° rotation
  316. if scale < 0.3 or scale > 3.0:
  317. return None
  318. if abs(rotation) > 20:
  319. return None
  320. # Transform corners via the affine matrix
  321. corners = np.float32([[0,0],[part_w,0],[part_w,part_h],[0,part_h]]).reshape(-1,1,2)
  322. transformed = cv2.transform(corners, M).reshape(-1, 2)
  323. x_min, y_min = transformed[:, 0].min(), transformed[:, 1].min()
  324. x_max, y_max = transformed[:, 0].max(), transformed[:, 1].max()
  325. out_w, out_h = x_max - x_min, y_max - y_min
  326. if out_w < 5 or out_h < 5:
  327. return None
  328. inlier_ratio = inliers / len(good) if good else 0
  329. return {
  330. "x": int(round(x_min)), "y": int(round(y_min)),
  331. "width": int(round(out_w)), "height": int(round(out_h)),
  332. "original_width": part_w, "original_height": part_h,
  333. "scale": round(scale, 4), "rotation": round(rotation, 2),
  334. "score": round(inlier_ratio, 4),
  335. "n_matches": inliers, "n_good": len(good),
  336. "n_keypoints": len(part_kp), "method": "sift",
  337. }
  338. def template_match_fallback(ref_bgr, ref_fg_mask, part_bgra,
  339. scales=None):
  340. """Fallback for parts too small/featureless for SIFT."""
  341. if scales is None:
  342. scales = (0.85, 0.9, 0.95, 1.0, 1.05, 1.1, 1.15)
  343. ref_h, ref_w = ref_bgr.shape[:2]
  344. best = None
  345. for scale in scales:
  346. sw = max(1, int(part_bgra.shape[1] * scale))
  347. sh = max(1, int(part_bgra.shape[0] * scale))
  348. if sw >= ref_w - 2 or sh >= ref_h - 2:
  349. continue
  350. interp = cv2.INTER_AREA if scale < 1 else cv2.INTER_LINEAR
  351. scaled = cv2.resize(part_bgra, (sw, sh), interpolation=interp)
  352. tmpl_bgr = cv2.cvtColor(scaled, cv2.COLOR_BGRA2BGR)
  353. mask = (scaled[:, :, 3] > 128).astype(np.uint8) * 255
  354. opaque = np.count_nonzero(mask)
  355. if opaque < 20:
  356. continue
  357. try:
  358. result = cv2.matchTemplate(ref_bgr, tmpl_bgr, cv2.TM_CCORR_NORMED, mask=mask)
  359. except cv2.error:
  360. continue
  361. _, max_val, _, max_loc = cv2.minMaxLoc(result)
  362. fg_region = ref_fg_mask[max_loc[1]:max_loc[1]+sh, max_loc[0]:max_loc[0]+sw]
  363. fg_ratio = 0.0
  364. if fg_region.shape == (sh, sw):
  365. fg_ratio = np.count_nonzero(fg_region[mask > 128] > 128) / max(1, opaque)
  366. combined = max_val * (0.3 + 0.7 * fg_ratio)
  367. if best is None or combined > best["score"]:
  368. best = {
  369. "x": int(max_loc[0]), "y": int(max_loc[1]),
  370. "width": sw, "height": sh,
  371. "original_width": part_bgra.shape[1], "original_height": part_bgra.shape[0],
  372. "scale": round(scale, 4), "rotation": 0.0,
  373. "score": round(combined, 4),
  374. "n_matches": 0, "n_good": 0, "n_keypoints": 0,
  375. "method": "template",
  376. }
  377. return best
  378. def find_all_positions(reference_path, parts_folder, ratio_thresh, min_matches):
  379. ref_rgba = load_rgba(reference_path)
  380. ref_gray = cv2.cvtColor(ref_rgba[:, :, :3], cv2.COLOR_RGB2GRAY)
  381. ref_bgra = cv2.cvtColor(ref_rgba, cv2.COLOR_RGBA2BGRA)
  382. ref_bgr = cv2.cvtColor(ref_bgra, cv2.COLOR_BGRA2BGR)
  383. fg_mask = create_foreground_mask(ref_rgba)
  384. # Tuned SIFT: lower contrast threshold to find more features on game art
  385. sift = cv2.SIFT_create(nfeatures=0, contrastThreshold=0.02, edgeThreshold=20)
  386. print("Computing SIFT on reference...")
  387. ref_kp, ref_des = sift.detectAndCompute(ref_gray, None)
  388. print(f" Reference: {ref_gray.shape[1]}x{ref_gray.shape[0]}, {len(ref_kp)} keypoints\n")
  389. part_files = sorted([f for f in os.listdir(parts_folder) if f.lower().endswith(('.png','.webp'))])
  390. # First pass: try SIFT on all parts
  391. sift_results = {}
  392. failed_parts = []
  393. for fname in part_files:
  394. name = Path(fname).stem
  395. part_rgba = load_rgba(os.path.join(parts_folder, fname))
  396. if np.count_nonzero(part_rgba[:,:,3] > 128) / part_rgba[:,:,3].size < 0.01:
  397. print(f" SKIP {name}: <1% opaque")
  398. continue
  399. result = sift_match_part(ref_gray, ref_kp, ref_des, part_rgba,
  400. sift, ratio_thresh, min_matches)
  401. if result:
  402. sift_results[name] = result
  403. print(f" SIFT {name:>20}: pos=({result['x']},{result['y']}) "
  404. f"scale={result['scale']:.3f} rot={result['rotation']:.1f}° "
  405. f"inliers={result['n_matches']}/{result['n_good']} "
  406. f"score={result['score']:.3f}")
  407. else:
  408. failed_parts.append((name, part_rgba))
  409. # Derive template matching scales from SIFT results
  410. tmpl_scales = (0.85, 0.9, 0.95, 1.0, 1.05, 1.1, 1.15)
  411. if sift_results:
  412. sift_scales = [r["scale"] for r in sift_results.values()]
  413. median_scale = float(np.median(sift_scales))
  414. # Generate scale range around the SIFT median: ±20%
  415. tmpl_scales = tuple(round(median_scale * f, 4)
  416. for f in (0.80, 0.85, 0.90, 0.95, 1.0, 1.05, 1.10, 1.15, 1.20))
  417. print(f"\n SIFT median scale: {median_scale:.3f} → template range: "
  418. f"{tmpl_scales[0]:.3f}–{tmpl_scales[-1]:.3f}")
  419. # Second pass: template matching for failed parts using SIFT-derived scales
  420. positions = dict(sift_results)
  421. for name, part_rgba in failed_parts:
  422. part_bgra = cv2.cvtColor(part_rgba, cv2.COLOR_RGBA2BGRA)
  423. result = template_match_fallback(ref_bgr, fg_mask, part_bgra, scales=tmpl_scales)
  424. if result:
  425. positions[name] = result
  426. print(f" TMPL {name:>20}: pos=({result['x']},{result['y']}) "
  427. f"scale={result['scale']:.3f} score={result['score']:.3f}")
  428. else:
  429. print(f" FAIL {name:>20}: no match")
  430. return positions, fg_mask
  431. # ─────────────────────────────────────────────────────────────────
  432. # Phase 2: Z-Order via Occlusion
  433. # ─────────────────────────────────────────────────────────────────
  434. def compute_z_order(reference_path, parts_folder, positions):
  435. reference = load_rgba(reference_path)
  436. ref_h, ref_w = reference.shape[:2]
  437. part_images = {}
  438. for name, pos in positions.items():
  439. fp = None
  440. for ext in ['.png','.webp']:
  441. c = os.path.join(parts_folder, name+ext)
  442. if os.path.exists(c): fp = c; break
  443. if not fp: continue
  444. img = load_rgba(fp)
  445. tw, th = pos["width"], pos["height"]
  446. if (tw, th) != (img.shape[1], img.shape[0]):
  447. img = np.array(Image.fromarray(img).resize((tw, th), Image.LANCZOS))
  448. part_images[name] = img
  449. names = list(part_images.keys())
  450. n = len(names)
  451. wins = defaultdict(lambda: defaultdict(int))
  452. print(f"\nZ-order analysis ({n} parts):")
  453. for i in range(n):
  454. for j in range(i+1, n):
  455. a, b = names[i], names[j]
  456. ap, bp = positions[a], positions[b]
  457. ai, bi = part_images[a], part_images[b]
  458. ox1 = max(ap["x"], bp["x"])
  459. oy1 = max(ap["y"], bp["y"])
  460. ox2 = min(ap["x"]+ap["width"], bp["x"]+bp["width"])
  461. oy2 = min(ap["y"]+ap["height"], bp["y"]+bp["height"])
  462. if ox1 >= ox2 or oy1 >= oy2: continue
  463. step = max(1, int(math.sqrt((ox2-ox1)*(oy2-oy1)/500)))
  464. aw, bw, tot = 0, 0, 0
  465. for sy in range(oy1, oy2, step):
  466. for sx in range(ox1, ox2, step):
  467. if sy >= ref_h or sx >= ref_w: continue
  468. rp = reference[sy, sx]
  469. if rp[3] < 128: continue
  470. aly, alx = sy-ap["y"], sx-ap["x"]
  471. bly, blx = sy-bp["y"], sx-bp["x"]
  472. if not (0<=alx<ai.shape[1] and 0<=aly<ai.shape[0]): continue
  473. if not (0<=blx<bi.shape[1] and 0<=bly<bi.shape[0]): continue
  474. apx, bpx = ai[aly, alx], bi[bly, blx]
  475. if apx[3] < 128 or bpx[3] < 128: continue
  476. ad = np.sqrt(np.sum((rp[:3].astype(float)-apx[:3].astype(float))**2))
  477. bd = np.sqrt(np.sum((rp[:3].astype(float)-bpx[:3].astype(float))**2))
  478. tot += 1
  479. if ad < bd - 5: aw += 1
  480. elif bd < ad - 5: bw += 1
  481. if tot > 5:
  482. if aw > bw * 1.2:
  483. wins[a][b] += aw
  484. print(f" {a} OVER {b} ({aw}/{tot})")
  485. elif bw > aw * 1.2:
  486. wins[b][a] += bw
  487. print(f" {b} OVER {a} ({bw}/{tot})")
  488. depth = {nm: 0.0 for nm in names}
  489. for a in names:
  490. for b in names:
  491. if a != b and wins[a][b] > 0:
  492. depth[b] -= wins[a][b]
  493. depth[a] += wins[a][b]
  494. result = sorted(names, key=lambda nm: depth[nm])
  495. print(f"\nDraw order (back -> front):")
  496. for i, nm in enumerate(result):
  497. print(f" z={i:>2}: {nm} (depth={depth[nm]:.0f}, {positions[nm]['method']})")
  498. return result, depth
  499. # ─────────────────────────────────────────────────────────────────
  500. # Debug Visualization
  501. # ─────────────────────────────────────────────────────────────────
  502. def generate_debug(ref_path, parts_folder, positions, z_order, fg_mask, debug_dir):
  503. os.makedirs(debug_dir, exist_ok=True)
  504. ref = load_rgba(ref_path)
  505. rh, rw = ref.shape[:2]
  506. # Composite
  507. comp = np.zeros((rh, rw, 4), dtype=np.uint8)
  508. comp[:,:,:3] = 255; comp[:,:,3] = 255
  509. for name in z_order:
  510. if name not in positions: continue
  511. pos = positions[name]
  512. fp = None
  513. for ext in ['.png','.webp']:
  514. c = os.path.join(parts_folder, name+ext)
  515. if os.path.exists(c): fp = c; break
  516. if not fp: continue
  517. img = load_rgba(fp)
  518. tw, th = pos["width"], pos["height"]
  519. if (tw, th) != (img.shape[1], img.shape[0]):
  520. img = np.array(Image.fromarray(img).resize((tw, th), Image.LANCZOS))
  521. x, y = pos["x"], pos["y"]
  522. ph, pw = img.shape[:2]
  523. sx1, sy1 = max(0,-x), max(0,-y)
  524. dx1, dy1 = max(0,x), max(0,y)
  525. sx2, sy2 = min(pw, rw-x), min(ph, rh-y)
  526. dx2, dy2 = dx1+(sx2-sx1), dy1+(sy2-sy1)
  527. if sx2<=sx1 or sy2<=sy1: continue
  528. pr = img[sy1:sy2, sx1:sx2]
  529. a = pr[:,:,3:4].astype(float)/255.0
  530. cr = comp[dy1:dy2, dx1:dx2, :3].astype(float)
  531. comp[dy1:dy2, dx1:dx2, :3] = (pr[:,:,:3].astype(float)*a + cr*(1-a)).astype(np.uint8)
  532. Image.fromarray(comp).save(os.path.join(debug_dir, "composite.png"))
  533. # Side-by-side
  534. gap = 10
  535. sb = np.zeros((rh, rw*2+gap, 4), dtype=np.uint8)
  536. sb[:,:,:3]=40; sb[:,:,3]=255
  537. sb[:rh,:rw] = ref; sb[:rh,rw+gap:rw*2+gap] = comp
  538. Image.fromarray(sb).save(os.path.join(debug_dir, "comparison.png"))
  539. # Bboxes
  540. rv = ref.copy()
  541. colors = [(255,80,80),(80,255,80),(80,80,255),(255,255,80),(255,80,255),
  542. (80,255,255),(200,140,80),(140,80,200),(80,200,140),
  543. (255,160,120),(120,255,160),(160,120,255),(200,200,100)]
  544. for i, (name, pos) in enumerate(positions.items()):
  545. c = colors[i % len(colors)]
  546. m = pos["method"][0].upper()
  547. x1, y1 = pos["x"], pos["y"]
  548. x2, y2 = x1+pos["width"], y1+pos["height"]
  549. cv2.rectangle(rv, (x1,y1), (x2,y2), c+(255,), 2)
  550. label = f"{name} [{m}] s={pos['scale']:.2f} m={pos.get('n_matches',0)}"
  551. cv2.putText(rv, label, (x1, y1-5),
  552. cv2.FONT_HERSHEY_SIMPLEX, 0.33, c+(255,), 1)
  553. Image.fromarray(rv).save(os.path.join(debug_dir, "bboxes.png"))
  554. # FG mask
  555. Image.fromarray(cv2.cvtColor(fg_mask, cv2.COLOR_GRAY2RGBA)).save(
  556. os.path.join(debug_dir, "fg_mask.png"))
  557. # Per-part SIFT match visualizations
  558. sift = cv2.SIFT_create(nfeatures=0, contrastThreshold=0.02, edgeThreshold=20)
  559. ref_gray = cv2.cvtColor(ref[:,:,:3], cv2.COLOR_RGB2GRAY)
  560. ref_kp, ref_des = sift.detectAndCompute(ref_gray, None)
  561. for name, pos in positions.items():
  562. if pos["method"] != "sift": continue
  563. fp = None
  564. for ext in ['.png','.webp']:
  565. c = os.path.join(parts_folder, name+ext)
  566. if os.path.exists(c): fp = c; break
  567. if not fp: continue
  568. prgba = load_rgba(fp)
  569. pgray = cv2.cvtColor(prgba[:,:,:3], cv2.COLOR_RGB2GRAY)
  570. pmask = (prgba[:,:,3] > 128).astype(np.uint8) * 255
  571. pkp, pdes = sift.detectAndCompute(pgray, pmask)
  572. if pdes is None: continue
  573. flann = cv2.FlannBasedMatcher(dict(algorithm=1, trees=5), dict(checks=150))
  574. matches = flann.knnMatch(pdes, ref_des, k=2)
  575. good = [m for m, n in matches if len([m,n])==2 and m.distance < 0.8*n.distance]
  576. if len(good) >= 4:
  577. src = np.float32([pkp[m.queryIdx].pt for m in good]).reshape(-1,1,2)
  578. dst = np.float32([ref_kp[m.trainIdx].pt for m in good]).reshape(-1,1,2)
  579. H, hmask = cv2.estimateAffinePartial2D(src, dst, method=cv2.RANSAC, ransacReprojThreshold=5.0)
  580. if hmask is not None:
  581. draw_p = dict(matchColor=(0,255,0), singlePointColor=(255,0,0),
  582. matchesMask=hmask.ravel().tolist(),
  583. flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
  584. pbgr = cv2.cvtColor(prgba[:,:,:3], cv2.COLOR_RGB2BGR)
  585. rbgr = cv2.cvtColor(ref[:,:,:3], cv2.COLOR_RGB2BGR)
  586. vis = cv2.drawMatches(pbgr, pkp, rbgr, ref_kp, good, None, **draw_p)
  587. cv2.imwrite(os.path.join(debug_dir, f"sift_{name}.jpg"), vis,
  588. [cv2.IMWRITE_JPEG_QUALITY, 70])
  589. print(f"\nDebug saved to {debug_dir}/")
  590. # ─────────────────────────────────────────────────────────────────
  591. # Main
  592. # ─────────────────────────────────────────────────────────────────
  593. def main():
  594. p = argparse.ArgumentParser(
  595. description="Position parts via SIFT+RANSAC homography + occlusion z-order")
  596. p.add_argument("--reference", required=True)
  597. p.add_argument("--parts", required=True)
  598. p.add_argument("--output", default="layout.json")
  599. p.add_argument("--min-matches", type=int, default=4,
  600. help="Min RANSAC inliers (default: 4)")
  601. p.add_argument("--ratio", type=float, default=0.80,
  602. help="Lowe's ratio threshold (default: 0.80)")
  603. p.add_argument("--debug", default=None)
  604. args = p.parse_args()
  605. print("=" * 60)
  606. print("PHASE 1: SIFT + RANSAC Homography")
  607. print("=" * 60)
  608. positions, fg_mask = find_all_positions(
  609. args.reference, args.parts, args.ratio, args.min_matches)
  610. if not positions:
  611. print("ERROR: No parts matched!"); sys.exit(1)
  612. sift_n = sum(1 for p in positions.values() if p["method"] == "sift")
  613. tmpl_n = sum(1 for p in positions.values() if p["method"] == "template")
  614. print(f"\nResult: {sift_n} SIFT, {tmpl_n} template fallback")
  615. print(f"\n{'='*60}")
  616. print("PHASE 2: Z-Order (Occlusion Analysis)")
  617. print("="*60)
  618. z_order, depth = compute_z_order(args.reference, args.parts, positions)
  619. for i, name in enumerate(z_order):
  620. if name in positions:
  621. positions[name]["z_index"] = i
  622. positions[name]["depth_score"] = depth[name]
  623. ref_img = Image.open(args.reference)
  624. output = {
  625. "reference_image": os.path.basename(args.reference),
  626. "canvas_width": ref_img.width, "canvas_height": ref_img.height,
  627. "parts": positions, "z_order": z_order,
  628. }
  629. with open(args.output, "w") as f:
  630. json.dump(output, f, indent=2)
  631. print(f"\nLayout saved: {args.output}")
  632. if args.debug:
  633. generate_debug(args.reference, args.parts, positions, z_order, fg_mask, args.debug)
  634. if __name__ == "__main__":
  635. main()
  636. ```
  637. </details>
  638. <!-- EMBED:scripts/build_spine_json.py -->
  639. <details>
  640. <summary>📄 <code>scripts/build_spine_json.py</code> (562 lines)</summary>
  641. ```python
  642. #!/usr/bin/env python3
  643. """
  644. build_spine_json.py — Generate a complete Spine-compatible JSON skeleton with animations.
  645. Accepts a config describing bones, slots, attachments, and desired animations,
  646. then outputs a valid Spine 4.2 JSON file.
  647. Usage:
  648. python3 build_spine_json.py --config config.json --output skeleton.json
  649. Config JSON format:
  650. {
  651. "skeleton": {
  652. "name": "my-character",
  653. "width": 400,
  654. "height": 600
  655. },
  656. "bones": [
  657. { "name": "root" },
  658. { "name": "hip", "parent": "root", "x": 0, "y": 200, "length": 30 },
  659. { "name": "torso", "parent": "hip", "length": 120 },
  660. ...
  661. ],
  662. "slots": [
  663. { "name": "torso", "bone": "torso", "attachment": "torso" },
  664. ...
  665. ],
  666. "attachments": {
  667. "torso": { "width": 120, "height": 200, "x": 0, "y": 60 },
  668. ...
  669. },
  670. "animations": ["idle", "walk", "wave", "jump", "run", "attack"],
  671. "custom_animations": {
  672. "my-custom": { "bones": { "head": { "rotate": [...] } } }
  673. }
  674. }
  675. """
  676. import argparse
  677. import json
  678. import hashlib
  679. import sys
  680. # ─── Bezier curve presets ────────────────────────────────────────────────────
  681. EASE = [0.25, 0, 0.75, 1] # Standard ease in-out (most common)
  682. EASE_IN = [0.42, 0, 1, 1] # Accelerate from rest
  683. EASE_OUT = [0, 0, 0.58, 1] # Decelerate to rest
  684. EASE_BOUNCE = [0.34, 1.56, 0.64, 1] # Slight overshoot
  685. EASE_FAST = [0.4, 0, 0.2, 1] # Quick but smooth
  686. def _has(bone_names, *names):
  687. """Check if any of the given bone names exist."""
  688. return any(n in bone_names for n in names)
  689. def _kf(time, angle=None, x=None, y=None, curve=EASE):
  690. """Build a keyframe dict, omitting None values.
  691. This is the authoring shorthand used by the generators below: rotations go
  692. under "angle", and `curve` is a single normalized bezier describing the
  693. segment that ends at this keyframe. `_to_spine_42` rewrites both into the
  694. wire format before the skeleton is serialized.
  695. """
  696. kf = {"time": round(time, 4)}
  697. if angle is not None:
  698. kf["angle"] = round(angle, 2)
  699. if x is not None:
  700. kf["x"] = round(x, 2)
  701. if y is not None:
  702. kf["y"] = round(y, 2)
  703. if curve:
  704. kf["curve"] = curve
  705. return kf
  706. # ─── Spine 4.2 wire format ──────────────────────────────────────────────────
  707. # Timeline type -> the properties it animates, with their default values.
  708. _TIMELINE_PROPERTIES = {
  709. "rotate": (("value", 0.0),),
  710. "translate": (("x", 0.0), ("y", 0.0)),
  711. "scale": (("x", 1.0), ("y", 1.0)),
  712. "shear": (("x", 0.0), ("y", 0.0)),
  713. "translatex": (("value", 0.0),),
  714. "translatey": (("value", 0.0),),
  715. "scalex": (("value", 1.0),),
  716. "scaley": (("value", 1.0),),
  717. "shearx": (("value", 0.0),),
  718. "sheary": (("value", 0.0),),
  719. }
  720. def _convert_timeline(kind, frames):
  721. """Rewrite one bone timeline in place into the Spine 4.2 wire format.
  722. Three things differ from the 3.8-era shorthand the generators author in:
  723. 1. Rotation values live under "value", not "angle". A 4.x runtime that
  724. finds "angle" reads every rotation as 0, so nothing turns.
  725. 2. A bezier is stored per ANIMATED PROPERTY, not per keyframe. `rotate`
  726. drives one property and needs 4 numbers, but `translate`, `scale` and
  727. `shear` drive two (x and y) and need 8. Given only 4, the runtime
  728. indexes past the end of the array, reads undefined, and NaN spreads
  729. through the bone transforms until the skeleton stops rasterizing
  730. entirely -- it renders the setup pose for one frame, then vanishes.
  731. 3. Control points are absolute, in the same units as `time` and `value`,
  732. not normalized to the segment. From Animation.js in spine-core:
  733. let dx = (cx1 - time1) * 0.3 + ...; let x = time1 + dx;
  734. Normalized points land outside the segment they belong to, which makes
  735. the interpolation lurch instead of ease.
  736. A keyframe's curve also governs the segment that STARTS at it, so curves
  737. shift one frame earlier: what the generators attach to frame i describes
  738. the segment i-1 -> i.
  739. """
  740. properties = _TIMELINE_PROPERTIES.get(kind)
  741. if not properties or len(frames) < 2:
  742. return
  743. if kind == "rotate":
  744. for kf in frames:
  745. if "angle" in kf:
  746. kf["value"] = kf.pop("angle")
  747. authored = [kf.pop("curve", None) for kf in frames]
  748. for i in range(len(frames) - 1):
  749. curve = authored[i + 1]
  750. if curve is None:
  751. continue
  752. if curve == "stepped":
  753. frames[i]["curve"] = "stepped"
  754. continue
  755. if not isinstance(curve, list) or len(curve) < 4:
  756. continue
  757. cx1, cy1, cx2, cy2 = curve[:4]
  758. time1, time2 = frames[i]["time"], frames[i + 1]["time"]
  759. span = time2 - time1
  760. absolute = []
  761. for name, default in properties:
  762. value1 = frames[i].get(name, default)
  763. value2 = frames[i + 1].get(name, default)
  764. delta = value2 - value1
  765. absolute += [
  766. round(time1 + span * cx1, 6), round(value1 + delta * cy1, 6),
  767. round(time1 + span * cx2, 6), round(value1 + delta * cy2, 6),
  768. ]
  769. frames[i]["curve"] = absolute
  770. def _to_spine_42(animations):
  771. """Convert every bone timeline in `animations` to the Spine 4.2 format."""
  772. for animation in animations.values():
  773. for timelines in animation.get("bones", {}).values():
  774. for kind, frames in timelines.items():
  775. _convert_timeline(kind, frames)
  776. # ─── Animation Generators ───────────────────────────────────────────────────
  777. def gen_idle(B):
  778. """Idle breathing/sway. Subtle, loopable. ~1.6s"""
  779. bones = {}
  780. D = 1.6
  781. for name, angle_amp, phase in [
  782. ("torso", 1.5, 0.5), ("neck", 1.0, 0.55), ("head", -2.0, 0.6)
  783. ]:
  784. if name in B:
  785. bones[name] = {"rotate": [
  786. _kf(0, 0, curve=None),
  787. _kf(D * phase, angle_amp),
  788. _kf(D, 0),
  789. ]}
  790. # Subtle torso lift
  791. if "torso" in B:
  792. bones.setdefault("torso", {})["translate"] = [
  793. _kf(0, x=0, y=0, curve=None),
  794. _kf(D * 0.5, x=0, y=1.5),
  795. _kf(D, x=0, y=0),
  796. ]
  797. # Gentle arm sway
  798. for side in ["left", "right"]:
  799. s = 1 if side == "left" else -1
  800. for part, amp, ph in [
  801. (f"{side}-upper-arm", s * 1.5, 0.5),
  802. (f"{side}-lower-arm", s * 1.0, 0.55),
  803. ]:
  804. if part in B:
  805. bones[part] = {"rotate": [
  806. _kf(0, 0, curve=None), _kf(D * ph, amp), _kf(D, 0),
  807. ]}
  808. return {"bones": bones} if bones else {}
  809. def gen_walk(B):
  810. """Walk cycle. Opposing arm-leg motion, hip bob. ~0.8s"""
  811. bones = {}
  812. D = 0.8
  813. Q = D / 4 # quarter
  814. if "hip" in B:
  815. bones["hip"] = {
  816. "translate": [
  817. _kf(0, x=0, y=0, curve=None),
  818. _kf(Q, x=0, y=3), _kf(Q*2, x=0, y=0),
  819. _kf(Q*3, x=0, y=3), _kf(D, x=0, y=0),
  820. ],
  821. "rotate": [
  822. _kf(0, 0, curve=None),
  823. _kf(Q, -2), _kf(Q*2, 0), _kf(Q*3, 2), _kf(D, 0),
  824. ],
  825. }
  826. if "torso" in B:
  827. bones["torso"] = {"rotate": [
  828. _kf(0, 0, curve=None),
  829. _kf(Q, 3), _kf(Q*2, 0), _kf(Q*3, -3), _kf(D, 0),
  830. ]}
  831. if "head" in B:
  832. bones["head"] = {"rotate": [
  833. _kf(0, 0, curve=None),
  834. _kf(Q, -1.5), _kf(Q*2, 0), _kf(Q*3, 1.5), _kf(D, 0),
  835. ]}
  836. # Legs: left forward at t=0, right forward at t=D/2
  837. for side, phase_shift in [("left", 0), ("right", 0.5)]:
  838. p = phase_shift * D
  839. upper = f"{side}-upper-leg"
  840. lower = f"{side}-lower-leg"
  841. foot = f"{side}-foot"
  842. if upper in B:
  843. bones[upper] = {"rotate": [
  844. _kf(0, -25 if phase_shift == 0 else 25, curve=None),
  845. _kf(Q, 0), _kf(Q*2, 25 if phase_shift == 0 else -25),
  846. _kf(Q*3, 0), _kf(D, -25 if phase_shift == 0 else 25),
  847. ]}
  848. if lower in B:
  849. # Back leg straight, front leg bent
  850. bones[lower] = {"rotate": [
  851. _kf(0, 5 if phase_shift == 0 else 35, curve=None),
  852. _kf(Q, 35), _kf(Q*2, 35 if phase_shift == 0 else 5),
  853. _kf(Q*3, 5), _kf(D, 5 if phase_shift == 0 else 35),
  854. ]}
  855. # Arms: oppose legs
  856. for side, phase_shift in [("left", 0.5), ("right", 0)]:
  857. upper = f"{side}-upper-arm"
  858. lower = f"{side}-lower-arm"
  859. if upper in B:
  860. bones[upper] = {"rotate": [
  861. _kf(0, -20 if phase_shift == 0 else 20, curve=None),
  862. _kf(Q, 0), _kf(Q*2, 20 if phase_shift == 0 else -20),
  863. _kf(Q*3, 0), _kf(D, -20 if phase_shift == 0 else 20),
  864. ]}
  865. if lower in B:
  866. bones[lower] = {"rotate": [
  867. _kf(0, -10 if phase_shift == 0 else -30, curve=None),
  868. _kf(Q, -20), _kf(Q*2, -30 if phase_shift == 0 else -10),
  869. _kf(Q*3, -20), _kf(D, -10 if phase_shift == 0 else -30),
  870. ]}
  871. return {"bones": bones} if bones else {}
  872. def gen_run(B):
  873. """Run cycle. Exaggerated walk, forward lean, bigger bounce. ~0.5s"""
  874. bones = {}
  875. D = 0.5
  876. Q = D / 4
  877. if "hip" in B:
  878. bones["hip"] = {
  879. "translate": [
  880. _kf(0, x=0, y=0, curve=None),
  881. _kf(Q, x=0, y=6), _kf(Q*2, x=0, y=-2),
  882. _kf(Q*3, x=0, y=6), _kf(D, x=0, y=0),
  883. ],
  884. "rotate": [
  885. _kf(0, 0, curve=None),
  886. _kf(Q, -3), _kf(Q*2, 0), _kf(Q*3, 3), _kf(D, 0),
  887. ],
  888. }
  889. if "torso" in B:
  890. bones["torso"] = {"rotate": [
  891. _kf(0, 8, curve=None), # Constant forward lean
  892. _kf(Q, 12), _kf(Q*2, 8), _kf(Q*3, 12), _kf(D, 8),
  893. ]}
  894. if "head" in B:
  895. bones["head"] = {"rotate": [
  896. _kf(0, -6, curve=None), # Compensate for torso lean
  897. _kf(Q, -8), _kf(Q*2, -6), _kf(Q*3, -8), _kf(D, -6),
  898. ]}
  899. for side, ph in [("left", 0), ("right", 0.5)]:
  900. upper = f"{side}-upper-leg"
  901. lower = f"{side}-lower-leg"
  902. if upper in B:
  903. bones[upper] = {"rotate": [
  904. _kf(0, -35 if ph == 0 else 40, curve=None),
  905. _kf(Q, 0), _kf(Q*2, 40 if ph == 0 else -35),
  906. _kf(Q*3, 0), _kf(D, -35 if ph == 0 else 40),
  907. ]}
  908. if lower in B:
  909. bones[lower] = {"rotate": [
  910. _kf(0, 10 if ph == 0 else 50, curve=None),
  911. _kf(Q, 50), _kf(Q*2, 50 if ph == 0 else 10),
  912. _kf(Q*3, 10), _kf(D, 10 if ph == 0 else 50),
  913. ]}
  914. for side, ph in [("left", 0.5), ("right", 0)]:
  915. upper = f"{side}-upper-arm"
  916. lower = f"{side}-lower-arm"
  917. if upper in B:
  918. bones[upper] = {"rotate": [
  919. _kf(0, -30 if ph == 0 else 30, curve=None),
  920. _kf(Q, 0), _kf(Q*2, 30 if ph == 0 else -30),
  921. _kf(Q*3, 0), _kf(D, -30 if ph == 0 else 30),
  922. ]}
  923. if lower in B:
  924. bones[lower] = {"rotate": [
  925. _kf(0, -20 if ph == 0 else -50, curve=None),
  926. _kf(Q, -35), _kf(Q*2, -50 if ph == 0 else -20),
  927. _kf(Q*3, -35), _kf(D, -20 if ph == 0 else -50),
  928. ]}
  929. return {"bones": bones} if bones else {}
  930. def gen_wave(B):
  931. """Waving greeting. Raise right arm, oscillate forearm. ~1.2s"""
  932. bones = {}
  933. D = 1.2
  934. if "right-upper-arm" in B:
  935. bones["right-upper-arm"] = {"rotate": [
  936. _kf(0, 0, curve=None),
  937. _kf(0.2, -130, curve=EASE_OUT),
  938. _kf(D - 0.2, -130, curve=None),
  939. _kf(D, 0, curve=EASE_IN),
  940. ]}
  941. if "right-lower-arm" in B:
  942. bones["right-lower-arm"] = {"rotate": [
  943. _kf(0, 0, curve=None),
  944. _kf(0.2, -30, curve=EASE_OUT),
  945. _kf(0.4, 20), _kf(0.6, -20), _kf(0.8, 20), _kf(1.0, -20),
  946. _kf(D, 0, curve=EASE_IN),
  947. ]}
  948. if "torso" in B:
  949. bones["torso"] = {"rotate": [
  950. _kf(0, 0, curve=None),
  951. _kf(0.2, -3), _kf(D - 0.2, -3, curve=None), _kf(D, 0),
  952. ]}
  953. if "head" in B:
  954. bones["head"] = {"rotate": [
  955. _kf(0, 0, curve=None),
  956. _kf(0.3, 5), _kf(D - 0.2, 5, curve=None), _kf(D, 0),
  957. ]}
  958. return {"bones": bones} if bones else {}
  959. def gen_jump(B):
  960. """Jump: anticipation squat → launch → air → land → settle. ~1.0s"""
  961. bones = {}
  962. D = 1.0
  963. if "hip" in B:
  964. bones["hip"] = {"translate": [
  965. _kf(0, x=0, y=0, curve=None),
  966. _kf(0.15, x=0, y=-20, curve=EASE_IN), # squat
  967. _kf(0.35, x=0, y=70, curve=EASE_OUT), # launch
  968. _kf(0.55, x=0, y=65, curve=None), # float
  969. _kf(0.80, x=0, y=-10, curve=EASE_IN), # land impact
  970. _kf(D, x=0, y=0, curve=EASE_OUT), # settle
  971. ]}
  972. if "torso" in B:
  973. bones["torso"] = {"rotate": [
  974. _kf(0, 0, curve=None),
  975. _kf(0.15, 8, curve=EASE_IN), # lean forward in squat
  976. _kf(0.35, -5, curve=EASE_OUT), # extend in air
  977. _kf(0.80, 5, curve=EASE_IN), # absorb landing
  978. _kf(D, 0, curve=EASE_OUT),
  979. ]}
  980. if "head" in B:
  981. bones["head"] = {"rotate": [
  982. _kf(0, 0, curve=None),
  983. _kf(0.15, 5), _kf(0.35, -8), _kf(0.80, 3), _kf(D, 0),
  984. ]}
  985. for side in ["left", "right"]:
  986. s = 1 if side == "left" else -1
  987. arm = f"{side}-upper-arm"
  988. if arm in B:
  989. bones[arm] = {"rotate": [
  990. _kf(0, 0, curve=None),
  991. _kf(0.15, s*10), _kf(0.35, s*-50, curve=EASE_OUT),
  992. _kf(0.80, s*8, curve=EASE_IN), _kf(D, 0),
  993. ]}
  994. upper = f"{side}-upper-leg"
  995. lower = f"{side}-lower-leg"
  996. if upper in B:
  997. bones[upper] = {"rotate": [
  998. _kf(0, 0, curve=None),
  999. _kf(0.15, 20), # squat bend
  1000. _kf(0.35, -15), # extend
  1001. _kf(0.55, 10), # tuck in air
  1002. _kf(0.80, 15), # absorb
  1003. _kf(D, 0),
  1004. ]}
  1005. if lower in B:
  1006. bones[lower] = {"rotate": [
  1007. _kf(0, 0, curve=None),
  1008. _kf(0.15, -30), _kf(0.35, 10), _kf(0.55, -15),
  1009. _kf(0.80, -20), _kf(D, 0),
  1010. ]}
  1011. return {"bones": bones} if bones else {}
  1012. def gen_attack(B):
  1013. """Melee attack: wind-up → strike → follow-through. ~0.6s"""
  1014. bones = {}
  1015. D = 0.6
  1016. if "right-upper-arm" in B:
  1017. bones["right-upper-arm"] = {"rotate": [
  1018. _kf(0, 0, curve=None),
  1019. _kf(0.1, 40, curve=EASE_IN), # wind up (pull back)
  1020. _kf(0.25, -80, curve=EASE_FAST), # strike forward
  1021. _kf(0.4, -60, curve=None), # follow through
  1022. _kf(D, 0, curve=EASE_OUT),
  1023. ]}
  1024. if "right-lower-arm" in B:
  1025. bones["right-lower-arm"] = {"rotate": [
  1026. _kf(0, 0, curve=None),
  1027. _kf(0.1, -40, curve=EASE_IN),
  1028. _kf(0.25, 10, curve=EASE_FAST),
  1029. _kf(0.4, -5, curve=None),
  1030. _kf(D, 0, curve=EASE_OUT),
  1031. ]}
  1032. if "torso" in B:
  1033. bones["torso"] = {"rotate": [
  1034. _kf(0, 0, curve=None),
  1035. _kf(0.1, -8, curve=EASE_IN), # lean back
  1036. _kf(0.25, 12, curve=EASE_FAST), # lunge forward
  1037. _kf(0.4, 5, curve=None),
  1038. _kf(D, 0, curve=EASE_OUT),
  1039. ]}
  1040. if "hip" in B:
  1041. bones["hip"] = {"translate": [
  1042. _kf(0, x=0, y=0, curve=None),
  1043. _kf(0.1, x=-5, y=-5, curve=EASE_IN),
  1044. _kf(0.25, x=10, y=2, curve=EASE_FAST),
  1045. _kf(D, x=0, y=0, curve=EASE_OUT),
  1046. ]}
  1047. return {"bones": bones} if bones else {}
  1048. PRESETS = {
  1049. "idle": gen_idle,
  1050. "walk": gen_walk,
  1051. "run": gen_run,
  1052. "wave": gen_wave,
  1053. "jump": gen_jump,
  1054. "attack": gen_attack,
  1055. }
  1056. # ─── Spine JSON Builder ──────────────────────────────────────────────────────
  1057. def build_spine_json(config):
  1058. """Build a complete Spine JSON structure from config."""
  1059. bone_names = {b["name"] for b in config["bones"]}
  1060. skel_meta = config.get("skeleton", {})
  1061. data_hash = hashlib.md5(json.dumps(config, sort_keys=True).encode()).hexdigest()[:20]
  1062. spine = {
  1063. "skeleton": {
  1064. "hash": data_hash,
  1065. "spine": "4.2.0",
  1066. "x": -(skel_meta.get("width", 400) // 2),
  1067. "y": 0,
  1068. "width": skel_meta.get("width", 400),
  1069. "height": skel_meta.get("height", 600),
  1070. "images": "./images/",
  1071. },
  1072. "bones": config["bones"],
  1073. "slots": config.get("slots", []),
  1074. "skins": [{"name": "default", "attachments": {}}],
  1075. "animations": {},
  1076. }
  1077. # Build attachments for default skin
  1078. attachments = config.get("attachments", {})
  1079. for slot in config.get("slots", []):
  1080. att_name = slot.get("attachment", slot["name"])
  1081. if att_name in attachments:
  1082. spine["skins"][0]["attachments"][slot["name"]] = {
  1083. att_name: attachments[att_name]
  1084. }
  1085. # Generate preset animations
  1086. for anim_name in config.get("animations", ["idle"]):
  1087. if anim_name in PRESETS:
  1088. data = PRESETS[anim_name](bone_names)
  1089. if data:
  1090. spine["animations"][anim_name] = data
  1091. else:
  1092. print(f" WARNING: Unknown animation preset '{anim_name}', skipping")
  1093. # Merge custom animations
  1094. for name, data in config.get("custom_animations", {}).items():
  1095. spine["animations"][name] = data
  1096. # Presets and custom animations alike are authored in the shorthand above;
  1097. # the file declares "spine": "4.2.0", so emit what a 4.x runtime expects.
  1098. _to_spine_42(spine["animations"])
  1099. return spine
  1100. def main():
  1101. parser = argparse.ArgumentParser(description="Build Spine JSON skeleton with animations")
  1102. parser.add_argument("--config", required=True, help="Skeleton configuration JSON")
  1103. parser.add_argument("--output", default="skeleton.json", help="Output Spine JSON")
  1104. args = parser.parse_args()
  1105. with open(args.config) as f:
  1106. config = json.load(f)
  1107. print(f"Building: {config.get('skeleton', {}).get('name', 'unnamed')}")
  1108. spine_json = build_spine_json(config)
  1109. with open(args.output, "w") as f:
  1110. json.dump(spine_json, f, indent=2)
  1111. print(f"Saved: {args.output}")
  1112. print(f" Bones: {len(spine_json['bones'])}")
  1113. print(f" Slots: {len(spine_json['slots'])}")
  1114. print(f" Animations: {list(spine_json['animations'].keys())}")
  1115. if __name__ == "__main__":
  1116. main()
  1117. ```
  1118. </details>
  1119. <!-- EMBED:scripts/make_atlas.py -->
  1120. <details>
  1121. <summary>📄 <code>scripts/make_atlas.py</code> (102 lines)</summary>
  1122. ```python
  1123. #!/usr/bin/env python3
  1124. """
  1125. make_atlas.py — Pack individual body part PNGs into a Spine-compatible texture atlas.
  1126. Usage:
  1127. python3 make_atlas.py --parts parts/ --output atlas/ --name skeleton
  1128. Input: Directory of individual .png files (head.png, torso.png, etc.)
  1129. Output: skeleton.png (spritesheet) + skeleton.atlas (Spine atlas metadata)
  1130. """
  1131. import argparse
  1132. import json
  1133. import math
  1134. import os
  1135. import sys
  1136. from pathlib import Path
  1137. try:
  1138. from PIL import Image
  1139. except ImportError:
  1140. print("ERROR: Pillow required. Install: pip install Pillow --break-system-packages")
  1141. sys.exit(1)
  1142. def next_pow2(v):
  1143. v -= 1
  1144. v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16
  1145. return max(v + 1, 1)
  1146. def pack(images, padding=2):
  1147. """Row-based bin packing. Returns (width, height, placements dict)."""
  1148. sorted_imgs = sorted(images.items(), key=lambda x: -x[1].height)
  1149. total_area = sum(img.width * img.height for img in images.values())
  1150. est = int(math.sqrt(total_area) * 1.3)
  1151. atlas_w = next_pow2(est)
  1152. placements = {}
  1153. rx, ry, rh, max_w = padding, padding, 0, 0
  1154. for name, img in sorted_imgs:
  1155. if rx + img.width + padding > atlas_w:
  1156. rx = padding
  1157. ry += rh + padding
  1158. rh = 0
  1159. placements[name] = (rx, ry, img.width, img.height)
  1160. max_w = max(max_w, rx + img.width + padding)
  1161. rh = max(rh, img.height)
  1162. rx += img.width + padding
  1163. return next_pow2(max_w), next_pow2(ry + rh + padding), placements
  1164. def main():
  1165. parser = argparse.ArgumentParser(description="Pack PNGs into a Spine texture atlas")
  1166. parser.add_argument("--parts", required=True, help="Directory with part PNG files")
  1167. parser.add_argument("--output", default=".", help="Output directory")
  1168. parser.add_argument("--name", default="skeleton", help="Base filename for atlas")
  1169. parser.add_argument("--padding", type=int, default=2, help="Pixel padding between regions")
  1170. args = parser.parse_args()
  1171. images = {}
  1172. for f in sorted(os.listdir(args.parts)):
  1173. if f.lower().endswith(".png"):
  1174. name = Path(f).stem
  1175. images[name] = Image.open(os.path.join(args.parts, f)).convert("RGBA")
  1176. print(f" {name}: {images[name].width}x{images[name].height}")
  1177. if not images:
  1178. print("ERROR: No PNGs found in", args.parts)
  1179. sys.exit(1)
  1180. aw, ah, placements = pack(images, args.padding)
  1181. print(f"Atlas: {aw}x{ah} ({len(images)} regions)")
  1182. # Compose atlas image
  1183. atlas = Image.new("RGBA", (aw, ah), (0, 0, 0, 0))
  1184. for name, (x, y, w, h) in placements.items():
  1185. atlas.paste(images[name], (x, y))
  1186. os.makedirs(args.output, exist_ok=True)
  1187. img_path = os.path.join(args.output, f"{args.name}.png")
  1188. atlas.save(img_path)
  1189. # Write .atlas file
  1190. lines = [f"{args.name}.png", f"size: {aw},{ah}",
  1191. "format: RGBA8888", "filter: Linear,Linear", "repeat: none"]
  1192. for name, (x, y, w, h) in placements.items():
  1193. lines += [name, " rotate: false", f" xy: {x}, {y}",
  1194. f" size: {w}, {h}", f" orig: {w}, {h}",
  1195. " offset: 0, 0", " index: -1"]
  1196. atlas_path = os.path.join(args.output, f"{args.name}.atlas")
  1197. with open(atlas_path, "w") as f:
  1198. f.write("\n".join(lines) + "\n")
  1199. print(f"Saved: {img_path}, {atlas_path}")
  1200. if __name__ == "__main__":
  1201. main()
  1202. ```
  1203. </details>
  1204. <!-- EMBED:scripts/generate_spine_player.py -->
  1205. <details>
  1206. <summary>📄 <code>scripts/generate_spine_player.py</code> (292 lines)</summary>
  1207. ```python
  1208. #!/usr/bin/env python3
  1209. """
  1210. generate_spine_player.py — Generate a self-contained HTML preview using the official Spine Web Player.
  1211. Embeds the skeleton JSON, atlas text, and atlas PNG as base64 data URIs via the
  1212. rawDataURIs configuration, so the resulting HTML file works standalone — no server needed.
  1213. Uses the official @esotericsoftware/spine-player from UNPKG CDN.
  1214. Usage:
  1215. python3 generate_spine_player.py \
  1216. --skeleton skeleton.json \
  1217. --atlas skeleton.atlas \
  1218. --atlas-image skeleton.png \
  1219. --output preview.html \
  1220. [--animation idle] \
  1221. [--background "#1a1a2eff"] \
  1222. [--skin default]
  1223. If no --atlas and --atlas-image are given but a --parts directory is provided,
  1224. the script will pack the parts into an atlas automatically.
  1225. """
  1226. import argparse
  1227. import base64
  1228. import json
  1229. import os
  1230. import sys
  1231. from pathlib import Path
  1232. def file_to_base64(path):
  1233. """Read a file and return its base64-encoded contents."""
  1234. with open(path, "rb") as f:
  1235. return base64.b64encode(f.read()).decode("ascii")
  1236. def json_to_base64(path):
  1237. """Read a JSON file and return it as base64."""
  1238. with open(path, "r") as f:
  1239. content = f.read()
  1240. return base64.b64encode(content.encode("utf-8")).decode("ascii")
  1241. def text_to_base64(path):
  1242. """Read a text file and return it as base64."""
  1243. with open(path, "r") as f:
  1244. content = f.read()
  1245. return base64.b64encode(content.encode("utf-8")).decode("ascii")
  1246. def find_atlas_images(atlas_path):
  1247. """Parse an atlas file to find all referenced PNG filenames."""
  1248. atlas_dir = os.path.dirname(os.path.abspath(atlas_path))
  1249. images = []
  1250. with open(atlas_path, "r") as f:
  1251. lines = f.readlines()
  1252. # The first line (or lines before the first region entry) contain page image filenames
  1253. # Atlas format: image filename is a line that ends with .png (or other image ext)
  1254. # followed by size:, format:, filter:, repeat: lines
  1255. i = 0
  1256. while i < len(lines):
  1257. line = lines[i].strip()
  1258. # A page image is the first non-empty line, or any line ending with an image extension
  1259. # that is followed by "size:" on the next line
  1260. if line and not line.startswith(" ") and not ":" in line:
  1261. # Check if next line starts with "size:" indicating this is a page name
  1262. if i + 1 < len(lines) and lines[i + 1].strip().startswith("size:"):
  1263. img_path = os.path.join(atlas_dir, line)
  1264. if os.path.exists(img_path):
  1265. images.append((line, img_path))
  1266. else:
  1267. print(f" WARNING: Atlas references '{line}' but file not found at {img_path}")
  1268. i += 1
  1269. return images
  1270. def generate_html(skeleton_path, atlas_path, atlas_images,
  1271. animation=None, skin=None, bg_color="#1a1a2eff",
  1272. show_controls=True, title="Spine Animation Preview"):
  1273. """Generate the complete HTML file with embedded Spine Web Player."""
  1274. # Get filenames for rawDataURIs keys
  1275. skel_filename = os.path.basename(skeleton_path)
  1276. atlas_filename = os.path.basename(atlas_path)
  1277. # Determine if JSON or binary
  1278. is_json = skel_filename.lower().endswith(".json")
  1279. skel_mime = "application/json" if is_json else "application/octet-stream"
  1280. # Encode all assets
  1281. skel_b64 = file_to_base64(skeleton_path)
  1282. atlas_b64 = file_to_base64(atlas_path)
  1283. # Build rawDataURIs object
  1284. raw_data_entries = []
  1285. raw_data_entries.append(
  1286. f' "{skel_filename}": "data:{skel_mime};base64,{skel_b64}"'
  1287. )
  1288. raw_data_entries.append(
  1289. f' "{atlas_filename}": "data:application/octet-stream;base64,{atlas_b64}"'
  1290. )
  1291. for img_name, img_path in atlas_images:
  1292. img_ext = Path(img_path).suffix.lower()
  1293. img_mime = "image/png" if img_ext == ".png" else "image/jpeg"
  1294. img_b64 = file_to_base64(img_path)
  1295. raw_data_entries.append(
  1296. f' "{img_name}": "data:{img_mime};base64,{img_b64}"'
  1297. )
  1298. raw_data_uris_js = ",\n".join(raw_data_entries)
  1299. # Build config options
  1300. config_lines = []
  1301. config_lines.append(f' skeleton: "{skel_filename}"')
  1302. config_lines.append(f' atlas: "{atlas_filename}"')
  1303. if animation:
  1304. config_lines.append(f' animation: "{animation}"')
  1305. if skin and skin != "default":
  1306. config_lines.append(f' skin: "{skin}"')
  1307. config_lines.append(f' backgroundColor: "{bg_color}"')
  1308. config_lines.append(f' showControls: {"true" if show_controls else "false"}')
  1309. config_lines.append(f' premultipliedAlpha: false')
  1310. config_lines.append(f' rawDataURIs: {{\n{raw_data_uris_js}\n }}')
  1311. # Error/success callbacks
  1312. config_lines.append(""" success: function(player) {
  1313. document.getElementById('status').textContent = 'Loaded successfully';
  1314. document.getElementById('status').style.color = '#4ade80';
  1315. // Log available animations
  1316. var anims = player.skeleton.data.animations.map(function(a) { return a.name; });
  1317. console.log('Available animations:', anims);
  1318. var skins = player.skeleton.data.skins.map(function(s) { return s.name; });
  1319. console.log('Available skins:', skins);
  1320. }""")
  1321. config_lines.append(""" error: function(player, reason) {
  1322. document.getElementById('status').textContent = 'Error: ' + reason;
  1323. document.getElementById('status').style.color = '#ef4444';
  1324. console.error('Spine Player error:', reason);
  1325. }""")
  1326. config_js = ",\n".join(config_lines)
  1327. html = f"""<!DOCTYPE html>
  1328. <html lang="en">
  1329. <head>
  1330. <meta charset="UTF-8">
  1331. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  1332. <title>{title}</title>
  1333. <!-- Official Spine Web Player -->
  1334. <script src="https://unpkg.com/@esotericsoftware/spine-player@4.2.*/dist/iife/spine-player.js"></script>
  1335. <link rel="stylesheet" href="https://unpkg.com/@esotericsoftware/spine-player@4.2.*/dist/spine-player.css">
  1336. <style>
  1337. * {{ margin: 0; padding: 0; box-sizing: border-box; }}
  1338. body {{
  1339. background: #0f0f1a;
  1340. color: #e0e0e0;
  1341. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  1342. display: flex;
  1343. flex-direction: column;
  1344. align-items: center;
  1345. min-height: 100vh;
  1346. padding: 20px;
  1347. }}
  1348. h1 {{
  1349. font-size: 1.5em;
  1350. margin-bottom: 10px;
  1351. color: #a8b2d1;
  1352. letter-spacing: 0.04em;
  1353. }}
  1354. #status {{
  1355. font-size: 0.85em;
  1356. margin-bottom: 15px;
  1357. color: #6b7da0;
  1358. transition: color 0.3s;
  1359. }}
  1360. #player-container {{
  1361. width: 700px;
  1362. height: 600px;
  1363. max-width: 95vw;
  1364. border-radius: 12px;
  1365. overflow: hidden;
  1366. box-shadow: 0 8px 32px rgba(0,0,0,0.5);
  1367. }}
  1368. .info {{
  1369. margin-top: 15px;
  1370. font-size: 0.8em;
  1371. color: #4a5568;
  1372. text-align: center;
  1373. max-width: 600px;
  1374. line-height: 1.5;
  1375. }}
  1376. .info a {{ color: #6b8aad; text-decoration: none; }}
  1377. .info a:hover {{ text-decoration: underline; }}
  1378. </style>
  1379. </head>
  1380. <body>
  1381. <h1>{title}</h1>
  1382. <div id="status">Loading Spine Player...</div>
  1383. <div id="player-container"></div>
  1384. <div class="info">
  1385. Rendered with the official
  1386. <a href="https://en.esotericsoftware.com/spine-player" target="_blank">Spine Web Player</a>.
  1387. Use the controls to switch animations, adjust speed, and toggle debug views.
  1388. </div>
  1389. <script>
  1390. new spine.SpinePlayer("player-container", {{
  1391. {config_js}
  1392. }});
  1393. </script>
  1394. </body>
  1395. </html>"""
  1396. return html
  1397. def main():
  1398. parser = argparse.ArgumentParser(
  1399. description="Generate a self-contained HTML preview using the official Spine Web Player"
  1400. )
  1401. parser.add_argument("--skeleton", required=True, help="Spine JSON or binary (.skel) file")
  1402. parser.add_argument("--atlas", required=True, help="Spine .atlas file")
  1403. parser.add_argument("--atlas-image", default=None,
  1404. help="Atlas PNG image (auto-detected from atlas if omitted)")
  1405. parser.add_argument("--output", default="preview.html", help="Output HTML file")
  1406. parser.add_argument("--animation", default=None, help="Default animation to play")
  1407. parser.add_argument("--skin", default=None, help="Default skin")
  1408. parser.add_argument("--background", default="#1a1a2eff", help="Background color (hex RGBA)")
  1409. parser.add_argument("--title", default="Spine Animation Preview", help="Page title")
  1410. parser.add_argument("--no-controls", action="store_true", help="Hide player controls")
  1411. args = parser.parse_args()
  1412. # Verify files exist
  1413. for path, name in [(args.skeleton, "Skeleton"), (args.atlas, "Atlas")]:
  1414. if not os.path.exists(path):
  1415. print(f"ERROR: {name} file not found: {path}")
  1416. sys.exit(1)
  1417. # Find atlas images
  1418. atlas_images = []
  1419. if args.atlas_image:
  1420. img_name = os.path.basename(args.atlas_image)
  1421. atlas_images.append((img_name, args.atlas_image))
  1422. else:
  1423. atlas_images = find_atlas_images(args.atlas)
  1424. if not atlas_images:
  1425. print("ERROR: No atlas images found. Specify --atlas-image or ensure atlas references valid PNGs.")
  1426. sys.exit(1)
  1427. print(f"Skeleton: {args.skeleton}")
  1428. print(f"Atlas: {args.atlas}")
  1429. for img_name, img_path in atlas_images:
  1430. print(f"Atlas image: {img_name} ({os.path.getsize(img_path) / 1024:.1f} KB)")
  1431. # Generate HTML
  1432. print("Generating HTML with embedded Spine Web Player...")
  1433. html = generate_html(
  1434. skeleton_path=args.skeleton,
  1435. atlas_path=args.atlas,
  1436. atlas_images=atlas_images,
  1437. animation=args.animation,
  1438. skin=args.skin,
  1439. bg_color=args.background,
  1440. show_controls=not args.no_controls,
  1441. title=args.title,
  1442. )
  1443. with open(args.output, "w") as f:
  1444. f.write(html)
  1445. size_kb = os.path.getsize(args.output) / 1024
  1446. print(f"\nPreview saved: {args.output} ({size_kb:.1f} KB)")
  1447. print("Open in a browser to see your animation (requires internet for the Spine Player CDN).")
  1448. if __name__ == "__main__":
  1449. main()
  1450. ```
  1451. </details>
  1452. After writing the scripts, verify:
  1453. ```bash
  1454. ls /home/claude/spine-scripts/
  1455. # Should show: split_character.py position_parts.py build_spine_json.py make_atlas.py generate_spine_player.py
  1456. ```
  1457. ---
  1458. ## What You Need From the User
  1459. At minimum, one of these asset sets:
  1460. | Asset Set | What to Expect |
  1461. |-----------|---------------|
  1462. | **Separated body part PNGs** | Individual transparent PNGs for head, torso, arms, legs, etc. |
  1463. | **Separated PNGs + reference image** | Parts + an assembled character image → enables auto-positioning |
  1464. | **Texture atlas + atlas PNG** | A `.atlas` file + spritesheet `.png` (standard Spine export) |
  1465. | **Full character image** | A single image — Claude will help define part regions |
  1466. | **Existing Spine JSON** | An existing `.json` to add/modify animations |
  1467. The user should also say what animations they want (idle, walk, run, attack, wave, jump, etc.)
  1468. ## Full Pipeline
  1469. ```
  1470. User Assets → Analyze Parts → [Auto-Position if reference] → Build Skeleton → Animate → Preview
  1471. ```
  1472. ### Step 0.5: Generate Parts From a Full Character Image (Optional)
  1473. If the user only has a **single full character image** (not separated body parts), use
  1474. `split_character.py` to generate a deconstructed sprite atlas via Google Gemini and then
  1475. automatically segment it into individual part PNGs.
  1476. **Requires:** `GEMINI_API_KEY` environment variable (free key at https://aistudio.google.com/app/apikey).
  1477. ```bash
  1478. GEMINI_API_KEY=your_key python /home/claude/spine-scripts/split_character.py character.png \
  1479. --output-dir parts/
  1480. ```
  1481. This sends the character image to Gemini, which generates a flat sprite-sheet atlas with
  1482. all body parts separated. OpenCV connected-components analysis then crops each part into
  1483. its own transparent PNG. The resulting `parts/` directory can be fed directly into
  1484. **Step 1** (`position_parts.py`).
  1485. ### Step 1: Analyze the Assets
  1486. Look at the uploaded files:
  1487. 1. **If separated PNGs**: Use Claude's vision to identify each part (head, torso, left-arm, etc.)
  1488. and note their dimensions. Determine the bone hierarchy from the part names and visual layout.
  1489. 2. **If atlas + spritesheet**: Parse the `.atlas` file to extract region names, positions, and sizes.
  1490. 3. **If full image only**: Use Claude's vision to identify body parts, then crop into separate PNGs.
  1491. 4. **If existing Spine JSON**: Parse it, understand the skeleton, and add new animations.
  1492. 5. **If separated PNGs + assembled reference image**: Run `position_parts.py` for auto-layout.
  1493. ### Step 1.5: Auto-Position Parts (when reference image is available)
  1494. If the user provides both separated body-part PNGs **and** an assembled reference image:
  1495. ```bash
  1496. python3 /home/claude/spine-scripts/position_parts.py \
  1497. --reference assembled_character.png \
  1498. --parts parts_folder/ \
  1499. --output layout.json \
  1500. --debug debug/ \
  1501. --min-matches 4 \
  1502. --ratio 0.80
  1503. ```
  1504. **Algorithm — SIFT + RANSAC similarity transform:**
  1505. 1. Extracts SIFT keypoints from each part (alpha-masked) and the reference image
  1506. 2. Matches via FLANN with Lowe's ratio test (default 0.80)
  1507. 3. Estimates similarity transform (4 DOF: translate + scale + rotation) via
  1508. `cv2.estimateAffinePartial2D` — more robust than full homography for game art
  1509. 4. SIFT tuning for stylized art: `contrastThreshold=0.02, edgeThreshold=20`
  1510. 5. Template matching fallback for tiny/featureless parts, using SIFT-derived median scale
  1511. 6. Z-order via pairwise occlusion voting
  1512. After running, **check `debug/comparison.png`** to verify positioning accuracy.
  1513. Per-part SIFT match visualizations: `debug/sift_<partname>.jpg`.
  1514. **Limitations:** Heavily occluded parts (e.g., thighs behind a belt) may need manual correction.
  1515. Compare composite vs reference with Claude's vision and adjust layout JSON offsets.
  1516. ### Step 2: Build Bone Hierarchy
  1517. Standard humanoid skeleton:
  1518. ```
  1519. root
  1520. └── hip
  1521. ├── torso
  1522. │ ├── neck → head → hat/hair
  1523. │ ├── left-shoulder → left-upper-arm → left-lower-arm → left-hand
  1524. │ └── right-shoulder → right-upper-arm → right-lower-arm → right-hand
  1525. ├── left-upper-leg → left-lower-leg → left-foot
  1526. └── right-upper-leg → right-lower-leg → right-foot
  1527. ```
  1528. **Coordinate system:** Spine uses Y-up, origin at character's feet center.
  1529. - `spine_x = pixel_x - center_x`
  1530. - `spine_y = bottom_y - pixel_y`
  1531. **Bone positions** are RELATIVE to parent:
  1532. - `relative_pos = child_world_pos - parent_world_pos`
  1533. **Attachment offsets** are relative to their bone:
  1534. - `att_offset = image_center_world_pos - bone_world_pos`
  1535. ### Step 3: Build Spine JSON
  1536. Spine JSON v4.2 structure:
  1537. ```json
  1538. {
  1539. "skeleton": { "hash": "...", "spine": "4.2", "width": 500, "height": 950 },
  1540. "bones": [
  1541. { "name": "root", "x": 0, "y": 0, "length": 0 },
  1542. { "name": "hip", "parent": "root", "x": 0, "y": 410, "length": 30 }
  1543. ],
  1544. "slots": [
  1545. { "name": "back-arm", "bone": "left-arm-bone", "attachment": "back-arm" }
  1546. ],
  1547. "skins": [{
  1548. "name": "default",
  1549. "attachments": {
  1550. "slot-name": {
  1551. "attachment-name": { "x": 5, "y": -10, "width": 100, "height": 200 }
  1552. }
  1553. }
  1554. }],
  1555. "animations": {
  1556. "idle": {
  1557. "bones": {
  1558. "hip": {
  1559. "translate": [
  1560. { "time": 0, "x": 0, "y": 0, "curve": [0.25, 0, 0.75, 1] },
  1561. { "time": 1.0, "x": 0, "y": 3 },
  1562. { "time": 2.0, "x": 0, "y": 0 }
  1563. ]
  1564. }
  1565. }
  1566. }
  1567. }
  1568. }
  1569. ```
  1570. **Slots** define draw order — first slot is drawn first (back), last is front.
  1571. ### Step 4: Create Animations
  1572. **Keyframe format:**
  1573. ```json
  1574. { "time": 0.0, "value": 0, "curve": [0.25, 0, 0.75, 1] }
  1575. ```
  1576. The `curve` is a cubic bezier `[cx1, cy1, cx2, cy2]`. Use `[0.25, 0, 0.75, 1]` for ease-in-out.
  1577. **Animation presets:**
  1578. | Preset | Duration | Key Technique |
  1579. |--------|----------|---------------|
  1580. | idle | 2.0s loop | Hip ±3px translate, torso ±1° rotate, head ±1.5° counter-sway |
  1581. | walk | 0.8s loop | Opposing arm-leg swing, hip ±5px bob, torso ±3° lean |
  1582. | run | 0.5s loop | Exaggerated walk + 5° forward lean + ±8px bounce |
  1583. | wave | 1.2s | Shoulder -45°, forearm oscillate ±15° |
  1584. | jump | 1.0s | Squat → launch → air → land (4 phases) |
  1585. | attack | 0.6s | Windup → strike → follow-through (3 phases) |
  1586. **Key principles:**
  1587. - Offset timing between related bones (head peaks 0.1s after torso = follow-through)
  1588. - Larger movements on larger bones (hip > torso > head)
  1589. - All loops must return to starting values
  1590. ### Step 5: Build Atlas
  1591. ```bash
  1592. python3 /home/claude/spine-scripts/make_atlas.py \
  1593. --parts parts_folder/ \
  1594. --output . \
  1595. --name character_name
  1596. ```
  1597. Outputs: `character_name.png` (spritesheet) + `character_name.atlas` (metadata).
  1598. ### Step 6: Generate Preview
  1599. For a **self-contained HTML Canvas preview** (recommended):
  1600. Build the HTML directly in Python with base64-embedded images, bone system, bezier interpolation,
  1601. and animation loop. No external dependencies needed.
  1602. For an **official Spine Web Player preview**:
  1603. ```bash
  1604. python3 /home/claude/spine-scripts/generate_spine_player.py \
  1605. --skeleton character.json \
  1606. --atlas character.atlas \
  1607. --atlas-image character.png \
  1608. --output preview.html
  1609. ```
  1610. ### Step 7: Interactive Editor (Optional)
  1611. Build an HTML editor that allows the user to fine-tune part positions:
  1612. - Click to select parts (purple dashed border + glow)
  1613. - Drag to reposition in real-time
  1614. - Arrow keys for 1px nudge (Shift for 10px)
  1615. - Side panel with numeric X/Y/rotation inputs
  1616. - Draggable z-order list
  1617. - Export button producing layout corrections JSON:
  1618. ```json
  1619. {
  1620. "adjustments": {
  1621. "part-name": {
  1622. "original_offset": { "x": 0, "y": 0 },
  1623. "user_offset": { "dx": 5.2, "dy": -3.1, "drot": 0 },
  1624. "final_offset": { "x": 5.2, "y": -3.1 }
  1625. }
  1626. },
  1627. "draw_order": ["back-part", "...", "front-part"]
  1628. }
  1629. ```
  1630. This JSON can be fed back to Claude to apply corrections to the skeleton.
README.md · README · 394 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # 🎭 Spine Animation AI
  2. > An AI-powered Claude skill for creating, rigging, and refining Spine 2D skeletal animations — from raw assets to interactive previews.
  3. [![License: PolyForm NC](https://img.shields.io/badge/License-PolyForm%20NC%201.0-blue.svg)](LICENSE)
  4. [![Spine Version](https://img.shields.io/badge/Spine-4.2-blue.svg)](http://esotericsoftware.com)
  5. [![Claude Skill](https://img.shields.io/badge/Claude-Skill-orange.svg)](SKILL.md)
  6. [![OpenClaw](https://img.shields.io/badge/OpenClaw-Compatible-green.svg)](https://openclaw.ai)
  7. ---
  8. <p align="center">
  9. <img src="demo/flow.gif" alt="Spine Animation AI demo" width="50%"/>
  10. </p>
  11. <p align="center">
  12. <a href="https://GenielabsOpenSource.github.io/spine-animation-ai/demo/sombrero_idle.html"><strong>▶ Live Animation Preview</strong></a>
  13. &nbsp;·&nbsp;
  14. <a href="https://GenielabsOpenSource.github.io/spine-animation-ai/demo/sombrero_editor.html"><strong>🎛 Interactive Part Editor</strong></a>
  15. </p>
  16. ---
  17. ## ✨ New: Reskin Studio
  18. **Restyle any rigged Spine character with a single sentence.** Open a Spine project, describe the look you want — *"emerald and silver royal robes"* — and Reskin Studio repaints the whole character with Gemini, slices the result back into clean per-slot textures, and drops the new skin straight onto the live rig. Retouch any part, refine masks, then export back to Spine. No redraw, no re-rig.
  19. <!-- TODO: drop the reskin demo gif at demo/reskin.gif -->
  20. <p align="center">
  21. <img src="demo/reskin.gif" alt="Reskin Studio demo" width="50%"/>
  22. </p>
  23. <p align="center">
  24. <a href="reskin-app/"><strong>→ Explore Reskin Studio</strong></a>
  25. </p>
  26. ---
  27. <div align="center">
  28. # 🔬 Genielabs — Pioneering AI Animation Research
  29. ## We are actively researching AI-driven animation pipelines.
  30. **[Genielabs](https://genielabs.tech)** is at the forefront of AI-powered 2D animation — using machine learning to automate character rigging, motion generation, and asset positioning for game production.
  31. This repository is a direct product of that research: an open-source skill that brings industrial-grade animation automation into Claude.
  32. ### 📬 Want to collaborate, license, or learn more?
  33. ## 👉 [**genielabs.tech**](https://genielabs.tech) 👈
  34. *Reach out — we'd love to hear from you.*
  35. </div>
  36. ---
  37. ## What Is This?
  38. **Spine Animation AI** is a [Claude agent skill](SKILL.md) that lets AI handle the tedious parts of Spine 2D animation production:
  39. - **Auto-position** body parts from reference images using SIFT + RANSAC
  40. - **Build skeleton JSON** with proper bone hierarchy and draw order
  41. - **Generate animations** (idle, walk, run, attack, wave, jump) using the 12 principles of animation
  42. - **Produce interactive HTML5 previews** using the official Spine Web Player
  43. - **Correct and refine** existing skeletons with AI-assisted offset adjustments
  44. Think of it as a Spine rigging co-pilot. You provide the art assets; Claude does the math.
  45. ---
  46. ## Quick Start
  47. ### Option A: Claude Projects (Recommended)
  48. The easiest way — works with any Claude account, no extra software needed.
  49. 1. Go to [claude.ai](https://claude.ai) → create a new **Project**
  50. 2. Open **Project Knowledge** → **Add content**
  51. 3. Copy the full contents of [`SKILL.md`](SKILL.md) and paste it in
  52. 4. Save — Claude now has the full skill baked in, **including all scripts embedded inline**
  53. 5. Upload your character assets and describe what you want:
  54. ```
  55. "I have separated body part PNGs for my character.
  56. Create idle and walk animations."
  57. ```
  58. Claude will write the scripts to disk, run the pipeline, and deliver `skeleton.json` + `preview.html`.
  59. > **Why it works:** `SKILL.md` is auto-generated with all 4 Python scripts embedded inside it — Claude extracts and runs them without needing to clone the repo.
  60. ---
  61. ### Option B: Claude Custom Skill (`/mnt/skills/` environments)
  62. For Claude environments that support mounted skill directories:
  63. ```bash
  64. git clone https://github.com/GenielabsOpenSource/spine-animation-ai.git /mnt/skills/user/spine-animation
  65. ```
  66. Claude will automatically discover and load the skill on next session start.
  67. ---
  68. ### Option C: Manual Pipeline (no Claude needed)
  69. **Step 0: Split a Full Character Into Parts (New!)**
  70. If you only have a single character image (not separated body parts), `split_character.py`
  71. uses Google Gemini to generate a deconstructed sprite atlas and then segments it into
  72. individual transparent PNGs via OpenCV connected-components analysis.
  73. Prerequisites:
  74. - `GEMINI_API_KEY` environment variable — get a free key at https://aistudio.google.com/app/apikey
  75. - `pip install google-generativeai`
  76. ```bash
  77. GEMINI_API_KEY=your_key python3 scripts/split_character.py character.png \
  78. --output-dir parts/
  79. ```
  80. Skip this step if you already have separated body-part PNGs.
  81. **1. Auto-position parts from a reference image**
  82. ```bash
  83. python3 scripts/position_parts.py \
  84. --reference assembled_character.png \
  85. --parts parts/ \
  86. --output layout.json \
  87. --debug debug/
  88. ```
  89. **2. Build the Spine JSON**
  90. ```bash
  91. python3 scripts/build_spine_json.py \
  92. --config layout.json \
  93. --output skeleton.json
  94. ```
  95. **3. Pack a texture atlas**
  96. ```bash
  97. python3 scripts/make_atlas.py \
  98. --parts parts/ \
  99. --output atlas/ \
  100. --name skeleton
  101. ```
  102. **4. Generate a self-contained HTML preview**
  103. ```bash
  104. python3 scripts/generate_spine_player.py \
  105. --skeleton skeleton.json \
  106. --atlas skeleton.atlas \
  107. --atlas-image skeleton.png \
  108. --output preview.html
  109. ```
  110. Open `preview.html` in any browser — no server needed.
  111. ---
  112. ## AI Adjustment Format
  113. When Claude analyzes a skeleton and recommends corrections, it outputs adjustments in this format:
  114. ```json
  115. {
  116. "adjustments": {
  117. "right-arm": {
  118. "original_offset": { "x": -1.5, "y": 0 },
  119. "user_offset": { "dx": -29.4, "dy": -84.1, "drot": 0 },
  120. "final_offset": { "x": -30.9, "y": -84.1 }
  121. },
  122. "head": {
  123. "original_offset": { "x": 3, "y": 20.5 },
  124. "user_offset": { "dx": -18.3, "dy": -2, "drot": 0 },
  125. "final_offset": { "x": -15.3, "y": 18.5 }
  126. }
  127. },
  128. "draw_order": [
  129. "right-arm", "left-leg", "right-thigh", "right-leg",
  130. "left-thigh", "waist", "left-hand", "torso", "hat", "head"
  131. ]
  132. }
  133. ```
  134. Each entry tracks the original offset, the AI-suggested correction delta, and the applied final value.
  135. This makes adjustments **reviewable, revertible, and composable**.
  136. See [docs/adjustment-format.md](docs/adjustment-format.md) for full specification.
  137. ---
  138. ## Included Example: Sombrero Character
  139. The `examples/sombrero/` directory contains a complete, working example:
  140. | File | Description |
  141. |------|-------------|
  142. | `sombrero.json` | Full Spine skeleton with idle animation |
  143. | `sombrero.atlas` | Texture atlas metadata |
  144. | `sombrero.png` | Packed atlas spritesheet (10 parts) |
  145. | `skeleton.json` | Skeleton-only version (no animation) |
  146. The sombrero character has **10 body parts**, **16 bones**, and a 2-second idle loop with:
  147. - Hip breathing bob
  148. - Torso sway
  149. - Head gentle rotation
  150. - Hat follow-through
  151. - Arm natural drift
  152. Open [`demo/sombrero_idle.html`](demo/sombrero_idle.html) to see it in action.
  153. Open [`demo/sombrero_editor.html`](demo/sombrero_editor.html) to interactively adjust part positions and export layout JSON.
  154. ---
  155. ## Project Structure
  156. ```
  157. spine-animation-ai/
  158. ├── SKILL.md ← Auto-generated (don't edit directly)
  159. ├── SKILL.template.md ← Human-editable source (edit this)
  160. ├── build_skill.py ← Builds SKILL.md from template + scripts
  161. ├── scripts/
  162. │ ├── position_parts.py ← SIFT+RANSAC auto-positioning
  163. │ ├── build_spine_json.py ← Spine JSON builder
  164. │ ├── make_atlas.py ← Texture atlas packer
  165. │ └── generate_spine_player.py ← HTML preview generator
  166. ├── .github/workflows/
  167. │ └── build-skill.yml ← Auto-rebuilds SKILL.md on push
  168. ├── references/
  169. │ └── spine-json-spec.md ← Spine format reference
  170. ├── examples/
  171. │ └── sombrero/ ← Full working example
  172. │ ├── sombrero.json
  173. │ ├── sombrero.atlas
  174. │ └── sombrero.png
  175. ├── demo/
  176. │ ├── sombrero_idle.html ← Idle animation preview
  177. │ ├── sombrero_editor.html ← Interactive part editor
  178. │ └── spine_animation_preview.html
  179. └── docs/
  180. ├── getting-started.md
  181. ├── adjustment-format.md
  182. └── claude-prompting-guide.md
  183. ```
  184. ---
  185. ## How the Auto-Positioning Works
  186. The `position_parts.py` script uses a two-phase algorithm:
  187. ### Phase 1: SIFT + RANSAC (primary)
  188. 1. Extract **SIFT keypoints** from each body part (alpha-masked to visible pixels)
  189. 2. Extract keypoints from the **assembled reference image**
  190. 3. Match with **FLANN** matcher + Lowe's ratio test
  191. 4. Estimate a **similarity transform** (translate + scale + rotate) via RANSAC
  192. 5. Accept if 4+ inlier matches are found; fall back otherwise
  193. This is more robust than full homography for stylized game art with sparse features.
  194. ### Phase 2: Z-Order via Occlusion Analysis
  195. For every overlapping pair of positioned parts:
  196. 1. Sample pixels in the overlap region
  197. 2. Compare each pixel to the reference image
  198. 3. The part whose color is closer to the reference is "on top"
  199. 4. Build a directed occlusion graph → topological sort → draw order
  200. ### Fallback: Template Matching
  201. Parts too small for SIFT (accessories, tiny objects) fall back to
  202. alpha-masked `TM_CCORR_NORMED` at multiple scales with background penalty scoring.
  203. ---
  204. ## Requirements
  205. ```
  206. Python 3.9+
  207. opencv-python >= 4.8
  208. Pillow >= 10.0
  209. numpy >= 1.24
  210. ```
  211. Install dependencies:
  212. ```bash
  213. pip install opencv-python Pillow numpy
  214. ```
  215. ---
  216. ## Claude Prompting Tips
  217. The best prompts for this skill are specific about assets and intent:
  218. ✅ **Good:**
  219. ```
  220. "I have separated body part PNGs for a robot character (head.png, torso.png,
  221. left-arm.png, right-arm.png, left-leg.png, right-leg.png) and a reference
  222. image showing the assembled character. Create idle and walk animations."
  223. ```
  224. ✅ **Also good:**
  225. ```
  226. "Here's my Spine JSON. The right arm is positioned wrong — it should be
  227. lower and more to the left. Also add a wave animation."
  228. ```
  229. ❌ **Too vague:**
  230. ```
  231. "Animate this character"
  232. ```
  233. See [docs/claude-prompting-guide.md](docs/claude-prompting-guide.md) for more examples.
  234. ---
  235. ## Animation Presets
  236. | Preset | Duration | Technique |
  237. |--------|----------|-----------|
  238. | `idle` | 2.0s loop | Overlapping sine waves on hip/torso/head |
  239. | `walk` | 0.8s loop | Opposing arm-leg swing with hip bob |
  240. | `run` | 0.5s loop | Exaggerated walk + forward lean + bounce |
  241. | `wave` | 1.2s | Raise arm, oscillate forearm |
  242. | `jump` | 1.0s | Anticipation squat → launch → land |
  243. | `attack` | 0.6s | Windup → strike → follow-through |
  244. All presets use **bezier easing** (`[0.25, 0, 0.75, 1]`) following the
  245. [12 principles of animation](https://en.wikipedia.org/wiki/Twelve_basic_principles_of_animation).
  246. ---
  247. ## How SKILL.md Stays in Sync
  248. `SKILL.md` is **auto-generated** — don't edit it directly. Instead:
  249. 1. Edit `SKILL.template.md` (the prose and instructions)
  250. 2. Edit scripts in `scripts/` (the actual code)
  251. 3. Push to `main` — GitHub Actions runs `build_skill.py` which:
  252. - Reads `SKILL.template.md`
  253. - Finds all `<!-- EMBED:scripts/filename.py -->` markers
  254. - Injects the actual script contents into collapsible `<details>` blocks
  255. - Commits the updated `SKILL.md` automatically
  256. This means `SKILL.md` is always a **self-contained document** — when someone pastes it into Claude Projects, Claude has the actual script code right there, no cloning needed.
  257. To build locally:
  258. ```bash
  259. python build_skill.py
  260. ```
  261. ---
  262. ## Contributing
  263. PRs welcome! See [CONTRIBUTING.md](CONTRIBUTING.md).
  264. Ideas for contributions:
  265. - New animation presets (dance, swim, fly, cast spell...)
  266. - Support for non-humanoid rigs (animals, vehicles, abstract)
  267. - Better occlusion detection for heavily layered characters
  268. - Blender / Aseprite asset pipeline integration
  269. - Spine Runtimes integration examples (Unity, Godot, Phaser)
  270. ---
  271. ## License
  272. [PolyForm Noncommercial 1.0.0](LICENSE) — free for all non-commercial use. Commercial use requires a separate license — contact us at [genielabs.tech](https://genielabs.tech).
  273. ---
  274. ## Credits
  275. Built with:
  276. - [Spine by Esoteric Software](http://esotericsoftware.com) — the industry-standard 2D animation tool
  277. - [OpenCV](https://opencv.org) — SIFT feature detection and RANSAC
  278. - [Claude AI](https://anthropic.com/claude) — the brain
  279. - [OpenClaw](https://openclaw.ai) — the agent runtime
  280. ---
  281. <p align="center">Made with ✨ by the community · Star if useful!</p>

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.