@wildshard/sdk 0.0.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (687) hide show
  1. package/GUIDE.md +790 -0
  2. package/README.md +13 -5
  3. package/bin/wildshard.mjs +38 -0
  4. package/lint/declaration-config.d.mts +2 -0
  5. package/lint/declaration-config.mjs +19 -0
  6. package/lint/engine-plugin.d.mts +2 -0
  7. package/lint/engine-plugin.mjs +40 -0
  8. package/lint/host-callbacks.d.mts +6 -0
  9. package/lint/host-callbacks.mjs +123 -0
  10. package/lint/host-files.d.mts +1 -0
  11. package/lint/host-files.mjs +7 -0
  12. package/lint/layer-exports.d.mts +2 -0
  13. package/lint/layer-exports.mjs +21 -0
  14. package/lint/legacy-line-basis.json +995 -0
  15. package/lint/nine-tiling-baseline.json +35 -0
  16. package/lint/ratchet.json +11 -0
  17. package/lint/runtime-files.d.mts +12 -0
  18. package/lint/runtime-files.json +16 -0
  19. package/lint/runtime-files.mjs +69 -0
  20. package/lint/runtime-performance.d.mts +6 -0
  21. package/lint/runtime-performance.mjs +184 -0
  22. package/lint/sdk-plugin.d.mts +4 -0
  23. package/lint/sdk-plugin.mjs +134 -0
  24. package/lint/shardfile-boundaries.d.mts +10 -0
  25. package/lint/shardfile-boundaries.mjs +122 -0
  26. package/lint/tile-bake-debt.json +556 -0
  27. package/package.json +365 -3
  28. package/scripts/agent-parity.mjs +1524 -0
  29. package/scripts/agent-sync.mjs +518 -0
  30. package/scripts/apfs-clone.mjs +67 -0
  31. package/scripts/assert-store-layout.mjs +23 -0
  32. package/scripts/astc6-phone-cap.d.mts +3 -0
  33. package/scripts/astc6-phone-cap.mjs +137 -0
  34. package/scripts/audit-assets.d.mts +10 -0
  35. package/scripts/audit-assets.mjs +151 -0
  36. package/scripts/bake/coatFiles.d.mts +6 -0
  37. package/scripts/bake/coatFiles.mjs +37 -0
  38. package/scripts/bake/environment.d.mts +2 -0
  39. package/scripts/bake/environment.mjs +58 -0
  40. package/scripts/bake/far-proxies.mjs +45 -0
  41. package/scripts/bake/keyed-sky.d.mts +4 -0
  42. package/scripts/bake/keyed-sky.mjs +34 -0
  43. package/scripts/bake/movers.mjs +56 -0
  44. package/scripts/bake/nativeWorld.d.mts +6 -0
  45. package/scripts/bake/nativeWorld.mjs +43 -0
  46. package/scripts/bake/navmeshGround.ts +22 -0
  47. package/scripts/bake/near-placeholder.mjs +331 -0
  48. package/scripts/bake/placeholderShards.mjs +41 -0
  49. package/scripts/bake/skins.mjs +15 -0
  50. package/scripts/bake/template-skins.mjs +33 -0
  51. package/scripts/bake/viewmodelBytes.ts +26 -0
  52. package/scripts/bake/viewmodelPage.ts +11 -0
  53. package/scripts/bake/worldHost.d.mts +35 -0
  54. package/scripts/bake/worldHost.mjs +110 -0
  55. package/scripts/bake-astc6.cache.json +80 -0
  56. package/scripts/bake-astc6.far-reach.cache.json +23 -0
  57. package/scripts/bake-astc6.list.json +111 -0
  58. package/scripts/bake-astc6.mjs +279 -0
  59. package/scripts/bake-astc6.nalati-grasslands.cache.json +42 -0
  60. package/scripts/bake-catalogue.mjs +44 -0
  61. package/scripts/bake-check.mjs +54 -0
  62. package/scripts/bake-chunk.mjs +124 -0
  63. package/scripts/bake-cloud-field.mjs +24 -0
  64. package/scripts/bake-coats.mjs +110 -0
  65. package/scripts/bake-data-maps.d.mts +24 -0
  66. package/scripts/bake-data-maps.mjs +72 -0
  67. package/scripts/bake-entry-programs.mjs +117 -0
  68. package/scripts/bake-geometry.mjs +106 -0
  69. package/scripts/bake-hybrid-tiles.mjs +28 -0
  70. package/scripts/bake-ktx2.cache.json +276 -0
  71. package/scripts/bake-ktx2.list.json +365 -0
  72. package/scripts/bake-ktx2.mjs +477 -0
  73. package/scripts/bake-map-glb.mjs +127 -0
  74. package/scripts/bake-map-rest.d.mts +7 -0
  75. package/scripts/bake-map-rest.mjs +50 -0
  76. package/scripts/bake-maps.mjs +200 -0
  77. package/scripts/bake-navmesh.mjs +259 -0
  78. package/scripts/bake-packs.mjs +129 -0
  79. package/scripts/bake-pickups.mjs +102 -0
  80. package/scripts/bake-query-terrain.mjs +64 -0
  81. package/scripts/bake-recurve-pool.mjs +16 -0
  82. package/scripts/bake-section-schemas.d.mts +3 -0
  83. package/scripts/bake-template-shardfile.mjs +32 -0
  84. package/scripts/bake-textures.mjs +80 -0
  85. package/scripts/bake-viewmodel-sets.json +45 -0
  86. package/scripts/bake-viewmodel-sets.mjs +137 -0
  87. package/scripts/bake-voxel-ao.mjs +119 -0
  88. package/scripts/bake-water-ripples.mjs +25 -0
  89. package/scripts/blender/README.md +129 -0
  90. package/scripts/blender/build.sh +166 -0
  91. package/scripts/blender/lib/export-scene.mjs +129 -0
  92. package/scripts/blender/lib/glb-digest.mjs +188 -0
  93. package/scripts/blender/lib/glb.py +68 -0
  94. package/scripts/blender/lib/save_blend.py +17 -0
  95. package/scripts/blender/lib/world_fixture.py +55 -0
  96. package/scripts/blender/targets.json +591 -0
  97. package/scripts/build-sdk.mjs +95 -0
  98. package/scripts/build-shardfiles.d.mts +7 -0
  99. package/scripts/build-shardfiles.mjs +206 -0
  100. package/scripts/capture-hero.mjs +137 -0
  101. package/scripts/check-lift-review.mjs +23 -0
  102. package/scripts/chromium-keychain-check.mjs +139 -0
  103. package/scripts/chromium-keychain.d.mts +1 -0
  104. package/scripts/chromium-keychain.mjs +5 -0
  105. package/scripts/compile-script.d.mts +3 -0
  106. package/scripts/compile-script.mjs +8 -0
  107. package/scripts/creature-color.mjs +255 -0
  108. package/scripts/decide/calibrate.py +127 -0
  109. package/scripts/decide/calibration/2026-10-03/labels-s1.tsv +281 -0
  110. package/scripts/decide/calibration/2026-10-03/labels-s2.tsv +97 -0
  111. package/scripts/decide/calibration/2026-10-03/labels-s3.tsv +48 -0
  112. package/scripts/decide/calibration/2026-10-03/labels-s3b.tsv +26 -0
  113. package/scripts/decide/calibration/2026-10-03/res-capture-status-v1.jsonl +376 -0
  114. package/scripts/decide/calibration/2026-10-03/res-text-garbled-strings.jsonl +48 -0
  115. package/scripts/decide/calibration/2026-10-03/res-text-garbled-v1.jsonl +73 -0
  116. package/scripts/decide/decide.py +262 -0
  117. package/scripts/decide/decide.sh +50 -0
  118. package/scripts/decide/layer-purity-pilot.mjs +41 -0
  119. package/scripts/decide/sets/capture-status.json +46 -0
  120. package/scripts/decide/sets/layer-purity.json +28 -0
  121. package/scripts/decide/sets/text-garbled.json +17 -0
  122. package/scripts/decide/test_decide.py +37 -0
  123. package/scripts/docs.mjs +15 -0
  124. package/scripts/entry-reads/crawl.ts +152 -0
  125. package/scripts/entry-reads/tsconfig.json +25 -0
  126. package/scripts/gen-format-schema.d.mts +2 -0
  127. package/scripts/gen-format-schema.mjs +21 -0
  128. package/scripts/gen-host-catalogue.d.mts +14 -0
  129. package/scripts/gen-host-catalogue.mjs +108 -0
  130. package/scripts/gen-shard-layout-doc.d.mts +4 -0
  131. package/scripts/gen-shard-layout-doc.mjs +55 -0
  132. package/scripts/gen-shards.d.mts +17 -0
  133. package/scripts/gen-shards.mjs +311 -0
  134. package/scripts/goldens/capture-inputs.d.mts +4 -0
  135. package/scripts/goldens/capture-inputs.mjs +34 -0
  136. package/scripts/goldens/colour_shift.py +27 -0
  137. package/scripts/goldens/native-residency.d.mts +10 -0
  138. package/scripts/goldens/native-residency.mjs +104 -0
  139. package/scripts/goldens/plot-inputs.d.mts +12 -0
  140. package/scripts/goldens/plot-inputs.mjs +46 -0
  141. package/scripts/gpu-texmem.mjs +98 -0
  142. package/scripts/horizon-matte/config.py +24 -0
  143. package/scripts/horizon-matte/encode.py +91 -0
  144. package/scripts/horizon-matte/key.py +141 -0
  145. package/scripts/horizon-matte/mkjobs.py +33 -0
  146. package/scripts/horizon-matte/mkjobs_day2.py +11 -0
  147. package/scripts/horizon-matte/overlap.py +80 -0
  148. package/scripts/horizon-matte/run_codex.py +57 -0
  149. package/scripts/horizon-matte/stitch.py +133 -0
  150. package/scripts/img2mesh/CC0.md +105 -0
  151. package/scripts/img2mesh/README.md +209 -0
  152. package/scripts/img2mesh/ab_board.py +102 -0
  153. package/scripts/img2mesh/birds/birds.json +255 -0
  154. package/scripts/img2mesh/birds/birds_atlas.py +150 -0
  155. package/scripts/img2mesh/birds/birds_fix_preview.mjs +103 -0
  156. package/scripts/img2mesh/birds/birds_fix_render.py +75 -0
  157. package/scripts/img2mesh/birds/birds_pack.py +110 -0
  158. package/scripts/img2mesh/birds/birds_phone_b.py +112 -0
  159. package/scripts/img2mesh/birds/birds_post.py +550 -0
  160. package/scripts/img2mesh/birds/birds_render.py +125 -0
  161. package/scripts/img2mesh/birds/birds_sheet.py +33 -0
  162. package/scripts/img2mesh/birds/birds_view.py +60 -0
  163. package/scripts/img2mesh/board.py +100 -0
  164. package/scripts/img2mesh/build_cc0.sh +52 -0
  165. package/scripts/img2mesh/build_driftwood.sh +12 -0
  166. package/scripts/img2mesh/build_faces.sh +53 -0
  167. package/scripts/img2mesh/build_props.py +81 -0
  168. package/scripts/img2mesh/cc0_export.py +186 -0
  169. package/scripts/img2mesh/driftwood_post.py +571 -0
  170. package/scripts/img2mesh/e304_faces.sh +67 -0
  171. package/scripts/img2mesh/face_remaster.py +911 -0
  172. package/scripts/img2mesh/face_views.py +95 -0
  173. package/scripts/img2mesh/faces-e304.json +9 -0
  174. package/scripts/img2mesh/faces.json +30 -0
  175. package/scripts/img2mesh/head_cut.py +100 -0
  176. package/scripts/img2mesh/hi3d_paint.py +94 -0
  177. package/scripts/img2mesh/hi3d_refine.py +161 -0
  178. package/scripts/img2mesh/hunyuan_cpu_rasterizer.sh +42 -0
  179. package/scripts/img2mesh/pine_hollow_phone.sh +13 -0
  180. package/scripts/img2mesh/props/coral-arch.json +32 -0
  181. package/scripts/img2mesh/props/ember-furnace.json +30 -0
  182. package/scripts/img2mesh/props/night-market-gate.json +10 -0
  183. package/scripts/img2mesh/render_still.py +86 -0
  184. package/scripts/img2mesh/rig_strip.mjs +46 -0
  185. package/scripts/img2mesh/rig_transfer.mjs +104 -0
  186. package/scripts/img2mesh/split_sheet.py +48 -0
  187. package/scripts/img2mesh/trellis_batch.py +110 -0
  188. package/scripts/img2mesh/versus_board.py +114 -0
  189. package/scripts/import-bundle.d.mts +2 -0
  190. package/scripts/import-bundle.mjs +20 -0
  191. package/scripts/ktx2-ab-board.py +133 -0
  192. package/scripts/ktx2-ab.mjs +111 -0
  193. package/scripts/ktx2-settings.mjs +18 -0
  194. package/scripts/land.d.mts +14 -0
  195. package/scripts/land.mjs +809 -0
  196. package/scripts/lint-dispatch.mjs +14 -0
  197. package/scripts/map-bake-frames.d.mts +4 -0
  198. package/scripts/map-bake-frames.mjs +23 -0
  199. package/scripts/map-geometry.d.mts +9 -0
  200. package/scripts/map-geometry.mjs +29 -0
  201. package/scripts/map-world.mjs +162 -0
  202. package/scripts/mockup-local.sh +46 -0
  203. package/scripts/music/export-midi.mjs +68 -0
  204. package/scripts/music/gen/analyze.py +308 -0
  205. package/scripts/music/gen/audio_jobs.py +46 -0
  206. package/scripts/music/gen/briefs.json +51 -0
  207. package/scripts/music/gen/build_page.py +334 -0
  208. package/scripts/music/gen/folk.json +3187 -0
  209. package/scripts/music/gen/gen_ace_step.py +156 -0
  210. package/scripts/music/gen/gen_heartmula.py +187 -0
  211. package/scripts/music/gen/gen_minimax.py +143 -0
  212. package/scripts/music/gen/gen_sao.py +122 -0
  213. package/scripts/music/gen/gen_sao_small.py +104 -0
  214. package/scripts/music/gen/gen_sfx.py +98 -0
  215. package/scripts/music/gen/gen_sfx_ezaudio.py +112 -0
  216. package/scripts/music/gen/gen_sfx_moss.py +112 -0
  217. package/scripts/music/gen/models.json +61 -0
  218. package/scripts/music/gen/nalati-jobs.json +104 -0
  219. package/scripts/music/gen/nalati-score-build.json +119 -0
  220. package/scripts/music/gen/nalati-score.json +3448 -0
  221. package/scripts/music/gen/ob7-fit-decisions.json +38 -0
  222. package/scripts/music/gen/ob7-score-jobs.json +152 -0
  223. package/scripts/music/gen/ob7-sfx-jobs.json +897 -0
  224. package/scripts/music/gen/ob7_build.py +469 -0
  225. package/scripts/music/gen/ob7_generate.py +67 -0
  226. package/scripts/music/gen/ob7_run.sh +42 -0
  227. package/scripts/music/gen/orchestral.json +3187 -0
  228. package/scripts/music/gen/own_score.py +486 -0
  229. package/scripts/music/gen/ph-jobs.json +27 -0
  230. package/scripts/music/gen/ph_page.py +222 -0
  231. package/scripts/music/gen/piano.json +3175 -0
  232. package/scripts/music/gen/rank_v3.py +248 -0
  233. package/scripts/music/gen/sfx-best.json +2486 -0
  234. package/scripts/music/gen/sfx-ezaudio.json +4082 -0
  235. package/scripts/music/gen/sfx-jobs.json +57 -0
  236. package/scripts/music/gen/sfx-minimax-jobs.json +16 -0
  237. package/scripts/music/gen/sfx-minimax.json +289 -0
  238. package/scripts/music/gen/sfx-moss.json +4082 -0
  239. package/scripts/music/gen/sfx-nalati-b3-jobs.json +17 -0
  240. package/scripts/music/gen/sfx-nalati-jobs.json +338 -0
  241. package/scripts/music/gen/sfx-nalati.json +11202 -0
  242. package/scripts/music/gen/sfx-nd-jobs.json +57 -0
  243. package/scripts/music/gen/sfx-nd-moss.json +2097 -0
  244. package/scripts/music/gen/sfx-nd-sa3-medium.json +2097 -0
  245. package/scripts/music/gen/sfx-nd-summary.json +38 -0
  246. package/scripts/music/gen/sfx-peaks.json +7 -0
  247. package/scripts/music/gen/sfx-ph-jobs.json +169 -0
  248. package/scripts/music/gen/sfx-ph-moss.json +6564 -0
  249. package/scripts/music/gen/sfx-ph-sa3-medium.json +7239 -0
  250. package/scripts/music/gen/sfx-ph-summary.json +63 -0
  251. package/scripts/music/gen/sfx-sa3-medium.json +4082 -0
  252. package/scripts/music/gen/sfx-sa3.json +4082 -0
  253. package/scripts/music/gen/sfx-summary.json +107 -0
  254. package/scripts/music/gen/sfx_build.py +332 -0
  255. package/scripts/music/gen/sfx_merge.py +255 -0
  256. package/scripts/music/gen/sfx_minimax.py +61 -0
  257. package/scripts/music/gen/sfx_nalati.py +331 -0
  258. package/scripts/music/gen/sfx_sprite.py +424 -0
  259. package/scripts/music/gen/stems.py +539 -0
  260. package/scripts/music/gen/test_loop_meter.py +29 -0
  261. package/scripts/music/gen/test_ob7_provenance.py +77 -0
  262. package/scripts/music/gen/v3-folk-build.json +148 -0
  263. package/scripts/music/gen/v3-folk.json +1818 -0
  264. package/scripts/music/gen/v3-jobs.json +145 -0
  265. package/scripts/music/gen/v3-orchestral-build.json +148 -0
  266. package/scripts/music/gen/v3-orchestral.json +1813 -0
  267. package/scripts/music/gen/v3-ph-folk-build.json +94 -0
  268. package/scripts/music/gen/v3-ph-folk.json +1806 -0
  269. package/scripts/music/gen/v3-ph-orchestral-build.json +94 -0
  270. package/scripts/music/gen/v3-ph-orchestral.json +1824 -0
  271. package/scripts/music/gen/v3-ph-piano-build.json +94 -0
  272. package/scripts/music/gen/v3-ph-piano.json +1818 -0
  273. package/scripts/music/gen/v3-piano-build.json +148 -0
  274. package/scripts/music/gen/v3-piano.json +1813 -0
  275. package/scripts/music/wildshard-theme.mid +0 -0
  276. package/scripts/music/wildshard-trailer30.mid +0 -0
  277. package/scripts/named-blob-output.d.mts +8 -0
  278. package/scripts/named-blob-output.mjs +48 -0
  279. package/scripts/pack-all.mjs +15 -0
  280. package/scripts/pid-lock.d.mts +1 -0
  281. package/scripts/pid-lock.mjs +63 -0
  282. package/scripts/practice/bake_dummy.py +53 -0
  283. package/scripts/practice/build_dummies.sh +43 -0
  284. package/scripts/practice/dummy_parts.py +568 -0
  285. package/scripts/practice/dummy_rig_gate.py +139 -0
  286. package/scripts/practice/gate_sheet.py +36 -0
  287. package/scripts/practice/generate_dummy_unimate.py +132 -0
  288. package/scripts/practice/pack_dummy.mjs +59 -0
  289. package/scripts/practice/repair_dummy_weights.mjs +68 -0
  290. package/scripts/practice/rig_dummy.py +828 -0
  291. package/scripts/practice/verify_unimate_skin.mjs +356 -0
  292. package/scripts/preparation-seed.mjs +15 -0
  293. package/scripts/prepare-basis-tool.mjs +6 -0
  294. package/scripts/prepare-product.d.mts +14 -0
  295. package/scripts/prepare-product.mjs +101 -0
  296. package/scripts/product-build-tools.d.mts +3 -0
  297. package/scripts/product-build-tools.json +3 -0
  298. package/scripts/product-build-tools.mjs +31 -0
  299. package/scripts/publish-public.mjs +7 -0
  300. package/scripts/push-tables.d.mts +1 -0
  301. package/scripts/push-tables.mjs +28 -0
  302. package/scripts/record-shard-mounts.mjs +133 -0
  303. package/scripts/sdk-externals.d.mts +2 -0
  304. package/scripts/sdk-externals.mjs +2 -0
  305. package/scripts/section-inventory.ts +209 -0
  306. package/scripts/select-candidate.mjs +15 -0
  307. package/scripts/shard-build-pool.d.mts +4 -0
  308. package/scripts/shard-build-pool.mjs +53 -0
  309. package/scripts/shard-line-baseline.json +17 -0
  310. package/scripts/shard-milestones.d.mts +15 -0
  311. package/scripts/shard-milestones.mjs +105 -0
  312. package/scripts/shard-output-report.d.mts +9 -0
  313. package/scripts/shard-output-report.mjs +85 -0
  314. package/scripts/shard-platform-cli.mjs +93 -0
  315. package/scripts/shard-progress.mjs +212 -0
  316. package/scripts/shard-timelapse.py +102 -0
  317. package/scripts/shardfile-cold-boot.mjs +79 -0
  318. package/scripts/shardfile-vite.d.mts +4 -0
  319. package/scripts/shardfile-vite.mjs +20 -0
  320. package/scripts/simplify-models.mjs +24 -0
  321. package/scripts/site-facts.mjs +88 -0
  322. package/scripts/test-template-gate.mjs +44 -0
  323. package/scripts/test_golden_compare.py +68 -0
  324. package/scripts/tex-tiers.cache.json +181 -0
  325. package/scripts/tex-tiers.mjs +240 -0
  326. package/scripts/texmem-probe.mjs +184 -0
  327. package/scripts/unused-assets.mjs +173 -0
  328. package/scripts/vite-tmp.d.mts +23 -0
  329. package/scripts/vite-tmp.mjs +157 -0
  330. package/scripts/wave-line-baselines.json +32 -0
  331. package/scripts/wildshard.d.mts +4 -0
  332. package/scripts/wildshard.mjs +105 -0
  333. package/scripts/witness-checkpoints.d.mts +10 -0
  334. package/scripts/witness-checkpoints.mjs +84 -0
  335. package/scripts/witness-generation.d.mts +10 -0
  336. package/scripts/witness-generation.mjs +45 -0
  337. package/scripts/witness-manifests.d.mts +8 -0
  338. package/scripts/witness-manifests.mjs +157 -0
  339. package/scripts/worktree-ignore.d.mts +4 -0
  340. package/scripts/worktree-ignore.mjs +36 -0
  341. package/scripts/worktree-reap.mjs +214 -0
  342. package/scripts/worktree.mjs +396 -0
  343. package/scripts/worldclaw/capture-front.sh +28 -0
  344. package/scripts/worldclaw/design-template.md +62 -0
  345. package/scripts/worldclaw/spec-map.py +92 -0
  346. package/scripts/worldclaw/spec.ts +96 -0
  347. package/skills/wildshard/SKILL.md +50 -0
  348. package/skills/wildshard-goldens/SKILL.md +54 -0
  349. package/skills/wildshard-mockup-to-model/SKILL.md +56 -0
  350. package/skills/wildshard-upgrade/SKILL.md +46 -0
  351. package/src/.oxfmtrc.json +50 -0
  352. package/src/.oxlintrc.json +173 -0
  353. package/src/cli/account/account.ts +199 -0
  354. package/src/cli/account/command.ts +193 -0
  355. package/src/cli/account/key.ts +154 -0
  356. package/src/cli/args.ts +97 -0
  357. package/src/cli/audio/audio.ts +24 -0
  358. package/src/cli/bin.mjs +8 -0
  359. package/src/cli/delete/delete.ts +258 -0
  360. package/src/cli/help.ts +196 -0
  361. package/src/cli/hero/adopt.ts +103 -0
  362. package/src/cli/hero/hero.ts +112 -0
  363. package/src/cli/hero/stamp.ts +298 -0
  364. package/src/cli/main.ts +292 -0
  365. package/src/cli/report.ts +16 -0
  366. package/src/cli/shardfile/command.ts +50 -0
  367. package/src/cli/shardfile/shardfile.ts +192 -0
  368. package/src/cli/upload/api.ts +246 -0
  369. package/src/cli/upload/compress.ts +55 -0
  370. package/src/cli/upload/hero.ts +62 -0
  371. package/src/cli/upload/placement.ts +115 -0
  372. package/src/cli/upload/provenance.ts +192 -0
  373. package/src/cli/upload/signature.ts +30 -0
  374. package/src/cli/upload/upload.ts +269 -0
  375. package/src/cli/upload/validate.ts +74 -0
  376. package/src/cli/upload/wire.ts +147 -0
  377. package/src/cli/version.ts +63 -0
  378. package/src/commons/bake/portableMath.ts +187 -0
  379. package/src/commons/catalogue.ts +10 -0
  380. package/src/commons/courseProgram.ts +32 -0
  381. package/src/commons/practiceCourse.ts +16 -0
  382. package/src/commons/scripts/abi.as +14 -0
  383. package/src/commons/scripts/bridge.as +14 -0
  384. package/src/commons/scripts/course.as +63 -0
  385. package/src/scripts/ask-new.sh +29 -0
  386. package/src/scripts/asks.mjs +141 -0
  387. package/src/scripts/herdr-prompt.sh +34 -0
  388. package/src/scripts/herdr-question-open.sh +67 -0
  389. package/src/scripts/md-wrap.mjs +229 -0
  390. package/src/server/app.ts +19 -0
  391. package/src/server/serve.ts +49 -0
  392. package/src/sharddev/admission.ts +7 -0
  393. package/src/sharddev/arenaView.ts +15 -0
  394. package/src/sharddev/as/groupBankV2.ts +36 -0
  395. package/src/sharddev/as/groupStepV2.ts +13 -0
  396. package/src/sharddev/as/ws.ts +30 -0
  397. package/src/sharddev/as/wsV2.ts +180 -0
  398. package/src/sharddev/assemblyscriptCompiler.d.mts +5 -0
  399. package/src/sharddev/assemblyscriptCompiler.mjs +14 -0
  400. package/src/sharddev/assetHandle.ts +84 -0
  401. package/src/sharddev/assetOwner.ts +70 -0
  402. package/src/sharddev/assetScope.ts +30 -0
  403. package/src/sharddev/assets.ts +21 -0
  404. package/src/sharddev/audio.ts +9 -0
  405. package/src/sharddev/audioEncode.ts +211 -0
  406. package/src/sharddev/author.ts +3 -0
  407. package/src/sharddev/authorError.ts +28 -0
  408. package/src/sharddev/authorManifest.ts +39 -0
  409. package/src/sharddev/bake/annulus.ts +19 -0
  410. package/src/sharddev/bake/assemblyscriptMemo.ts +76 -0
  411. package/src/sharddev/bake/assemblyscriptMemoPort.ts +4 -0
  412. package/src/sharddev/bake/authoredWorld.ts +201 -0
  413. package/src/sharddev/bake/basisEncoder.ts +95 -0
  414. package/src/sharddev/bake/basisGlb.ts +85 -0
  415. package/src/sharddev/bake/basisTool.ts +74 -0
  416. package/src/sharddev/bake/basisToolInputs.ts +476 -0
  417. package/src/sharddev/bake/byteCodec.ts +33 -0
  418. package/src/sharddev/bake/canvasAtlas.ts +406 -0
  419. package/src/sharddev/bake/coarseCopy.ts +59 -0
  420. package/src/sharddev/bake/colliders.ts +87 -0
  421. package/src/sharddev/bake/compactGlb.ts +224 -0
  422. package/src/sharddev/bake/compileScript.ts +119 -0
  423. package/src/sharddev/bake/compileScriptV2.ts +75 -0
  424. package/src/sharddev/bake/contactRows.ts +84 -0
  425. package/src/sharddev/bake/creaturePlacement.ts +117 -0
  426. package/src/sharddev/bake/export.ts +67 -0
  427. package/src/sharddev/bake/facetedGeometry.ts +379 -0
  428. package/src/sharddev/bake/farImpostor.ts +120 -0
  429. package/src/sharddev/bake/forest.ts +100 -0
  430. package/src/sharddev/bake/format-hook.mjs +2 -0
  431. package/src/sharddev/bake/generatorGlb.ts +23 -0
  432. package/src/sharddev/bake/geometryBounds.ts +77 -0
  433. package/src/sharddev/bake/geometryError.ts +48 -0
  434. package/src/sharddev/bake/glb.ts +355 -0
  435. package/src/sharddev/bake/glbCompression.ts +143 -0
  436. package/src/sharddev/bake/gltfSource.ts +59 -0
  437. package/src/sharddev/bake/groundMap.ts +142 -0
  438. package/src/sharddev/bake/image.ts +20 -0
  439. package/src/sharddev/bake/isleMap.ts +64 -0
  440. package/src/sharddev/bake/json.mjs +84 -0
  441. package/src/sharddev/bake/keyedSky.ts +47 -0
  442. package/src/sharddev/bake/keyedSkyMemo.ts +39 -0
  443. package/src/sharddev/bake/kinds.ts +137 -0
  444. package/src/sharddev/bake/lightSources.ts +31 -0
  445. package/src/sharddev/bake/mapAssembly.ts +84 -0
  446. package/src/sharddev/bake/mapRaster.ts +173 -0
  447. package/src/sharddev/bake/mapRest.ts +57 -0
  448. package/src/sharddev/bake/mapScenes.ts +234 -0
  449. package/src/sharddev/bake/materialGraph.ts +32 -0
  450. package/src/sharddev/bake/meadow.ts +27 -0
  451. package/src/sharddev/bake/meshoptChoiceMemo.ts +34 -0
  452. package/src/sharddev/bake/nativeInteractionFacts.ts +5 -0
  453. package/src/sharddev/bake/nativeLattice.ts +178 -0
  454. package/src/sharddev/bake/nativeRaster.ts +106 -0
  455. package/src/sharddev/bake/nativeTerrainField.ts +11 -0
  456. package/src/sharddev/bake/navigation-json.mjs +38 -0
  457. package/src/sharddev/bake/navigation.ts +113 -0
  458. package/src/sharddev/bake/navigationAsset.ts +18 -0
  459. package/src/sharddev/bake/nearPlaceholder.ts +206 -0
  460. package/src/sharddev/bake/normalizeRig.ts +80 -0
  461. package/src/sharddev/bake/phoneAstc.ts +93 -0
  462. package/src/sharddev/bake/placeholders.ts +581 -0
  463. package/src/sharddev/bake/placement.ts +80 -0
  464. package/src/sharddev/bake/portableBytes.ts +18 -0
  465. package/src/sharddev/bake/portableBytesMemo.ts +50 -0
  466. package/src/sharddev/bake/practiceCourse.ts +49 -0
  467. package/src/sharddev/bake/primitives.ts +96 -0
  468. package/src/sharddev/bake/props.ts +443 -0
  469. package/src/sharddev/bake/questPlacement.ts +98 -0
  470. package/src/sharddev/bake/rawTexture.ts +26 -0
  471. package/src/sharddev/bake/riderArms.ts +97 -0
  472. package/src/sharddev/bake/rig.ts +95 -0
  473. package/src/sharddev/bake/riggedHullRecipes.ts +40 -0
  474. package/src/sharddev/bake/signPlacements.ts +25 -0
  475. package/src/sharddev/bake/simplifier.ts +52 -0
  476. package/src/sharddev/bake/skinned.ts +312 -0
  477. package/src/sharddev/bake/slabChunks.ts +149 -0
  478. package/src/sharddev/bake/slabs.ts +263 -0
  479. package/src/sharddev/bake/source-loader.mjs +55 -0
  480. package/src/sharddev/bake/sourceMetadata.ts +54 -0
  481. package/src/sharddev/bake/species.ts +368 -0
  482. package/src/sharddev/bake/specimenCatalogue.ts +47 -0
  483. package/src/sharddev/bake/splatGround.ts +141 -0
  484. package/src/sharddev/bake/staticMaterials.ts +171 -0
  485. package/src/sharddev/bake/terrain.ts +195 -0
  486. package/src/sharddev/bake/texture.ts +33 -0
  487. package/src/sharddev/bake/textureWasm.ts +81 -0
  488. package/src/sharddev/bake/tileEncoder.ts +11 -0
  489. package/src/sharddev/bake/tileGrid.ts +62 -0
  490. package/src/sharddev/bake/v2Finite.ts +160 -0
  491. package/src/sharddev/bake/v2Fuel.ts +71 -0
  492. package/src/sharddev/bake/wholePartition.ts +74 -0
  493. package/src/sharddev/bake/wholePieceJoin.ts +147 -0
  494. package/src/sharddev/bake/world.ts +173 -0
  495. package/src/sharddev/bake/worldCollision.ts +128 -0
  496. package/src/sharddev/bake/worldGeometry.ts +237 -0
  497. package/src/sharddev/bake/worldGlb.ts +123 -0
  498. package/src/sharddev/bake/worldImage.ts +12 -0
  499. package/src/sharddev/bake/worldLod.ts +128 -0
  500. package/src/sharddev/bake/worldRows.ts +102 -0
  501. package/src/sharddev/bake/worldTextureMemo.ts +63 -0
  502. package/src/sharddev/bake/zstdBytesMemo.ts +52 -0
  503. package/src/sharddev/bake.ts +193 -0
  504. package/src/sharddev/bakePublication.ts +31 -0
  505. package/src/sharddev/behaviourSource.ts +94 -0
  506. package/src/sharddev/bin/wildshard.mjs +7 -0
  507. package/src/sharddev/blobBytes.ts +65 -0
  508. package/src/sharddev/blobs.ts +138 -0
  509. package/src/sharddev/bootInventory.ts +129 -0
  510. package/src/sharddev/bossProfiles.ts +18 -0
  511. package/src/sharddev/buildBehaviour.ts +77 -0
  512. package/src/sharddev/buildCacheMetrics.ts +17 -0
  513. package/src/sharddev/buildDecisionScripts.ts +122 -0
  514. package/src/sharddev/check.ts +117 -0
  515. package/src/sharddev/checkProject.ts +126 -0
  516. package/src/sharddev/cli.ts +191 -0
  517. package/src/sharddev/clientChannels.ts +169 -0
  518. package/src/sharddev/clientScripts.ts +10 -0
  519. package/src/sharddev/commons.ts +77 -0
  520. package/src/sharddev/commonsCosts.ts +11 -0
  521. package/src/sharddev/compileMovers.ts +11 -0
  522. package/src/sharddev/configBoundary.ts +6 -0
  523. package/src/sharddev/cookInput.ts +40 -0
  524. package/src/sharddev/crowds.ts +6 -0
  525. package/src/sharddev/decisionBindingMap.ts +11 -0
  526. package/src/sharddev/decisionScriptBindings.ts +117 -0
  527. package/src/sharddev/decisionScripts.ts +28 -0
  528. package/src/sharddev/decisionSource.ts +51 -0
  529. package/src/sharddev/dev.ts +113 -0
  530. package/src/sharddev/director.ts +26 -0
  531. package/src/sharddev/directorAbi.ts +77 -0
  532. package/src/sharddev/discoveryDocument.ts +97 -0
  533. package/src/sharddev/draft.ts +11 -0
  534. package/src/sharddev/eliteEntryRows.ts +29 -0
  535. package/src/sharddev/entries.ts +76 -0
  536. package/src/sharddev/entryReads.ts +73 -0
  537. package/src/sharddev/executeBundle.ts +55 -0
  538. package/src/sharddev/finds.ts +5 -0
  539. package/src/sharddev/formatJsonSchema.ts +3 -0
  540. package/src/sharddev/generationCache.ts +257 -0
  541. package/src/sharddev/generationRecipe.ts +94 -0
  542. package/src/sharddev/handwritten.ts +110 -0
  543. package/src/sharddev/immutable.ts +14 -0
  544. package/src/sharddev/interactions.ts +38 -0
  545. package/src/sharddev/kit/bakedGeometry.ts +16 -0
  546. package/src/sharddev/kit/geometryPack.ts +110 -0
  547. package/src/sharddev/ledger.ts +13 -0
  548. package/src/sharddev/looks/tileField.ts +67 -0
  549. package/src/sharddev/materialGraphFiles.ts +57 -0
  550. package/src/sharddev/materials.ts +574 -0
  551. package/src/sharddev/measure.ts +18 -0
  552. package/src/sharddev/modes.ts +115 -0
  553. package/src/sharddev/moverPrograms.ts +213 -0
  554. package/src/sharddev/movers.ts +75 -0
  555. package/src/sharddev/nativePopulationRows.ts +46 -0
  556. package/src/sharddev/newProject.ts +247 -0
  557. package/src/sharddev/noise.ts +54 -0
  558. package/src/sharddev/outputProduct.ts +188 -0
  559. package/src/sharddev/outputRuntime.ts +66 -0
  560. package/src/sharddev/performancePolicy.ts +18 -0
  561. package/src/sharddev/phasedBoss.ts +34 -0
  562. package/src/sharddev/physics.ts +194 -0
  563. package/src/sharddev/platformSections.ts +42 -0
  564. package/src/sharddev/plumbing.ts +8 -0
  565. package/src/sharddev/productOutput.ts +128 -0
  566. package/src/sharddev/project.ts +337 -0
  567. package/src/sharddev/projectCompilerIdentity.ts +94 -0
  568. package/src/sharddev/projectDecisions.ts +66 -0
  569. package/src/sharddev/projectEntryProof.ts +32 -0
  570. package/src/sharddev/projectGeneration.ts +219 -0
  571. package/src/sharddev/projectInputFiles.ts +47 -0
  572. package/src/sharddev/projectManifest.ts +108 -0
  573. package/src/sharddev/projectMap.ts +35 -0
  574. package/src/sharddev/projectOutput.ts +242 -0
  575. package/src/sharddev/projectPolicy.ts +17 -0
  576. package/src/sharddev/projectSections.ts +27 -0
  577. package/src/sharddev/questGraph.ts +25 -0
  578. package/src/sharddev/quests.ts +65 -0
  579. package/src/sharddev/random.ts +61 -0
  580. package/src/sharddev/refusals.ts +234 -0
  581. package/src/sharddev/reportCard.ts +13 -0
  582. package/src/sharddev/returnProjectionV2.ts +81 -0
  583. package/src/sharddev/rows.ts +192 -0
  584. package/src/sharddev/runtimeImports.ts +38 -0
  585. package/src/sharddev/runtimeMirrors.ts +39 -0
  586. package/src/sharddev/runtimePerformance.ts +38 -0
  587. package/src/sharddev/scene.ts +321 -0
  588. package/src/sharddev/sceneAnimation.ts +54 -0
  589. package/src/sharddev/sceneAudio.ts +64 -0
  590. package/src/sharddev/sceneDeclarations.ts +100 -0
  591. package/src/sharddev/sceneGraph.ts +139 -0
  592. package/src/sharddev/sceneTransform.ts +12 -0
  593. package/src/sharddev/schemaValidation.ts +61 -0
  594. package/src/sharddev/sections.ts +47 -0
  595. package/src/sharddev/shardSource.ts +59 -0
  596. package/src/sharddev/sourceReader.ts +26 -0
  597. package/src/sharddev/spawns.ts +38 -0
  598. package/src/sharddev/species/clips.ts +24 -0
  599. package/src/sharddev/species.ts +29 -0
  600. package/src/sharddev/speciesBrains.ts +19 -0
  601. package/src/sharddev/synth.ts +66 -0
  602. package/src/sharddev/test/compileDualScriptV2.ts +71 -0
  603. package/src/sharddev/test/compileSimV2.ts +21 -0
  604. package/src/sharddev/test/diskScriptScenario.ts +86 -0
  605. package/src/sharddev/test/scriptScenario.ts +249 -0
  606. package/src/sharddev/test/scriptSource.ts +12 -0
  607. package/src/sharddev/version.ts +4 -0
  608. package/src/sharddev/weapons/bowProfile.ts +20 -0
  609. package/src/sharddev/weapons/firearmRows.ts +11 -0
  610. package/src/sharddev/weapons/meleeProfile.ts +71 -0
  611. package/src/sharddev/weapons/thrownProfile.ts +10 -0
  612. package/src/sharddev/worldScenes.ts +308 -0
  613. package/src/sharddev/worldSource.ts +82 -0
  614. package/src/shards/_template/README.md +78 -0
  615. package/src/shards/_template/assets/2bf489fdb15f1734ddb4c4f32d500ec6da85c765ec7a4eb28dc6781160e7ec8c +0 -0
  616. package/src/shards/_template/assets/97ec4d8f75f5fa6239ee919444d6dc19fd35896bb305930c1f050ac6e0e0e6a6 +1 -0
  617. package/src/shards/_template/assets/a6a587a31327f936b1b04c05ade818c73fc8964260918662db43539465e27586 +0 -0
  618. package/src/shards/_template/assets/b4fbde0422e125b498c3dc8b9a5cc2516c8598f09e9d0e5f6b639b32f98179e6 +0 -0
  619. package/src/shards/_template/assets/bfa4dfc9c18979f904557ee8deab0058b8a399be10266f5fb1578b403f482fd4 +1 -0
  620. package/src/shards/_template/assets/ef3b7ff4fd22715771cb7d68a3977a903c5e7c3dc293542687d04b3ef3ace2cb +0 -0
  621. package/src/shards/_template/assets/f2db05998615ce1cb79ea96be32c168842eb6a2b34ec01feb86d36404603ee54 +0 -0
  622. package/src/shards/_template/assets/fef98ebb7fce6f66b26e78ac699e5c90f9bdcfaf8cabeb2b58125347eea8b4ab +0 -0
  623. package/src/shards/_template/behaviour/boss.as +39 -0
  624. package/src/shards/_template/behaviour/door.as +32 -0
  625. package/src/shards/_template/behaviour/hooks.json +129 -0
  626. package/src/shards/_template/behaviour/idle.as +75 -0
  627. package/src/shards/_template/behaviour/items.as +22 -0
  628. package/src/shards/_template/card/landscape.jpg +0 -0
  629. package/src/shards/_template/card/portrait.jpg +0 -0
  630. package/src/shards/_template/card/thumb.jpg +0 -0
  631. package/src/shards/_template/data/audio.json +45 -0
  632. package/src/shards/_template/data/bossDecision.json +83 -0
  633. package/src/shards/_template/data/budgets.json +70 -0
  634. package/src/shards/_template/data/card.json +281 -0
  635. package/src/shards/_template/data/clientScripts.json +987 -0
  636. package/src/shards/_template/data/creatures.json +65 -0
  637. package/src/shards/_template/data/director.json +39 -0
  638. package/src/shards/_template/data/encounters.json +96 -0
  639. package/src/shards/_template/data/items.json +172 -0
  640. package/src/shards/_template/data/layout.json +66 -0
  641. package/src/shards/_template/data/ledger.json +32 -0
  642. package/src/shards/_template/data/look.json +521 -0
  643. package/src/shards/_template/data/map.json +64 -0
  644. package/src/shards/_template/data/moves.json +16 -0
  645. package/src/shards/_template/data/placeholder.json +8 -0
  646. package/src/shards/_template/data/plumbing.json +32 -0
  647. package/src/shards/_template/data/quests.json +223 -0
  648. package/src/shards/_template/data/rows.json +423 -0
  649. package/src/shards/_template/data/skins.json +66 -0
  650. package/src/shards/_template/data/spawn.json +6 -0
  651. package/src/shards/_template/data/targets.json +150 -0
  652. package/src/shards/_template/data/text.json +12 -0
  653. package/src/shards/_template/data/ui.json +33 -0
  654. package/src/shards/_template/data/water.json +13 -0
  655. package/src/shards/_template/generators/behaviour.ts +34 -0
  656. package/src/shards/_template/generators/boss.ts +29 -0
  657. package/src/shards/_template/generators/buildOptions.ts +2 -0
  658. package/src/shards/_template/generators/cell.ts +224 -0
  659. package/src/shards/_template/generators/districts.ts +215 -0
  660. package/src/shards/_template/generators/farLook.ts +15 -0
  661. package/src/shards/_template/generators/generate.ts +27 -0
  662. package/src/shards/_template/generators/ground.ts +15 -0
  663. package/src/shards/_template/generators/kit.ts +69 -0
  664. package/src/shards/_template/generators/landscape.ts +59 -0
  665. package/src/shards/_template/generators/landscapeNoise.ts +62 -0
  666. package/src/shards/_template/generators/mapInputs.ts +10 -0
  667. package/src/shards/_template/generators/product.ts +100 -0
  668. package/src/shards/_template/generators/productOutput.ts +18 -0
  669. package/src/shards/_template/generators/props.ts +9 -0
  670. package/src/shards/_template/generators/templatePropsSource.ts +58 -0
  671. package/src/shards/_template/generators/terrain.ts +17 -0
  672. package/src/shards/_template/generators/world.ts +630 -0
  673. package/src/shards/_template/hero.json +10 -0
  674. package/src/shards/_template/look/entry-reads.json +20 -0
  675. package/src/shards/_template/manifest.json +281 -0
  676. package/src/shards/_template/shard.config.ts +10 -0
  677. package/src/shared/health.ts +10 -0
  678. package/src/tools/build-web.ts +59 -0
  679. package/src/tsconfig.json +30 -0
  680. package/src/web/app.tsx +53 -0
  681. package/src/web/index.html +12 -0
  682. package/src/web/main.tsx +10 -0
  683. package/src/web/tsconfig.json +13 -0
  684. package/tsconfig.author.json +23 -0
  685. package/tsconfig.commons.json +21 -0
  686. package/tsconfig.json +47 -0
  687. package/tsconfig.sharddev.json +20 -0
@@ -0,0 +1,911 @@
1
+ """Face remaster for Nalati's image-to-3D camp people (NALATI-FINISH B5 / E302, the user: "all the models have terrible
2
+ faces … remaster the faces with Blender or Trellis or … Hunyuan 3D").
3
+
4
+ Why the faces are bad: a whole-body generation spends texels by surface area, so the head gets ~5 % of the atlas, and the
5
+ game packs each figure into a 256² cell on the phone (src/shards/nalati-grasslands/campPeopleModels.ts): the face ends up ~15 texels wide.
6
+ Every variant here therefore re-UVs the figure with the HEAD PRIORITISED (xatlas on a copy whose head is scaled up
7
+ `--head-scale` times, so its charts get that squared share of the atlas) and re-bakes, and then:
8
+
9
+ (no --graft / --paint) the current head, only re-UV'd + re-baked
10
+ --graft <bust.glb> the head replaced by a generated head-and-shoulders bust (Hunyuan3D-2 or TRELLIS.2 from a
11
+ new front portrait): the body above the neck cut is deleted, the bust scaled so its
12
+ neck→top matches the body's, centred on the old head, clipped a little below its neck
13
+ (so it tucks into the collar), decimated to --head-tris; baked from both hi sources
14
+ --paint <json> a simple readable face in the procedural figures' style painted on the head: the face
15
+ smoothed to one skin tone, then eyes (white, iris, lid), brows, a nose shade and a mouth,
16
+ drawn in the head's front projection (position / normal maps baked from the low mesh)
17
+
18
+ blender -b -P face_remaster.py -- --body body.glb --out out.glb --neck 0.77 [--tex 1024] [--head-scale 2.6]
19
+ [--graft bust.glb --bust-neck 0.52 --bust-clip 0.03 --head-tris 1800] [--paint '{"eye":0.9,...}']
20
+ [--front front.png]
21
+
22
+ --neck the procedural figure's neck height / its height (campPeople.ts: elder 0.769, herders 0.8, child 0.765,
23
+ cook 0.829); the cut is the narrowest cross-section near it, as the runtime rig finds it
24
+ --bust-neck where the bust's neck is, as a fraction of the bust's height from its top (from the portrait)
25
+ --front an unlit ortho render of the head from the front (for tuning the paint; not shipped)
26
+ Output: <out> (uncompressed GLB, one material, one --tex² atlas) + <out>.json. Metres, +Y up, feet on 0, facing +Z.
27
+ """
28
+ import bpy, bmesh, sys, os, json, math, argparse
29
+ import numpy as np
30
+ from mathutils import Vector, Matrix
31
+
32
+ argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
33
+ ap = argparse.ArgumentParser()
34
+ ap.add_argument("--body", required=True)
35
+ ap.add_argument("--out", required=True)
36
+ ap.add_argument("--neck", type=float, required=True)
37
+ ap.add_argument("--neck-exact", action="store_true", help="E304: cut at --neck itself (no narrowest-section search: the "
38
+ "King's hood is narrower at the face than at the neck)")
39
+ ap.add_argument("--tex", type=int, default=1024)
40
+ ap.add_argument("--head-scale", type=float, default=1.4)
41
+ ap.add_argument("--face-scale", type=float, default=5.0)
42
+ ap.add_argument("--face-top", type=float, default=0.6, help="the face's top (the hat brim), fraction of neck cut → head top")
43
+ ap.add_argument("--graft", default=None)
44
+ ap.add_argument("--bust-neck", type=float, default=0.5)
45
+ ap.add_argument("--bust-clip", type=float, default=0.03)
46
+ ap.add_argument("--bust-grow", type=float, default=1.0, help="extra scale on the bust (1 = neck-to-top matched)")
47
+ ap.add_argument("--bust-dz", type=float, default=0.0, help="nudge the bust up/down (fraction of the figure height)")
48
+ ap.add_argument("--bust-dy", type=float, default=0.0, help="nudge the bust forward (+) / back (fraction of height)")
49
+ ap.add_argument("--head-tris", type=int, default=4000)
50
+ ap.add_argument("--bust-beard", type=float, nargs=2, default=[0.0, 0.0], help="keep a front strip below the cut: half-width, depth (fractions of H)")
51
+ ap.add_argument("--no-weld", action="store_true")
52
+ ap.add_argument("--body-collar", type=float, nargs=2, default=None, help="E304: keep the body's faces over the cut up to <h> "
53
+ "farther than <r> from the head's axis (a coat's high collar; fractions of H)")
54
+ ap.add_argument("--bust-collar", type=float, nargs=2, default=None, help="E304: drop the bust's collar and shoulders: its faces "
55
+ "below the cut + <h> farther than <r> from the head's axis (both fractions of H; the beard strip is kept)")
56
+ ap.add_argument("--keep-above", type=float, default=None,
57
+ help="E304: keep the body's own head above this height (fraction of H: the Golden King's tall hat); the bust "
58
+ "is cut there, and scaled so --bust-top lands on it")
59
+ ap.add_argument("--bust-top", type=float, default=None, help="with --keep-above: the bust point (fraction of its height from "
60
+ "the top) that meets the kept part (the King's gold hood frame)")
61
+ ap.add_argument("--bust-overlap", type=float, default=0.006, help="with --keep-above: the bust reaches this far (fraction of "
62
+ "H) over the cut, into the kept hat, so no gap shows")
63
+ ap.add_argument("--bust-image", default=None, help="the cutout the bust was generated from: projected on its front")
64
+ ap.add_argument("--project-top", type=float, default=None, help="E304: project the portrait only below this height (fraction "
65
+ "of the neck cut → head top): a hat brim in front of the forehead took the portrait's forehead")
66
+ ap.add_argument("--paint", default=None)
67
+ ap.add_argument("--smooth-face", type=float, default=0.0, help="0..1: bend the face normals toward a head ellipsoid")
68
+ ap.add_argument("--front", default=None)
69
+ ap.add_argument("--graft-v2", action="store_true", help="E339 graft fix: the bust cut at ITS OWN neck (the narrowest section "
70
+ "under the chin, so it never carries a collar), placed and scaled by it, both cuts straight (bisect), the bust's "
71
+ "neck ring blended onto the body's (shape and colour), thin / sliver / floating fragments dropped, the head smooth")
72
+ ap.add_argument("--bust-neck-auto", type=float, nargs=2, default=None, help="with --graft-v2: search the bust's neck between "
73
+ "these fractions of its height from the top (else --bust-neck)")
74
+ ap.add_argument("--bust-fit", default="height", choices=["height", "box"], help="scale the bust by neck-to-top (height) or by "
75
+ "the geometric mean of that and the head's width (box: Pine Hollow's heads came out smaller than A's)")
76
+ ap.add_argument("--cut-tilt", type=float, default=30.0, help="with --graft-v2: the neck cut dips this many degrees toward the "
77
+ "front (under the jaw: a level cut took the new chin off and left the old one)")
78
+ ap.add_argument("--ring-band", type=float, default=0.035, help="with --graft-v2: how far up the bust's neck (fraction of H) its "
79
+ "ring is blended onto the body's")
80
+ ap.add_argument("--normal-map", action="store_true", help="E304 (Pine Hollow, PBR): also bake a tangent-space normal map from "
81
+ "the hi sources (the body's own normal map included) and export it")
82
+ a = ap.parse_args(argv)
83
+
84
+
85
+ def log(*x):
86
+ print("[face]", *x, flush=True)
87
+
88
+
89
+ def import_mesh(path, name):
90
+ before = set(bpy.data.objects)
91
+ bpy.ops.import_scene.gltf(filepath=path)
92
+ new = [o for o in bpy.data.objects if o not in before]
93
+ meshes = [o for o in new if o.type == "MESH"]
94
+ for o in bpy.context.scene.objects:
95
+ o.select_set(o in meshes)
96
+ bpy.context.view_layer.objects.active = meshes[0]
97
+ if len(meshes) > 1:
98
+ bpy.ops.object.join()
99
+ ob = bpy.context.view_layer.objects.active
100
+ mw = ob.matrix_world.copy()
101
+ ob.parent = None
102
+ ob.data.transform(mw)
103
+ ob.matrix_world = Matrix.Identity(4)
104
+ for o in new:
105
+ if o != ob:
106
+ bpy.data.objects.remove(o)
107
+ ob.name = name
108
+ # non-metallic sources (a Hunyuan GLB leaves metallicFactor unset = 1: the colour bake comes out black)
109
+ for ms in ob.material_slots:
110
+ m = ms.material
111
+ if m and m.node_tree:
112
+ for n in m.node_tree.nodes:
113
+ if n.type == "BSDF_PRINCIPLED":
114
+ for l in list(n.inputs["Metallic"].links):
115
+ m.node_tree.links.remove(l)
116
+ n.inputs["Metallic"].default_value = 0.0
117
+ return ob
118
+
119
+
120
+ def verts_np(ob):
121
+ co = np.empty(len(ob.data.vertices) * 3, dtype=np.float64)
122
+ ob.data.vertices.foreach_get("co", co)
123
+ return co.reshape(-1, 3)
124
+
125
+
126
+ def delete_faces(ob, pred):
127
+ """delete the faces whose centroid satisfies pred(centroid: Vector) -> bool"""
128
+ bm = bmesh.new(); bm.from_mesh(ob.data)
129
+ kill = [f for f in bm.faces if pred(f.calc_center_median())]
130
+ bmesh.ops.delete(bm, geom=kill, context="FACES")
131
+ loose = [v for v in bm.verts if not v.link_faces]
132
+ bmesh.ops.delete(bm, geom=loose, context="VERTS")
133
+ bm.to_mesh(ob.data); bm.free(); ob.data.update()
134
+ return len(kill)
135
+
136
+
137
+ def ntris(ob):
138
+ return sum(len(p.vertices) - 2 for p in ob.data.polygons)
139
+
140
+
141
+ def project_portrait(ob, path, neck_z):
142
+ """lay the portrait the bust was generated from (its cutout: alpha = the subject) over the bust's front, orthographic
143
+ along -Y: the generator rebuilt the subject in that image's frame, so its silhouette box = the alpha box. The generated
144
+ paint keeps the sides and the back; the face comes from the portrait itself (the generator's own paint splits a face
145
+ over several UV islands and leaves dark cracks at their seams)"""
146
+ im = bpy.data.images.load(path)
147
+ W_, H_ = im.size
148
+ px_ = np.empty(W_ * H_ * 4, dtype=np.float32); im.pixels.foreach_get(px_)
149
+ al = px_.reshape(H_, W_, 4)[..., 3] # row 0 = the image's bottom
150
+ ys, xs = np.where(al > 0.5)
151
+ ax0, ax1, ay0, ay1 = xs.min(), xs.max() + 1, ys.min(), ys.max() + 1 # in bottom-up rows
152
+ Bv = verts_np(ob)
153
+ x0, x1, z0, z1 = Bv[:, 0].min(), Bv[:, 0].max(), Bv[:, 2].min(), Bv[:, 2].max()
154
+ # image column = a + x·k, row (bottom-up) = b + z·k: ONE scale (the generator keeps the aspect). A first guess from
155
+ # the boxes (widths, tops), then fitted: the mesh's front silhouette against the alpha over the head (upper 60 %).
156
+ # The box guess alone left the eyes a few rows off the geometry's sockets (a dark crease across the cook's eyes)
157
+ k0 = (ax1 - ax0) / max(x1 - x0, 1e-6)
158
+ step = int(np.ceil(max(W_, H_) / 256)); f_ = 1 / step
159
+ am = al[::step, ::step] > 0.5
160
+ hr, wr = am.shape
161
+ top_rows = slice(int((ay1 - 0.6 * (ay1 - ay0)) * f_), hr)
162
+ best_ = (-1.0, k0, ax0 - x0 * k0, ay0 - z0 * (ay1 - ay0) / max(z1 - z0, 1e-6))
163
+ sz_box = (ay1 - ay0) / H_ / max(z1 - z0, 1e-6)
164
+ for kk_ in ([] if os.environ.get("PORTRAIT_FIT", "0") != "1" else np.linspace(0.75, 1.15, 41) * k0):
165
+ for da in np.linspace(-0.03, 0.03, 7) * W_:
166
+ for db in np.linspace(-0.05, 0.05, 11) * H_:
167
+ a_ = (ax0 + ax1) / 2 - (x0 + x1) / 2 * kk_ + da
168
+ b_ = ay1 - z1 * kk_ + db
169
+ cc = ((a_ + Bv[:, 0] * kk_) * f_).astype(int); rr = ((b_ + Bv[:, 2] * kk_) * f_).astype(int)
170
+ ok = (cc >= 0) & (cc < wr) & (rr >= 0) & (rr < hr)
171
+ mm = np.zeros((hr, wr), bool); mm[rr[ok], cc[ok]] = True
172
+ mm = mm | np.roll(mm, 1, 0) | np.roll(mm, -1, 0) | np.roll(mm, 1, 1) | np.roll(mm, -1, 1)
173
+ A_, M_ = am[top_rows], mm[top_rows]
174
+ iou = (A_ & M_).sum() / max(1, (A_ | M_).sum())
175
+ if iou > best_[0]:
176
+ best_ = (iou, kk_, a_, b_)
177
+ iou, kf, af, bf = best_
178
+ if iou >= 0: # PORTRAIT_FIT=1 (off: the silhouette is mostly headwear, and the fit moved the eyes off the sockets)
179
+ log(f"portrait fit: IoU {iou:.3f}, scale {kf / k0:.3f} of the box guess")
180
+ sx = kf / W_; sz = kf / H_
181
+ ax0, x0, ay0, z0 = af, 0.0, bf, 0.0
182
+ else: # the boxes: u = ax0/W + (x - x0)·sx ; v = ay0/H + (z - z0)·sz (the alpha box's bottom is the bust's)
183
+ sx = k0 / W_; sz = sz_box
184
+ hv = Bv[Bv[:, 2] > neck_z] # the head: above the neck
185
+ hcen = (hv.max(0) + hv.min(0)) / 2; hrad = np.maximum((hv.max(0) - hv.min(0)) / 2, 1e-3)
186
+ for ms in ob.material_slots:
187
+ m = ms.material
188
+ if not (m and m.node_tree):
189
+ continue
190
+ nt_ = m.node_tree
191
+ bs = next((n for n in nt_.nodes if n.type == "BSDF_PRINCIPLED"), None)
192
+ if bs is None or not bs.inputs["Base Color"].links:
193
+ continue
194
+ src = bs.inputs["Base Color"].links[0].from_socket
195
+ tc = nt_.nodes.new("ShaderNodeTexCoord"); sep = nt_.nodes.new("ShaderNodeSeparateXYZ")
196
+ nt_.links.new(tc.outputs["Object"], sep.inputs[0])
197
+ def lin(sock, k, c):
198
+ mm = nt_.nodes.new("ShaderNodeMath"); mm.operation = "MULTIPLY_ADD"
199
+ nt_.links.new(sock, mm.inputs[0]); mm.inputs[1].default_value = k; mm.inputs[2].default_value = c
200
+ return mm.outputs[0]
201
+ u = lin(sep.outputs["X"], sx, ax0 / W_ - x0 * sx)
202
+ v = lin(sep.outputs["Z"], sz, ay0 / H_ - z0 * sz)
203
+ cmb = nt_.nodes.new("ShaderNodeCombineXYZ"); nt_.links.new(u, cmb.inputs[0]); nt_.links.new(v, cmb.inputs[1])
204
+ ti = nt_.nodes.new("ShaderNodeTexImage"); ti.image = im; ti.extension = "CLIP"; ti.interpolation = "Cubic"
205
+ nt_.links.new(cmb.outputs[0], ti.inputs["Vector"])
206
+ # facing the camera, from the POSITION round the head's centre (an ellipsoid), not the surface normal: a dense
207
+ # generated surface's normals are noise, and a normal test cut the face into a patchwork of portrait and paint
208
+ sub = nt_.nodes.new("ShaderNodeVectorMath"); sub.operation = "SUBTRACT"
209
+ nt_.links.new(tc.outputs["Object"], sub.inputs[0]); sub.inputs[1].default_value = tuple(hcen)
210
+ scl = nt_.nodes.new("ShaderNodeVectorMath"); scl.operation = "MULTIPLY"
211
+ nt_.links.new(sub.outputs[0], scl.inputs[0]); scl.inputs[1].default_value = tuple(1 / r for r in hrad)
212
+ nrmz = nt_.nodes.new("ShaderNodeVectorMath"); nrmz.operation = "NORMALIZE"
213
+ nt_.links.new(scl.outputs[0], nrmz.inputs[0])
214
+ sn = nt_.nodes.new("ShaderNodeSeparateXYZ"); nt_.links.new(nrmz.outputs[0], sn.inputs[0])
215
+ mr = nt_.nodes.new("ShaderNodeMapRange"); mr.inputs["From Min"].default_value = -0.2; mr.inputs["From Max"].default_value = -0.6
216
+ nt_.links.new(sn.outputs["Y"], mr.inputs["Value"])
217
+ fac = nt_.nodes.new("ShaderNodeMath"); fac.operation = "MULTIPLY"
218
+ nt_.links.new(mr.outputs["Result"], fac.inputs[0]); nt_.links.new(ti.outputs["Alpha"], fac.inputs[1])
219
+ if a.project_top is not None:
220
+ zt = neck_z + a.project_top * (Bv[:, 2].max() - neck_z)
221
+ mz = nt_.nodes.new("ShaderNodeMapRange"); mz.inputs["From Min"].default_value = zt
222
+ mz.inputs["From Max"].default_value = zt - 0.012 * (Bv[:, 2].max() - neck_z) * 2
223
+ nt_.links.new(sep.outputs["Z"], mz.inputs["Value"])
224
+ fac2 = nt_.nodes.new("ShaderNodeMath"); fac2.operation = "MULTIPLY"
225
+ nt_.links.new(fac.outputs[0], fac2.inputs[0]); nt_.links.new(mz.outputs["Result"], fac2.inputs[1])
226
+ fac = fac2
227
+ mix = nt_.nodes.new("ShaderNodeMix"); mix.data_type = "RGBA"
228
+ nt_.links.new(fac.outputs[0], mix.inputs["Factor"])
229
+ nt_.links.new(src, mix.inputs[6]); nt_.links.new(ti.outputs["Color"], mix.inputs[7])
230
+ nt_.links.new(mix.outputs[2], bs.inputs["Base Color"])
231
+ log(f"portrait {os.path.basename(path)} projected on the bust front (alpha box {ax1 - ax0}x{ay1 - ay0} px)")
232
+
233
+
234
+ def split_at(ob, z):
235
+ """cut every face that crosses the plane z (no geometry removed): a straight edge there instead of a zig-zag"""
236
+ bm = bmesh.new(); bm.from_mesh(ob.data)
237
+ bmesh.ops.bisect_plane(bm, geom=bm.verts[:] + bm.edges[:] + bm.faces[:], dist=1e-6, plane_co=(0, 0, z), plane_no=(0, 0, 1))
238
+ bm.to_mesh(ob.data); bm.free(); ob.data.update()
239
+
240
+
241
+ def drop_fragments(ob, sliver=0.0, keep_frac=0.02):
242
+ """E339: the generated bust's torn paper — connected pieces smaller than keep_frac of the largest (collar flakes, loose
243
+ strands), degenerate triangles, and (sliver > 0) needle triangles whose shortest height is under sliver × longest edge"""
244
+ bm = bmesh.new(); bm.from_mesh(ob.data)
245
+ bmesh.ops.triangulate(bm, faces=bm.faces)
246
+ kill = set()
247
+ if sliver > 0:
248
+ # needles are collapsed, never deleted (a deleted needle is a hole): their shortest edge merged away
249
+ for _ in range(3):
250
+ short = []
251
+ for f in bm.faces:
252
+ if not f.is_valid or len(f.verts) != 3:
253
+ continue
254
+ es = sorted(f.edges, key=lambda e: e.calc_length())
255
+ lmax = es[-1].calc_length()
256
+ if lmax > 0 and 2 * f.calc_area() / lmax < sliver * lmax and es[0].is_valid:
257
+ short.append(es[0])
258
+ short = list({e for e in short if e.is_valid})
259
+ if not short:
260
+ break
261
+ bmesh.ops.collapse(bm, edges=short, uvs=True)
262
+ bmesh.ops.triangulate(bm, faces=bm.faces)
263
+ for f in bm.faces:
264
+ if f.calc_area() < 1e-12:
265
+ kill.add(f)
266
+ bmesh.ops.delete(bm, geom=list(kill), context="FACES")
267
+ # islands by shared edges
268
+ seen, islands = set(), []
269
+ for f in bm.faces:
270
+ if f in seen:
271
+ continue
272
+ stack, isl = [f], []
273
+ seen.add(f)
274
+ while stack:
275
+ g = stack.pop(); isl.append(g)
276
+ for e in g.edges:
277
+ for h in e.link_faces:
278
+ if h not in seen:
279
+ seen.add(h); stack.append(h)
280
+ islands.append((sum(x.calc_area() for x in isl), isl))
281
+ n = len(kill)
282
+ if islands:
283
+ big = max(i[0] for i in islands)
284
+ small = [f for area, isl in islands if area < keep_frac * big for f in isl]
285
+ bmesh.ops.delete(bm, geom=small, context="FACES"); n += len(small)
286
+ loose = [v for v in bm.verts if not v.link_faces]
287
+ bmesh.ops.delete(bm, geom=loose, context="VERTS")
288
+ bm.to_mesh(ob.data); bm.free(); ob.data.update()
289
+ return n
290
+
291
+
292
+ def ring_blend(bust, body, z, band):
293
+ """E339: the bust's neck meets the body's. Both are cut straight at z; per angle round the neck the bust's ring is moved
294
+ onto the body's ring (radius and centre), fading out up to z + band, and its rim tucked a hair inside and below the
295
+ body's so no crack shows"""
296
+ BV = verts_np(body)
297
+ rim = BV[np.abs(BV[:, 2] - z) < 1e-4 * max(1.0, abs(z) + 1)]
298
+ Bu = verts_np(bust)
299
+ brim = Bu[np.abs(Bu[:, 2] - z) < 1e-4 * max(1.0, abs(z) + 1)]
300
+ if len(rim) < 6 or len(brim) < 6:
301
+ log(f"ring blend skipped (rims: body {len(rim)}, bust {len(brim)})"); return
302
+ # only the body rim round the neck (the cut also crosses a beard or a raised collar): near the bust's rim centre
303
+ bc_ = brim[:, :2].mean(0)
304
+ rr = np.hypot(rim[:, 0] - bc_[0], rim[:, 1] - bc_[1])
305
+ rim = rim[rr < np.percentile(rr, 60) * 1.6]
306
+ c_body, c_bust = rim[:, :2].mean(0), brim[:, :2].mean(0)
307
+ NB = 36
308
+ def prof(P, c):
309
+ ang = np.arctan2(P[:, 1] - c[1], P[:, 0] - c[0]); r = np.hypot(P[:, 0] - c[0], P[:, 1] - c[1])
310
+ out = np.full(NB, np.nan)
311
+ idx = ((ang + np.pi) / (2 * np.pi) * NB).astype(int) % NB
312
+ for b in range(NB):
313
+ if (idx == b).any():
314
+ out[b] = r[idx == b].max()
315
+ ok = ~np.isnan(out)
316
+ xs = np.arange(NB)
317
+ return np.interp(xs, xs[ok], out[ok], period=NB) if ok.any() else out
318
+ rb, ru = prof(rim, c_body), prof(brim, c_bust)
319
+ # where the bust's rim is a beard / chin (far out from its neck), leave it: only the neck proper is blended
320
+ wbin = np.clip((1.35 - ru / max(np.median(ru), 1e-6)) / 0.2, 0, 1)
321
+ me = bust.data
322
+ moved = 0
323
+ for v in me.vertices:
324
+ h = v.co.z - z
325
+ if h > band or h < -1e-4: # the neck band only (a beard kept below the cut is left alone)
326
+ continue
327
+ t = max(0.0, min(1.0, h / band)); w = 1 - t * t * (3 - 2 * t)
328
+ dx, dy = v.co.x - c_bust[0], v.co.y - c_bust[1]
329
+ ang = math.atan2(dy, dx); r = math.hypot(dx, dy)
330
+ b = (ang + math.pi) / (2 * math.pi) * NB
331
+ i0 = int(math.floor(b)) % NB; fr = b - math.floor(b); i1 = (i0 + 1) % NB
332
+ tb = rb[i0] * (1 - fr) + rb[i1] * fr; tu = ru[i0] * (1 - fr) + ru[i1] * fr
333
+ wb_ = wbin[i0] * (1 - fr) + wbin[i1] * fr
334
+ # only the neck's own surface: a jaw or chin just above the cut stands far out of the rim — left where it is
335
+ wb_ *= min(1.0, max(0.0, (1.2 - r / max(tu, 1e-6)) / 0.2))
336
+ k_ = 1 + ((tb * 0.97) / max(tu, 1e-6) - 1) * w * wb_
337
+ cx = c_bust[0] + (c_body[0] - c_bust[0]) * w * wb_; cy = c_bust[1] + (c_body[1] - c_bust[1]) * w * wb_
338
+ v.co.x = cx + math.cos(ang) * r * k_; v.co.y = cy + math.sin(ang) * r * k_
339
+ if h < 1e-4 and wb_ > 0.5:
340
+ v.co.z = z - 0.004 * H
341
+ moved += 1
342
+ me.update()
343
+ log(f"ring blend: {moved} bust verts onto the body's neck (body rim r≈{np.median(rb):.3f}, bust rim r≈{np.median(ru):.3f})")
344
+
345
+
346
+ bpy.ops.wm.read_factory_settings(use_empty=True)
347
+ body = import_mesh(a.body, "body")
348
+ V = verts_np(body)
349
+ zmin, zmax = V[:, 2].min(), V[:, 2].max()
350
+ H = zmax - zmin
351
+ # ── the neck cut: the narrowest torso cross-section near the procedural neck (the runtime rig's own search) ──
352
+ best, zc = 1e9, zmin + a.neck * H
353
+ for z in np.arange(zmin + (a.neck - 0.07) * H, zmin + (a.neck + 0.05) * H, 0.005 * H):
354
+ band = V[(np.abs(V[:, 2] - z) < 0.006 * H) & (np.abs(V[:, 0]) < 0.14 * H)]
355
+ if len(band) == 0:
356
+ continue
357
+ w = np.abs(band[:, 0]).max()
358
+ if w < best:
359
+ best, zc = w, z
360
+ if a.neck_exact:
361
+ zc, best = zmin + a.neck * H, float("nan")
362
+ head_sel = V[:, 2] > zc
363
+ hc = V[head_sel].mean(0)
364
+ log(f"body {os.path.basename(a.body)}: H {H:.3f} m, neck cut z {zc - zmin:.3f} ({(zc - zmin) / H:.3f} H), half-width {best:.3f}, "
365
+ f"head centre x {hc[0]:.3f} y {hc[1]:.3f}, tris {ntris(body)}")
366
+
367
+ his = [body]
368
+ if a.graft:
369
+ bust = import_mesh(a.graft, "bust")
370
+ # weld: the generator splits its vertices along every UV seam, and bake rays slipped through those hairline cracks
371
+ # to the back of the head (white scarf lines across the face)
372
+ # (not a TRELLIS crust: welded, its flakes turn non-manifold and the collapse stalls at ~30 k triangles)
373
+ if not a.no_weld:
374
+ bm = bmesh.new(); bm.from_mesh(bust.data)
375
+ bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-5 * max(bust.dimensions))
376
+ bm.to_mesh(bust.data); bm.free(); bust.data.update()
377
+ B = verts_np(bust)
378
+ bt, bb = B[:, 2].max(), B[:, 2].min()
379
+ bc = bt - a.bust_neck * (bt - bb)
380
+ if a.graft_v2 and a.bust_neck_auto is not None:
381
+ # the neck = the narrowest section of the head's back half (a beard hangs in front) between chin and shoulders
382
+ hb_ = bt - bb; tp_ = B[B[:, 2] > bt - 0.3 * hb_]; tcx, tcy = tp_[:, 0].mean(), tp_[:, 1].mean()
383
+ bw_, bf_ = 1e9, a.bust_neck
384
+ for f_ in np.arange(a.bust_neck_auto[0], a.bust_neck_auto[1] + 1e-6, 0.0125):
385
+ z_ = bt - f_ * hb_
386
+ band_ = B[np.abs(B[:, 2] - z_) < 0.006 * hb_]
387
+ back_ = band_[band_[:, 1] > tcy - 0.02 * hb_]
388
+ if len(back_) < 8:
389
+ continue
390
+ w_ = np.percentile(np.abs(back_[:, 0] - tcx), 95)
391
+ if w_ < bw_:
392
+ bw_, bf_ = w_, f_
393
+ log(f"bust neck measured at {bf_:.3f} of its height from the top (was --bust-neck {a.bust_neck:.3f})")
394
+ bc = bt - bf_ * hb_
395
+ ztop = zmax if a.keep_above is None else zmin + a.keep_above * H
396
+ btop = bt if a.bust_top is None else bt - a.bust_top * (bt - bb)
397
+ s = (ztop - zc) / max(1e-6, btop - bc) * a.bust_grow
398
+ if a.bust_fit == "box":
399
+ # match the old head's width too (above the cut; the hat brim included), the geometric mean of the two scales
400
+ ow_ = np.percentile(np.abs(V[V[:, 2] > zc][:, 0] - hc[0]), 99)
401
+ bhv_ = B[B[:, 2] > bc]; nw_ = np.percentile(np.abs(bhv_[:, 0] - bhv_[:, 0].mean()), 99)
402
+ sw_ = ow_ / max(nw_, 1e-6) * a.bust_grow
403
+ log(f"bust scale: {s:.4f} by neck-to-top, {sw_:.4f} by width → {math.sqrt(s * sw_):.4f}")
404
+ s = math.sqrt(s * sw_)
405
+ # centre: the bust's head (above its neck) on the old head, horizontally; its neck on the cut
406
+ bh = B[B[:, 2] > bc]
407
+ bcx, bcy = bh[:, 0].mean(), bh[:, 1].mean()
408
+ M = Matrix.Translation((hc[0], hc[1] - a.bust_dy * H, zc + a.bust_dz * H)) @ Matrix.Scale(s, 4) @ Matrix.Translation((-bcx, -bcy, -bc))
409
+ bust.data.transform(M); bust.data.update()
410
+ if a.bust_image:
411
+ project_portrait(bust, a.bust_image, zc)
412
+ if a.keep_above is not None:
413
+ # the kept hat flares at its foot to the bust's width there (tapering to nothing at its tip), so the two meet
414
+ def half_w(Vx, z):
415
+ b_ = Vx[np.abs(Vx[:, 2] - z) < 0.01 * H]
416
+ return (b_[:, 0].max() - b_[:, 0].min()) / 2 if len(b_) else 0.0, (b_[:, 1].max() - b_[:, 1].min()) / 2 if len(b_) else 0.0
417
+ bwx, bwy = half_w(verts_np(bust), ztop)
418
+ hwx, hwy = half_w(V, ztop)
419
+ kx, ky = (bwx / hwx if hwx > 0 else 1.0), (bwy / hwy if hwy > 0 else 1.0)
420
+ for ob_ in (body,):
421
+ for v_ in ob_.data.vertices:
422
+ if v_.co.z > ztop - 0.01 * H:
423
+ f_ = max(0.0, 1 - (v_.co.z - ztop) / max(1e-6, zmax - ztop))
424
+ v_.co.x = hc[0] + (v_.co.x - hc[0]) * (1 + (kx - 1) * f_)
425
+ v_.co.y = hc[1] + (v_.co.y - hc[1]) * (1 + (ky - 1) * f_)
426
+ ob_.data.update()
427
+ log(f"kept hat above {ztop - zmin:.3f}: its foot flared x{kx:.2f} / y{ky:.2f} to the bust's")
428
+ tilt = None
429
+ if a.graft_v2 and a.keep_above is None and a.cut_tilt > 0:
430
+ # the cut dips under the jaw: work in a frame turned about x so that plane is level (turned back after the cuts)
431
+ # (a shear, level behind the neck's centre and dipping in front of it: a turned plane rose at the back and left
432
+ # the old neck standing up behind the new head like a collar)
433
+ tk_ = math.tan(math.radians(a.cut_tilt)); py_ = float(hc[1])
434
+ def tilt(ob_, sign):
435
+ co_ = np.empty(len(ob_.data.vertices) * 3); ob_.data.vertices.foreach_get("co", co_); co_ = co_.reshape(-1, 3)
436
+ co_[:, 2] += sign * np.maximum(0.0, py_ - co_[:, 1]) * tk_
437
+ ob_.data.vertices.foreach_set("co", co_.ravel()); ob_.data.update()
438
+ for ob_ in (body, bust):
439
+ tilt(ob_, 1)
440
+ if a.graft_v2:
441
+ split_at(bust, zc); split_at(body, zc) # straight cuts: the centroid rule left a zig-zag hem on both
442
+ clip = zc - a.bust_clip * H if not a.graft_v2 else zc
443
+ bw, bd = a.bust_beard
444
+ # a beard hangs over the chest: keep the bust's front strip down to bd below the cut (bw wide) so the new beard
445
+ # covers the old one
446
+ if a.graft_v2:
447
+ # the chin / beard that hangs forward of the neck below the cut: the bust keeps its own, the body loses its old one
448
+ # (both measured against their own neck's front at the cut)
449
+ def neck_front(ob):
450
+ P_ = verts_np(ob); r_ = P_[(np.abs(P_[:, 2] - zc) < 0.004 * H) & (np.abs(P_[:, 0] - hc[0]) < 0.05 * H)]
451
+ return np.percentile(r_[:, 1], 50) if len(r_) else hc[1]
452
+ fb_, fo_ = neck_front(bust), neck_front(body)
453
+ fwd_b = lambda c: bw > 0 and abs(c.x - hc[0]) < bw * H and c.z > zc - bd * H and c.y < fb_ - 0.01 * H
454
+ k = delete_faces(bust, lambda c: c.z < zc and not fwd_b(c))
455
+ else:
456
+ k = delete_faces(bust, lambda c: c.z < clip and not (bw > 0 and abs(c.x - hc[0]) < bw * H and c.z > zc - bd * H and c.y < hc[1] - 0.02 * H))
457
+ if a.keep_above is not None:
458
+ k += delete_faces(bust, lambda c: c.z > ztop + a.bust_overlap * H)
459
+ if a.bust_collar is not None:
460
+ ch, cr = a.bust_collar
461
+ k += delete_faces(bust, lambda c: c.z < zc + ch * H and math.hypot(c.x - hc[0], c.y - hc[1]) > cr * H
462
+ and not (bw > 0 and abs(c.x - hc[0]) < bw * H and c.y < hc[1] - 0.02 * H))
463
+ log(f"bust {os.path.basename(a.graft)}: scale {s:.4f}, neck at {a.bust_neck:.2f} of its height, clipped {k} faces below {clip - zmin:.3f}")
464
+ # the body keeps what is under the cut
465
+ body_hi = body.copy(); body_hi.data = body.data.copy(); body_hi.name = "body_hi"
466
+ bpy.context.collection.objects.link(body_hi)
467
+ in_beard = lambda c: bw > 0 and abs(c.x - hc[0]) < bw * H * 0.9 and c.z > zc - bd * H * 0.9 and c.y < hc[1] - 0.03 * H
468
+ if a.graft_v2:
469
+ # the old beard goes only where the new one covers it (a face in the strip with the bust in front of it): a fixed
470
+ # strip cut a hole in the coat wherever the new beard was shorter than the old (Baqyt Ata)
471
+ from mathutils.bvhtree import BVHTree as _BVH
472
+ _bm = bmesh.new(); _bm.from_mesh(bust.data); _tree = _BVH.FromBMesh(_bm); _bm.free()
473
+ def in_beard(c):
474
+ if not (bw > 0 and abs(c.x - hc[0]) < bw * H and c.z > zc - bd * H and c.z <= zc and c.y < fo_ - 0.015 * H):
475
+ return False
476
+ hit = _tree.ray_cast(Vector((c.x, c.y + 0.002 * H, c.z)), Vector((0.0, -1.0, 0.0)), 0.08 * H)
477
+ return hit[0] is not None
478
+ kept = (lambda c: False) if a.keep_above is None else (lambda c: c.z > ztop)
479
+ if a.body_collar is not None:
480
+ # a high coat collar: the body keeps its faces over the cut (up to <h>) farther than <r> from the head's axis (a
481
+ # flat cut there left a jagged hem round the neck); the bust takes the inside
482
+ kept0, (ch_, cr_) = kept, a.body_collar
483
+ kept = lambda c: kept0(c) or (c.z < zc + ch_ * H and math.hypot(c.x - hc[0], c.y - hc[1]) > cr_ * H)
484
+ k = delete_faces(body, lambda c: (c.z > zc and not kept(c)) or in_beard(c)) # the old beard goes with the old head
485
+ log(f"body: {k} head faces removed")
486
+ if a.graft_v2:
487
+ k = drop_fragments(bust)
488
+ log(f"bust: {k} floating / sliver faces dropped")
489
+ if a.keep_above is None:
490
+ ring_blend(bust, body, zc, a.ring_band * H)
491
+ delete_faces(body_hi, lambda c: (c.z > zc and not kept(c)) or in_beard(c))
492
+ if tilt is not None:
493
+ for ob_ in (body, body_hi, bust):
494
+ tilt(ob_, -1)
495
+ # low bust: decimated copy
496
+ bust_lo = bust.copy(); bust_lo.data = bust.data.copy(); bust_lo.name = "bust_lo"
497
+ bpy.context.collection.objects.link(bust_lo)
498
+ if ntris(bust_lo) > a.head_tris:
499
+ m = bust_lo.modifiers.new("dec", "DECIMATE"); m.decimate_type = "COLLAPSE"
500
+ m.ratio = a.head_tris / ntris(bust_lo); m.use_collapse_triangulate = True
501
+ bpy.context.view_layer.objects.active = bust_lo
502
+ bpy.ops.object.modifier_apply(modifier="dec")
503
+ # the collapse flips a few triangles (see-through holes in a face once three culls back faces): turn each low face
504
+ # to agree with the dense bust's surface nearest to it
505
+ from mathutils.bvhtree import BVHTree
506
+ dg = bpy.context.evaluated_depsgraph_get()
507
+ tree = BVHTree.FromObject(bust, dg)
508
+ bm = bmesh.new(); bm.from_mesh(bust_lo.data)
509
+ flip = []
510
+ for f in bm.faces:
511
+ hit = tree.find_nearest(f.calc_center_median())
512
+ if hit[1] is not None and f.normal.dot(hit[1]) < -0.2:
513
+ flip.append(f)
514
+ bmesh.ops.reverse_faces(bm, faces=flip)
515
+ # then against its neighbours: a face whose winding disagrees with its corners' (area-weighted) vertex normals is
516
+ # still inside out — drawn double-sided, three lights it from behind: a dark line across the eyes (the cook)
517
+ nmore = 0
518
+ for _ in range(3):
519
+ bm.normal_update()
520
+ more = [f for f in bm.faces if f.normal.dot(sum((v.normal for v in f.verts), Vector())) < 0]
521
+ if not more:
522
+ break
523
+ bmesh.ops.reverse_faces(bm, faces=more); nmore += len(more)
524
+ flip += [None] * nmore
525
+ bm.to_mesh(bust_lo.data); bm.free(); bust_lo.data.update()
526
+ log(f"bust: {ntris(bust_lo)} tris after the collapse, {len(flip)} flipped faces turned back")
527
+ if a.graft_v2:
528
+ log(f"bust lo: {drop_fragments(bust_lo, sliver=0.06)} sliver / floating faces dropped after the collapse")
529
+ # hi = the untouched body minus its head + the full bust; low = the body minus its head + the decimated bust
530
+ if not a.graft_v2:
531
+ delete_faces(body_hi, lambda c: (c.z > zc and not kept(c)) or in_beard(c))
532
+ his = [body_hi, bust]
533
+ for o in bpy.context.scene.objects:
534
+ o.select_set(o in (body, bust_lo))
535
+ bpy.context.view_layer.objects.active = body
536
+ bpy.ops.object.join()
537
+ low = body
538
+ else:
539
+ low = body.copy(); low.data = body.data.copy(); low.name = "low"
540
+ bpy.context.collection.objects.link(low)
541
+ low.name = "low"
542
+
543
+ # ── fresh UVs, head first ──
544
+ sys.path.append(os.path.expanduser(os.environ.get("XATLAS_PY", "~/ml/img2mesh/blender-py")))
545
+ import xatlas # noqa: E402
546
+ bm = bmesh.new(); bm.from_mesh(low.data)
547
+ bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-5 * H)
548
+ bmesh.ops.triangulate(bm, faces=bm.faces); bm.to_mesh(low.data); bm.free()
549
+ while low.data.uv_layers:
550
+ low.data.uv_layers.remove(low.data.uv_layers[0])
551
+ low.data.uv_layers.new(name="UVMap")
552
+ LV = verts_np(low).astype(np.float32)
553
+ F = np.array([p.vertices[:] for p in low.data.polygons], dtype=np.uint32)
554
+ t = np.clip((LV[:, 2] - (zc - 0.04 * H)) / (0.05 * H), 0, 1)
555
+ t = t * t * (3 - 2 * t)
556
+ # the face (the head's front, below the hat) gets --face-scale, the rest of the head --head-scale — a smooth field, so the
557
+ # charts that cross it only stretch (a little more texel there), never tear
558
+ LN = np.empty(len(low.data.vertices) * 3, dtype=np.float32); low.data.vertices.foreach_get("normal", LN); LN = LN.reshape(-1, 3)
559
+ ftop = zc + a.face_top * (zmax - zc)
560
+ fr = np.clip((-LN[:, 1] - 0.15) / 0.5, 0, 1) * np.clip((ftop - LV[:, 2]) / (0.08 * (zmax - zc)), 0, 1)
561
+ kk = 1 + t * ((a.head_scale - 1) + (a.face_scale - a.head_scale) * fr)
562
+ piv = np.array([hc[0], hc[1], zc + 0.4 * (zmax - zc)], dtype=np.float32)
563
+ LVs = piv + (LV - piv) * kk[:, None]
564
+ atlas = xatlas.Atlas(); atlas.add_mesh(LVs, F)
565
+ po = xatlas.PackOptions(); po.resolution = a.tex; po.padding = 8; po.bilinear = True; po.bruteForce = True
566
+ co_ = xatlas.ChartOptions()
567
+ co_.max_cost = float(os.environ.get("XATLAS_COST", "8")); co_.normal_seam_weight = 1.0 # fewer, bigger charts: a face in one piece
568
+ atlas.generate(co_, po)
569
+ vmap, idx, uvs = atlas[0]
570
+ # the face as ONE planar chart (front projection): xatlas still cut it into 2–4 charts, and on the phone's 256-px cell
571
+ # with its mipmaps every cut through the face read as a dark line (the cook's "glasses")
572
+ FF = F.astype(np.int64)
573
+ c3 = LV[FF].mean(1)
574
+ nf = np.cross(LV[FF[:, 1]] - LV[FF[:, 0]], LV[FF[:, 2]] - LV[FF[:, 0]])
575
+ nf /= np.maximum(np.linalg.norm(nf, axis=1, keepdims=True), 1e-12)
576
+ face_tri = (c3[:, 2] > zc + 0.01 * H) & (c3[:, 2] < ftop) & (nf[:, 1] < -0.3) & (c3[:, 1] < hc[1])
577
+ if face_tri.sum() > 8 and os.environ.get("FACE_CHART", "1") == "1":
578
+ keys, P2, U2 = {}, [], []
579
+ F2 = np.zeros_like(FF)
580
+ for t in range(len(FF)):
581
+ for k in range(3):
582
+ if face_tri[t]:
583
+ ov = int(FF[t, k]); uv = (10.0 + float(LV[ov, 0]), float(LV[ov, 2])); key = (ov, "f")
584
+ pos_ = LVs[ov]
585
+ else:
586
+ av = int(idx[t][k]); ov = int(vmap[av]); uv = (float(uvs[av][0]), float(uvs[av][1])); key = (ov, av)
587
+ pos_ = LVs[ov]
588
+ j = keys.get(key)
589
+ if j is None:
590
+ j = keys[key] = len(P2); P2.append(pos_); U2.append(uv)
591
+ F2[t, k] = j
592
+ at2 = xatlas.Atlas()
593
+ at2.add_mesh(np.array(P2, np.float32), F2.astype(np.uint32), None, np.array(U2, np.float32))
594
+ co2 = xatlas.ChartOptions(); co2.use_input_mesh_uvs = True
595
+ at2.generate(co2, po)
596
+ _, idx, uvs = at2[0]
597
+ log(f"face chart: {int(face_tri.sum())} triangles in one front projection, {at2.chart_count} charts")
598
+ uvl = low.data.uv_layers["UVMap"]
599
+ for p, tri in zip(low.data.polygons, idx):
600
+ for li, q in zip(p.loop_indices, tri):
601
+ uvl.data[li].uv = uvs[q]
602
+ # how much of the atlas the head got (uv area share of the faces above the cut)
603
+ def uv_area(sel):
604
+ s = 0.0
605
+ for p, tri in zip(low.data.polygons, idx):
606
+ if sel(p):
607
+ u = uvs[tri]
608
+ s += abs((u[1][0] - u[0][0]) * (u[2][1] - u[0][1]) - (u[2][0] - u[0][0]) * (u[1][1] - u[0][1])) / 2
609
+ return s
610
+ ha, ta = uv_area(lambda p: p.center.z > zc), uv_area(lambda p: True)
611
+ fa = uv_area(lambda p: zc < p.center.z < ftop and p.normal.y < -0.5)
612
+ log(f"xatlas: {atlas.chart_count} charts, head {ha / max(ta, 1e-9):.2f} / face {fa / max(ta, 1e-9):.2f} of the charts (x{a.head_scale} / x{a.face_scale})")
613
+
614
+ # ── bake the base colour hi → low ── (low smooth-shaded first: the cage is extruded along its normals, and flat
615
+ # faces tore the cage at every edge — the rays there hit the scarf behind the cheek: light lines along the edges)
616
+ for poly in low.data.polygons:
617
+ poly.use_smooth = True
618
+ img = bpy.data.images.new("atlas", a.tex, a.tex, alpha=False)
619
+ mat = bpy.data.materials.new("atlas"); mat.use_nodes = True
620
+ nt = mat.node_tree
621
+ bsdf = nt.nodes.get("Principled BSDF")
622
+ tex = nt.nodes.new("ShaderNodeTexImage"); tex.image = img
623
+ nt.links.new(tex.outputs["Color"], bsdf.inputs["Base Color"])
624
+ bsdf.inputs["Roughness"].default_value = 0.85; bsdf.inputs["Metallic"].default_value = 0.0
625
+ low.data.materials.clear(); low.data.materials.append(mat)
626
+ nt.nodes.active = tex
627
+ sc = bpy.context.scene
628
+ sc.render.engine = "CYCLES"
629
+ try:
630
+ prefs = bpy.context.preferences.addons["cycles"].preferences
631
+ prefs.compute_device_type = "METAL"; prefs.get_devices()
632
+ for d in prefs.devices:
633
+ d.use = True
634
+ sc.cycles.device = "GPU"
635
+ except Exception:
636
+ pass
637
+ sc.cycles.samples = 4
638
+ for o in sc.objects:
639
+ o.select_set(o in his or o == low)
640
+ bpy.context.view_layer.objects.active = low
641
+ ext = float(os.environ.get("BAKE_EXT", "0.012")) * H
642
+ bpy.ops.object.bake(type="DIFFUSE", pass_filter={"COLOR"}, use_selected_to_active=True, cage_extrusion=ext,
643
+ max_ray_distance=ext * 4, margin=3, margin_type="EXTEND") # margin < padding / 2: no chart's margin runs into its neighbour
644
+ nimg = None
645
+ if a.normal_map:
646
+ nimg = bpy.data.images.new("normal", a.tex, a.tex, alpha=False)
647
+ nimg.colorspace_settings.name = "Non-Color"
648
+ ntex = nt.nodes.new("ShaderNodeTexImage"); ntex.image = nimg
649
+ nt.nodes.active = ntex
650
+ bpy.ops.object.bake(type="NORMAL", normal_space="TANGENT", use_selected_to_active=True, cage_extrusion=ext,
651
+ max_ray_distance=ext * 4, margin=3, margin_type="EXTEND")
652
+ nmap = nt.nodes.new("ShaderNodeNormalMap")
653
+ nt.links.new(ntex.outputs["Color"], nmap.inputs["Color"]); nt.links.new(nmap.outputs["Normal"], bsdf.inputs["Normal"])
654
+ nt.nodes.active = tex
655
+ log("normal map baked (tangent space)")
656
+ for o in his:
657
+ bpy.data.objects.remove(o)
658
+
659
+
660
+ def raster_maps(zlo):
661
+ """the low mesh's position + face normal per texel (uv-rasterised, faces above zlo only) → two (tex, tex, 3) arrays,
662
+ row 0 = v 0 (Blender's pixel order); texels off those faces stay far away (pos 1e3) so no paint lands there"""
663
+ T = a.tex
664
+ pos = np.full((T, T, 3), 1e3, np.float32); nrm = np.zeros((T, T, 3), np.float32)
665
+ uvd = low.data.uv_layers["UVMap"].data
666
+ vco = low.data.vertices
667
+ cov = np.zeros((T, T), bool)
668
+ for poly in low.data.polygons:
669
+ head = poly.center.z >= zlo
670
+ li = list(poly.loop_indices)
671
+ uv = np.array([uvd[k].uv[:] for k in li], np.float64) * T - 0.5
672
+ P3 = np.array([vco[low.data.loops[k].vertex_index].co[:] for k in li], np.float64)
673
+ for t in range(1, len(li) - 1):
674
+ U = uv[[0, t, t + 1]]; Q = P3[[0, t, t + 1]]
675
+ x0, y0 = np.floor(U.min(0)).astype(int); x1, y1 = np.ceil(U.max(0)).astype(int)
676
+ x0, y0 = max(x0 - 1, 0), max(y0 - 1, 0); x1, y1 = min(x1 + 1, T - 1), min(y1 + 1, T - 1)
677
+ gx, gy = np.meshgrid(np.arange(x0, x1 + 1), np.arange(y0, y1 + 1))
678
+ d = (U[1, 1] - U[2, 1]) * (U[0, 0] - U[2, 0]) + (U[2, 0] - U[1, 0]) * (U[0, 1] - U[2, 1])
679
+ if abs(d) < 1e-12:
680
+ continue
681
+ l0 = ((U[1, 1] - U[2, 1]) * (gx - U[2, 0]) + (U[2, 0] - U[1, 0]) * (gy - U[2, 1])) / d
682
+ l1 = ((U[2, 1] - U[0, 1]) * (gx - U[2, 0]) + (U[0, 0] - U[2, 0]) * (gy - U[2, 1])) / d
683
+ l2 = 1 - l0 - l1
684
+ e_ = -0.6 / max(1.0, np.abs(U.max(0) - U.min(0)).max()) # a little over the edge: no seams
685
+ ins = (l0 >= e_) & (l1 >= e_) & (l2 >= e_)
686
+ if not ins.any():
687
+ continue
688
+ w = np.stack([l0[ins], l1[ins], l2[ins]], -1)
689
+ cov[gy[ins], gx[ins]] = True
690
+ if head:
691
+ pos[gy[ins], gx[ins]] = w @ Q
692
+ nrm[gy[ins], gx[ins]] = poly.normal[:]
693
+ return pos, nrm, cov
694
+
695
+
696
+ if a.graft and a.graft_v2 and a.keep_above is None:
697
+ # E339: the neck's colour runs on from the body into the bust over the blended band (the bust's own neck paint met the
698
+ # body's in a hard line): per angle round the neck, the bust side shifted by the difference of the two sides' means
699
+ pos, nrm, _ = raster_maps(zc - 0.06 * H)
700
+ px = np.empty(a.tex * a.tex * 4, dtype=np.float32); img.pixels.foreach_get(px)
701
+ col = px.reshape(a.tex, a.tex, 4)
702
+ ok = pos[..., 0] < 1e2
703
+ rel = pos[..., 2] - zc
704
+ rad = np.hypot(pos[..., 0] - hc[0], pos[..., 1] - hc[1])
705
+ near = ok & (rad < 0.12 * H)
706
+ NB_ = 24
707
+ bi = (((np.arctan2(pos[..., 1] - hc[1], pos[..., 0] - hc[0]) + np.pi) / (2 * np.pi)) * NB_).astype(int) % NB_
708
+ below = near & (rel > -0.03 * H) & (rel < -0.004 * H)
709
+ above = near & (rel > 0.004 * H) & (rel < 0.03 * H)
710
+ band_ = a.ring_band * H
711
+ if below.sum() > 20 and above.sum() > 20:
712
+ gb, ga = col[below][:, :3].mean(0), col[above][:, :3].mean(0)
713
+ dif = np.zeros((NB_, 3), np.float32)
714
+ for b in range(NB_):
715
+ mb = below & (bi == b); ma = above & (bi == b)
716
+ dif[b] = (col[mb][:, :3].mean(0) if mb.sum() > 4 else gb) - (col[ma][:, :3].mean(0) if ma.sum() > 4 else ga)
717
+ sel = near & (rel > -0.002 * H) & (rel < band_)
718
+ t = np.clip(rel / band_, 0, 1); w = (1 - t * t * (3 - 2 * t)) * 0.85
719
+ col[..., :3] = np.where(sel[..., None], np.clip(col[..., :3] + dif[bi] * w[..., None], 0, 1), col[..., :3])
720
+ img.pixels.foreach_set(col.ravel())
721
+ log(f"neck colour blended over {int(sel.sum())} texels (mean body-bust gap {np.abs(gb - ga).mean():.3f})")
722
+
723
+ if a.paint:
724
+ P = json.loads(a.paint)
725
+ pos, nrm, _ = raster_maps(zc - 0.06 * H)
726
+ px = np.empty(a.tex * a.tex * 4, dtype=np.float32); img.pixels.foreach_get(px)
727
+ col = px.reshape(a.tex, a.tex, 4)
728
+ rgb = col[..., :3]
729
+ # the face frame: front = -Y (glTF +Z); x across (the figure's LEFT is +x); z up. Units: eye spacing e (m)
730
+ # the spec is in the --front render's pixels (768², ortho): "eyes": [x left, x right, y] and optional rows
731
+ # "brow_y", "nose_y", "mouth_y", "keep_y" (the beard / scarf below stay as generated), "face_y" (the oval's centre)
732
+ fscale = (zmax - zc) * 1.5; mpp = fscale / 768; fmid = zc + (zmax - zc) * 0.45
733
+ zpx = lambda py: fmid + (384 - py) * mpp
734
+ xl, xr, ey = P["eyes"]
735
+ e = (xr - xl) * mpp
736
+ cx = hc[0] + ((xl + xr) / 2 - 384) * mpp
737
+ ez = zpx(ey)
738
+ vpx = lambda py: (zpx(py) - ez) / e
739
+ for k in ("brow", "nose", "mouth", "keep", "face"):
740
+ if f"{k}_y" in P:
741
+ P[{"keep": "keep_below", "face": "face_cv"}.get(k, f"{k}_v")] = vpx(P[f"{k}_y"])
742
+ u = (pos[..., 0] - cx) / e
743
+ v = (pos[..., 2] - ez) / e
744
+ front = np.clip((-nrm[..., 1] - 0.15) / 0.45, 0, 1) # facing the camera
745
+ ahead = pos[..., 1] < (hc[1] + P.get("dy", 0.0) * e) # the front half of the head
746
+ fw = front * ahead * (pos[..., 2] > zc - 0.02 * H)
747
+ log(f"paint maps: pos x {pos[..., 0].min():.2f}..{pos[..., 0].max():.2f} z {pos[..., 2].min():.2f}..{pos[..., 2].max():.2f}, "
748
+ f"-ny>0.5 on {(nrm[..., 1] < -0.5).mean():.3f}, front-facing head texels {(fw > 0.5).sum()}")
749
+
750
+ def ell(cu, cv, ru, rv, soft=0.35):
751
+ d = np.sqrt(((u - cu) / ru) ** 2 + ((v - cv) / rv) ** 2)
752
+ return np.clip((1 - d) / soft, 0, 1)
753
+
754
+ def put(mask, c, alpha=1.0):
755
+ m = (mask * fw * alpha)[..., None]
756
+ rgb[...] = rgb * (1 - m) + np.array(c, dtype=np.float32)[None, None, :] * m
757
+
758
+ # 1. one skin tone over the face oval (the generated face is mottled: blotches read as dirt at 3 m) — only on
759
+ # skin-coloured texels (not the beard, the scarf, the hat brim), below the brim (top_y) and above keep_y
760
+ fu, fv = P.get("face", [1.25, 1.55])
761
+ oval = ell(0, P.get("face_cv", -0.35), fu, fv, soft=0.5)
762
+ r_, g_, b_ = rgb[..., 0], rgb[..., 1], rgb[..., 2]
763
+ lum = (r_ + g_ + b_) / 3
764
+ skin0 = np.clip(((r_ - b_) - 0.08) / 0.1, 0, 1) * (r_ >= g_) * (lum > 0.2) * (lum < 0.92)
765
+ # the middle of the face: the dark streaks and blotches go too (only white — a beard, a scarf — stays)
766
+ inner = ell(0, P.get("face_cv", -0.35), fu * 0.72, fv * 0.72, soft=0.3) * (lum < 0.8)
767
+ skinlike = np.maximum(skin0, inner * P.get("blemish", 1.0))
768
+ inface = oval * (v > P.get("keep_below", -99.0)) * (v < (vpx(P["top_y"]) if "top_y" in P else 99.0))
769
+ sel = (inface > 0.6) & (fw > 0.6) & (skin0 > 0.5)
770
+ skin = np.array(P["skin"], np.float32) if "skin" in P else (np.median(rgb[sel], axis=0) if sel.sum() > 20 else np.array([0.72, 0.5, 0.38], np.float32))
771
+ ml = lum[sel].mean() if sel.sum() > 20 else 0.5
772
+ shade = (0.5 + 0.5 * np.clip(lum / max(ml, 1e-3), 0.85, 1.12))[..., None]
773
+ m = (inface * fw * skinlike * P.get("smooth", 0.85))[..., None]
774
+ rgb[...] = rgb * (1 - m) + (skin[None, None, :] * shade) * m
775
+ dark = np.array(P.get("line", [0.12, 0.07, 0.05]), np.float32)
776
+ # 2. cheeks: a warm flush
777
+ for s in (-1, 1):
778
+ put(ell(s * 0.62, -0.62, 0.34, 0.22, soft=1.0), P.get("cheek", [0.78, 0.42, 0.36]), P.get("cheek_a", 0.35))
779
+ # 3. eyes: white, iris, pupil, upper lid (the procedural figures' black eyes, grown into something that reads)
780
+ er = P.get("eye_r", [0.22, 0.12])
781
+ for s in (-1, 1):
782
+ put(ell(s * 0.5, 0, er[0], er[1], 0.25), P.get("white", [0.93, 0.9, 0.84]))
783
+ put(ell(s * 0.5, -0.005, er[1] * 1.0, er[1] * 1.0, 0.25), P.get("iris", [0.2, 0.12, 0.07]))
784
+ put(ell(s * 0.5, -0.005, er[1] * 0.45, er[1] * 0.45, 0.3), [0.03, 0.02, 0.02])
785
+ put(ell(s * 0.5, er[1] * 0.75, er[0] * 1.08, er[1] * 0.38, 0.4), dark)
786
+ # 4. brows
787
+ bc = P.get("brow", [0.14, 0.09, 0.06])
788
+ put(ell(s * 0.52, P.get("brow_v", 0.36), 0.3, P.get("brow_t", 0.075), 0.4), bc)
789
+ # 5. nose: a shade under it and on its side
790
+ put(ell(0, P.get("nose_v", -0.62), 0.2, 0.08, 0.8), [x * 0.72 for x in skin.tolist()], 0.8)
791
+ put(ell(0.1, P.get("nose_v", -0.62) + 0.3, 0.07, 0.28, 0.9), [x * 0.85 for x in skin.tolist()], 0.6)
792
+ # 6. mouth
793
+ if P.get("mouth", True):
794
+ put(ell(0, P.get("mouth_v", -1.02), P.get("mouth_w", 0.34), 0.055, 0.45), P.get("lip", [0.45, 0.16, 0.13]))
795
+ if P.get("moustache"):
796
+ mv = P.get("mouth_v", -1.02) + 0.13
797
+ put(ell(0, mv, P.get("moustache_w", 0.5), 0.06, 0.4), P.get("moustache_c", [0.1, 0.07, 0.05]))
798
+ for s in (-1, 1): # the ends droop
799
+ put(ell(s * P.get("moustache_w", 0.5) * 0.85, mv - 0.08, 0.1, 0.1, 0.5), P.get("moustache_c", [0.1, 0.07, 0.05]))
800
+ col[..., :3] = np.clip(rgb, 0, 1)
801
+ img.pixels.foreach_set(col.ravel())
802
+ log(f"painted face: eye z {ez - zmin:.3f}, spacing {e:.3f} m, skin {np.round(skin, 2).tolist()}")
803
+
804
+ # ── fill every texel off the charts (push-pull): the black gutters bled into the faces as dark seams once the phone's
805
+ # 256² cell and its mipmaps averaged across them ──
806
+ _, _, cov = raster_maps(1e9)
807
+ for _ in range(3): # keep the bake's own EXTEND margin round every chart (bilinear reads half a texel past the edge)
808
+ cov = cov | np.roll(cov, 1, 0) | np.roll(cov, -1, 0) | np.roll(cov, 1, 1) | np.roll(cov, -1, 1)
809
+ px = np.empty(a.tex * a.tex * 4, dtype=np.float32); img.pixels.foreach_get(px)
810
+ col = px.reshape(a.tex, a.tex, 4)
811
+
812
+
813
+ def push_pull(c, m):
814
+ if c.shape[0] <= 1:
815
+ return c
816
+ w = m.astype(np.float32)
817
+ h2 = c.shape[0] // 2
818
+ cw = (c * w[..., None]).reshape(h2, 2, h2, 2, 3).sum((1, 3))
819
+ ww = w.reshape(h2, 2, h2, 2).sum((1, 3))
820
+ small = np.where(ww[..., None] > 0, cw / np.maximum(ww[..., None], 1e-6), 0)
821
+ small = push_pull(small, ww > 0)
822
+ up = small.repeat(2, 0).repeat(2, 1)
823
+ return np.where(m[..., None], c, up)
824
+
825
+
826
+ if os.environ.get("NO_FILL") != "1":
827
+ col[..., :3] = push_pull(col[..., :3].copy(), cov)
828
+ img.pixels.foreach_set(col.ravel())
829
+ log(f"gutters filled: {(~cov).mean():.2f} of the atlas was off the charts")
830
+ img.file_format = "PNG"
831
+ img.pack()
832
+ if nimg is not None:
833
+ npx = np.empty(a.tex * a.tex * 4, dtype=np.float32); nimg.pixels.foreach_get(npx)
834
+ ncol = npx.reshape(a.tex, a.tex, 4)
835
+ if os.environ.get("NO_FILL") != "1":
836
+ ncol[..., :3] = push_pull(ncol[..., :3].copy(), cov)
837
+ nimg.pixels.foreach_set(ncol.ravel())
838
+ nimg.file_format = "PNG"
839
+ nimg.pack()
840
+ # smooth shading, hard only past 50° (the join + weld dropped the imported normals: a grafted head came out faceted, every
841
+ # decimated triangle its own flat patch under the cel bands — rings round the eyes, shards in a beard)
842
+ for o in bpy.context.scene.objects:
843
+ o.select_set(o == low)
844
+ bpy.context.view_layer.objects.active = low
845
+ bpy.ops.object.shade_smooth_by_angle(angle=math.radians(50))
846
+ for md in list(low.modifiers):
847
+ try:
848
+ bpy.ops.object.modifier_apply(modifier=md.name)
849
+ except Exception:
850
+ pass
851
+ if a.graft and a.graft_v2:
852
+ # E339: the grafted head smooth all over (the 50° split left beards, scarves and fur as torn-paper facets)
853
+ bm = bmesh.new(); bm.from_mesh(low.data)
854
+ for f_ in bm.faces:
855
+ if f_.calc_center_median().z > zc - 0.01 * H:
856
+ f_.smooth = True
857
+ for e_ in f_.edges:
858
+ e_.smooth = True
859
+ bm.to_mesh(low.data); bm.free(); low.data.update()
860
+ if a.smooth_face > 0:
861
+ # the generated face is a few hundred lumpy facets: under the painterly cel bands a dent reads as a dark blob (the
862
+ # cook's cheek, the child's nose). Bend the face's normals toward an ellipsoid round the head — the procedural
863
+ # figures' smooth sphere head, lit as one surface — keeping the silhouette
864
+ Vn = verts_np(low)
865
+ Nn = np.empty(len(low.data.vertices) * 3, dtype=np.float64); low.data.vertices.foreach_get("normal", Nn); Nn = Nn.reshape(-1, 3)
866
+ band = (Vn[:, 2] > zc) & (Vn[:, 2] < ftop)
867
+ c = Vn[band].mean(0); r = np.maximum((Vn[band].max(0) - Vn[band].min(0)) / 2, 1e-3)
868
+ ne = (Vn - c) / (r * r); ne /= np.maximum(np.linalg.norm(ne, axis=1, keepdims=True), 1e-9)
869
+ tt = np.clip((Vn[:, 2] - zc) / (0.03 * H), 0, 1) * np.clip((ftop - Vn[:, 2]) / (0.05 * H), 0, 1)
870
+ wf = tt * np.clip((-Nn[:, 1] + 0.2) / 0.5, 0, 1) * a.smooth_face
871
+ nn = Nn * (1 - wf[:, None]) + ne * wf[:, None]
872
+ nn /= np.maximum(np.linalg.norm(nn, axis=1, keepdims=True), 1e-9)
873
+ for poly in low.data.polygons:
874
+ poly.use_smooth = True
875
+ low.data.normals_split_custom_set_from_vertices([tuple(x) for x in nn])
876
+ log(f"face normals smoothed toward the head ellipsoid on {(wf > 0.05).sum()} verts")
877
+ low.data.name = low.name = os.path.splitext(os.path.basename(a.out))[0]
878
+ for o in bpy.context.scene.objects:
879
+ o.select_set(o == low)
880
+ bpy.context.view_layer.objects.active = low
881
+ # the neck cut rides along as a node extra (glTF extras.neckCut, fraction of the height): the game's rig pivots the head
882
+ # there (campPeopleModels.ts). Its own search — the narrowest cross-section near the procedural neck — found a new
883
+ # head's face narrower than the neck and bent the face across the eyes whenever the head turned (a crease under the brows)
884
+ low["neckCut"] = round(float((zc - zmin) / H), 4)
885
+ bpy.ops.export_scene.gltf(filepath=a.out, export_format="GLB", use_selection=True, export_image_format="AUTO",
886
+ export_yup=True, export_apply=True, export_extras=True,
887
+ export_tangents=a.normal_map)
888
+ json.dump({"tris": ntris(low), "verts": len(low.data.vertices), "neck_cut": round(float((zc - zmin) / H), 4),
889
+ "head_share": round(float(ha / max(ta, 1e-9)), 3), "height": round(float(H), 3)}, open(a.out + ".json", "w"), indent=1)
890
+ log(f"{a.out}: {ntris(low)} tris, {len(low.data.vertices)} verts")
891
+
892
+ if a.front:
893
+ # an unlit ortho render of the head from the front, with a z grid every 1 % of H (for tuning the paint)
894
+ sc.render.engine = "BLENDER_EEVEE"
895
+ sc.render.resolution_x = sc.render.resolution_y = 768
896
+ world = bpy.data.worlds.new("w"); sc.world = world; world.use_nodes = True
897
+ world.node_tree.nodes["Background"].inputs[0].default_value = (0.5, 0.5, 0.5, 1)
898
+ em = nt.nodes.new("ShaderNodeEmission"); nt.links.new(tex.outputs["Color"], em.inputs["Color"])
899
+ nt.links.new(em.outputs["Emission"], nt.nodes["Material Output"].inputs["Surface"])
900
+ sc.view_settings.view_transform = "Standard"
901
+ cam = bpy.data.objects.new("cam", bpy.data.cameras.new("cam"))
902
+ cam.data.type = "ORTHO"; cam.data.ortho_scale = (zmax - zc) * 1.5
903
+ sc.collection.objects.link(cam); sc.camera = cam
904
+ mid = zc + (zmax - zc) * 0.45
905
+ cam.location = (hc[0], hc[1] - 3, mid); cam.rotation_euler = (math.pi / 2, 0, 0)
906
+ sc.render.filepath = a.front
907
+ bpy.ops.render.render(write_still=True)
908
+ json.dump({"z_bottom": float((mid - cam.data.ortho_scale / 2 - zmin) / H), "z_top": float((mid + cam.data.ortho_scale / 2 - zmin) / H),
909
+ "x0": float(hc[0] - cam.data.ortho_scale / 2), "scale": float(cam.data.ortho_scale), "H": float(H)},
910
+ open(a.front + ".json", "w"), indent=1)
911
+ log(f"front render {a.front}: rows span z {(mid - cam.data.ortho_scale / 2 - zmin) / H:.3f}..{(mid + cam.data.ortho_scale / 2 - zmin) / H:.3f} H")