diffneusim 1.0.0__py3-none-any.whl

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 (682) hide show
  1. diffneusim/__init__.py +1 -0
  2. diffneusim/_cache.py +42 -0
  3. diffneusim/_paths.py +5 -0
  4. diffneusim/bindings/rew14_ext.cu +115 -0
  5. diffneusim/bindings/soft14_capi.cpp +443 -0
  6. diffneusim/bindings/soft14_engine_ext.cu +596 -0
  7. diffneusim/bindings/soft_capi.cpp +782 -0
  8. diffneusim/bindings/soft_engine_ext.cu +495 -0
  9. diffneusim/core/cpu_engine/build.sh +40 -0
  10. diffneusim/core/cpu_engine/fiber/cuda_runtime.h +445 -0
  11. diffneusim/core/cpu_engine/x14_cpu.cpp +283 -0
  12. diffneusim/core/diff/dual.h +126 -0
  13. diffneusim/core/include/diffneusim/macros.h +35 -0
  14. diffneusim/core/kin/kinematic_tree.h +273 -0
  15. diffneusim/core/math/so3.h +182 -0
  16. diffneusim/core/soft/adj/out_adj.h +102 -0
  17. diffneusim/core/soft/adj/rnea_adj.h +425 -0
  18. diffneusim/core/soft/adj/rows_adj.h +439 -0
  19. diffneusim/core/soft/adj/rows_functor.h +89 -0
  20. diffneusim/core/soft/adj/rows_lanes.h +443 -0
  21. diffneusim/core/soft/adj/shell_adj.h +243 -0
  22. diffneusim/core/soft/adj/tree_adj.h +356 -0
  23. diffneusim/core/soft/collide.h +183 -0
  24. diffneusim/core/soft/gpu/adj14.cuh +233 -0
  25. diffneusim/core/soft/gpu/adj14_mus.cuh +98 -0
  26. diffneusim/core/soft/gpu/adj_shell.cuh +50 -0
  27. diffneusim/core/soft/gpu/adj_tab.cuh +49 -0
  28. diffneusim/core/soft/gpu/body14.cuh +47 -0
  29. diffneusim/core/soft/gpu/chol_rn.cuh +458 -0
  30. diffneusim/core/soft/gpu/chol_small.cuh +123 -0
  31. diffneusim/core/soft/gpu/chol_split.cuh +193 -0
  32. diffneusim/core/soft/gpu/engine_launch.cuh +263 -0
  33. diffneusim/core/soft/gpu/fk_rn.cuh +109 -0
  34. diffneusim/core/soft/gpu/generated/body_019e20820f86_mmfloor.cuh +28 -0
  35. diffneusim/core/soft/gpu/generated/body_62f77a4bb16b_mmfloor.cuh +52 -0
  36. diffneusim/core/soft/gpu/generated/body_77dbb7213f26_mmfloor_rampsb3l_n6t12.cuh +28 -0
  37. diffneusim/core/soft/gpu/generated/body_8989b60e4486_mmfloor_rampsb3l_n6t12.cuh +28 -0
  38. diffneusim/core/soft/gpu/generated/body_8989b60e4486_mmfloor_rhlsd05_n6t12.cuh +28 -0
  39. diffneusim/core/soft/gpu/generated/body_8989b60e4486_mmfloor_rhlsdef_n6t12.cuh +28 -0
  40. diffneusim/core/soft/gpu/generated/body_8989b60e4486_mmfloor_rhlsmjd_n6t12.cuh +28 -0
  41. diffneusim/core/soft/gpu/generated/body_a1e8b196b2cd_mmfloor_rampsb3l_n6t12.cuh +52 -0
  42. diffneusim/core/soft/gpu/generated/body_a944653edd64_mmfloor.cuh +25 -0
  43. diffneusim/core/soft/gpu/generated/body_a944653edd64_mmfloor_rampsb3l_n6t12.cuh +25 -0
  44. diffneusim/core/soft/gpu/generated/g1_soft_5db44fd45286.cuh +74 -0
  45. diffneusim/core/soft/gpu/generated/split_62f77a4bb16b_mmfloor.cuh +18 -0
  46. diffneusim/core/soft/gpu/generated/split_a1e8b196b2cd_mmfloor_rampsb3l_n6t12.cuh +18 -0
  47. diffneusim/core/soft/gpu/generated/x14_soft_019e20820f86_mmfloor.cuh +123 -0
  48. diffneusim/core/soft/gpu/generated/x14_soft_62f77a4bb16b_mmfloor.cuh +129 -0
  49. diffneusim/core/soft/gpu/generated/x14_soft_77dbb7213f26_mmfloor_rampsb3l_n6t12.cuh +123 -0
  50. diffneusim/core/soft/gpu/generated/x14_soft_8989b60e4486_mmfloor_rampsb3l_n6t12.cuh +123 -0
  51. diffneusim/core/soft/gpu/generated/x14_soft_8989b60e4486_mmfloor_rhlsd05_n6t12.cuh +123 -0
  52. diffneusim/core/soft/gpu/generated/x14_soft_8989b60e4486_mmfloor_rhlsdef_n6t12.cuh +123 -0
  53. diffneusim/core/soft/gpu/generated/x14_soft_8989b60e4486_mmfloor_rhlsmjd_n6t12.cuh +123 -0
  54. diffneusim/core/soft/gpu/generated/x14_soft_a1e8b196b2cd_mmfloor_rampsb3l_n6t12.cuh +129 -0
  55. diffneusim/core/soft/gpu/generated/x14_soft_a944653edd64_mmfloor.cuh +123 -0
  56. diffneusim/core/soft/gpu/generated/x14_soft_a944653edd64_mmfloor_rampsb3l_n6t12.cuh +123 -0
  57. diffneusim/core/soft/gpu/k_mus.cuh +1038 -0
  58. diffneusim/core/soft/gpu/k_mus_host.cuh +377 -0
  59. diffneusim/core/soft/gpu/k_pre.cuh +52 -0
  60. diffneusim/core/soft/gpu/kernel_p.cuh +490 -0
  61. diffneusim/core/soft/gpu/kp14.cuh +465 -0
  62. diffneusim/core/soft/gpu/l2v2.cuh +367 -0
  63. diffneusim/core/soft/gpu/l2x14.cuh +319 -0
  64. diffneusim/core/soft/gpu/l3.cuh +1483 -0
  65. diffneusim/core/soft/gpu/model_view.cuh +48 -0
  66. diffneusim/core/soft/gpu/mus_case_fits.h +15 -0
  67. diffneusim/core/soft/gpu/mus_classes.h +182 -0
  68. diffneusim/core/soft/gpu/mus_row_cf.h +44 -0
  69. diffneusim/core/soft/gpu/rew14.cuh +177 -0
  70. diffneusim/core/soft/gpu/rows_ctab.cuh +44 -0
  71. diffneusim/core/soft/gpu/tree_m.cuh +247 -0
  72. diffneusim/core/soft/gpu/x14_engine_kernels.cuh +260 -0
  73. diffneusim/core/soft/gpu/x14_rowcf.h +14 -0
  74. diffneusim/core/soft/hand.h +124 -0
  75. diffneusim/core/soft/impedance.h +115 -0
  76. diffneusim/core/soft/jvp.h +202 -0
  77. diffneusim/core/soft/kin.h +250 -0
  78. diffneusim/core/soft/muscle.h +1208 -0
  79. diffneusim/core/soft/newton.h +371 -0
  80. diffneusim/core/soft/rows.h +176 -0
  81. diffneusim/core/soft/step.h +188 -0
  82. diffneusim/core/soft/tape.h +313 -0
  83. diffneusim/core/soft/x14/collide14.h +69 -0
  84. diffneusim/core/soft/x14/jvp14.h +182 -0
  85. diffneusim/core/soft/x14/law14.h +453 -0
  86. diffneusim/core/soft/x14adj/collide14_adj.h +134 -0
  87. diffneusim/core/soft/x14adj/passive14_adj.h +162 -0
  88. diffneusim/core/soft/x14adj/reward14.h +484 -0
  89. diffneusim/core/soft/x14adj/rows14_adj.h +400 -0
  90. diffneusim/core/soft/x14adj/scan14.h +349 -0
  91. diffneusim/core/soft/x14adj/shell14_adj.h +122 -0
  92. diffneusim/core/soft/x14adj/sweep14.h +255 -0
  93. diffneusim/core/soft/x14adj/tree14_adj.h +500 -0
  94. diffneusim/core/soft/x14adj/x14adj_common.h +96 -0
  95. diffneusim/data/mirror/H1622v2k_geyer_hfdeq.npz +0 -0
  96. diffneusim/data/mirror/H1622v2k_hfd.npz +0 -0
  97. diffneusim/data/mirror/H1622v2k_millard_hfdeq.npz +0 -0
  98. diffneusim/data/mirror/fullbody_contact.npz +0 -0
  99. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_millard.npz +0 -0
  100. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_p2str.npz +0 -0
  101. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_p2str_rigid.npz +0 -0
  102. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src.npz +0 -0
  103. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_rigid.npz +0 -0
  104. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq.npz +0 -0
  105. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin.npz +0 -0
  106. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_calf2_pe.npz +0 -0
  107. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc.npz +0 -0
  108. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_axfix.npz +0 -0
  109. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_axfixlegs01.npz +0 -0
  110. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_jd01.npz +0 -0
  111. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_jd01legs.npz +0 -0
  112. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_jd01lumbar.npz +0 -0
  113. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_lumbfix.npz +0 -0
  114. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_lumbfixlegs01.npz +0 -0
  115. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1.npz +0 -0
  116. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1a.npz +0 -0
  117. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n2.npz +0 -0
  118. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_rom23.npz +0 -0
  119. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair.npz +0 -0
  120. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc.npz +0 -0
  121. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_hinge.npz +0 -0
  122. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1.npz +0 -0
  123. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1a.npz +0 -0
  124. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n2.npz +0 -0
  125. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_rom23.npz +0 -0
  126. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_lspine_girdle_osimeq.npz +0 -0
  127. diffneusim/data/mirror/fullbody_contact_spinecoupled_lspine_girdle_millard.npz +0 -0
  128. diffneusim/data/mirror/fullbody_contact_spinecoupled_lspine_girdle_osimeq.npz +0 -0
  129. diffneusim/data/mirror/myoleg26_3d_compound_g14eq.npz +0 -0
  130. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq.npz +0 -0
  131. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose.npz +0 -0
  132. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose_spin.npz +0 -0
  133. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose_spin_ank30.npz +0 -0
  134. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose_spin_ank30_hip30.npz +0 -0
  135. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose_spin_ank30_hip30_luispe.npz +0 -0
  136. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose_spin_ank30_hip30_trunk0701.npz +0 -0
  137. diffneusim/data/muscle_fit/wang_mass_volume_14t.json +91 -0
  138. diffneusim/data/muscle_fit/wang_mass_volume_14t_axfix.json +91 -0
  139. diffneusim/data/muscle_fit/wang_mass_volume_14t_axfixlegs01.json +91 -0
  140. diffneusim/data/muscle_fit/wang_mass_volume_14t_jd01.json +91 -0
  141. diffneusim/data/muscle_fit/wang_mass_volume_14t_jd01legs.json +91 -0
  142. diffneusim/data/muscle_fit/wang_mass_volume_14t_jd01lumbar.json +91 -0
  143. diffneusim/data/muscle_fit/wang_mass_volume_14t_lumbfix.json +91 -0
  144. diffneusim/data/muscle_fit/wang_mass_volume_14t_lumbfixlegs01.json +91 -0
  145. diffneusim/data/muscle_fit/wang_mass_volume_14t_n1.json +91 -0
  146. diffneusim/data/muscle_fit/wang_mass_volume_14t_n1a.json +91 -0
  147. diffneusim/data/muscle_fit/wang_mass_volume_14t_n2.json +91 -0
  148. diffneusim/data/muscle_fit/wang_mass_volume_14t_rom23.json +91 -0
  149. diffneusim/data/reference/musclemimic/myofullbody_mimic_sites.json +261 -0
  150. diffneusim/data/reference/pose3/pose3_scone.json +305 -0
  151. diffneusim/data/reference/pose3/pose3_scone.txt +3 -0
  152. diffneusim/data/reference/pose3/pose3_scone_gait.npz +0 -0
  153. diffneusim/data/reference/pose3/pose3_scone_mirror.npz +0 -0
  154. diffneusim/data/reference/pose3/pose3_scone_stand.npz +0 -0
  155. diffneusim/data/reference/x016run/MD5SUMS +241 -0
  156. diffneusim/data/reference/x016run/x016run_states.txt +240 -0
  157. diffneusim/data/reference/x016run/x016run_v3p00_s0_l0.npz +0 -0
  158. diffneusim/data/reference/x016run/x016run_v3p00_s0_l1.npz +0 -0
  159. diffneusim/data/reference/x016run/x016run_v3p00_s0_l2.npz +0 -0
  160. diffneusim/data/reference/x016run/x016run_v3p00_s0_l3.npz +0 -0
  161. diffneusim/data/reference/x016run/x016run_v3p00_s0_r0.npz +0 -0
  162. diffneusim/data/reference/x016run/x016run_v3p00_s0_r1.npz +0 -0
  163. diffneusim/data/reference/x016run/x016run_v3p00_s0_r2.npz +0 -0
  164. diffneusim/data/reference/x016run/x016run_v3p00_s0_r3.npz +0 -0
  165. diffneusim/data/reference/x016run/x016run_v3p00_s1_l0.npz +0 -0
  166. diffneusim/data/reference/x016run/x016run_v3p00_s1_l1.npz +0 -0
  167. diffneusim/data/reference/x016run/x016run_v3p00_s1_l2.npz +0 -0
  168. diffneusim/data/reference/x016run/x016run_v3p00_s1_l3.npz +0 -0
  169. diffneusim/data/reference/x016run/x016run_v3p00_s1_r0.npz +0 -0
  170. diffneusim/data/reference/x016run/x016run_v3p00_s1_r1.npz +0 -0
  171. diffneusim/data/reference/x016run/x016run_v3p00_s1_r2.npz +0 -0
  172. diffneusim/data/reference/x016run/x016run_v3p00_s1_r3.npz +0 -0
  173. diffneusim/data/reference/x016run/x016run_v3p00_s2_l0.npz +0 -0
  174. diffneusim/data/reference/x016run/x016run_v3p00_s2_l1.npz +0 -0
  175. diffneusim/data/reference/x016run/x016run_v3p00_s2_l2.npz +0 -0
  176. diffneusim/data/reference/x016run/x016run_v3p00_s2_l3.npz +0 -0
  177. diffneusim/data/reference/x016run/x016run_v3p00_s2_r0.npz +0 -0
  178. diffneusim/data/reference/x016run/x016run_v3p00_s2_r1.npz +0 -0
  179. diffneusim/data/reference/x016run/x016run_v3p00_s2_r2.npz +0 -0
  180. diffneusim/data/reference/x016run/x016run_v3p00_s2_r3.npz +0 -0
  181. diffneusim/data/reference/x016run/x016run_v3p00_s3_l0.npz +0 -0
  182. diffneusim/data/reference/x016run/x016run_v3p00_s3_l1.npz +0 -0
  183. diffneusim/data/reference/x016run/x016run_v3p00_s3_l2.npz +0 -0
  184. diffneusim/data/reference/x016run/x016run_v3p00_s3_l3.npz +0 -0
  185. diffneusim/data/reference/x016run/x016run_v3p00_s3_r0.npz +0 -0
  186. diffneusim/data/reference/x016run/x016run_v3p00_s3_r1.npz +0 -0
  187. diffneusim/data/reference/x016run/x016run_v3p00_s3_r2.npz +0 -0
  188. diffneusim/data/reference/x016run/x016run_v3p00_s3_r3.npz +0 -0
  189. diffneusim/data/reference/x016run/x016run_v3p00_s4_l0.npz +0 -0
  190. diffneusim/data/reference/x016run/x016run_v3p00_s4_l1.npz +0 -0
  191. diffneusim/data/reference/x016run/x016run_v3p00_s4_l2.npz +0 -0
  192. diffneusim/data/reference/x016run/x016run_v3p00_s4_l3.npz +0 -0
  193. diffneusim/data/reference/x016run/x016run_v3p00_s4_r0.npz +0 -0
  194. diffneusim/data/reference/x016run/x016run_v3p00_s4_r1.npz +0 -0
  195. diffneusim/data/reference/x016run/x016run_v3p00_s4_r2.npz +0 -0
  196. diffneusim/data/reference/x016run/x016run_v3p00_s4_r3.npz +0 -0
  197. diffneusim/data/reference/x016run/x016run_v3p00_s5_l0.npz +0 -0
  198. diffneusim/data/reference/x016run/x016run_v3p00_s5_l1.npz +0 -0
  199. diffneusim/data/reference/x016run/x016run_v3p00_s5_l2.npz +0 -0
  200. diffneusim/data/reference/x016run/x016run_v3p00_s5_l3.npz +0 -0
  201. diffneusim/data/reference/x016run/x016run_v3p00_s5_r0.npz +0 -0
  202. diffneusim/data/reference/x016run/x016run_v3p00_s5_r1.npz +0 -0
  203. diffneusim/data/reference/x016run/x016run_v3p00_s5_r2.npz +0 -0
  204. diffneusim/data/reference/x016run/x016run_v3p00_s5_r3.npz +0 -0
  205. diffneusim/data/reference/x016run/x016run_v3p00_s6_l0.npz +0 -0
  206. diffneusim/data/reference/x016run/x016run_v3p00_s6_l1.npz +0 -0
  207. diffneusim/data/reference/x016run/x016run_v3p00_s6_l2.npz +0 -0
  208. diffneusim/data/reference/x016run/x016run_v3p00_s6_l3.npz +0 -0
  209. diffneusim/data/reference/x016run/x016run_v3p00_s6_r0.npz +0 -0
  210. diffneusim/data/reference/x016run/x016run_v3p00_s6_r1.npz +0 -0
  211. diffneusim/data/reference/x016run/x016run_v3p00_s6_r2.npz +0 -0
  212. diffneusim/data/reference/x016run/x016run_v3p00_s6_r3.npz +0 -0
  213. diffneusim/data/reference/x016run/x016run_v3p00_s7_l0.npz +0 -0
  214. diffneusim/data/reference/x016run/x016run_v3p00_s7_l1.npz +0 -0
  215. diffneusim/data/reference/x016run/x016run_v3p00_s7_l2.npz +0 -0
  216. diffneusim/data/reference/x016run/x016run_v3p00_s7_l3.npz +0 -0
  217. diffneusim/data/reference/x016run/x016run_v3p00_s7_r0.npz +0 -0
  218. diffneusim/data/reference/x016run/x016run_v3p00_s7_r1.npz +0 -0
  219. diffneusim/data/reference/x016run/x016run_v3p00_s7_r2.npz +0 -0
  220. diffneusim/data/reference/x016run/x016run_v3p00_s7_r3.npz +0 -0
  221. diffneusim/data/reference/x016run/x016run_v3p25_s0_l0.npz +0 -0
  222. diffneusim/data/reference/x016run/x016run_v3p25_s0_l1.npz +0 -0
  223. diffneusim/data/reference/x016run/x016run_v3p25_s0_l2.npz +0 -0
  224. diffneusim/data/reference/x016run/x016run_v3p25_s0_l3.npz +0 -0
  225. diffneusim/data/reference/x016run/x016run_v3p25_s0_r0.npz +0 -0
  226. diffneusim/data/reference/x016run/x016run_v3p25_s0_r1.npz +0 -0
  227. diffneusim/data/reference/x016run/x016run_v3p25_s0_r2.npz +0 -0
  228. diffneusim/data/reference/x016run/x016run_v3p25_s0_r3.npz +0 -0
  229. diffneusim/data/reference/x016run/x016run_v3p25_s1_l0.npz +0 -0
  230. diffneusim/data/reference/x016run/x016run_v3p25_s1_l1.npz +0 -0
  231. diffneusim/data/reference/x016run/x016run_v3p25_s1_l2.npz +0 -0
  232. diffneusim/data/reference/x016run/x016run_v3p25_s1_l3.npz +0 -0
  233. diffneusim/data/reference/x016run/x016run_v3p25_s1_r0.npz +0 -0
  234. diffneusim/data/reference/x016run/x016run_v3p25_s1_r1.npz +0 -0
  235. diffneusim/data/reference/x016run/x016run_v3p25_s1_r2.npz +0 -0
  236. diffneusim/data/reference/x016run/x016run_v3p25_s1_r3.npz +0 -0
  237. diffneusim/data/reference/x016run/x016run_v3p25_s2_l0.npz +0 -0
  238. diffneusim/data/reference/x016run/x016run_v3p25_s2_l1.npz +0 -0
  239. diffneusim/data/reference/x016run/x016run_v3p25_s2_l2.npz +0 -0
  240. diffneusim/data/reference/x016run/x016run_v3p25_s2_l3.npz +0 -0
  241. diffneusim/data/reference/x016run/x016run_v3p25_s2_r0.npz +0 -0
  242. diffneusim/data/reference/x016run/x016run_v3p25_s2_r1.npz +0 -0
  243. diffneusim/data/reference/x016run/x016run_v3p25_s2_r2.npz +0 -0
  244. diffneusim/data/reference/x016run/x016run_v3p25_s2_r3.npz +0 -0
  245. diffneusim/data/reference/x016run/x016run_v3p25_s3_l0.npz +0 -0
  246. diffneusim/data/reference/x016run/x016run_v3p25_s3_l1.npz +0 -0
  247. diffneusim/data/reference/x016run/x016run_v3p25_s3_l2.npz +0 -0
  248. diffneusim/data/reference/x016run/x016run_v3p25_s3_l3.npz +0 -0
  249. diffneusim/data/reference/x016run/x016run_v3p25_s3_r0.npz +0 -0
  250. diffneusim/data/reference/x016run/x016run_v3p25_s3_r1.npz +0 -0
  251. diffneusim/data/reference/x016run/x016run_v3p25_s3_r2.npz +0 -0
  252. diffneusim/data/reference/x016run/x016run_v3p25_s3_r3.npz +0 -0
  253. diffneusim/data/reference/x016run/x016run_v3p25_s4_l0.npz +0 -0
  254. diffneusim/data/reference/x016run/x016run_v3p25_s4_l1.npz +0 -0
  255. diffneusim/data/reference/x016run/x016run_v3p25_s4_l2.npz +0 -0
  256. diffneusim/data/reference/x016run/x016run_v3p25_s4_l3.npz +0 -0
  257. diffneusim/data/reference/x016run/x016run_v3p25_s4_r0.npz +0 -0
  258. diffneusim/data/reference/x016run/x016run_v3p25_s4_r1.npz +0 -0
  259. diffneusim/data/reference/x016run/x016run_v3p25_s4_r2.npz +0 -0
  260. diffneusim/data/reference/x016run/x016run_v3p25_s4_r3.npz +0 -0
  261. diffneusim/data/reference/x016run/x016run_v3p25_s5_l0.npz +0 -0
  262. diffneusim/data/reference/x016run/x016run_v3p25_s5_l1.npz +0 -0
  263. diffneusim/data/reference/x016run/x016run_v3p25_s5_l2.npz +0 -0
  264. diffneusim/data/reference/x016run/x016run_v3p25_s5_l3.npz +0 -0
  265. diffneusim/data/reference/x016run/x016run_v3p25_s5_r0.npz +0 -0
  266. diffneusim/data/reference/x016run/x016run_v3p25_s5_r1.npz +0 -0
  267. diffneusim/data/reference/x016run/x016run_v3p25_s5_r2.npz +0 -0
  268. diffneusim/data/reference/x016run/x016run_v3p25_s5_r3.npz +0 -0
  269. diffneusim/data/reference/x016run/x016run_v3p25_s6_l0.npz +0 -0
  270. diffneusim/data/reference/x016run/x016run_v3p25_s6_l1.npz +0 -0
  271. diffneusim/data/reference/x016run/x016run_v3p25_s6_l2.npz +0 -0
  272. diffneusim/data/reference/x016run/x016run_v3p25_s6_l3.npz +0 -0
  273. diffneusim/data/reference/x016run/x016run_v3p25_s6_r0.npz +0 -0
  274. diffneusim/data/reference/x016run/x016run_v3p25_s6_r1.npz +0 -0
  275. diffneusim/data/reference/x016run/x016run_v3p25_s6_r2.npz +0 -0
  276. diffneusim/data/reference/x016run/x016run_v3p25_s6_r3.npz +0 -0
  277. diffneusim/data/reference/x016run/x016run_v3p25_s7_l0.npz +0 -0
  278. diffneusim/data/reference/x016run/x016run_v3p25_s7_l1.npz +0 -0
  279. diffneusim/data/reference/x016run/x016run_v3p25_s7_l2.npz +0 -0
  280. diffneusim/data/reference/x016run/x016run_v3p25_s7_l3.npz +0 -0
  281. diffneusim/data/reference/x016run/x016run_v3p25_s7_r0.npz +0 -0
  282. diffneusim/data/reference/x016run/x016run_v3p25_s7_r1.npz +0 -0
  283. diffneusim/data/reference/x016run/x016run_v3p25_s7_r2.npz +0 -0
  284. diffneusim/data/reference/x016run/x016run_v3p25_s7_r3.npz +0 -0
  285. diffneusim/data/reference/x016run/x016run_v3p50_s0_l0.npz +0 -0
  286. diffneusim/data/reference/x016run/x016run_v3p50_s0_l1.npz +0 -0
  287. diffneusim/data/reference/x016run/x016run_v3p50_s0_l2.npz +0 -0
  288. diffneusim/data/reference/x016run/x016run_v3p50_s0_l3.npz +0 -0
  289. diffneusim/data/reference/x016run/x016run_v3p50_s0_r0.npz +0 -0
  290. diffneusim/data/reference/x016run/x016run_v3p50_s0_r1.npz +0 -0
  291. diffneusim/data/reference/x016run/x016run_v3p50_s0_r2.npz +0 -0
  292. diffneusim/data/reference/x016run/x016run_v3p50_s0_r3.npz +0 -0
  293. diffneusim/data/reference/x016run/x016run_v3p50_s1_l0.npz +0 -0
  294. diffneusim/data/reference/x016run/x016run_v3p50_s1_l1.npz +0 -0
  295. diffneusim/data/reference/x016run/x016run_v3p50_s1_l2.npz +0 -0
  296. diffneusim/data/reference/x016run/x016run_v3p50_s1_l3.npz +0 -0
  297. diffneusim/data/reference/x016run/x016run_v3p50_s1_r0.npz +0 -0
  298. diffneusim/data/reference/x016run/x016run_v3p50_s1_r1.npz +0 -0
  299. diffneusim/data/reference/x016run/x016run_v3p50_s1_r2.npz +0 -0
  300. diffneusim/data/reference/x016run/x016run_v3p50_s1_r3.npz +0 -0
  301. diffneusim/data/reference/x016run/x016run_v3p50_s2_l0.npz +0 -0
  302. diffneusim/data/reference/x016run/x016run_v3p50_s2_l1.npz +0 -0
  303. diffneusim/data/reference/x016run/x016run_v3p50_s2_l2.npz +0 -0
  304. diffneusim/data/reference/x016run/x016run_v3p50_s2_l3.npz +0 -0
  305. diffneusim/data/reference/x016run/x016run_v3p50_s2_r0.npz +0 -0
  306. diffneusim/data/reference/x016run/x016run_v3p50_s2_r1.npz +0 -0
  307. diffneusim/data/reference/x016run/x016run_v3p50_s2_r2.npz +0 -0
  308. diffneusim/data/reference/x016run/x016run_v3p50_s2_r3.npz +0 -0
  309. diffneusim/data/reference/x016run/x016run_v3p50_s3_l0.npz +0 -0
  310. diffneusim/data/reference/x016run/x016run_v3p50_s3_l1.npz +0 -0
  311. diffneusim/data/reference/x016run/x016run_v3p50_s3_l2.npz +0 -0
  312. diffneusim/data/reference/x016run/x016run_v3p50_s3_l3.npz +0 -0
  313. diffneusim/data/reference/x016run/x016run_v3p50_s3_r0.npz +0 -0
  314. diffneusim/data/reference/x016run/x016run_v3p50_s3_r1.npz +0 -0
  315. diffneusim/data/reference/x016run/x016run_v3p50_s3_r2.npz +0 -0
  316. diffneusim/data/reference/x016run/x016run_v3p50_s3_r3.npz +0 -0
  317. diffneusim/data/reference/x016run/x016run_v3p50_s5_l0.npz +0 -0
  318. diffneusim/data/reference/x016run/x016run_v3p50_s5_l1.npz +0 -0
  319. diffneusim/data/reference/x016run/x016run_v3p50_s5_l2.npz +0 -0
  320. diffneusim/data/reference/x016run/x016run_v3p50_s5_l3.npz +0 -0
  321. diffneusim/data/reference/x016run/x016run_v3p50_s5_r0.npz +0 -0
  322. diffneusim/data/reference/x016run/x016run_v3p50_s5_r1.npz +0 -0
  323. diffneusim/data/reference/x016run/x016run_v3p50_s5_r2.npz +0 -0
  324. diffneusim/data/reference/x016run/x016run_v3p50_s5_r3.npz +0 -0
  325. diffneusim/data/reference/x016run/x016run_v3p50_s6_l0.npz +0 -0
  326. diffneusim/data/reference/x016run/x016run_v3p50_s6_l1.npz +0 -0
  327. diffneusim/data/reference/x016run/x016run_v3p50_s6_l2.npz +0 -0
  328. diffneusim/data/reference/x016run/x016run_v3p50_s6_l3.npz +0 -0
  329. diffneusim/data/reference/x016run/x016run_v3p50_s6_r0.npz +0 -0
  330. diffneusim/data/reference/x016run/x016run_v3p50_s6_r1.npz +0 -0
  331. diffneusim/data/reference/x016run/x016run_v3p50_s6_r2.npz +0 -0
  332. diffneusim/data/reference/x016run/x016run_v3p50_s6_r3.npz +0 -0
  333. diffneusim/data/reference/x016run/x016run_v3p50_s7_l0.npz +0 -0
  334. diffneusim/data/reference/x016run/x016run_v3p50_s7_l1.npz +0 -0
  335. diffneusim/data/reference/x016run/x016run_v3p50_s7_l2.npz +0 -0
  336. diffneusim/data/reference/x016run/x016run_v3p50_s7_l3.npz +0 -0
  337. diffneusim/data/reference/x016run/x016run_v3p50_s7_r0.npz +0 -0
  338. diffneusim/data/reference/x016run/x016run_v3p50_s7_r1.npz +0 -0
  339. diffneusim/data/reference/x016run/x016run_v3p50_s7_r2.npz +0 -0
  340. diffneusim/data/reference/x016run/x016run_v3p50_s7_r3.npz +0 -0
  341. diffneusim/data/reference/x016run/x016run_v3p75_s0_l0.npz +0 -0
  342. diffneusim/data/reference/x016run/x016run_v3p75_s0_l1.npz +0 -0
  343. diffneusim/data/reference/x016run/x016run_v3p75_s0_l2.npz +0 -0
  344. diffneusim/data/reference/x016run/x016run_v3p75_s0_l3.npz +0 -0
  345. diffneusim/data/reference/x016run/x016run_v3p75_s0_r0.npz +0 -0
  346. diffneusim/data/reference/x016run/x016run_v3p75_s0_r1.npz +0 -0
  347. diffneusim/data/reference/x016run/x016run_v3p75_s0_r2.npz +0 -0
  348. diffneusim/data/reference/x016run/x016run_v3p75_s0_r3.npz +0 -0
  349. diffneusim/data/reference/x016run/x016run_v3p75_s1_l0.npz +0 -0
  350. diffneusim/data/reference/x016run/x016run_v3p75_s1_l1.npz +0 -0
  351. diffneusim/data/reference/x016run/x016run_v3p75_s1_l2.npz +0 -0
  352. diffneusim/data/reference/x016run/x016run_v3p75_s1_l3.npz +0 -0
  353. diffneusim/data/reference/x016run/x016run_v3p75_s1_r0.npz +0 -0
  354. diffneusim/data/reference/x016run/x016run_v3p75_s1_r1.npz +0 -0
  355. diffneusim/data/reference/x016run/x016run_v3p75_s1_r2.npz +0 -0
  356. diffneusim/data/reference/x016run/x016run_v3p75_s1_r3.npz +0 -0
  357. diffneusim/data/reference/x016run/x016run_v3p75_s2_l0.npz +0 -0
  358. diffneusim/data/reference/x016run/x016run_v3p75_s2_l1.npz +0 -0
  359. diffneusim/data/reference/x016run/x016run_v3p75_s2_l2.npz +0 -0
  360. diffneusim/data/reference/x016run/x016run_v3p75_s2_l3.npz +0 -0
  361. diffneusim/data/reference/x016run/x016run_v3p75_s2_r0.npz +0 -0
  362. diffneusim/data/reference/x016run/x016run_v3p75_s2_r1.npz +0 -0
  363. diffneusim/data/reference/x016run/x016run_v3p75_s2_r2.npz +0 -0
  364. diffneusim/data/reference/x016run/x016run_v3p75_s2_r3.npz +0 -0
  365. diffneusim/data/reference/x016run/x016run_v3p75_s3_l0.npz +0 -0
  366. diffneusim/data/reference/x016run/x016run_v3p75_s3_l1.npz +0 -0
  367. diffneusim/data/reference/x016run/x016run_v3p75_s3_l2.npz +0 -0
  368. diffneusim/data/reference/x016run/x016run_v3p75_s3_l3.npz +0 -0
  369. diffneusim/data/reference/x016run/x016run_v3p75_s3_r0.npz +0 -0
  370. diffneusim/data/reference/x016run/x016run_v3p75_s3_r1.npz +0 -0
  371. diffneusim/data/reference/x016run/x016run_v3p75_s3_r2.npz +0 -0
  372. diffneusim/data/reference/x016run/x016run_v3p75_s3_r3.npz +0 -0
  373. diffneusim/data/reference/x016run/x016run_v3p75_s5_l0.npz +0 -0
  374. diffneusim/data/reference/x016run/x016run_v3p75_s5_l1.npz +0 -0
  375. diffneusim/data/reference/x016run/x016run_v3p75_s5_l2.npz +0 -0
  376. diffneusim/data/reference/x016run/x016run_v3p75_s5_l3.npz +0 -0
  377. diffneusim/data/reference/x016run/x016run_v3p75_s5_r0.npz +0 -0
  378. diffneusim/data/reference/x016run/x016run_v3p75_s5_r1.npz +0 -0
  379. diffneusim/data/reference/x016run/x016run_v3p75_s5_r2.npz +0 -0
  380. diffneusim/data/reference/x016run/x016run_v3p75_s5_r3.npz +0 -0
  381. diffneusim/data/reference/x016run/x016run_v3p75_s6_l0.npz +0 -0
  382. diffneusim/data/reference/x016run/x016run_v3p75_s6_l1.npz +0 -0
  383. diffneusim/data/reference/x016run/x016run_v3p75_s6_l2.npz +0 -0
  384. diffneusim/data/reference/x016run/x016run_v3p75_s6_l3.npz +0 -0
  385. diffneusim/data/reference/x016run/x016run_v3p75_s6_r0.npz +0 -0
  386. diffneusim/data/reference/x016run/x016run_v3p75_s6_r1.npz +0 -0
  387. diffneusim/data/reference/x016run/x016run_v3p75_s6_r2.npz +0 -0
  388. diffneusim/data/reference/x016run/x016run_v3p75_s6_r3.npz +0 -0
  389. diffneusim/data/reference/x016run/x016run_v3p75_s7_l0.npz +0 -0
  390. diffneusim/data/reference/x016run/x016run_v3p75_s7_l1.npz +0 -0
  391. diffneusim/data/reference/x016run/x016run_v3p75_s7_l2.npz +0 -0
  392. diffneusim/data/reference/x016run/x016run_v3p75_s7_l3.npz +0 -0
  393. diffneusim/data/reference/x016run/x016run_v3p75_s7_r0.npz +0 -0
  394. diffneusim/data/reference/x016run/x016run_v3p75_s7_r1.npz +0 -0
  395. diffneusim/data/reference/x016run/x016run_v3p75_s7_r2.npz +0 -0
  396. diffneusim/data/reference/x016run/x016run_v3p75_s7_r3.npz +0 -0
  397. diffneusim/data/state_prior/lumbar_poly_fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc.npz +0 -0
  398. diffneusim/engine/__init__.py +0 -0
  399. diffneusim/engine/build_tag.py +52 -0
  400. diffneusim/engine/case_tables.py +46 -0
  401. diffneusim/engine/d16_body.py +80 -0
  402. diffneusim/engine/engine14.py +367 -0
  403. diffneusim/engine/gen_split.py +159 -0
  404. diffneusim/engine/hand_format.py +69 -0
  405. diffneusim/engine/live14.py +149 -0
  406. diffneusim/engine/phase_b_tree.py +137 -0
  407. diffneusim/engine/soft14.py +130 -0
  408. diffneusim/engine/soft_capi.py +373 -0
  409. diffneusim/engine/soft_engine.py +165 -0
  410. diffneusim/engine/step14.py +132 -0
  411. diffneusim/engine/tape_format.py +89 -0
  412. diffneusim/engine/x14cpu.py +163 -0
  413. diffneusim/env/__init__.py +0 -0
  414. diffneusim/env/absent.py +20 -0
  415. diffneusim/env/cpu14.py +105 -0
  416. diffneusim/env/e0loop14.py +224 -0
  417. diffneusim/env/env14.py +568 -0
  418. diffneusim/env/kin_contact14.py +193 -0
  419. diffneusim/env/mimic_sites_x14.json +366 -0
  420. diffneusim/env/old_count.py +78 -0
  421. diffneusim/env/rew14.py +114 -0
  422. diffneusim/env/rew14_hook.py +105 -0
  423. diffneusim/g1/__init__.py +1 -0
  424. diffneusim/g1/arm_a2.py +165 -0
  425. diffneusim/g1/arm_a3.py +576 -0
  426. diffneusim/g1/read_a3.py +79 -0
  427. diffneusim/g1/rg1_read.py +89 -0
  428. diffneusim/model/__init__.py +66 -0
  429. diffneusim/model/case.py +17 -0
  430. diffneusim/model/dnmodel.py +79 -0
  431. diffneusim/model/fuse_fixed.py +281 -0
  432. diffneusim/model/monitor.py +834 -0
  433. diffneusim/models/BODIES.toml +48 -0
  434. diffneusim/models/MANIFEST.toml +979 -0
  435. diffneusim/models/cases/G290/case.bin +0 -0
  436. diffneusim/models/cases/G290/case.json +1 -0
  437. diffneusim/models/cases/G356-SRC/case.bin +0 -0
  438. diffneusim/models/cases/G356-SRC/case.json +1 -0
  439. diffneusim/models/cases/G416/case.bin +0 -0
  440. diffneusim/models/cases/G416/case.json +1 -0
  441. diffneusim/models/cases/M290C-SRC/case.bin +0 -0
  442. diffneusim/models/cases/M290C-SRC/case.json +1 -0
  443. diffneusim/models/cases/M290R-SRC/case.bin +0 -0
  444. diffneusim/models/cases/M290R-SRC/case.json +1 -0
  445. diffneusim/models/cases/M356C-SRC/case.bin +0 -0
  446. diffneusim/models/cases/M356C-SRC/case.json +1 -0
  447. diffneusim/models/cases/M356R-SRC/case.bin +0 -0
  448. diffneusim/models/cases/M356R-SRC/case.json +1 -0
  449. diffneusim/models/cases/M416C-SRC/case.bin +0 -0
  450. diffneusim/models/cases/M416C-SRC/case.json +1 -0
  451. diffneusim/models/derived/d16_expanded_62f77a4bb16b1e67_mmfloor.xml +673 -0
  452. diffneusim/models/derived/d16_expanded_a1e8b196b2cd7b3c_mmfloor.xml +673 -0
  453. diffneusim/models/derived/d16_soft_law_019e20820f8633b9_mmfloor.json +7844 -0
  454. diffneusim/models/derived/d16_soft_law_62f77a4bb16b1e67_mmfloor.json +16855 -0
  455. diffneusim/models/derived/d16_soft_law_77dbb7213f26e821_mmfloor_rampsb3l_n6t12.json +7883 -0
  456. diffneusim/models/derived/d16_soft_law_8989b60e44860c5b_mmfloor_rampsb3l_n6t12.json +7883 -0
  457. diffneusim/models/derived/d16_soft_law_8989b60e44860c5b_mmfloor_rhlsd05_n6t12.json +7868 -0
  458. diffneusim/models/derived/d16_soft_law_8989b60e44860c5b_mmfloor_rhlsdef_n6t12.json +7868 -0
  459. diffneusim/models/derived/d16_soft_law_8989b60e44860c5b_mmfloor_rhlsmjd_n6t12.json +7868 -0
  460. diffneusim/models/derived/d16_soft_law_a1e8b196b2cd7b3c_mmfloor_rampsb3l_n6t12.json +16894 -0
  461. diffneusim/models/derived/d16_soft_law_a944653edd642082_mmfloor.json +12655 -0
  462. diffneusim/models/derived/d16_soft_law_a944653edd642082_mmfloor_rampsb3l_n6t12.json +12700 -0
  463. diffneusim/models/derived/unitree_g1_soft_law.json +15580 -0
  464. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src.dnmodel +28913 -0
  465. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_qk.txt +1 -0
  466. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_rigid.dnmodel +29202 -0
  467. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_rigid_qk.txt +1 -0
  468. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_axfixlegs01.dnmodel +1 -0
  469. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1.dnmodel +1 -0
  470. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1_qk.txt +1 -0
  471. diffneusim/models/fullbody_contact_spinecoupled_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src.dnmodel +46970 -0
  472. diffneusim/models/fullbody_contact_spinecoupled_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_qk.txt +1 -0
  473. diffneusim/models/fullbody_contact_spinecoupled_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1.dnmodel +1 -0
  474. diffneusim/models/fullbody_contact_spinecoupled_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1_qk.txt +1 -0
  475. diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src.dnmodel +38570 -0
  476. diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_qk.txt +1 -0
  477. diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_rigid.dnmodel +38923 -0
  478. diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_rigid_qk.txt +1 -0
  479. diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1.dnmodel +1 -0
  480. diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1_qk.txt +1 -0
  481. diffneusim/models/fullbody_meshes/1mc.stl +0 -0
  482. diffneusim/models/fullbody_meshes/2distph.stl +0 -0
  483. diffneusim/models/fullbody_meshes/2mc.stl +0 -0
  484. diffneusim/models/fullbody_meshes/2midph.stl +0 -0
  485. diffneusim/models/fullbody_meshes/2proxph.stl +0 -0
  486. diffneusim/models/fullbody_meshes/3distph.stl +0 -0
  487. diffneusim/models/fullbody_meshes/3mc.stl +0 -0
  488. diffneusim/models/fullbody_meshes/3midph.stl +0 -0
  489. diffneusim/models/fullbody_meshes/3proxph.stl +0 -0
  490. diffneusim/models/fullbody_meshes/4distph.stl +0 -0
  491. diffneusim/models/fullbody_meshes/4mc.stl +0 -0
  492. diffneusim/models/fullbody_meshes/4midph.stl +0 -0
  493. diffneusim/models/fullbody_meshes/4proxph.stl +0 -0
  494. diffneusim/models/fullbody_meshes/5distph.stl +0 -0
  495. diffneusim/models/fullbody_meshes/5mc.stl +0 -0
  496. diffneusim/models/fullbody_meshes/5midph.stl +0 -0
  497. diffneusim/models/fullbody_meshes/5proxph.stl +0 -0
  498. diffneusim/models/fullbody_meshes/NOTICE +2 -0
  499. diffneusim/models/fullbody_meshes/capitate.stl +0 -0
  500. diffneusim/models/fullbody_meshes/clavicle.stl +0 -0
  501. diffneusim/models/fullbody_meshes/hamate.stl +0 -0
  502. diffneusim/models/fullbody_meshes/hat_cervical.stl +0 -0
  503. diffneusim/models/fullbody_meshes/hat_jaw.stl +0 -0
  504. diffneusim/models/fullbody_meshes/hat_skull.stl +0 -0
  505. diffneusim/models/fullbody_meshes/humerus.stl +0 -0
  506. diffneusim/models/fullbody_meshes/l_bofoot.stl +0 -0
  507. diffneusim/models/fullbody_meshes/l_femur.stl +0 -0
  508. diffneusim/models/fullbody_meshes/l_fibula.stl +0 -0
  509. diffneusim/models/fullbody_meshes/l_foot.stl +0 -0
  510. diffneusim/models/fullbody_meshes/l_patella.stl +0 -0
  511. diffneusim/models/fullbody_meshes/l_pelvis.stl +0 -0
  512. diffneusim/models/fullbody_meshes/l_talus.stl +0 -0
  513. diffneusim/models/fullbody_meshes/l_tibia.stl +0 -0
  514. diffneusim/models/fullbody_meshes/lumbar1.stl +0 -0
  515. diffneusim/models/fullbody_meshes/lumbar2.stl +0 -0
  516. diffneusim/models/fullbody_meshes/lumbar3.stl +0 -0
  517. diffneusim/models/fullbody_meshes/lumbar4.stl +0 -0
  518. diffneusim/models/fullbody_meshes/lumbar5.stl +0 -0
  519. diffneusim/models/fullbody_meshes/lunate.stl +0 -0
  520. diffneusim/models/fullbody_meshes/pisiform.stl +0 -0
  521. diffneusim/models/fullbody_meshes/r_bofoot.stl +0 -0
  522. diffneusim/models/fullbody_meshes/r_femur.stl +0 -0
  523. diffneusim/models/fullbody_meshes/r_fibula.stl +0 -0
  524. diffneusim/models/fullbody_meshes/r_foot.stl +0 -0
  525. diffneusim/models/fullbody_meshes/r_patella.stl +0 -0
  526. diffneusim/models/fullbody_meshes/r_pelvis.stl +0 -0
  527. diffneusim/models/fullbody_meshes/r_talus.stl +0 -0
  528. diffneusim/models/fullbody_meshes/r_tibia.stl +0 -0
  529. diffneusim/models/fullbody_meshes/radius.stl +0 -0
  530. diffneusim/models/fullbody_meshes/sacrum.stl +0 -0
  531. diffneusim/models/fullbody_meshes/scaphoid.stl +0 -0
  532. diffneusim/models/fullbody_meshes/scapula.stl +0 -0
  533. diffneusim/models/fullbody_meshes/thoracic10_s.stl +0 -0
  534. diffneusim/models/fullbody_meshes/thoracic11_s.stl +0 -0
  535. diffneusim/models/fullbody_meshes/thoracic12_s.stl +0 -0
  536. diffneusim/models/fullbody_meshes/thoracic1_s.stl +0 -0
  537. diffneusim/models/fullbody_meshes/thoracic2_s.stl +0 -0
  538. diffneusim/models/fullbody_meshes/thoracic3_s.stl +0 -0
  539. diffneusim/models/fullbody_meshes/thoracic4_s.stl +0 -0
  540. diffneusim/models/fullbody_meshes/thoracic5_s.stl +0 -0
  541. diffneusim/models/fullbody_meshes/thoracic6_s.stl +0 -0
  542. diffneusim/models/fullbody_meshes/thoracic7_s.stl +0 -0
  543. diffneusim/models/fullbody_meshes/thoracic8_s.stl +0 -0
  544. diffneusim/models/fullbody_meshes/thoracic9_s.stl +0 -0
  545. diffneusim/models/fullbody_meshes/thorax.stl +0 -0
  546. diffneusim/models/fullbody_meshes/thumbdist.stl +0 -0
  547. diffneusim/models/fullbody_meshes/thumbprox.stl +0 -0
  548. diffneusim/models/fullbody_meshes/trapezium.stl +0 -0
  549. diffneusim/models/fullbody_meshes/trapezoid.stl +0 -0
  550. diffneusim/models/fullbody_meshes/triquetrum.stl +0 -0
  551. diffneusim/models/fullbody_meshes/ulna.stl +0 -0
  552. diffneusim/models/source/myo_fullbody/UPSTREAM.md +91 -0
  553. diffneusim/models/source/myoleg/UPSTREAM.md +52 -0
  554. diffneusim/models/source/unitree_g1/LICENSE.mjlab +202 -0
  555. diffneusim/models/source/unitree_g1/UPSTREAM.md +38 -0
  556. diffneusim/models/source/unitree_g1/assets/head_link.STL +0 -0
  557. diffneusim/models/source/unitree_g1/assets/left_ankle_pitch_link.STL +0 -0
  558. diffneusim/models/source/unitree_g1/assets/left_ankle_roll_link.STL +0 -0
  559. diffneusim/models/source/unitree_g1/assets/left_elbow_link.STL +0 -0
  560. diffneusim/models/source/unitree_g1/assets/left_hip_pitch_link.STL +0 -0
  561. diffneusim/models/source/unitree_g1/assets/left_hip_roll_link.STL +0 -0
  562. diffneusim/models/source/unitree_g1/assets/left_hip_yaw_link.STL +0 -0
  563. diffneusim/models/source/unitree_g1/assets/left_knee_link.STL +0 -0
  564. diffneusim/models/source/unitree_g1/assets/left_rubber_hand.STL +0 -0
  565. diffneusim/models/source/unitree_g1/assets/left_shoulder_pitch_link.STL +0 -0
  566. diffneusim/models/source/unitree_g1/assets/left_shoulder_roll_link.STL +0 -0
  567. diffneusim/models/source/unitree_g1/assets/left_shoulder_yaw_link.STL +0 -0
  568. diffneusim/models/source/unitree_g1/assets/left_wrist_pitch_link.STL +0 -0
  569. diffneusim/models/source/unitree_g1/assets/left_wrist_roll_link.STL +0 -0
  570. diffneusim/models/source/unitree_g1/assets/left_wrist_yaw_link.STL +0 -0
  571. diffneusim/models/source/unitree_g1/assets/logo_link.STL +0 -0
  572. diffneusim/models/source/unitree_g1/assets/pelvis.STL +0 -0
  573. diffneusim/models/source/unitree_g1/assets/pelvis_contour_link.STL +0 -0
  574. diffneusim/models/source/unitree_g1/assets/right_ankle_pitch_link.STL +0 -0
  575. diffneusim/models/source/unitree_g1/assets/right_ankle_roll_link.STL +0 -0
  576. diffneusim/models/source/unitree_g1/assets/right_elbow_link.STL +0 -0
  577. diffneusim/models/source/unitree_g1/assets/right_hip_pitch_link.STL +0 -0
  578. diffneusim/models/source/unitree_g1/assets/right_hip_roll_link.STL +0 -0
  579. diffneusim/models/source/unitree_g1/assets/right_hip_yaw_link.STL +0 -0
  580. diffneusim/models/source/unitree_g1/assets/right_knee_link.STL +0 -0
  581. diffneusim/models/source/unitree_g1/assets/right_rubber_hand.STL +0 -0
  582. diffneusim/models/source/unitree_g1/assets/right_shoulder_pitch_link.STL +0 -0
  583. diffneusim/models/source/unitree_g1/assets/right_shoulder_roll_link.STL +0 -0
  584. diffneusim/models/source/unitree_g1/assets/right_shoulder_yaw_link.STL +0 -0
  585. diffneusim/models/source/unitree_g1/assets/right_wrist_pitch_link.STL +0 -0
  586. diffneusim/models/source/unitree_g1/assets/right_wrist_roll_link.STL +0 -0
  587. diffneusim/models/source/unitree_g1/assets/right_wrist_yaw_link.STL +0 -0
  588. diffneusim/models/source/unitree_g1/assets/torso_link_rev_1_0.STL +0 -0
  589. diffneusim/models/source/unitree_g1/assets/waist_roll_link_rev_1_0.STL +0 -0
  590. diffneusim/models/source/unitree_g1/assets/waist_yaw_link_rev_1_0.STL +0 -0
  591. diffneusim/models/source/unitree_g1/dump_mjlab_reference.py +30 -0
  592. diffneusim/models/source/unitree_g1/g1.xml +308 -0
  593. diffneusim/models/source/unitree_g1/g1_constants.py +298 -0
  594. diffneusim/models/source/unitree_g1/mjlab_compiled_reference.json +857 -0
  595. diffneusim/models/unitree_g1.dnmodel +4393 -0
  596. diffneusim/models/unitree_g1_selfcol.dnmodel +20824 -0
  597. diffneusim/rl/__init__.py +2 -0
  598. diffneusim/rl/dynsyn_layer.py +146 -0
  599. diffneusim/rl/footstep_plan.py +337 -0
  600. diffneusim/rl/g1_bm_env.py +572 -0
  601. diffneusim/rl/g1_bm_eval.py +168 -0
  602. diffneusim/rl/g1_bm_fused.py +275 -0
  603. diffneusim/rl/g1_bm_ppo.py +622 -0
  604. diffneusim/rl/g1_bm_sapo.py +551 -0
  605. diffneusim/rl/g1_ppo.py +395 -0
  606. diffneusim/rl/g1_sapo_soft.py +240 -0
  607. diffneusim/rl/g1_soft_env.py +452 -0
  608. diffneusim/rl/g1_soft_grad.py +145 -0
  609. diffneusim/rl/geyer_curves_torch.py +108 -0
  610. diffneusim/rl/gpu_fullbody_vec_env.py +1241 -0
  611. diffneusim/rl/imitation.py +2027 -0
  612. diffneusim/rl/imitation_reward_v2.py +248 -0
  613. diffneusim/rl/imitation_reward_v3.py +349 -0
  614. diffneusim/rl/latent_task.py +175 -0
  615. diffneusim/rl/llc_reward.py +316 -0
  616. diffneusim/rl/millard_curves_torch.py +154 -0
  617. diffneusim/rl/mirror_symmetry.py +212 -0
  618. diffneusim/rl/model_path.py +35 -0
  619. diffneusim/rl/mvae_recon.py +123 -0
  620. diffneusim/rl/nets_shac.py +599 -0
  621. diffneusim/rl/reset_pool.py +154 -0
  622. diffneusim/rl/sapo_capture.py +873 -0
  623. diffneusim/rl/sapo_vec.py +1051 -0
  624. diffneusim/rl/shac_vec.py +346 -0
  625. diffneusim/rl/state_prior.py +151 -0
  626. diffneusim/rl/step_library.py +105 -0
  627. diffneusim/rl/task_walk_env.py +1793 -0
  628. diffneusim/rl/task_walk_reward.py +3300 -0
  629. diffneusim/run.py +23 -0
  630. diffneusim/run_env.py +46 -0
  631. diffneusim/tasks/__init__.py +147 -0
  632. diffneusim/tasks/legacy_names.py +63 -0
  633. diffneusim/tasks/paths.py +79 -0
  634. diffneusim/tasks/settings.py +202 -0
  635. diffneusim/third_party/instantmimic_947430ee/LICENSE +202 -0
  636. diffneusim/third_party/instantmimic_947430ee/NOTICE +19 -0
  637. diffneusim/third_party/instantmimic_947430ee/README.md +31 -0
  638. diffneusim/third_party/instantmimic_947430ee/instantmimic/envs/unitree_g1/tasks/beyondmimic_tracking/benchmark_protocol.py +106 -0
  639. diffneusim/third_party/instantmimic_947430ee/instantmimic/envs/unitree_g1/tasks/beyondmimic_tracking/metrics.py +214 -0
  640. diffneusim/third_party/instantmimic_947430ee/instantmimic/envs/unitree_g1/tasks/beyondmimic_tracking/reference.py +513 -0
  641. diffneusim/third_party/instantmimic_947430ee/instantmimic/motion/quaternion.py +193 -0
  642. diffneusim/train/__init__.py +0 -0
  643. diffneusim/train/eval_ckpt.py +239 -0
  644. diffneusim/train/eval_mimic.py +133 -0
  645. diffneusim/train/gait_report.py +203 -0
  646. diffneusim/train/gcot_chain.py +51 -0
  647. diffneusim/train/levers.py +135 -0
  648. diffneusim/train/masked_reset.py +314 -0
  649. diffneusim/train/rl_algorithm_suite.py +917 -0
  650. diffneusim/train/train14.py +240 -0
  651. diffneusim/train/train_tw14.py +674 -0
  652. diffneusim/viz/__init__.py +5 -0
  653. diffneusim/viz/__main__.py +41 -0
  654. diffneusim/viz/camera.py +115 -0
  655. diffneusim/viz/dnrec.py +118 -0
  656. diffneusim/viz/dnrec_io.py +686 -0
  657. diffneusim/viz/hud.py +565 -0
  658. diffneusim/viz/meshes.py +458 -0
  659. diffneusim/viz/play.py +237 -0
  660. diffneusim/viz/record.py +74 -0
  661. diffneusim/viz/render.py +1402 -0
  662. diffneusim/viz/renderer.py +268 -0
  663. diffneusim/viz/rl_env_render.py +635 -0
  664. diffneusim/viz/snapshot.py +54 -0
  665. diffneusim/viz/strobe.py +124 -0
  666. diffneusim/viz/to_mp4.py +58 -0
  667. diffneusim/viz/ui.py +481 -0
  668. diffneusim/viz/viewer.py +2086 -0
  669. diffneusim-1.0.0.dist-info/METADATA +226 -0
  670. diffneusim-1.0.0.dist-info/RECORD +682 -0
  671. diffneusim-1.0.0.dist-info/WHEEL +5 -0
  672. diffneusim-1.0.0.dist-info/licenses/LICENSE +201 -0
  673. diffneusim-1.0.0.dist-info/licenses/LICENSES/BSD-3-Clause-NC-ARMS-hand-wrist-4.3.txt +20 -0
  674. diffneusim-1.0.0.dist-info/licenses/LICENSES/BSD-3-Clause-NC-MoBL-ARMS.txt +25 -0
  675. diffneusim-1.0.0.dist-info/licenses/LICENSES/CC-BY-3.0-OpenSim-geometry.txt +25 -0
  676. diffneusim-1.0.0.dist-info/licenses/LICENSES/MIT-Christophy2012-lumbarspine.txt +10 -0
  677. diffneusim-1.0.0.dist-info/licenses/LICENSES/MIT-Lai2017-model-high-flex.txt +10 -0
  678. diffneusim-1.0.0.dist-info/licenses/LICENSES/MIT-Lee2015-hand_muscle.txt +11 -0
  679. diffneusim-1.0.0.dist-info/licenses/LICENSES/MIT-Rajagopal2016-full_body.txt +11 -0
  680. diffneusim-1.0.0.dist-info/licenses/LICENSES/MIT-Uhlrich2022-fbmodpassivecal.txt +10 -0
  681. diffneusim-1.0.0.dist-info/licenses/NOTICE +274 -0
  682. diffneusim-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2086 @@
1
+ """Interactive cross-platform viewer for `.dnmodel` / `.dnrec` (Blender + MuJoCo-viewer style).
2
+
3
+ python -m diffneusim.viz.viewer <path.dnmodel|.dnrec> # pops a live native window
4
+ python -m diffneusim.viz.viewer <model.dnmodel> --ref # play the model's imitation REFERENCE motion
5
+ python -m diffneusim.viz.viewer <model.dnmodel> --sim # live physics (real engine; needs CUDA)
6
+ python -m diffneusim.viz.viewer <model.dnmodel> --sim --hang # ... with the model HUNG in the air (cannot fall)
7
+ python -m diffneusim.viz.viewer <path> --shot out.png # headless: render one frame to PNG and exit
8
+ [--muscles off] [--geom-groups 0,7] [--camera yaw,pitch,dist] [--dist-scale S]
9
+
10
+ A `.dnmodel` shows a default STATIC pose (auto-loaded from a sibling `*_qk.txt`, else an
11
+ identity-quaternion zero pose). A `.dnrec` animates its trajectory in a loop. `--ref` plays the
12
+ imitation reference clip the model trains against (bare = the per-model default, or `--ref PATH`)
13
+ on the model's own bones/muscles, with the normal playback controls. Drag & drop ANY
14
+ `.dnmodel`/`.dnrec` onto the window to (re)load it.
15
+
16
+ Everything draws through the SINGLE shared render path -- `tools/viz/dnrec_io.py`
17
+ (`fk_poses` + `render_bodies_from_visual_geoms` + `write_dnrec`) produces a `.dnrec` clip and
18
+ `tools/viz/renderer.py` (`make_scene` / `resolve_camera` / the `render.Scene`) draws it, so the
19
+ window matches the mp4 renderer's look (camera framing, lighting, ground grid, geom colors) exactly.
20
+ This module adds only the interactive shell (window, Blender-style navigation, axis gizmo, HUD,
21
+ drag&drop, playback) -- it never forks the renderer. Torch-free: numpy + moderngl(-window) only.
22
+
23
+ Live simulation (Phase 2, .dnmodel only): press M to step the model live through the REAL production
24
+ engine (`diffneusim.load(path).step()/.activate()` — single-env, forward-only, wall-clock-paced). This is
25
+ CUDA-only; on a machine with no NVIDIA GPU it prints "live-sim needs CUDA" and stays a viewer. Press O
26
+ for a physics-options panel (dt / muscle excitation / speed are live-editable and feed the same engine;
27
+ gravity / contact / precision are model-file facts — change them by editing the .dnmodel and re-dropping).
28
+
29
+ BAKE (.dnmodel only): live physics is slow on a heavy model, so press N (or click "Bake") to PRE-COMPUTE
30
+ a fixed number of frames once through the real engine, assemble them into an in-memory `.dnrec`, and then
31
+ replay/scrub that instantly — you pay the physics cost a single time and get smooth playback. "frames"
32
+ and "steps/frame" are editable numbers (click the value to TYPE, or use the −/+ steppers); the bake runs
33
+ non-blocking with a progress bar and starts from the model's initial pose with the current dt/excitation.
34
+ Runs on CUDA (production `diffneusim.load()`) OR, with no GPU (Mac), the engine's forward-only CPU ext
35
+ (`diffneusim.ext`, same core physics) for fullbody / myoLeg26 / myoLeg22 / ant — build it once with
36
+ `cmake --build bindings/build_cpu --target _diffneusim_rl`.
37
+
38
+ Controls
39
+ A control panel (top-left) shows EVERY control with its current state; CLICK any row to toggle/run it.
40
+ The keyboard shortcuts below are just accelerators (each is shown as a chip on its row).
41
+ Model click the "Model:" row (FILE section) to switch to any registered models/*.dnmodel live
42
+ (CLI: `view.py NAME` or `--model NAME` to preselect; `--list` to see the registry)
43
+ Space START / pause the live sim (MuJoCo-style, on a static model) · play/pause a clip
44
+ Left / Right step one frame (playback) Home/End jump to start/end
45
+ M toggle live sim on/off (stop = freeze at the current pose; Space also starts it)
46
+ N bake N frames of physics -> fast replay (see BAKE above)
47
+ R restart / reset sim V reset camera to fit
48
+ K camera tracks the COM (follows the subject; orbit/zoom stay relative to it)
49
+ Y HANG the model in the air (.dnmodel): its floating base is pinned at a fixed floor
50
+ clearance, so live physics still drives every internal joint / muscle / contact while
51
+ the body cannot fall over -- the way to watch ONE muscle pull ONE joint. "clearance"
52
+ is editable; turn "hold base orientation" off and it swings from the pin instead.
53
+ Per model with no per-model constants: which coordinates carry the base, and which way
54
+ they move it in the world, are read off the loaded .dnmodel.
55
+ [ / ] speed down / up O or C show/hide the control panel
56
+ U show/hide the right-side JOINT / MUSCLE control panel (.dnmodel). Drag a joint slider to
57
+ POSE the model (kinematic: sets qpos + re-FK; ball/free joints expose 3 rotation-vector
58
+ sliders) -- available on the static pose (also seeds live-sim). Drag a muscle slider to
59
+ set its activation: it COLOURS the muscle when static, and drives THAT muscle's excitation
60
+ during live-sim. Wheel over the panel scrolls it; click a slider's value to type a number.
61
+ A PD-actuated model (the G1's `actuators` block, diffneusim.pd) holds its start pose in
62
+ live-sim, and dragging an actuated joint's slider moves that joint's PD TARGET (on the
63
+ CPU ext dt is capped at 1 ms: explicit contact and PD damping there). The left panel
64
+ scrolls under the wheel too (the model picker).
65
+ Drag LMB/MMB orbit Shift+drag (or RMB) pan Wheel zoom
66
+ F contact arrow · G muscle mode · J muscle fibres · B muscle bundle · T COM trail · H shadow · 0-9 groups
67
+ (1 ground contacts · 7 self colliders)
68
+ P capture PNG -> ~/Pictures/diffneusim/ and reveal it in Finder
69
+ Esc / Q cancel bake · cancel edit · quit
70
+ Editable numbers (dt / speed / excitation / bake frames / steps): CLICK the value to type it in, press
71
+ Enter to commit / Esc to cancel, or click the −/+ steppers to nudge. A scrub bar along the bottom shows
72
+ the timeline; click / drag it to seek.
73
+ """
74
+ from __future__ import annotations
75
+
76
+ import argparse
77
+ import datetime
78
+ import os
79
+ import pathlib
80
+ import re
81
+ import subprocess
82
+ import sys
83
+ import tempfile
84
+ import time
85
+
86
+ import numpy as np
87
+
88
+ from diffneusim._paths import ROOT as ROOT # (3a) the repo root
89
+ # The shared render modules import each other by bare name (`from dnrec import DnRec`), so both
90
+ # tools/ and tools/viz/ must be on sys.path -- exactly what tools/render_fullbody.py does.
91
+ # (3a) was: sys.path.insert(0, str(ROOT / "tools"))
92
+ # (3a) was: sys.path.insert(0, str(ROOT / "tools" / "viz"))
93
+ # The engine package of THIS checkout, ahead of the venv's editable install: a worktree that shares the main
94
+ # checkout's venv would otherwise live-sim on the main checkout's `diffneusim` (its CPU dispatch and ext).
95
+ # (3a) was: sys.path.insert(0, str(ROOT / "python"))
96
+
97
+
98
+ def discover_models():
99
+ """General model registry for the viewer: RENDERABLE ``models/*.dnmodel`` as (name=stem, path), sorted.
100
+ Model-agnostic by design -- nothing is hardcoded per model, so dropping a new ``.dnmodel`` into
101
+ ``models/`` registers it automatically. Models with no ``visual_geoms`` block (the renderer needs real
102
+ per-body geometry) are skipped so the picker never offers a model it can't draw."""
103
+ out = []
104
+ for p in sorted((ROOT / "models").glob("*.dnmodel")):
105
+ try:
106
+ if '"visual_geoms"' in p.read_text():
107
+ out.append((p.stem, str(p)))
108
+ except OSError:
109
+ pass
110
+ return out
111
+
112
+
113
+ def _wrap_at_underscores(text, font, maxw, indent=" "):
114
+ """Split a model name into lines no wider than `maxw` px in `font`, breaking after an underscore; continuation
115
+ lines are indented. A single token wider than the line is cut by characters rather than dropped."""
116
+ fits = lambda s: font.getbbox(s)[2] <= maxw # noqa: E731
117
+ tokens = [t for t in re.split(r"(?<=_)", text) if t]
118
+ lines, line = [], ""
119
+ for t in tokens:
120
+ pre = indent if lines else ""
121
+ if fits(pre + line + t):
122
+ line += t
123
+ continue
124
+ if line:
125
+ lines.append(pre + line)
126
+ pre, line = indent, ""
127
+ while not fits(pre + t) and len(t) > 1: # a token too long for any line: hard-cut it
128
+ k = len(t)
129
+ while k > 1 and not fits(pre + t[:k]):
130
+ k -= 1
131
+ lines.append(pre + t[:k])
132
+ t = t[k:]
133
+ line = t
134
+ if line:
135
+ lines.append((indent if lines else "") + line)
136
+ return lines
137
+
138
+
139
+ def resolve_model(sel, models):
140
+ """Resolve a CLI selector to a model path: a registered NAME, an explicit .dnmodel/.dnrec PATH, or
141
+ None. None -> the canonical coupled full-body if registered, else the first model."""
142
+ by_name = dict(models)
143
+ if sel is None:
144
+ return by_name.get("fullbody_contact_spinecoupled_lspine_girdle_osimeq") or (models[0][1] if models else None)
145
+ if os.path.exists(sel):
146
+ return sel
147
+ if sel in by_name:
148
+ return by_name[sel]
149
+ if pathlib.Path(sel).stem in by_name:
150
+ return by_name[pathlib.Path(sel).stem]
151
+ raise SystemExit(f"unknown model {sel!r}; run with --list to see the registry, or pass a file path")
152
+
153
+ from diffneusim.viz.dnrec_io import com_track, fk_poses, load_dnmodel, load_record, motion_half_extent, render_bodies_from_visual_geoms, write_dnrec, RECORD_SUFFIXES, MODEL_SUFFIXES # noqa: E402
154
+ from diffneusim.viz.dnrec import DnRec # noqa: E402
155
+
156
+ # NOTE: the viewer deliberately does NOT re-impose the Walker knee equality on the displayed pose. The
157
+ # engine integrates the knee's patella/tibia-glide secondaries as FREE dofs (no equality constraint), so
158
+ # they drift under load and the knee visibly separates -- that is a REAL model gap, and a faithful viewer
159
+ # (same pipeline as training) must SHOW it, not cosmetically hide it. The fix belongs in the model/engine.
160
+
161
+ # joint -> number of q (position) coordinates it consumes (nq dof, not nv).
162
+ _JOINT_QDOF = {"free": 7, "ball": 4, "hinge": 1, "revolute": 1, "slide": 1, "prismatic": 1, "fixed": 0}
163
+ # dnmodel-stem suffix tokens stripped when hunting for a sibling *_qk.txt (fullbody_contact -> fullbody_qk.txt).
164
+ _STEM_SUFFIXES = ("contact", "f64", "f32", "dense", "source", "aba", "compound",
165
+ # myoleg26 derived variants (build_myoleg.py steps 6c-6j): they share the
166
+ # base skeleton, so they share myoleg26_3d_qk.txt and none needs its own.
167
+ "selfcol", "kneeexp", "kneestop5", "kneestop12", "ankle", "oslen", "osscale", "geyerfl",
168
+ "bdamp01", "bfsgeyer", "geyerhalf", "geyerstr", "vasgeyer", "toelock")
169
+
170
+
171
+ # --- quaternion <-> rotation-vector (exp/log map) for the joint sliders -------------------------------
172
+ # A ball / free-base orientation is a unit quaternion, which has no intuitive per-component slider (the 4
173
+ # components must stay normalized). Exposing the 3-vector log map (axis * angle, radians) instead gives
174
+ # three independent, gimbal-free sliders that round-trip cleanly for |angle| < pi -- exactly what an
175
+ # interactive posing control wants. `q` is [w, x, y, z], matching dnrec_io's quat convention.
176
+ def _quat_to_rotvec(q):
177
+ q = np.asarray(q, dtype=np.float64)
178
+ n = float(np.linalg.norm(q))
179
+ if n < 1e-12:
180
+ return np.zeros(3)
181
+ q = q / n
182
+ if q[0] < 0.0: # canonical hemisphere (q and -q are the same rotation)
183
+ q = -q
184
+ w = min(1.0, max(-1.0, float(q[0])))
185
+ s = float(np.sqrt(max(0.0, 1.0 - w * w)))
186
+ if s < 1e-8: # near-identity: axis ill-defined, angle ~ 0
187
+ return np.zeros(3)
188
+ return (q[1:4] / s) * (2.0 * np.arccos(w))
189
+
190
+
191
+ def _rotvec_to_quat(v):
192
+ v = np.asarray(v, dtype=np.float64)
193
+ ang = float(np.linalg.norm(v))
194
+ if ang < 1e-8:
195
+ return np.array([1.0, 0.0, 0.0, 0.0])
196
+ ax = v / ang
197
+ return np.concatenate([[np.cos(ang / 2.0)], ax * np.sin(ang / 2.0)])
198
+
199
+
200
+ def _dof_slider_range(rng, lo_default, hi_default):
201
+ """A joint's slider (lo, hi): the model's declared `range` if it is a real 2-tuple with hi > lo (and
202
+ not the [0,0] placeholder), else the passed defaults (hinge = ±pi, slide = ±0.5, rotvec = ±pi)."""
203
+ if (isinstance(rng, (list, tuple)) and len(rng) == 2
204
+ and float(rng[1]) > float(rng[0]) and (float(rng[0]) != 0.0 or float(rng[1]) != 0.0)):
205
+ return float(rng[0]), float(rng[1])
206
+ return lo_default, hi_default
207
+
208
+
209
+ def _joint_slider_descriptors(jm):
210
+ """Per-DOF joint slider descriptors for a parsed `.dnmodel` (pure -- no viewer state, so unit-testable).
211
+ Each is a dict: `kind` ('scalar'|'pos'|'rotvec') + a `label` + the slider range (`lo`,`hi`) + either an
212
+ `idx` into q (scalar/pos) or a quaternion base `base` + component `comp` (rotvec). Order follows body
213
+ order; `fixed` joints (0 DOF) are skipped; a `ball` becomes 3 rotation-vector sliders and a `free` base
214
+ 3 translation + 3 rotation-vector sliders. Resolved by the viewer's `_dof_get/_dof_set`."""
215
+ pi = float(np.pi)
216
+ out = []
217
+
218
+ def rng(src): # model range, but only when the joint is limited
219
+ return src.get("range") if src.get("limited", True) is not False else None
220
+
221
+ for b in jm["bodies"]:
222
+ nm = b.get("name", "?")
223
+ qa = b.get("qadr")
224
+ if "coupled" in b: # driven ("mimic") joint: 0 own coords, its angle is
225
+ continue # poly(q_master). Its qadr ALIASES the next owned dof,
226
+ # so a slider here would drive THAT dof (e.g. a Ball hip).
227
+ if "joints" in b: # compound scalar-primitive stack (hinge/slide)
228
+ if qa is None:
229
+ continue
230
+ off = 0
231
+ for prim in b["joints"]:
232
+ t = prim.get("type")
233
+ if t in ("hinge", "revolute"):
234
+ lo, hi = _dof_slider_range(rng(prim), -pi, pi)
235
+ elif t in ("slide", "prismatic"):
236
+ lo, hi = _dof_slider_range(rng(prim), -0.5, 0.5)
237
+ else:
238
+ off += 1
239
+ continue
240
+ out.append(dict(kind="scalar", idx=int(qa) + off, lo=lo, hi=hi,
241
+ label=f"{nm}.{prim.get('name', t)}"))
242
+ off += 1
243
+ continue
244
+ j = b.get("joint")
245
+ if j in (None, "fixed") or qa is None:
246
+ continue
247
+ qa = int(qa)
248
+ if j in ("hinge", "revolute"):
249
+ lo, hi = _dof_slider_range(rng(b), -pi, pi)
250
+ out.append(dict(kind="scalar", idx=qa, lo=lo, hi=hi, label=nm))
251
+ elif j in ("slide", "prismatic"):
252
+ lo, hi = _dof_slider_range(rng(b), -0.5, 0.5)
253
+ out.append(dict(kind="scalar", idx=qa, lo=lo, hi=hi, label=nm))
254
+ elif j == "ball": # quat -> 3 rotation-vector sliders
255
+ for k in range(3):
256
+ out.append(dict(kind="rotvec", base=qa, comp=k, lo=-pi, hi=pi, label=f"{nm}.r{'xyz'[k]}"))
257
+ elif j == "free": # 3 translation + 3 rotation-vector
258
+ for k in range(3):
259
+ out.append(dict(kind="pos", idx=qa + k, lo=-2.0, hi=2.0, label=f"{nm}.{'xyz'[k]}"))
260
+ for k in range(3):
261
+ out.append(dict(kind="rotvec", base=qa + 3, comp=k, lo=-pi, hi=pi, label=f"{nm}.r{'xyz'[k]}"))
262
+ return out
263
+
264
+
265
+ # ----------------------------------------------------------------------------- dnmodel -> clip
266
+ def _body_qdof(body):
267
+ if "joints" in body: # ordered scalar-primitive compound stack (hinge/slide, 1 q each)
268
+ return len(body["joints"])
269
+ return _JOINT_QDOF[body["joint"]]
270
+
271
+
272
+ def _geom_lowest_z(pose, g):
273
+ """World z of the lowest point of a contact sphere, given the FK poses of one frame."""
274
+ b = int(g["body"])
275
+ c = np.asarray(g["center"], float)
276
+ w, x, y, z = pose[b, 3:7]
277
+ cz = (c[0] * 2 * (x * z - w * y) + c[1] * 2 * (y * z + w * x) + c[2] * (1 - 2 * (x * x + y * y)))
278
+ return float(pose[b, 2] + cz - float(g["radius"]))
279
+
280
+
281
+ # --- root suspension: hang the model's floating base in the air --------------------------------------
282
+ # A model dropped into live physics FALLS, which is exactly right for a gait run and exactly wrong when
283
+ # the question is "what does this one muscle do to this one joint". Suspending it needs two model facts,
284
+ # and the viewer is model-agnostic, so BOTH are read off the loaded `.dnmodel`: which coordinates carry
285
+ # the floating base (`_base_dof_spec`), and which direction each of those coordinates moves the body in
286
+ # the WORLD (`_base_world_dirs`) -- myoleg26's free joint is ordered (x, z, -y) while the full body's is
287
+ # a plain (x, y, z), so "lift it straight up" is a per-model fact that differencing the real FK reads off
288
+ # instead of a per-model constant.
289
+ def _base_dof_spec(jm):
290
+ """The model's FLOATING-BASE dofs -- the coordinates that place the whole body in the world, as
291
+ opposed to its internal joints -- as `dict(label, body, q_pos, q_rot, v_pos, v_rot)` of q/v INDEX
292
+ lists, or None for a world-fixed model with no base to hold. Pure (no viewer state, so testable).
293
+
294
+ * the first `free` joint: 3 translation q + the 4 quaternion q. Its 6 velocity dofs are
295
+ `[omega(3), v(3)]` -- ANGULAR FIRST, body frame (core/dyn/articulated.h).
296
+ * else the LEADING `slide`/`prismatic` dofs plus the ONE rotation dof that follows them, which is
297
+ how a planar model carries its base (myoleg22_2d's pelvis_tx/pelvis_ty bodies, H0918's
298
+ pelvis slide/slide/revolute stack).
299
+ """
300
+ for i, b in enumerate(jm["bodies"]):
301
+ if b.get("joint") == "free":
302
+ qa, va = int(b["qadr"]), int(b["vadr"])
303
+ return dict(label=f"{b.get('name', '?')} free base", body=i,
304
+ q_pos=[qa, qa + 1, qa + 2], q_rot=[qa + 3, qa + 4, qa + 5, qa + 6],
305
+ v_pos=[va + 3, va + 4, va + 5], v_rot=[va, va + 1, va + 2])
306
+ q_pos, v_pos, q_rot, v_rot, body, name = [], [], [], [], -1, "?"
307
+ for i, b in enumerate(jm["bodies"]):
308
+ if "coupled" in b: # a driven ("mimic") joint owns no coordinate:
309
+ continue # its qadr ALIASES the next owned dof
310
+ qa, va = int(b["qadr"]), int(b["vadr"])
311
+ prims = list(b["joints"]) if "joints" in b else [dict(type=b.get("joint"))]
312
+ stop = False
313
+ for k, prim in enumerate(prims):
314
+ t = prim.get("type")
315
+ if t in (None, "fixed"): # 0 own coordinates -> nothing to hold here
316
+ continue
317
+ if t in ("slide", "prismatic") and not q_rot: # a base translation
318
+ q_pos.append(qa + k); v_pos.append(va + k); body = i
319
+ name = b.get("name") or name
320
+ elif t in ("hinge", "revolute") and q_pos and not q_rot:
321
+ q_rot.append(qa + k); v_rot.append(va + k); body = i # the tilt closes a planar base
322
+ name = b.get("name") or name
323
+ else: # a real internal joint: the base ends here
324
+ stop = True
325
+ break
326
+ if stop:
327
+ break
328
+ if not q_pos:
329
+ return None
330
+ return dict(label=f"{name} planar base ({len(q_pos)}T+{len(q_rot)}R)", body=body,
331
+ q_pos=q_pos, q_rot=q_rot, v_pos=v_pos, v_rot=v_rot)
332
+
333
+
334
+ def _base_world_dirs(jm, q, spec):
335
+ """(3, n) -- the WORLD direction one unit of each base TRANSLATION dof moves the body in, measured by
336
+ differencing the real FK (a translation coordinate enters the FK linearly, so a unit step is exact,
337
+ not a finite-difference approximation)."""
338
+ q = np.asarray(q, dtype=np.float64)
339
+ p0 = fk_poses(jm, q)[int(spec["body"]), :3]
340
+ out = np.zeros((3, len(spec["q_pos"])))
341
+ for k, i in enumerate(spec["q_pos"]):
342
+ q2 = q.copy()
343
+ q2[i] += 1.0
344
+ out[:, k] = fk_poses(jm, q2)[int(spec["body"]), :3] - p0
345
+ return out
346
+
347
+
348
+ def _base_lifts_vertically(dirs):
349
+ """True if the base translation dofs can produce a PURE vertical world translation -- what hanging
350
+ the model needs. A base with no vertical freedom (a body that only slides in the floor plane) can't
351
+ be hung, and the viewer disables the control instead of moving it sideways."""
352
+ D = np.asarray(dirs, dtype=np.float64)
353
+ if D.size == 0:
354
+ return False
355
+ t = np.array([0.0, 0.0, 1.0])
356
+ x, *_ = np.linalg.lstsq(D, t, rcond=None)
357
+ return bool(np.linalg.norm(D @ x - t) <= 1e-6)
358
+
359
+
360
+ def _model_lowest_z(jm, pose):
361
+ """World z of the model's lowest CONTACT sphere -- the point that meets the floor, so it is what a
362
+ "clearance above the ground" has to be measured from. A model that declares no contact geoms has no
363
+ contact geometry to measure, and falls back to its lowest body ORIGIN (a proxy)."""
364
+ contact = jm.get("contact") if isinstance(jm.get("contact"), dict) else {}
365
+ geoms = contact.get("geoms") or []
366
+ if geoms:
367
+ return min(_geom_lowest_z(pose, g) for g in geoms)
368
+ return float(np.min(np.asarray(pose)[:, 2]))
369
+
370
+
371
+ def _lift_to_clearance(jm, q, spec, clearance, dirs=None):
372
+ """`(q_lifted, dz)`: a copy of `q` whose BASE TRANSLATION dofs are moved so the model's lowest point
373
+ sits `clearance` metres above the floor, with the POSE itself -- every internal joint, and the base
374
+ orientation -- untouched. The required world lift is mapped onto the base dofs by least squares over
375
+ their measured world directions, so a plain (x,y,z) free base, myoleg26's rotated one and a planar 2D
376
+ base are all handled by the same three lines."""
377
+ q = np.asarray(q, dtype=np.float64).copy()
378
+ D = _base_world_dirs(jm, q, spec) if dirs is None else np.asarray(dirs, dtype=np.float64)
379
+ dz = float(clearance) - _model_lowest_z(jm, fk_poses(jm, q))
380
+ target = np.array([0.0, 0.0, dz])
381
+ x, *_ = np.linalg.lstsq(D, target, rcond=None)
382
+ err = float(np.linalg.norm(D @ x - target))
383
+ assert err <= 1e-6 * max(1.0, abs(dz)), (
384
+ f"base dofs {spec['q_pos']} cannot translate this model vertically (residual {err:.3g} m) -- "
385
+ f"there is nothing to hang it by")
386
+ q[spec["q_pos"]] += x
387
+ return q, dz
388
+
389
+
390
+ def _identity_pose(jm):
391
+ """A valid default pose: zeros everywhere EXCEPT free/ball joint quaternions, which get the
392
+ identity [1,0,0,0]. A plain zero vector would leave a free/ball quat = [0,0,0,0] (norm 0) and
393
+ `fk_poses`'s normalize would divide by zero -- so the "else zeros" default must seed identity quats."""
394
+ bodies = jm["bodies"]
395
+ nq = 0
396
+ for b in bodies:
397
+ nq = max(nq, int(b["qadr"]) + _body_qdof(b))
398
+ q = np.zeros(nq, dtype=np.float64)
399
+ for b in bodies:
400
+ qa = int(b["qadr"])
401
+ j = b.get("joint")
402
+ if j == "free":
403
+ q[qa + 3] = 1.0 # free: [px,py,pz, qw,qx,qy,qz] -> qw at qa+3
404
+ elif j == "ball":
405
+ q[qa] = 1.0 # ball: [qw,qx,qy,qz] -> qw at qa
406
+ return q
407
+
408
+
409
+ def _find_pose_file(dnmodel_path):
410
+ """Sibling default-pose file: `<stem>_qk.txt`, falling back to progressively suffix-stripped
411
+ stems (so fullbody_contact.dnmodel finds fullbody_qk.txt). Returns a Path or None."""
412
+ p = pathlib.Path(dnmodel_path)
413
+ stem = p.stem
414
+ seen, cands = set(), []
415
+ while stem and stem not in seen:
416
+ seen.add(stem)
417
+ cands.append(stem)
418
+ parts = stem.rsplit("_", 1)
419
+ stem = parts[0] if len(parts) == 2 and parts[1] in _STEM_SUFFIXES else ""
420
+ for c in cands:
421
+ f = p.with_name(f"{c}_qk.txt")
422
+ if f.exists():
423
+ return f
424
+ return None
425
+
426
+
427
+ def _load_q(path):
428
+ """Load a pose / trajectory as (T, nq): .txt (whitespace), .npy (nq | T,nq), .npz (key `q`, opt `dt`)."""
429
+ path = pathlib.Path(path)
430
+ dt = None
431
+ if path.suffix == ".npz":
432
+ d = load_record(path) # canonical reader (.npz or v2 .dnrec); dnrec-format.md P4
433
+ q = np.asarray(d["q"], dtype=np.float64)
434
+ dt = float(d["dt"]) if "dt" in d else None
435
+ elif path.suffix == ".npy":
436
+ q = np.asarray(np.load(path), dtype=np.float64)
437
+ else:
438
+ q = np.asarray(np.loadtxt(path), dtype=np.float64)
439
+ if q.ndim == 1:
440
+ q = q[None, :]
441
+ assert q.ndim == 2, q.shape
442
+ return q, dt
443
+
444
+
445
+ # The imitation REFERENCE clip to play for each model. These are the LOOP refs (start pose ~= end pose,
446
+ # tools/reference/make_loopable_ref.py; docs/training/concepts/loopable-refs.md) that training uses -- so a bare `--ref`
447
+ # plays a motion that WRAPS SEAMLESSLY (the playback loops the clip, exactly like the imitation phase-wrap).
448
+ # Matches the training ref_path defaults (diffneusim.rl/gpu_*_vec_env.py). $DN_REF overrides. A reference
449
+ # is just a (T, nq) qpos trajectory .npz, so `--ref` plays it like a `--pose` trajectory through normal playback.
450
+ _MODEL_DEFAULT_REF = {
451
+ "myoleg26": "data/reference/cmu/35_01_loop_myoleg26_ref.npz",
452
+ "myoleg22": "data/reference/cmu/07_01_loop_myoleg22_ref_global.npz",
453
+ # 35_01 is the shared USER-selected default for both leg + full body (matches gpu_*_vec_env.py).
454
+ "fullbody": "data/reference/cmu/35_01_loop_fullbody_ref.npz",
455
+ }
456
+
457
+
458
+ def _default_ref_for_model(dnmodel_path):
459
+ """Resolve the training reference clip for a `.dnmodel`: $DN_REF if set, else the per-model default.
460
+ Fail-fast (dev-rules) listing the available refs when the model has no mapping."""
461
+ env = os.environ.get("DN_REF")
462
+ if env:
463
+ assert pathlib.Path(env).exists(), f"$DN_REF does not exist: {env}"
464
+ return env
465
+ stem = pathlib.Path(dnmodel_path).stem
466
+ for key, rel in _MODEL_DEFAULT_REF.items():
467
+ if key in stem:
468
+ p = ROOT / rel
469
+ assert p.exists(), f"default reference for {key} not found: {p} (pass --ref <path>)"
470
+ return str(p)
471
+ avail = sorted((ROOT / "data/reference/cmu").glob("*ref*.npz"))
472
+ raise AssertionError(
473
+ f"no default reference mapping for model {stem!r}; pass an explicit --ref <path>. Available:\n "
474
+ + "\n ".join(str(a.relative_to(ROOT)) for a in avail))
475
+
476
+
477
+ def _resolve_pose(dnmodel_path, jm, pose_override=None):
478
+ """Choose the pose/trajectory (T, nq) to show for a `.dnmodel` + a human label: an explicit override,
479
+ then the sibling `*_qk.txt`, else the identity-quaternion default."""
480
+ if pose_override is not None:
481
+ q, _dt = _load_q(pose_override)
482
+ return q, f"pose={pathlib.Path(pose_override).name}"
483
+ pose_file = _find_pose_file(dnmodel_path)
484
+ if pose_file is not None:
485
+ q, _dt = _load_q(pose_file)
486
+ return q, f"pose={pose_file.name}"
487
+ # STAND IT ON THE GROUND. The identity pose puts a free root at z = 0, so a biped's legs -- and
488
+ # anything drawn on them, including the self-collision capsules -- sit BELOW the floor and are
489
+ # hidden by it. Lift the base until the lowest contact sphere just touches z = 0, through the SAME
490
+ # base-dof mapping the viewer's "hang root" uses: the lift goes on whichever base coordinates
491
+ # actually point up in the world, not on "the third one". (myoleg26's free joint is ordered
492
+ # (x, z, -y), so writing q[qadr+2] moved such a model SIDEWAYS.) A model with no base dofs, no
493
+ # vertical base freedom, or no contact geoms is left exactly as it was.
494
+ q = _identity_pose(jm)
495
+ spec = _base_dof_spec(jm)
496
+ geoms = (jm.get("contact") or {}).get("geoms", []) if isinstance(jm.get("contact"), dict) else []
497
+ if spec is not None and geoms and _base_lifts_vertically(_base_world_dirs(jm, q, spec)):
498
+ q, dz = _lift_to_clearance(jm, q, spec, 0.0)
499
+ return q[None, :], f"pose=identity, standing (base lifted {dz * 1000:.0f} mm)"
500
+ return q[None, :], "pose=identity(default)"
501
+
502
+
503
+ def _muscle_channels_for(jm, q, pose, activation=0.2, act_vec=None):
504
+ """Muscle via-point polylines for a pose-only `.dnrec` so the viewer DRAWS the model's muscles
505
+ (myoLeg / full body). Kinematic reference -> baseline activation, OR a live per-muscle activation
506
+ vector (`act_vec`, shape (M,)) that colors the muscles by the running sim. Empty channels for a rigid
507
+ model. Reuses the shared torch-free `rl_env_render.muscle_channels` (no viz-only fork)."""
508
+ T = pose.shape[0]
509
+ muscles = jm.get("muscles")
510
+ if not muscles:
511
+ return np.zeros((T, 0, 7), np.float32), np.zeros((T, 0, 4), np.float32)
512
+ from diffneusim.viz.rl_env_render import muscle_channels # lazy: a rigid model never imports it
513
+ act_arr = None
514
+ if act_vec is not None:
515
+ act_arr = np.broadcast_to(np.asarray(act_vec, np.float64).reshape(1, -1), (T, len(muscles))).copy()
516
+
517
+ class _Ref: # npz-like shim (muscle_channels reads data["q"]/["activation"] + .files)
518
+ def __init__(self, qq, aa):
519
+ self._q = np.asarray(qq, np.float64); self._a = aa
520
+ self.files = ["q"] + (["activation"] if aa is not None else [])
521
+
522
+ def __getitem__(self, k):
523
+ if k == "q":
524
+ return self._q
525
+ if k == "activation" and self._a is not None:
526
+ return self._a
527
+ raise KeyError(k)
528
+
529
+ def __contains__(self, k): # muscle_channels tests `"activation" in data` (dict-style, not .files)
530
+ return k in self.files
531
+
532
+ mtu, act, _ = muscle_channels(jm, _Ref(q, act_arr), pose.astype(np.float64),
533
+ kinematic_reference=True, reference_activation=activation)
534
+ return mtu.astype(np.float32), act.astype(np.float32)
535
+
536
+
537
+ def _dnmodel_to_dnrec(dnmodel_path, out_dnrec, pose_override=None):
538
+ """Pose-only `.dnrec` from a `.dnmodel` (torch-free), mirroring tools/render_fullbody.build_dnrec:
539
+ FK the pose(s) through the real body tree + carry the model's `visual_geoms` + the muscle via-point
540
+ polylines (so muscle models draw their muscles). Returns (jm, q, n_bodies, source_label)."""
541
+ jm = load_dnmodel(dnmodel_path)
542
+ bodies = render_bodies_from_visual_geoms(jm) # fail-fast if the model carries no visual_geoms
543
+ q, src = _resolve_pose(dnmodel_path, jm, pose_override=pose_override)
544
+ q = np.asarray(q, np.float64) # RAW pose (no viz-only knee coupling) -> faithful to the model/physics
545
+ # A pose/reference must match this model's DOF layout, or FK silently misassigns qpos and renders a
546
+ # garbage pose (e.g. a myoleg26 Ball reference nq=21 played on the compound 3-hinge variant nq=19).
547
+ _qd = {"free": 7, "ball": 4, "hinge": 1, "revolute": 1, "slide": 1, "prismatic": 1, "fixed": 0}
548
+ nq = max((int(b["qadr"]) + (sum(_qd[j["type"]] for j in b["joints"]) if "joints" in b
549
+ else _qd.get(b.get("joint"), 0))) for b in jm["bodies"])
550
+ assert q.shape[1] == nq, (
551
+ f"pose/reference nq={q.shape[1]} != model {pathlib.Path(dnmodel_path).stem!r} nq={nq} ({src}); the "
552
+ f"trajectory does not match this model's DOF layout (a nq=21 Ball ref can't play on the nq=19 "
553
+ f"compound hip, etc.). Pass a matching --ref/--pose.")
554
+ T = q.shape[0]
555
+ pose = np.stack([fk_poses(jm, q[t]) for t in range(T)]).astype(np.float32) # (T, nb, 7)
556
+ dt = float(jm["dt"]) if "dt" in jm else (1.0 / 60.0)
557
+ mtu_poly, activation = _muscle_channels_for(jm, q, pose)
558
+ write_dnrec(out_dnrec, pose,
559
+ np.zeros((T, 0), np.float32), # qvel
560
+ mtu_poly, activation,
561
+ np.zeros((T, 0), np.float32), # contact
562
+ bodies, dt, scene=pathlib.Path(dnmodel_path).stem, qpos=q.astype(np.float32),
563
+ ground_half_extent=motion_half_extent(pose, floor=2.5, margin=1.5),
564
+ com=com_track(jm, pose)) # COM-trail overlay (T key); pure kinematics from the pose
565
+ return jm, q, pose.shape[1], src
566
+
567
+
568
+ def _read_physics(jm):
569
+ """Physics options declared in the `.dnmodel` (dt, gravity, contact mode/params, solver, precision,
570
+ muscle coupling). Only the RUNTIME-live ones (dt) feed step() without a reload; the rest are model
571
+ facts (change them by editing the `.dnmodel` and re-dropping it -- the engine binds params per file)."""
572
+ contact = jm.get("contact") if isinstance(jm.get("contact"), dict) else {}
573
+ return dict(
574
+ dt=float(jm["dt"]) if "dt" in jm else (1.0 / 600.0),
575
+ gravity=list(jm.get("gravity", [0.0, 0.0, -9.81])),
576
+ contact_mode=jm.get("contact_mode", jm.get("integrator", "explicit")),
577
+ precision=jm.get("precision", "f32"),
578
+ muscle_coupling=jm.get("muscle_coupling"),
579
+ contact_params=contact.get("params"),
580
+ solver=jm.get("solver", jm.get("options")),
581
+ )
582
+
583
+
584
+ class ClipSource:
585
+ """Resolves a path (`.dnmodel` | `.dnrec`) to a loadable `.dnrec` on disk + human-readable meta.
586
+ A `.dnrec` is used verbatim; a `.dnmodel` is compiled to a `.dnrec` in a private temp dir (reused
587
+ across reloads). For a `.dnmodel` the parsed model + initial pose + declared physics are stashed in
588
+ the meta so the live engine (LiveSim) can be seeded from the exact same source."""
589
+
590
+ def __init__(self):
591
+ self._tmp = pathlib.Path(tempfile.mkdtemp(prefix="diffneusim_view_"))
592
+
593
+ def resolve(self, path, pose_override=None):
594
+ path = pathlib.Path(path)
595
+ assert path.exists(), f"no such file: {path}"
596
+ suffix = path.suffix.lower()
597
+ if suffix in RECORD_SUFFIXES:
598
+ clip = DnRec(str(path))
599
+ meta = dict(kind="dnrec", n_bodies=clip.header["n_bodies"],
600
+ scene=clip.header.get("scene", ""), source="",
601
+ dnmodel_path=None, jm=None, q0=None, physics=None)
602
+ return str(path), path, clip, meta
603
+ if suffix in MODEL_SUFFIXES:
604
+ out = self._tmp / (path.stem + ".dnrec")
605
+ jm, q, nb, src = _dnmodel_to_dnrec(str(path), str(out), pose_override=pose_override)
606
+ clip = DnRec(str(out))
607
+ meta = dict(kind="dnmodel", n_bodies=nb, scene=path.stem, source=src,
608
+ dnmodel_path=str(path), jm=jm, q0=q[0].copy(), physics=_read_physics(jm))
609
+ return str(out), path, clip, meta
610
+ raise AssertionError(f"unsupported file type {suffix!r} (expected a body {MODEL_SUFFIXES} or a record {RECORD_SUFFIXES})")
611
+
612
+
613
+ # ----------------------------------------------------------------------------- live simulation
614
+ def live14_runs(meta):
615
+ """the shipped CPU engine runs this body (a shipped muscle body, its case present, a C++ compiler): diffneusim/engine/live14.py"""
616
+ from diffneusim.engine.live14 import LiveSim14
617
+ return bool(meta) and LiveSim14.available(meta.get("dnmodel_path"))
618
+
619
+
620
+ def live_sim_available(meta):
621
+ """a live sim can start for the clip's body: the CPU engine runs it (live14_runs)"""
622
+ return live14_runs(meta)
623
+
624
+
625
+ def make_live_sim(dnmodel_path, jm, q0_np):
626
+ """the live sim: the shipped CPU engine on a shipped muscle body (diffneusim/engine/live14.py)"""
627
+ from diffneusim.engine.live14 import LiveSim14
628
+ return LiveSim14(dnmodel_path, jm, q0_np)
629
+
630
+
631
+ # ----------------------------------------------------------------------------- headless shot
632
+ def render_shot(clip_path, out_png, frame=0, width=1280, height=720,
633
+ muscles="auto", geom_groups=None, camera="auto", dist_scale=1.0, hud=True):
634
+ """Render ONE frame of a clip to a PNG via the shared offscreen renderer (no window needed).
635
+ Uses the identical camera/muscle/ground policy as to_mp4, so the still matches the mp4 look.
636
+
637
+ The muscle/group/camera arguments are the SAME RenderOptions fields tools/viz/snapshot.py exposes;
638
+ they are passed through here because snapshot.py only takes a `.dnrec`, and a `.dnmodel` has to come
639
+ through this module's ClipSource first. Without them a model shot was stuck at muscles-on and the
640
+ scene's default framing -- which hides exactly what a collider shot is for (the muscle volumes cover
641
+ the capsules, and a default camera puts a leg model in the middle distance)."""
642
+ from diffneusim.viz import renderer
643
+ opt = renderer.RenderOptions(width=width, height=height, muscle=muscles, geom_groups=geom_groups,
644
+ camera=camera, dist_scale=dist_scale, hud=hud)
645
+ prefix = str(pathlib.Path(out_png).with_suffix(""))
646
+ written = renderer.snapshots(clip_path, prefix, frames=[int(frame)], opt=opt)
647
+ return written[0]
648
+
649
+
650
+ _ACCEPTS_FIRST_MOUSE_IMP = None
651
+
652
+
653
+ def _install_accepts_first_mouse():
654
+ """macOS: give pyglet's content view ``-acceptsFirstMouse: == YES`` so the FIRST click on an inactive
655
+ window is delivered to the app (camera orbit / buttons) instead of being swallowed just to focus the
656
+ window -- the "have to double-click first" symptom. Idempotent; keeps the IMP alive (ObjC would call a
657
+ garbage-collected callback and crash). No-op / guarded off macOS or if the class isn't registered yet."""
658
+ global _ACCEPTS_FIRST_MOUSE_IMP
659
+ if _ACCEPTS_FIRST_MOUSE_IMP is not None or sys.platform != "darwin":
660
+ return
661
+ import pyglet.window.cocoa.pyglet_view # noqa: F401 -- ensures the PygletView ObjC class is registered
662
+ from pyglet.libs.darwin.cocoapy import runtime
663
+ cls = runtime.get_class('PygletView')
664
+ if not cls:
665
+ return
666
+ def _yes(self, cmd, event): # -(BOOL)acceptsFirstMouse:(NSEvent*) encoding B@:@
667
+ return True
668
+ _ACCEPTS_FIRST_MOUSE_IMP = runtime.add_method(cls, b'acceptsFirstMouse:', _yes, b'B@:@')
669
+
670
+
671
+ # ----------------------------------------------------------------------------- interactive window
672
+ def _run_window(init_path, pose_override, width, height, start_frame, selftest_out=None, start_sim=False,
673
+ start_bake_frames=None, start_hang=None, start_picker=False):
674
+ import moderngl
675
+ import moderngl_window as mglw
676
+ from diffneusim.viz.camera import OrbitCamera # noqa: F401 (re-exported for reset via resolve_camera)
677
+ from diffneusim.viz.hud import AxisGizmo
678
+ from diffneusim.viz.ui import ControlPanel, Row
679
+ from diffneusim.viz.render import MUSCLE_RENDER_MODES
680
+ from diffneusim.viz import renderer
681
+
682
+ class Viewer(mglw.WindowConfig):
683
+ gl_version = (3, 3)
684
+ title = "diffneusim viewer"
685
+ window_size = (width, height)
686
+ aspect_ratio = None
687
+ resizable = True
688
+
689
+ def __init__(self, **kwargs):
690
+ super().__init__(**kwargs)
691
+ self._src = ClipSource()
692
+ # Modern control panel (Blender/MuJoCo style): every control shown with its live state, and
693
+ # each row is clickable (the keyboard shortcut, shown as a chip, is just an accelerator).
694
+ self._panel = ControlPanel(self.ctx, width_px=384, font_size=19)
695
+ self._panel_visible = True
696
+ self._hover_row = -1
697
+ # inline numeric editor: which value row is being typed into (its `action`) + the keystroke buffer.
698
+ self._edit_action = ""
699
+ self._edit_buf = ""
700
+ self._px = 1.0 # framebuffer-px / window-pt (retina); set each render
701
+ self._make_overlays()
702
+ # playback / input state
703
+ self.frame = float(start_frame)
704
+ self.playing = True
705
+ self.speed = 1.0
706
+ self._drag = None # 'orbit' | 'pan' | 'scrub'
707
+ self._shift = False
708
+ self._last = (0, 0)
709
+ self._cam_track = False # K: keep the camera target locked on the COM (orbit/zoom still work)
710
+ self._selftest_out = selftest_out # smoke test: capture the window framebuffer + auto-close
711
+ self._render_count = 0
712
+ self._activated = False # macOS: bring the window to the foreground once (see on_render)
713
+ self._capture_pending = False # P / Capture button: grab the frame BEFORE the panel draws
714
+ # idle throttle: moderngl-window redraws the (heavy) scene EVERY vsync tick, so a static view
715
+ # still pins the GPU and drains the battery. When nothing is animating and there's been no input
716
+ # for a moment, sleep in on_render to cap the redraw rate way down (a big battery win); any input
717
+ # or animation instantly restores full framerate. Times in seconds; rates in fps.
718
+ self._last_input_t = time.perf_counter()
719
+ self._idle_after = 0.4 # grace before throttling (keeps interaction snappy)
720
+ self._idle_fps = 6.0 # cap while briefly idle
721
+ self._deep_idle_after = 5.0 # after this long idle, throttle harder
722
+ self._deep_idle_fps = 2.0
723
+ # live-sim (Phase 2) state: real engine, CUDA-only, off by default
724
+ self.sim = None # LiveSim | None
725
+ self.sim_running = False
726
+ self.sim_dt = 1.0 / 600.0 # editable step dt (feeds the real step())
727
+ self.sim_excite = 0.0 # editable muscle excitation u in [0,1]
728
+ self._sim_budget = 0.0 # wall-clock pacing accumulator
729
+ self._sim_cap = 8 # max engine steps per frame (never block the UI / never fake speed)
730
+ # bake (pre-compute N frames of physics, then replay them instantly): editable frame count +
731
+ # steps/frame (steps/frame auto-tracks dt for ~real-time replay until the design brief sets it).
732
+ self._bake_target = 300 # frames to record
733
+ self._bake_substeps = 8 # engine steps per recorded frame (auto-set from dt on load)
734
+ self._bake_substeps_user = False
735
+ self._baked = False # the current clip is a baked trajectory (not the static pose)
736
+ self._reset_bake_state()
737
+ # right-side JOINT / MUSCLE control panel (dnmodel only): a scrollable panel of per-DOF joint
738
+ # sliders (kinematic pose-edit) + per-muscle activation sliders. Off by default (U toggles it).
739
+ self._ctrl_panel = ControlPanel(self.ctx, width_px=404, font_size=17, viewport_h=100)
740
+ self._ctrl_visible = True # on by default (dnmodel); U or the left-panel button hides it
741
+ self._ctrl_hover = -1
742
+ self._mouse_xy = (0, 0) # last cursor pos (window pt) -> route the wheel to the panel it's over
743
+ self._joint_ctl = [] # per-DOF slider descriptors (built per model in _build_dof_controls)
744
+ self._ctl_by_action = {} # action-id -> descriptor
745
+ self._ctrl_q = None # (nq,) editable kinematic pose (None until a dnmodel is loaded)
746
+ self._ctrl_u = np.zeros(0) # (nm,) per-muscle activation / excitation in [0,1]
747
+ self._muscle_names = []
748
+ # muscle-follow throttle for a JOINT drag: rebuilding all muscle via-points is cheap on a small
749
+ # model (myoLeg ~2 ms) but not on full body (~24 ms), so during a drag we recompute muscles only
750
+ # once at least the LAST rebuild's own duration has elapsed (<=50% duty cycle) -- self-tuning, so
751
+ # light models follow every frame (no lag) and heavy models stay smooth. Release does a final one.
752
+ self._ctrl_last_muscle_t = 0.0 # perf_counter of the last in-drag muscle rebuild
753
+ self._ctrl_muscle_ms = 0.0 # measured cost (ms) of the last muscle rebuild
754
+ self._ctrl_live_q = None # throttled snapshot of the live sim q (read-only joint tracking)
755
+ self._ctrl_live_t = 0.0
756
+ self._pose_dirty = False # a joint/muscle edit is pending -> applied ONCE per render frame
757
+ self._models = discover_models() # general registry for the in-viewer Model picker
758
+ self._model_picker = bool(start_picker) # picker overlay open? (click the Model row to toggle; --pick)
759
+ # root suspension ("hang the model in the air", Y): live physics makes an unsupported model
760
+ # FALL, which hides the very thing a muscle/joint inspection wants to see. Hanging holds the
761
+ # model's floating-base coordinates at a fixed floor clearance -- a kinematic clamp re-applied
762
+ # after every engine step (LiveSim.set_pin), so the internal joints, muscles and contacts run
763
+ # the normal physics while the body cannot go anywhere. Per model, no per-model constants:
764
+ # the base dofs and their world directions come off the loaded .dnmodel (_base_dof_spec).
765
+ self._hang = False
766
+ self._hang_clear = 0.30 # target floor clearance (m) under the model's lowest point
767
+ self._hang_hold_rot = True # hold the base ORIENTATION too (a test stand) vs let it swing
768
+ self._base_spec = None # base-dof descriptor of the loaded model (None = nothing to hold)
769
+ self._base_dirs = None # (3, n) world direction of each base translation dof
770
+ self.load(init_path, pose_override=pose_override)
771
+ print(__doc__.split("Controls")[1])
772
+ if start_hang is not None: # --hang: suspend FIRST, so a --sim/--bake seeds from it
773
+ self._hang_clear = float(start_hang)
774
+ self.toggle_hang()
775
+ if start_bake_frames: # --bake N: launch straight into a bake -> instant replay
776
+ self._bake_target = int(start_bake_frames)
777
+ self._start_bake()
778
+ elif start_sim: # --sim: launch straight into live simulation
779
+ self.toggle_sim()
780
+ elif selftest_out: # smoke test also exercises the Phase-2 UI + CUDA gate
781
+ self._ctrl_visible = self.meta["kind"] == "dnmodel" # + the joint/muscle control panel
782
+ self.toggle_sim()
783
+
784
+ # --- (re)load a file ------------------------------------------------
785
+ def load(self, path, pose_override=None):
786
+ try:
787
+ clip_path, orig_path, clip, meta = self._src.resolve(path, pose_override=pose_override)
788
+ except Exception as e: # a bad/unrenderable model must not kill the viewer
789
+ print(f"could not load {pathlib.Path(path).name}: {e}")
790
+ return
791
+ self.clip_path = clip_path
792
+ self.orig_path = pathlib.Path(orig_path)
793
+ self.meta = meta
794
+ self._opt = renderer.RenderOptions()
795
+ self._install_clip(clip, reset_cam=True)
796
+ # reset any live-sim / bake on (re)load; seed the editable dt from the model's declared physics.
797
+ self.sim = None
798
+ self.sim_running = False
799
+ self._sim_budget = 0.0
800
+ self._baked = False
801
+ self._hang = False # a different model is not silently left hanging
802
+ self._edit_action = ""; self._edit_buf = ""
803
+ self._reset_bake_state()
804
+ if meta.get("physics"):
805
+ self.sim_dt = float(meta["physics"]["dt"])
806
+ self._bake_substeps = max(1, round((1.0 / 60.0) / max(self.sim_dt, 1e-9))) # ~real-time replay
807
+ self._bake_substeps_user = False
808
+ self._build_dof_controls() # rebuild the joint/muscle sliders for the new model
809
+ self._ctrl_panel.scroll = 0.0
810
+ print(f"loaded {self.orig_path.name}: {meta['kind']} scene={meta['scene']} "
811
+ f"frames={clip.n_frames} bodies={meta['n_bodies']} "
812
+ f"channels={list(clip.channels)} {meta['source']}")
813
+
814
+ def _install_clip(self, clip, reset_cam):
815
+ """Swap in a clip (loaded file OR a freshly baked trajectory) and rebuild the render Scene from
816
+ it, WITHOUT touching `self.meta` -- so a bake keeps the source `.dnmodel` meta (for re-baking /
817
+ live-sim) while replaying the recorded frames. `reset_cam` refits the camera (a fresh file), or
818
+ leaves it put (a bake, so the view doesn't jump)."""
819
+ self.clip = clip
820
+ self.scene = renderer.make_scene(self.ctx, clip, self._opt)
821
+ self.scene.show_hud = False # this module owns the HUD (its own info line)
822
+ self.fps_clip = 1.0 / clip.dt if clip.dt > 0 else 60.0
823
+ self.frame = min(self.frame, max(0, clip.n_frames - 1))
824
+ if reset_cam:
825
+ self.reset_camera()
826
+
827
+ # --- joint / muscle control panel (right side) -----------------------
828
+ def _build_dof_controls(self):
829
+ """Build the per-DOF joint slider descriptors + the per-muscle activation vector for the
830
+ current model, from the parsed `.dnmodel`. Called on every (re)load. A `.dnrec` (no jm) or a
831
+ rigid model yields empty joint/muscle lists (the panel then just shows a hint). Descriptors are
832
+ plain dicts (kind + indices + range) resolved by `_dof_get/_dof_set` -- no per-DOF closures."""
833
+ self._joint_ctl = []
834
+ self._ctl_by_action = {}
835
+ self._muscle_names = []
836
+ self._base_spec = None
837
+ self._base_dirs = None
838
+ jm = self.meta.get("jm")
839
+ q0 = self.meta.get("q0")
840
+ if jm is None or q0 is None: # a .dnrec: nothing to pose-edit
841
+ self._ctrl_q = None
842
+ self._ctrl_u = np.zeros(0)
843
+ return
844
+ self._base_spec = _base_dof_spec(jm) # the floating base the Y key hangs the model by
845
+ if self._base_spec is not None:
846
+ self._base_dirs = _base_world_dirs(jm, q0, self._base_spec)
847
+ self._ctrl_q = np.asarray(q0, dtype=np.float64).copy()
848
+ for k, desc in enumerate(_joint_slider_descriptors(jm)):
849
+ desc["action"] = f"j{k}"
850
+ self._joint_ctl.append(desc)
851
+ self._ctl_by_action[desc["action"]] = desc
852
+ muscles = jm.get("muscles") or []
853
+ self._muscle_names = [m.get("name", f"m{i}") for i, m in enumerate(muscles)]
854
+ self._ctrl_u = np.zeros(len(muscles), dtype=np.float64) # start relaxed (0 = passive)
855
+
856
+ def _dof_get(self, c, q=None):
857
+ q = self._ctrl_q if q is None else q # read from an explicit q (live tracking) or the edit pose
858
+ if c["kind"] in ("scalar", "pos"):
859
+ return float(q[c["idx"]])
860
+ return float(_quat_to_rotvec(q[c["base"]:c["base"] + 4])[c["comp"]])
861
+
862
+ def _dof_set(self, c, v):
863
+ q = self._ctrl_q
864
+ v = min(c["hi"], max(c["lo"], float(v)))
865
+ if c["kind"] in ("scalar", "pos"):
866
+ q[c["idx"]] = v
867
+ else: # rotvec component -> recompose the quat
868
+ rv = _quat_to_rotvec(q[c["base"]:c["base"] + 4])
869
+ rv[c["comp"]] = v
870
+ q[c["base"]:c["base"] + 4] = _rotvec_to_quat(rv)
871
+
872
+ def _slider_spec(self, action):
873
+ """(lo, hi, getter, setter) for a slider `action` (joint DOF or `mus<i>` muscle), or None."""
874
+ if action.startswith("mus"):
875
+ i = int(action[3:])
876
+ if not (0 <= i < self._ctrl_u.size):
877
+ return None
878
+ return (0.0, 1.0, (lambda: float(self._ctrl_u[i])), (lambda v: self._set_muscle(i, v)))
879
+ c = self._ctl_by_action.get(action)
880
+ if c is None:
881
+ return None
882
+ return (c["lo"], c["hi"], (lambda: self._dof_get(c)), (lambda v: self._dof_set(c, v)))
883
+
884
+ def _set_muscle(self, i, v):
885
+ self._ctrl_u[i] = min(1.0, max(0.0, float(v)))
886
+
887
+ def _set_slider(self, action, frac):
888
+ """Set a slider from a track fraction in [0,1] (click / drag), then refresh the view."""
889
+ spec = self._slider_spec(action)
890
+ if spec is None:
891
+ return
892
+ lo, hi, _get, setter = spec
893
+ setter(lo + frac * (hi - lo))
894
+ self._after_ctrl_edit(action)
895
+
896
+ def _pd_qadr(self):
897
+ """The q indices a PD actuator drives (the model's `actuators` block), as a set."""
898
+ return {int(a["qadr"]) for a in self.meta["jm"].get("actuators", [])}
899
+
900
+ def _cap_cpu_pd_dt(self):
901
+ """A PD model on the CPU ext keeps dt <= 1 ms: that path steps contact explicitly and cannot take the PD's
902
+ dt * kd armature fold. At the G1's own 5 ms it bounces and diverges; at 1 ms its root height follows
903
+ MuJoCo's (implicitfast, 5 ms) to ~5 mm over the first second of a PD hold."""
904
+ fd = getattr(self.sim, "fixed_dt", None) # the D16 CPU engine steps its law's substep only (live14.py)
905
+ if fd is not None and self.sim_dt != fd:
906
+ print(f"live-sim on {self.sim.label}: dt {self.sim_dt:.1e} -> {fd:.1e} (the law's substep)")
907
+ self.sim_dt = fd
908
+ if not self._bake_substeps_user:
909
+ self._bake_substeps = max(1, round((1.0 / 60.0) / self.sim_dt))
910
+ if self.sim.pd is not None and self.sim.backend == "cpu" and self.sim_dt > 1e-3:
911
+ print(f"PD model on the CPU ext: dt {self.sim_dt:.1e} -> 1.0e-03 (explicit contact and PD damping)")
912
+ self.sim_dt = 1e-3
913
+ if not self._bake_substeps_user: # keep steps/frame ~real-time
914
+ self._bake_substeps = max(1, round((1.0 / 60.0) / self.sim_dt))
915
+
916
+ def _after_ctrl_edit(self, action):
917
+ """Flag the edit for a SINGLE coalesced apply in `on_render` (so a fast slider drag, which fires
918
+ many mouse events per frame, can't stack FK + muscle rebuilds and stall the loop). A muscle edit
919
+ during live-sim needs nothing here (the engine reads `_ctrl_u` each step)."""
920
+ if action.startswith("mus") and self.sim is not None:
921
+ return
922
+ if self.sim is not None and self.sim.pd is not None: # live PD: a joint slider moves its TARGET
923
+ self.sim.set_pd_targets(self._ctrl_q)
924
+ return
925
+ self._pose_dirty = True
926
+
927
+ def _maybe_apply_pose_edit(self):
928
+ """Apply a pending pose/muscle edit ONCE per render frame (coalesced). FK is cheap and always
929
+ runs; the ~2-24 ms muscle via-point rebuild is SKIPPED ENTIRELY when the muscle render is off
930
+ (that was the joint-drag lag "even with muscles off"), and during a drag is throttled to <=50%
931
+ of its own cost so a heavy model still drags smoothly (a later frame catches the muscles up)."""
932
+ if not self._pose_dirty or self._ctrl_q is None or self.sim is not None or self._baking:
933
+ return
934
+ if self.scene.poses.shape[0] != 1: # only the static single-frame pose is editable
935
+ self._pose_dirty = False
936
+ return
937
+ self._pose_dirty = False
938
+ muscles = self.scene.muscle_mode != "off"
939
+ dragging = isinstance(self._drag, tuple) and self._drag and self._drag[0] == "slider"
940
+ if muscles and dragging:
941
+ now = time.perf_counter()
942
+ if (now - self._ctrl_last_muscle_t) * 1000.0 < self._ctrl_muscle_ms:
943
+ muscles = False # skip this frame; revisit to refresh muscles
944
+ self._pose_dirty = True
945
+ else:
946
+ self._ctrl_last_muscle_t = now
947
+ self._refresh_pose_edit(muscles=muscles)
948
+
949
+ def _refresh_pose_edit(self, muscles=True):
950
+ """Push the editable kinematic pose `_ctrl_q` (+ `_ctrl_u` muscle colours) into the Scene.
951
+ Only meaningful for a static single-frame dnmodel pose that no live-sim / bake owns -- so it is
952
+ a no-op during live-sim, baking, or trajectory playback (those drive frame 0 themselves)."""
953
+ if (self._ctrl_q is None or self.sim is not None or self._baking
954
+ or self.scene.poses.shape[0] != 1):
955
+ return
956
+ jm = self.meta["jm"]
957
+ qc = self._ctrl_q
958
+ self.scene.poses[0, :, :] = fk_poses(jm, qc).astype(np.float32)
959
+ # rebuild muscle via-points ONLY when the muscles are actually drawn (mode != off) -- the whole-
960
+ # model rebuild is the expensive part, and computing it for a hidden overlay is pure waste.
961
+ if (muscles and self.scene.muscle_mode != "off"
962
+ and self.scene.mtu_poly is not None and self.scene.mtu_poly.shape[1] > 0):
963
+ _t = time.perf_counter()
964
+ mtu, act = _muscle_channels_for(jm, qc[None, :], self.scene.poses[0][None, :],
965
+ act_vec=(self._ctrl_u if self._ctrl_u.size else None))
966
+ self.scene.mtu_poly[0] = mtu[0]
967
+ if self.scene.activation is not None:
968
+ self.scene.activation[0] = act[0]
969
+ self.scene.mark_muscle_dirty()
970
+ self._ctrl_muscle_ms = (time.perf_counter() - _t) * 1000.0 # feeds the drag throttle above
971
+
972
+ def _build_control_rows(self, fi):
973
+ """Rows for the right-side control panel: per-DOF joint sliders (static pose-edit) + per-muscle
974
+ activation sliders (colour when static, per-muscle drive during live-sim)."""
975
+ rows = [Row("header", "CONTROL"), Row("button", "✕ close", key="U", action="ctrlpanel")]
976
+ if self.meta.get("jm") is None:
977
+ rows.append(Row("text", "controls", value="need a .dnmodel"))
978
+ return rows
979
+ static = self.sim is None and not self._baking and self.clip.n_frames == 1
980
+ live = self.sim is not None
981
+ if self._joint_ctl:
982
+ pd_q = self._pd_qadr() if live and self.sim.pd is not None else set()
983
+ rows.append(Row("header", "JOINTS" + (" · PD targets (live)" if pd_q else
984
+ " · live (read-only)" if live else "")))
985
+ if static or live:
986
+ qsrc = None
987
+ if static:
988
+ rows.append(Row("button", "Reset pose", action="ctrl_reset"))
989
+ else: # live-sim: the joint VALUES track the sim (no edit)
990
+ now = time.perf_counter() # throttle the GPU->CPU q read to ~15 fps
991
+ if self._ctrl_live_q is None or now - self._ctrl_live_t > 0.066:
992
+ self._ctrl_live_q = self.sim.q_np(); self._ctrl_live_t = now
993
+ qsrc = self._ctrl_live_q
994
+ for c in self._joint_ctl:
995
+ target = c["kind"] == "scalar" and c["idx"] in pd_q # a live PD target: editable
996
+ v = self._dof_get(c, None if target else qsrc)
997
+ lo, hi = c["lo"], c["hi"]
998
+ frac = (v - lo) / (hi - lo) if hi > lo else 0.5
999
+ rows.append(Row("slider", c["label"], value=f"{v:+.2f}",
1000
+ frac=min(1.0, max(0.0, frac)), action=c["action"],
1001
+ enabled=static or target)) # other live rows are read-only (value follows)
1002
+ else:
1003
+ rows.append(Row("text", "joints", value="static pose or live-sim"))
1004
+ if self._muscle_names:
1005
+ rows.append(Row("header", f"MUSCLES · {'drive' if live else 'colour'}"))
1006
+ if static or live: # actionable: colour the static pose, or drive live-sim
1007
+ rows += [Row("button", "Relax all (0)", action="mus_zero"),
1008
+ Row("button", "Set all 0.5", action="mus_half")]
1009
+ for i, nm in enumerate(self._muscle_names):
1010
+ u = float(self._ctrl_u[i])
1011
+ rows.append(Row("slider", nm, value=f"{u:.2f}", frac=u, action=f"mus{i}"))
1012
+ else: # baked replay owns frame 0 -> sliders can't update it
1013
+ rows.append(Row("text", "muscles", value="static pose or live-sim"))
1014
+ return rows
1015
+
1016
+ # --- root suspension: hang the model in the air (Y) ------------------
1017
+ def _hang_why_not(self):
1018
+ """Empty when this model can be hung, else the short reason (shown on the disabled row)."""
1019
+ if self.meta["kind"] != "dnmodel":
1020
+ return "needs a .dnmodel"
1021
+ if self._base_spec is None:
1022
+ return "no floating base"
1023
+ if not _base_lifts_vertically(self._base_dirs):
1024
+ return "base has no vertical dof"
1025
+ return ""
1026
+
1027
+ def toggle_hang(self):
1028
+ """Y / the panel toggle: suspend the model by its floating base, or release it (releasing
1029
+ leaves it where it hangs -- the next step drops it from there, same as stopping the sim)."""
1030
+ if self._baking: # the pin is part of the physics being recorded
1031
+ print("bake in progress — cancel it (Esc) first")
1032
+ return
1033
+ if self._hang:
1034
+ self._hang = False
1035
+ if self.sim is not None:
1036
+ self.sim.set_pin(None)
1037
+ print("root hang OFF (base released)")
1038
+ return
1039
+ why = self._hang_why_not()
1040
+ if why:
1041
+ print(f"root hang unavailable: {why}")
1042
+ return
1043
+ self._hang = True
1044
+ self._hang_refit()
1045
+
1046
+ def _hang_refit(self):
1047
+ """Fit the suspension to the CURRENT pose: lift the base until the model's lowest point sits
1048
+ `_hang_clear` above the floor, then hold those base coordinates -- as a pin the engine step
1049
+ cannot move (live-sim / bake) and/or on the static editable pose (which is also what a later
1050
+ live-sim seeds from). Re-called whenever the clearance or the hold-orientation setting
1051
+ changes and after a sim (re)start / reset, so the pin always matches the pose it was hung in.
1052
+ A no-op when nothing is hanging."""
1053
+ if not self._hang or self._base_spec is None:
1054
+ return
1055
+ jm, spec = self.meta["jm"], self._base_spec
1056
+ live = self.sim is not None
1057
+ if not live and self._ctrl_q is None:
1058
+ return
1059
+ if live and not self.sim.finite(): # a diverged qpos has no lowest point to measure
1060
+ print("root hang: the sim has diverged (non-finite qpos); reset it (R) first")
1061
+ return
1062
+ q = self.sim.q_np().astype(np.float64) if live else np.asarray(self._ctrl_q, np.float64)
1063
+ qh, dz = _lift_to_clearance(jm, q, spec, self._hang_clear) # dirs measured at THIS pose
1064
+ q_idx = list(spec["q_pos"]) + (list(spec["q_rot"]) if self._hang_hold_rot else [])
1065
+ v_idx = list(spec["v_pos"]) + (list(spec["v_rot"]) if self._hang_hold_rot else [])
1066
+ if live:
1067
+ self.sim.set_pin(q_idx, qh[q_idx], v_idx)
1068
+ self._push_sim_pose() # show the lift immediately, even while paused
1069
+ else:
1070
+ self._ctrl_q[:] = qh
1071
+ self._pose_dirty = True
1072
+ print(f"root hang ON: {spec['label']} held at {self._hang_clear:.2f} m clearance "
1073
+ f"(lifted {dz * 1000:+.0f} mm), orientation "
1074
+ f"{'held' if self._hang_hold_rot else 'free (swings from the pin)'}")
1075
+
1076
+ # --- live simulation (Phase 2): the REAL engine, CUDA-only -----------
1077
+ def toggle_sim(self):
1078
+ """Start/stop live physics through the REAL engine (`diffneusim.load()` on CUDA, or the CPU ext
1079
+ on a no-GPU Mac). dnmodel-only. An unsupported CPU model is reported and the tool stays a viewer."""
1080
+ if self._baking: # a bake owns the sim; don't yank it out mid-record
1081
+ print("bake in progress — cancel it (Esc) first")
1082
+ return
1083
+ if self.sim is not None: # already live -> stop, FREEZE at the current pose
1084
+ self.sim = None
1085
+ self.sim_running = False
1086
+ # keep the last simulated pose (bones AND muscles stay put) rather than snapping back to
1087
+ # the loaded model pose -- stopping should freeze the result, not teleport to reset.
1088
+ print("live-sim stopped (frozen at current pose)")
1089
+ return
1090
+ if self.meta["kind"] != "dnmodel":
1091
+ print("live-sim needs a .dnmodel (a .dnrec is a recorded trajectory -- just play it)")
1092
+ return
1093
+ if not live_sim_available(self.meta):
1094
+ print("live-sim unavailable: no CUDA GPU and the CPU ext is not built. Build it with "
1095
+ "`cmake -S bindings -B bindings/build_cpu -GNinja -DPython_EXECUTABLE=$(pwd)/python/"
1096
+ ".venv/bin/python && cmake --build bindings/build_cpu --target _diffneusim_rl`.")
1097
+ return
1098
+ try:
1099
+ self.sim = make_live_sim(self.meta["dnmodel_path"], self.meta["jm"],
1100
+ self._ctrl_q if self._ctrl_q is not None else self.meta["q0"])
1101
+ except Exception as e: # e.g. CPU ext has no backend for this size
1102
+ print(f"live-sim not started: {e}")
1103
+ self.sim = None
1104
+ return
1105
+ self._cap_cpu_pd_dt()
1106
+ self.sim.dt = self.sim_dt
1107
+ self.sim_running = True
1108
+ self._sim_budget = 0.0
1109
+ self.scene._trail_pts = [] # fresh COM track for this live-sim run (T-key overlay)
1110
+ # live contact-force arrows: the dnmodel clip carries no contact channel, so allocate one
1111
+ # (1, ncon, 7) and drive it from the engine's own contact force each step (see _sim_advance).
1112
+ # Default ON so contacts are visible immediately; the F key / panel toggle still hides them.
1113
+ if self.sim.ncon > 0:
1114
+ self.scene.contact = np.zeros((1, self.sim.ncon, 7), np.float32)
1115
+ self.scene.show_contact = True
1116
+ print(f"live-sim ON [{self.sim.backend}]: {self.meta['scene']} nq={self.sim.nq} nv={self.sim.nv} "
1117
+ f"muscles={self.sim.nm} contacts={self.sim.ncon} dt={self.sim_dt:.2e}")
1118
+ self._hang_refit() # a fresh LiveSim carries no pin: re-install it if hung
1119
+
1120
+ def _sim_advance(self, frametime):
1121
+ """Wall-clock-paced forward stepping of the real engine. Steps to consume the elapsed wall
1122
+ time (x speed) at the true engine rate -- capped per frame so a heavy model just runs in
1123
+ slow motion (its real speed) instead of blocking the UI. Then push the live qpos into the
1124
+ Scene pose buffer, FK'd through the same body tree as playback."""
1125
+ self.sim.dt = self.sim_dt
1126
+ self.sim.excitation = self.sim_excite
1127
+ if self.sim.has_muscle: # per-muscle drive from the control-panel sliders
1128
+ self.sim.excitation_vec = self._ctrl_u if self._ctrl_u.size == self.sim.nm else None
1129
+ self._sim_budget += frametime * self.speed
1130
+ nsteps = min(self._sim_cap, int(self._sim_budget / max(self.sim_dt, 1e-6)))
1131
+ self._sim_budget -= nsteps * self.sim_dt
1132
+ for _ in range(nsteps):
1133
+ self.sim.step(self.sim_dt)
1134
+ if not self.sim.finite():
1135
+ self.sim_running = False
1136
+ print(f"live-sim diverged (non-finite qpos) at step {self.sim.n_steps}; paused")
1137
+ return # freeze at the last good pose; NEVER FK / muscle-channel a non-finite
1138
+ # qpos (the via-points collapse -> muscle_channels asserts -> viewer dies)
1139
+ # FK the engine's live qpos and drive the Scene's frame-0 pose buffer (same visual_geoms path).
1140
+ # FAITHFUL: the RAW engine qpos is shown -- no viz-only correction. (The free knee-glide dofs
1141
+ # drift under load = a real model gap; the viewer must show it, not hide it. Fix belongs in the
1142
+ # model/engine so training benefits too.)
1143
+ self._push_sim_pose()
1144
+
1145
+ def _push_sim_pose(self):
1146
+ """FK the engine's current qpos into the Scene (bones + muscles + contact). Shared by the live
1147
+ step loop AND reset, so a paused reset snaps the view back to the reset pose immediately
1148
+ (previously reset changed the sim state but not the display until you resumed stepping)."""
1149
+ qc = self.sim.q_np()
1150
+ pose = fk_poses(self.meta["jm"], qc).astype(np.float32)
1151
+ self.scene.poses[0, :, :] = pose
1152
+ if self.scene.show_trail: # live COM trail (frame-0-pinned sim accumulates it)
1153
+ self.scene._trail_pts.append(com_track(self.meta["jm"], pose[None])[0, 0])
1154
+ if len(self.scene._trail_pts) > 400:
1155
+ del self.scene._trail_pts[0]
1156
+ if self.scene.mtu_poly is not None and self.scene.mtu_poly.shape[1] > 0: # live muscles follow the pose
1157
+ mtu, act = _muscle_channels_for(self.meta["jm"], qc[None, :], pose[None, :],
1158
+ act_vec=self.sim.act_np() if self.sim.has_muscle else None)
1159
+ self.scene.mtu_poly[0] = mtu[0]
1160
+ if self.scene.activation is not None:
1161
+ self.scene.activation[0] = act[0]
1162
+ self.scene.mark_muscle_dirty() # in-place mutation at frame 0 -> rebuild the cached tubes
1163
+ if self.scene.show_contact and self.scene.contact is not None and self.sim.ncon > 0: # live GRF arrows
1164
+ try:
1165
+ c = self.sim.contact_np()
1166
+ if c is not None:
1167
+ self.scene.contact[0] = c
1168
+ except Exception as e:
1169
+ self.scene.show_contact = False
1170
+ print(f"contact-force readout unavailable ({e}); arrows off")
1171
+
1172
+ # --- bake (pre-compute N frames -> instant replay) -------------------
1173
+ def _reset_bake_state(self):
1174
+ self._baking = False
1175
+ self._bake_i = 0
1176
+ self._bake_pose = []; self._bake_q = []
1177
+ self._bake_mtu = []; self._bake_act = []; self._bake_con = []
1178
+
1179
+ def _start_bake(self):
1180
+ """Kick off a non-blocking bake: (re)seed a LiveSim at the model's initial pose and record
1181
+ `_bake_target` frames (each = `_bake_substeps` engine steps) with the current dt/excitation.
1182
+ The frames are accumulated incrementally by `_bake_step` (called from on_render), so the UI /
1183
+ progress bar stay live while a heavy model bakes."""
1184
+ if self.meta["kind"] != "dnmodel":
1185
+ print("bake needs a .dnmodel (a .dnrec is already a recorded trajectory -- just play it)")
1186
+ return
1187
+ if self._baking:
1188
+ return
1189
+ if not live_sim_available(self.meta):
1190
+ print("bake unavailable: no CUDA GPU and the CPU ext is not built (see the live-sim hint).")
1191
+ return
1192
+ try:
1193
+ if self.sim is None:
1194
+ self.sim = make_live_sim(self.meta["dnmodel_path"], self.meta["jm"],
1195
+ self._ctrl_q if self._ctrl_q is not None else self.meta["q0"])
1196
+ else:
1197
+ self.sim.reset() # deterministic: every bake starts from the same q0
1198
+ except Exception as e: # e.g. CPU ext has no backend for this size
1199
+ print(f"bake not started: {e}")
1200
+ self.sim = None
1201
+ return
1202
+ self._cap_cpu_pd_dt()
1203
+ if self.sim.pd is not None and self._ctrl_q is not None: # the panel's targets, not the reset's
1204
+ self.sim.set_pd_targets(self._ctrl_q)
1205
+ self.sim.dt = self.sim_dt
1206
+ self._hang_refit() # bake the SUSPENDED model when the root is hung
1207
+ self.sim_running = False # the bake loop drives stepping, not the live-sim loop
1208
+ self._reset_bake_state()
1209
+ self._baking = True
1210
+ self._bake_has_muscle = bool(self.meta["jm"].get("muscles"))
1211
+ self._bake_ncon = self.sim.ncon
1212
+ print(f"baking {self._bake_target} frames x {self._bake_substeps} steps @ dt={self.sim_dt:.3e} "
1213
+ f"[{self.sim.backend}] -> replay dt={self.sim_dt * self._bake_substeps:.3e}")
1214
+
1215
+ def _bake_step(self):
1216
+ """Advance the bake by a wall-time-budgeted chunk (keeps the window responsive): step the engine
1217
+ `_bake_substeps` per recorded frame, FK + muscle + contact each frame, and mirror the latest
1218
+ pose into the Scene so the design brief watches it build. Finishes / diverges -> assemble the clip."""
1219
+ self.sim.excitation = self.sim_excite # live edits to excitation apply as the bake runs
1220
+ if self.sim.has_muscle: # per-muscle drive from the control-panel sliders
1221
+ self.sim.excitation_vec = self._ctrl_u if self._ctrl_u.size == self.sim.nm else None
1222
+ jm = self.meta["jm"]
1223
+ t_end = time.perf_counter() + 0.08 # ~80 ms/frame budget -> UI still refreshes during bake
1224
+ last = None
1225
+ while self._bake_i < self._bake_target and time.perf_counter() < t_end:
1226
+ for _ in range(self._bake_substeps):
1227
+ self.sim.step(self.sim_dt)
1228
+ if not self.sim.finite():
1229
+ print(f"bake diverged (non-finite qpos) at frame {self._bake_i}; keeping the good frames")
1230
+ self._bake_target = self._bake_i
1231
+ break
1232
+ qc = self.sim.q_np()
1233
+ pose = fk_poses(jm, qc).astype(np.float32)
1234
+ mtu = act = None
1235
+ if self._bake_has_muscle:
1236
+ mtu, act = _muscle_channels_for(jm, qc[None, :], pose[None, :],
1237
+ act_vec=self.sim.act_np() if self.sim.has_muscle else None)
1238
+ self._bake_mtu.append(mtu[0]); self._bake_act.append(act[0])
1239
+ if self._bake_ncon > 0:
1240
+ c = self.sim.contact_np()
1241
+ self._bake_con.append(c if c is not None else np.zeros((self._bake_ncon, 7), np.float32))
1242
+ self._bake_pose.append(pose); self._bake_q.append(qc.astype(np.float32))
1243
+ self._bake_i += 1
1244
+ last = (pose, mtu, act)
1245
+ if last is not None: # show the bake progressing (bones + muscles follow)
1246
+ pose, mtu, act = last
1247
+ self.scene.poses[0, :, :] = pose
1248
+ if mtu is not None and self.scene.mtu_poly is not None and self.scene.mtu_poly.shape[1] > 0:
1249
+ self.scene.mtu_poly[0] = mtu[0]
1250
+ if self.scene.activation is not None:
1251
+ self.scene.activation[0] = act[0]
1252
+ self.scene.mark_muscle_dirty()
1253
+ if self._bake_i >= self._bake_target:
1254
+ self._finish_bake()
1255
+
1256
+ def _finish_bake(self):
1257
+ """Assemble the recorded frames into a `.dnrec` (shared writer -> identical render path) and
1258
+ install it as the current clip, so playback/scrub is now instant. Keeps the `.dnmodel` meta so
1259
+ the BAKE / live-sim controls stay available for another run."""
1260
+ jm = self.meta["jm"]
1261
+ T = self._bake_i
1262
+ if T < 2:
1263
+ print("bake produced <2 frames; nothing to replay")
1264
+ self.sim = None
1265
+ self._reset_bake_state()
1266
+ return
1267
+ poses = np.stack(self._bake_pose[:T]).astype(np.float32)
1268
+ qpos = np.stack(self._bake_q[:T]).astype(np.float32)
1269
+ if self._bake_has_muscle and self._bake_mtu:
1270
+ mtu = np.stack(self._bake_mtu[:T]).astype(np.float32)
1271
+ act = np.stack(self._bake_act[:T]).astype(np.float32)
1272
+ else:
1273
+ mtu = np.zeros((T, 0, 7), np.float32); act = np.zeros((T, 0, 4), np.float32)
1274
+ con = (np.stack(self._bake_con[:T]).astype(np.float32)
1275
+ if self._bake_ncon > 0 and self._bake_con else np.zeros((T, 0, 7), np.float32))
1276
+ bodies = render_bodies_from_visual_geoms(jm)
1277
+ dt_clip = self.sim_dt * self._bake_substeps
1278
+ out = self._src._tmp / f"{self.meta['scene']}_bake.dnrec"
1279
+ write_dnrec(str(out), poses, np.zeros((T, 0), np.float32), mtu, act, con, bodies, dt_clip,
1280
+ scene=self.meta["scene"], qpos=qpos,
1281
+ ground_half_extent=motion_half_extent(poses), com=com_track(jm, poses))
1282
+ self.sim = None # baking done: back to (fast) playback of the clip
1283
+ self.sim_running = False
1284
+ self._reset_bake_state()
1285
+ self._install_clip(DnRec(str(out)), reset_cam=False)
1286
+ self._baked = True
1287
+ self.frame = 0.0
1288
+ self.playing = True
1289
+ print(f"baked {T} frames @ dt={dt_clip:.3e} ({T * dt_clip:.2f}s) -> replaying")
1290
+
1291
+ def _cancel_bake(self):
1292
+ self._reset_bake_state()
1293
+ self.sim = None
1294
+ print("bake cancelled")
1295
+
1296
+ # --- idle detection (drives the on_render battery throttle) ----------
1297
+ def _note_input(self):
1298
+ """Mark 'the user just interacted' -> restore full framerate (called from every input handler)."""
1299
+ self._last_input_t = time.perf_counter()
1300
+
1301
+ def _animating(self):
1302
+ """True when the view is genuinely changing on its own and must keep rendering at full rate:
1303
+ playing a multi-frame clip, live-sim stepping, baking, mid-drag, or a pending capture/selftest."""
1304
+ return bool(
1305
+ self._baking
1306
+ or (self.sim is not None and self.sim_running)
1307
+ or (self.sim is None and self.playing and self.clip.n_frames > 1)
1308
+ or self._drag is not None
1309
+ or self._capture_pending
1310
+ or self._selftest_out)
1311
+
1312
+ def reset_camera(self):
1313
+ self.cam = renderer.resolve_camera(self.clip, self._opt)
1314
+
1315
+ def _current_com(self, fi):
1316
+ """World COM the camera tracks. A live-sim computes it from the current pose (so tracking is
1317
+ independent of the COM-trail toggle); playback reads the precomputed com channel. None if the
1318
+ clip carries no COM (camera stays put)."""
1319
+ if self.sim is not None:
1320
+ return com_track(self.meta["jm"], self.scene.poses[0][None])[0, 0]
1321
+ if self.scene.com is not None:
1322
+ return np.asarray(self.scene.com[fi, 0], np.float32)
1323
+ return None
1324
+
1325
+ # --- overlay GL resources (scrub bar + axis gizmo; controls via ui.ControlPanel) --
1326
+ def _make_overlays(self):
1327
+ self._bar_prog = self.ctx.program(
1328
+ vertex_shader="""#version 330
1329
+ in vec2 in_pos; uniform vec4 u_rect;
1330
+ void main(){ vec2 p=u_rect.xy+in_pos*u_rect.zw; gl_Position=vec4(p*2.0-1.0,0.0,1.0); }""",
1331
+ fragment_shader="""#version 330
1332
+ uniform vec4 u_color; out vec4 f; void main(){ f=u_color; }""")
1333
+ quad = np.array([0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1], dtype="f4")
1334
+ self._bar_vao = self.ctx.vertex_array(
1335
+ self._bar_prog, [(self.ctx.buffer(quad.tobytes()), "2f", "in_pos")])
1336
+ # axis gizmo: the SHARED renderer widget (labeled X/Y/Z balls, top-right) so the window's
1337
+ # orientation cue matches the mp4 renderer's exactly (one implementation, one look).
1338
+ self._gizmo = AxisGizmo(self.ctx, size_px=108)
1339
+
1340
+ # --- per-frame ------------------------------------------------------
1341
+ def on_render(self, t, frametime):
1342
+ _t0 = time.perf_counter()
1343
+ if not self._activated:
1344
+ self._activated = True
1345
+ # moderngl-window runs its OWN loop, NOT pyglet.app.run(), so pyglet's macOS app setup --
1346
+ # set the NSApplication activation policy to Regular + finishLaunching + activate -- never
1347
+ # runs. Without it a terminal-launched process stays an "accessory" app whose window only
1348
+ # INTERMITTENTLY becomes key, so keyboard/mouse (orbit, buttons) intermittently drop out
1349
+ # (render is clock-driven so it still animates). Run that setup once here.
1350
+ if sys.platform == "darwin":
1351
+ try:
1352
+ import pyglet
1353
+ # accessing platform_event_loop constructs it -> its __init__ sets the Regular
1354
+ # activation policy; start() then finishLaunching + activateIgnoringOtherApps (once).
1355
+ pyglet.app.platform_event_loop.start()
1356
+ self.wnd._window.activate()
1357
+ _install_accepts_first_mouse() # first click on an inactive window registers (no double-click)
1358
+ except Exception:
1359
+ pass
1360
+ if self._baking: # bake mode: pre-computing frames (non-blocking)
1361
+ self._bake_step()
1362
+ fi = 0
1363
+ elif self.sim is not None: # live-sim mode: engine drives frame 0
1364
+ if self.sim_running:
1365
+ self._sim_advance(frametime)
1366
+ fi = 0
1367
+ else: # playback / static mode
1368
+ if self.playing and self.clip.n_frames > 1:
1369
+ self.frame += frametime * self.fps_clip * self.speed
1370
+ if self.frame >= self.clip.n_frames:
1371
+ self.frame = 0.0
1372
+ fi = int(self.frame) % self.clip.n_frames
1373
+ self._maybe_apply_pose_edit() # coalesce joint/muscle slider edits -> one FK/frame
1374
+ if self._cam_track: # lock the orbit target on the COM so it stays framed
1375
+ c = self._current_com(fi) # while walking (orbit/zoom stay relative to the COM)
1376
+ if c is not None:
1377
+ self.cam.target = c.astype(np.float32)
1378
+ self.ctx.clear(0.10, 0.11, 0.13, 1.0)
1379
+ w, h = self.wnd.buffer_size
1380
+ self._px = w / max(1, self.wnd.size[0]) # framebuffer px per window pt (retina = 2.0)
1381
+ proj = self.cam.proj(w / h)
1382
+ view = self.cam.view()
1383
+ self.scene.render(fi, view, proj, self.cam.eye())
1384
+ if self.scene.show_hud:
1385
+ self.scene.draw_hud(w, h, fi, view, proj)
1386
+ self._draw_gizmo(w, h, view) # top-right (panel is top-left -> no conflict)
1387
+ if self._capture_pending: # grab the clean render+HUD frame (no panel/scrub)
1388
+ self._capture_pending = False
1389
+ self._save_capture(w, h)
1390
+ if self._panel_visible:
1391
+ # capped at the window (above the bottom scrub bar) so a long panel -- the model picker -- scrolls
1392
+ self._panel.viewport_h = max(120, h - int(14 * self._px) - int(max(46 * self._px, h * 0.06)))
1393
+ self._panel.layout(self._build_rows(fi))
1394
+ self._panel.draw(w, h, int(14 * self._px), int(14 * self._px), hover=self._hover_row,
1395
+ edit_action=self._edit_action, edit_buf=self._edit_buf)
1396
+ if self._ctrl_visible and self.meta["kind"] == "dnmodel": # right-side joint/muscle panel (scrollable)
1397
+ cp = self._ctrl_panel
1398
+ top = int(130 * self._px) # clear the top-right axis gizmo
1399
+ margin = int(12 * self._px)
1400
+ bottom = int(max(46 * self._px, h * 0.06)) # keep clear of the bottom scrub bar
1401
+ cp.viewport_h = max(120, h - top - bottom)
1402
+ cp.layout(self._build_control_rows(fi))
1403
+ cp.draw(w, h, w - cp.W - margin, top, hover=self._ctrl_hover,
1404
+ edit_action=self._edit_action, edit_buf=self._edit_buf)
1405
+ if self.sim is None and not self._baking:
1406
+ self._draw_scrub(fi)
1407
+ self._render_count += 1
1408
+ if self._selftest_out and self._render_count >= 5 and not self._baking: # let a --bake finish first
1409
+ # Prove the real window GL context rendered: read its framebuffer, save, close.
1410
+ data = self.ctx.screen.read(components=3, alignment=1)
1411
+ img = np.flipud(np.frombuffer(data, np.uint8).reshape(h, w, 3))
1412
+ from PIL import Image
1413
+ Image.fromarray(img).save(self._selftest_out)
1414
+ print(f"selftest window framebuffer -> {self._selftest_out}")
1415
+ self.wnd.close()
1416
+ # idle throttle: when nothing is animating and there's been no recent input, sleep out the rest
1417
+ # of a slow frame so the heavy scene stops redrawing at full refresh (battery). The moderngl-window
1418
+ # loop dispatches input right after this returns, so the next event wakes us straight back to full
1419
+ # framerate; the worst-case wake latency is one throttled frame (~0.17s idle, ~0.5s deep-idle).
1420
+ if not self.wnd.is_closing and not self._animating():
1421
+ idle = time.perf_counter() - self._last_input_t
1422
+ if idle > self._idle_after:
1423
+ fps = self._deep_idle_fps if idle > self._deep_idle_after else self._idle_fps
1424
+ rest = (1.0 / fps) - (time.perf_counter() - _t0)
1425
+ if rest > 0.0:
1426
+ time.sleep(rest)
1427
+
1428
+ def _build_rows(self, fi):
1429
+ """Flat list of control Rows built from the live state -- every action is shown with its
1430
+ current value + the key that triggers it, and (via `action`) is clickable."""
1431
+ s = self.scene
1432
+ if self._model_picker: # picker overlay owns the panel while open
1433
+ return self._model_picker_rows()
1434
+ is_dnmodel = self.meta["kind"] == "dnmodel"
1435
+ has_muscle = bool(self.meta.get("jm") and self.meta["jm"].get("muscles"))
1436
+ rows = [Row("header", "FILE"),
1437
+ Row("text", self.orig_path.name), # full width (may be long; no chip to collide)
1438
+ Row("text", f"{self.meta['n_bodies']} bodies · {self.meta['kind']}", value=self.meta["scene"]),
1439
+ Row("button", f"Model: {self.orig_path.stem} ▸", action="modelpick")]
1440
+ if is_dnmodel: # right-side joint/muscle control panel
1441
+ rows.append(Row("button", ("▾ " if self._ctrl_visible else "▸ ") + "Joint / Muscle control",
1442
+ key="U", action="ctrlpanel"))
1443
+ # --- SIMULATE (dnmodel only): live-sim controls + the editable engine params (dt/excitation) ---
1444
+ if is_dnmodel:
1445
+ rows.append(Row("header", f"SIMULATE{' · ' + self.sim.backend if self.sim else ''}"))
1446
+ if self._baking: # baking: no live-sim controls (they'd kill it)
1447
+ rows.append(Row("text", "state", value="baking…"))
1448
+ elif self.sim is not None: # live simulation running
1449
+ rows += [Row("button", "Stop live-sim", key="M", action="sim"),
1450
+ Row("button", "Pause stepping" if self.sim_running else "Resume stepping",
1451
+ key="Space", action="playpause"),
1452
+ Row("button", "Reset to initial", key="R", action="reset"),
1453
+ Row("text", "step", value=f"{self.sim.n_steps} "
1454
+ + ("running" if self.sim_running else "paused"))]
1455
+ else:
1456
+ ok = live_sim_available(self.meta)
1457
+ rows.append(Row("button", "Start live-sim (real engine)" + ("" if ok else " — no GPU/ext"),
1458
+ key="M", action="sim", enabled=ok))
1459
+ rows.append(Row("value", "dt", value=f"{self.sim_dt:.3e}", action="dt"))
1460
+ if has_muscle:
1461
+ rows.append(Row("value", "excitation", value=f"{self.sim_excite:.2f}", action="excite"))
1462
+ # root suspension: hold the floating base in the air so the model cannot fall
1463
+ why = self._hang_why_not()
1464
+ rows.append(Row("toggle", "Hang root in air", key="Y", checked=self._hang,
1465
+ action="hang", enabled=not why))
1466
+ if why:
1467
+ rows.append(Row("text", "hang", value=why))
1468
+ elif self._hang:
1469
+ rows += [Row("value", "clearance", value=f"{self._hang_clear:.2f} m", action="hangclear"),
1470
+ Row("toggle", "hold base orientation", checked=self._hang_hold_rot,
1471
+ action="hangrot")]
1472
+ # --- BAKE: pre-compute N frames of physics, then replay them instantly ---
1473
+ rows.append(Row("header", "BAKE"))
1474
+ if self._baking:
1475
+ rows.append(Row("progress", "baking",
1476
+ value=f"{self._bake_i}/{self._bake_target}",
1477
+ frac=self._bake_i / max(1, self._bake_target)))
1478
+ rows.append(Row("button", "Cancel bake", key="Esc", action="bakecancel"))
1479
+ else:
1480
+ okb = live_sim_available(self.meta)
1481
+ dt_clip = self.sim_dt * self._bake_substeps
1482
+ rows += [Row("value", "frames", value=str(self._bake_target), action="bakeframes"),
1483
+ Row("value", "steps/frame", value=str(self._bake_substeps), action="bakesubsteps"),
1484
+ Row("text", "≈ motion", value=f"{self._bake_target * dt_clip:.2f}s · {1.0 / max(dt_clip, 1e-9):.0f}fps"),
1485
+ Row("button", "Bake » record & replay" + ("" if okb else " — no GPU/ext"),
1486
+ key="N", action="bake", enabled=okb)]
1487
+ if self._baked:
1488
+ rows.append(Row("text", "replaying bake", value=f"{self.clip.n_frames} frames"))
1489
+ rows.append(Row("button", "Reload model pose", action="reload"))
1490
+ # --- PLAYBACK (any clip that isn't live-sim / baking): scrub the current trajectory ---
1491
+ if self.sim is None and not self._baking:
1492
+ rows.append(Row("header", "PLAYBACK"))
1493
+ if self.clip.n_frames <= 1:
1494
+ rows.append(Row("text", "static pose", value="1 frame — bake or live-sim it"))
1495
+ else:
1496
+ rows += [Row("button", "Pause" if self.playing else "Play", key="Space", action="playpause"),
1497
+ Row("button", "Restart", key="R", action="reset"),
1498
+ Row("text", "frame", value=f"{fi + 1}/{self.clip.n_frames} {int(round(self.fps_clip))}fps"),
1499
+ Row("value", "speed", value=f"{self.speed:.2f}x", key="[ ]", action="speed")]
1500
+ elif self.sim is not None: # live-sim: speed paces the wall clock
1501
+ rows.append(Row("value", "speed", value=f"{self.speed:.2f}x", key="[ ]", action="speed"))
1502
+ rows.append(Row("header", "DISPLAY"))
1503
+ # A group is named by what its geoms ARE (the `collider` tag dnrec_io stamps on the overlays),
1504
+ # not by its number: the self-collision capsules live in group 7, which a bare "group 7" hid.
1505
+ cname = {"sphere": "Ground contacts", "self": "Self colliders"}
1506
+ for gi in sorted({int(g["group"]) for g in s.geoms}): # geom render groups (labeled + stateful)
1507
+ members = [g for g in s.geoms if int(g["group"]) == gi]
1508
+ accent = tuple(members[0]["rgba"][:3])
1509
+ kinds = {g["collider"] for g in members}
1510
+ label = ("Model" if gi == 0
1511
+ else cname[next(iter(kinds))] if len(kinds) == 1 and next(iter(kinds)) in cname
1512
+ else f"group {gi}")
1513
+ rows.append(Row("toggle", label, key=str(gi),
1514
+ checked=gi in s.enabled_geom_groups, action=f"group{gi}", accent=accent))
1515
+ rows += [Row("toggle", "Shadow", key="H", checked=s.show_shadow, action="shadow"),
1516
+ Row("toggle", "COM trail", key="T", checked=s.show_trail, action="trail"),
1517
+ Row("toggle", "Contact arrows", key="F", checked=s.show_contact, action="contact")]
1518
+ if s._has_muscle_data():
1519
+ rows.append(Row("segmented", "Muscle render", key="G",
1520
+ options=MUSCLE_RENDER_MODES, value=s.muscle_mode, action="muscle"))
1521
+ rows.append(Row("toggle", "Muscle fibres", key="J",
1522
+ checked=s.fascicle_strength > 0.0, action="fascicle"))
1523
+ rows.append(Row("toggle", "Muscle bundle", key="B",
1524
+ checked=s.muscle_bundle > 1, action="bundle"))
1525
+ rows.append(Row("button", "Capture PNG → Finder", key="P", action="capture"))
1526
+ rows += [Row("header", "CAMERA"),
1527
+ Row("button", "Reset view (fit)", key="V", action="cam"),
1528
+ Row("toggle", "Track COM", key="K", checked=self._cam_track, action="camtrack"),
1529
+ Row("text", "drag orbit · shift pan · wheel zoom")]
1530
+ phys = self.meta.get("physics")
1531
+ rows.append(Row("header", "PHYSICS"))
1532
+ if phys is not None:
1533
+ g = phys["gravity"]
1534
+ rows += [Row("text", "gravity", value=f"[{g[0]:.1f}, {g[1]:.1f}, {g[2]:.1f}]"),
1535
+ Row("text", "contact", value=str(phys["contact_mode"])),
1536
+ Row("text", "precision", value=str(phys["precision"]))]
1537
+ live = "D16 CPU engine" if live14_runs(self.meta) else "no (a shipped muscle body only)"
1538
+ rows.append(Row("text", "live-sim", value=live))
1539
+ return rows
1540
+
1541
+ def _model_picker_rows(self):
1542
+ """Panel content while the model picker is open: one clickable button per registered model
1543
+ (current marked), replacing the normal sections; the panel scrolls when the list is taller than
1544
+ the window. A name wider than the panel wraps at its underscores onto continuation rows that pick
1545
+ the same model (the full-body variants share a 40-character prefix, so a truncated name cannot
1546
+ tell them apart), and a gap separates name families (the first `_` token)."""
1547
+ cur = pathlib.Path(self.orig_path).resolve()
1548
+ p = self._panel
1549
+ rows = [Row("header", f"select model ({len(self._models)})"), Row("button", "✕ close", action="modelpick")]
1550
+ family = None
1551
+ for i, (name, path) in enumerate(self._models):
1552
+ is_cur = pathlib.Path(path).resolve() == cur
1553
+ if family is not None and name.split("_")[0] != family:
1554
+ rows.append(Row("gap"))
1555
+ family = name.split("_")[0]
1556
+ swatch = int(p.row_h * 0.34) + 8 if is_cur else 0 # the accent swatch before the label
1557
+ lines = _wrap_at_underscores(("● " if is_cur else "") + name, p.font, p.W - 2 * p.pad - 16 - swatch)
1558
+ for k, line in enumerate(lines):
1559
+ rows.append(Row("button", line, action=f"model:{i}",
1560
+ accent=(1.0, 0.71, 0.18) if is_cur and k == 0 else ()))
1561
+ return rows
1562
+
1563
+ def _dispatch(self, action):
1564
+ """Apply a clicked/keyed control action (same effect as its keyboard accelerator)."""
1565
+ s = self.scene
1566
+ if action == "modelpick": # toggle the general model picker overlay
1567
+ self._model_picker = not self._model_picker
1568
+ self._panel.scroll = 0.0
1569
+ return
1570
+ if action.startswith("model:"): # load a picked model (swaps the whole clip/scene)
1571
+ self._model_picker = False
1572
+ self._panel.scroll = 0.0
1573
+ self.load(self._models[int(action.split(":", 1)[1])][1])
1574
+ return
1575
+ if action == "sim":
1576
+ self.toggle_sim()
1577
+ elif action == "playpause":
1578
+ if self.sim is not None:
1579
+ self.sim_running = not self.sim_running
1580
+ elif (not self._baking and self.meta["kind"] == "dnmodel"
1581
+ and self.clip.n_frames <= 1 and live_sim_available(self.meta)):
1582
+ self.toggle_sim() # MuJoCo-style: Space starts the live sim on a static model
1583
+ else:
1584
+ self.playing = not self.playing
1585
+ elif action == "reset":
1586
+ if self._baking:
1587
+ return # a bake resets from q0 on its own; don't disturb it
1588
+ if self.sim is not None:
1589
+ self.sim.reset(); self._sim_budget = 0.0
1590
+ if self.sim.pd is not None and self._ctrl_q is not None: # keep the panel's PD targets
1591
+ self.sim.set_pd_targets(self._ctrl_q)
1592
+ self.scene._trail_pts = [] # fresh COM trail from the reset pose
1593
+ self._hang_refit() # reset to the HUNG pose when suspended
1594
+ self._push_sim_pose() # snap the view back to the reset pose immediately
1595
+ else:
1596
+ self.frame = 0; self.playing = True
1597
+ elif action == "hang":
1598
+ self.toggle_hang()
1599
+ elif action == "hangrot": # held base orientation (test stand) vs free to swing
1600
+ self._hang_hold_rot = not self._hang_hold_rot
1601
+ if self._hang:
1602
+ self._hang_refit() # reinstall the pin with/without the rotation dofs
1603
+ else:
1604
+ print(f"root hang: base orientation {'held' if self._hang_hold_rot else 'free (swings)'}")
1605
+ elif action == "bake":
1606
+ self._start_bake()
1607
+ elif action == "bakecancel":
1608
+ self._cancel_bake()
1609
+ elif action == "reload": # drop the baked clip, show the model's static pose again
1610
+ self.load(str(self.meta["dnmodel_path"]))
1611
+ elif action.startswith("group"):
1612
+ self._toggle_group(int(action[5:]))
1613
+ elif action == "shadow":
1614
+ s.show_shadow = not s.show_shadow
1615
+ elif action == "trail":
1616
+ s.show_trail = not s.show_trail
1617
+ elif action == "contact":
1618
+ s.show_contact = not s.show_contact
1619
+ elif action == "muscle":
1620
+ print(f"muscle render: {s.cycle_muscle_mode()}")
1621
+ elif action == "fascicle":
1622
+ print(f"muscle fibres: {s.toggle_fascicle()}")
1623
+ elif action == "bundle":
1624
+ print(f"muscle bundle: {s.toggle_bundle()} rods")
1625
+ elif action == "capture":
1626
+ self._request_capture()
1627
+ elif action == "cam":
1628
+ self.reset_camera()
1629
+ elif action == "camtrack":
1630
+ self._cam_track = not self._cam_track
1631
+ print(f"camera track COM: {'on' if self._cam_track else 'off'}")
1632
+ elif action == "ctrlpanel": # show/hide the right-side joint/muscle panel
1633
+ self._ctrl_visible = not self._ctrl_visible
1634
+ if self._ctrl_visible:
1635
+ self._ctrl_panel.scroll = 0.0
1636
+ self._pose_dirty = True # sync the shown pose/colours to the editable state
1637
+ elif action == "ctrl_reset": # restore the model's initial pose + relax muscles
1638
+ if self._ctrl_q is not None:
1639
+ self._ctrl_q[:] = np.asarray(self.meta["q0"], dtype=np.float64)
1640
+ self._ctrl_u[:] = 0.0
1641
+ self._pose_dirty = True
1642
+ elif action == "mus_zero":
1643
+ if self._ctrl_u.size:
1644
+ self._ctrl_u[:] = 0.0; self.sim_excite = 0.0
1645
+ self._after_ctrl_edit("mus0")
1646
+ elif action == "mus_half":
1647
+ if self._ctrl_u.size:
1648
+ self._ctrl_u[:] = 0.5; self.sim_excite = 0.5
1649
+ self._after_ctrl_edit("mus0")
1650
+
1651
+ # --- editable numeric fields (dt / speed / excitation / bake frames+steps) -----
1652
+ # An editable `value` row supports two gestures: click −/+ to NUDGE, or click the value to TYPE a
1653
+ # number in (Enter commits, Esc cancels). `_apply_value` is the single place a parsed/clamped number
1654
+ # is written back to the matching state, shared by the editor commit and the steppers.
1655
+ def _apply_value(self, action, v):
1656
+ """Write a validated float `v` to the state behind `action`, clamped to a sane range."""
1657
+ if action == "dt":
1658
+ self.sim_dt = float(min(1e-1, max(1e-6, v)))
1659
+ if not self._bake_substeps_user: # keep steps/frame ~real-time
1660
+ self._bake_substeps = max(1, round((1.0 / 60.0) / max(self.sim_dt, 1e-9)))
1661
+ if self.sim is not None:
1662
+ self.sim.dt = self.sim_dt
1663
+ elif action == "speed":
1664
+ self.speed = float(min(64.0, max(0.01, v)))
1665
+ elif action == "excite":
1666
+ self.sim_excite = float(min(1.0, max(0.0, v)))
1667
+ if self._ctrl_u.size: # "excitation" is a SET-ALL for the per-muscle vector
1668
+ self._ctrl_u[:] = self.sim_excite
1669
+ if self.sim is not None:
1670
+ self.sim.excitation = self.sim_excite
1671
+ self._after_ctrl_edit("mus0") # static: recolour; live: no-op
1672
+ elif action == "hangclear":
1673
+ self._hang_clear = float(min(5.0, max(0.0, v)))
1674
+ self._hang_refit()
1675
+ elif action == "bakeframes":
1676
+ self._bake_target = int(min(200000, max(1, round(v))))
1677
+ elif action == "bakesubsteps":
1678
+ self._bake_substeps = int(max(1, round(v)))
1679
+ self._bake_substeps_user = True
1680
+ else: # joint / muscle slider (typed value)
1681
+ spec = self._slider_spec(action)
1682
+ if spec is not None:
1683
+ _lo, _hi, _get, setter = spec
1684
+ setter(v)
1685
+ self._after_ctrl_edit(action)
1686
+
1687
+ def _nudge(self, action, up):
1688
+ """−/+ stepper: multiplicative for dt/speed/steps (span decades cleanly), additive for the rest."""
1689
+ if action == "dt":
1690
+ self._apply_value("dt", self.sim_dt * (1.5 if up else 1 / 1.5))
1691
+ elif action == "speed":
1692
+ self._apply_value("speed", self.speed * (1.5 if up else 1 / 1.5))
1693
+ elif action == "excite":
1694
+ self._apply_value("excite", self.sim_excite + (0.05 if up else -0.05))
1695
+ elif action == "hangclear":
1696
+ self._apply_value("hangclear", self._hang_clear + (0.05 if up else -0.05))
1697
+ elif action == "bakeframes":
1698
+ self._apply_value("bakeframes", self._bake_target + (50 if up else -50))
1699
+ elif action == "bakesubsteps":
1700
+ self._apply_value("bakesubsteps", round(self._bake_substeps * (1.5 if up else 1 / 1.5))
1701
+ if up else max(1, round(self._bake_substeps / 1.5)))
1702
+
1703
+ def _begin_edit(self, action):
1704
+ """Open the inline editor on `action`'s value row (committing any editor already open)."""
1705
+ self._commit_edit()
1706
+ self._edit_action = action
1707
+ self._edit_buf = ""
1708
+
1709
+ def _commit_edit(self):
1710
+ """Parse the typed buffer and apply it; a blank/invalid buffer just closes the editor (keeps
1711
+ the old value). User keyboard input is untrusted I/O, so the float parse is guarded (a typo like
1712
+ "1.2.3" must not crash the viewer) -- this is input validation, not swallowing a logic error."""
1713
+ action, buf = self._edit_action, self._edit_buf.strip()
1714
+ self._edit_action = ""; self._edit_buf = ""
1715
+ if not action or not buf:
1716
+ return
1717
+ try:
1718
+ v = float(buf)
1719
+ except ValueError:
1720
+ print(f"ignored invalid number for {action!r}: {buf!r}")
1721
+ return
1722
+ self._apply_value(action, v)
1723
+
1724
+ def _handle_edit_key(self, key, keys):
1725
+ """Keys while the inline editor is open. Number entry reads PHYSICAL key codes (digits / . / -
1726
+ / e / +) rather than composed unicode, so a non-Latin input mode (e.g. a Korean keyboard layout)
1727
+ can't turn a keystroke into a Hangul character -- the numeric field stays usable in any IME
1728
+ state. Enter commits, Esc cancels, Backspace deletes."""
1729
+ if key in (keys.ENTER, getattr(keys, "NUMPAD_ENTER", -1)):
1730
+ self._commit_edit()
1731
+ return
1732
+ if key == keys.ESCAPE:
1733
+ self._edit_action = ""; self._edit_buf = ""
1734
+ return
1735
+ if key == keys.BACKSPACE:
1736
+ self._edit_buf = self._edit_buf[:-1]
1737
+ return
1738
+ ch = self._edit_char_for(key, keys)
1739
+ if ch and len(self._edit_buf) < 16:
1740
+ self._edit_buf += ch
1741
+
1742
+ def _edit_char_for(self, key, keys):
1743
+ """Map a PHYSICAL key code to the character it contributes to a numeric field, or None.
1744
+ Layout-independent (uses key codes, not the IME's composed text)."""
1745
+ d = self._digit(key, keys)
1746
+ if d is not None:
1747
+ return str(d)
1748
+ table = {getattr(keys, "PERIOD", -9): ".", getattr(keys, "NUMPAD_DECIMAL", -9): ".",
1749
+ getattr(keys, "MINUS", -9): "-", getattr(keys, "NUMPAD_SUBTRACT", -9): "-",
1750
+ getattr(keys, "PLUS", -9): "+", getattr(keys, "NUMPAD_ADD", -9): "+",
1751
+ getattr(keys, "E", -9): "e"}
1752
+ return table.get(key)
1753
+
1754
+ def on_unicode_char_entered(self, char):
1755
+ """Numeric entry is driven from PHYSICAL key codes in `_handle_edit_key` (IME-independent), so
1756
+ composed unicode characters are intentionally ignored here (a Korean layout would otherwise
1757
+ insert Hangul); we only note the keystroke for the idle throttle."""
1758
+ self._note_input()
1759
+
1760
+ def _draw_gizmo(self, w, h, view):
1761
+ self._gizmo.draw(w, h, view) # shared labeled X/Y/Z widget, top-right
1762
+
1763
+ def _draw_scrub(self, fi):
1764
+ self.ctx.disable(moderngl.DEPTH_TEST)
1765
+ self.ctx.enable(moderngl.BLEND)
1766
+ self.ctx.blend_func = moderngl.SRC_ALPHA, moderngl.ONE_MINUS_SRC_ALPHA
1767
+ self._bar_prog["u_rect"].value = (0.04, 0.028, 0.92, 0.016)
1768
+ self._bar_prog["u_color"].value = (0.25, 0.25, 0.30, 0.8)
1769
+ self._bar_vao.render(moderngl.TRIANGLES)
1770
+ frac = fi / max(1, self.clip.n_frames - 1)
1771
+ self._bar_prog["u_rect"].value = (0.04, 0.028, 0.92 * frac, 0.016)
1772
+ self._bar_prog["u_color"].value = ((1.0, 0.7, 0.1, 0.95) if self.playing
1773
+ else (0.6, 0.6, 0.65, 0.95))
1774
+ self._bar_vao.render(moderngl.TRIANGLES)
1775
+ self.ctx.disable(moderngl.BLEND)
1776
+ self.ctx.enable(moderngl.DEPTH_TEST)
1777
+
1778
+ # --- input ----------------------------------------------------------
1779
+ def on_files_dropped_event(self, x, y, paths):
1780
+ self._note_input()
1781
+ if not paths:
1782
+ return
1783
+ try: # a bad drop should not kill the window; keep the current clip
1784
+ self.load(paths[0])
1785
+ except Exception as e: # noqa: BLE001 (interactive UX: report + keep running)
1786
+ print(f"drop load failed for {paths[0]}: {e}")
1787
+
1788
+ def on_key_event(self, key, action, modifiers):
1789
+ self._note_input()
1790
+ keys = self.wnd.keys
1791
+ self._shift = modifiers.shift
1792
+ if action != keys.ACTION_PRESS:
1793
+ return
1794
+ if self._edit_action: # inline numeric editor owns the keyboard
1795
+ self._handle_edit_key(key, keys)
1796
+ return
1797
+ digit = self._digit(key, keys)
1798
+ if digit is not None:
1799
+ self._toggle_group(digit)
1800
+ return
1801
+ if key in (keys.ESCAPE, keys.Q):
1802
+ if self._baking: # Esc first cancels an in-progress bake, not the app
1803
+ self._cancel_bake()
1804
+ else:
1805
+ self.wnd.close()
1806
+ elif key == keys.M:
1807
+ self.toggle_sim()
1808
+ elif key == keys.N:
1809
+ self._start_bake()
1810
+ elif key in (keys.O, keys.C): # show/hide the control panel (clean view)
1811
+ self._panel_visible = not self._panel_visible
1812
+ elif key == keys.U: # show/hide the joint/muscle control panel
1813
+ self._dispatch("ctrlpanel")
1814
+ elif key == keys.SPACE:
1815
+ self._dispatch("playpause")
1816
+ elif key == keys.RIGHT and self.sim is None:
1817
+ self.playing = False; self.frame = min(self.clip.n_frames - 1, int(self.frame) + 1)
1818
+ elif key == keys.LEFT and self.sim is None:
1819
+ self.playing = False; self.frame = max(0, int(self.frame) - 1)
1820
+ elif key == keys.HOME and self.sim is None:
1821
+ self.frame = 0
1822
+ elif key == keys.END and self.sim is None:
1823
+ self.frame = self.clip.n_frames - 1
1824
+ elif key == keys.R:
1825
+ self._dispatch("reset")
1826
+ elif key == keys.V:
1827
+ self.reset_camera()
1828
+ elif key == keys.RIGHT_BRACKET:
1829
+ self.speed = min(8.0, self.speed * 1.5); print(f"speed {self.speed:.2f}x")
1830
+ elif key == keys.LEFT_BRACKET:
1831
+ self.speed = max(0.05, self.speed / 1.5); print(f"speed {self.speed:.2f}x")
1832
+ elif key == keys.F:
1833
+ self._dispatch("contact")
1834
+ elif key == keys.G:
1835
+ self._dispatch("muscle")
1836
+ elif key == keys.J:
1837
+ self._dispatch("fascicle")
1838
+ elif key == keys.B:
1839
+ self._dispatch("bundle")
1840
+ elif key == keys.T:
1841
+ self._dispatch("trail")
1842
+ elif key == keys.K:
1843
+ self._dispatch("camtrack")
1844
+ elif key == keys.Y:
1845
+ self._dispatch("hang")
1846
+ elif key == keys.H:
1847
+ self._dispatch("shadow")
1848
+ elif key == keys.P:
1849
+ self._request_capture()
1850
+
1851
+ def _toggle_group(self, digit):
1852
+ groups = set(self.scene.enabled_geom_groups)
1853
+ if digit in groups:
1854
+ if len(groups) == 1:
1855
+ print(f"geom groups: {sorted(groups)} (refusing to hide the last group)")
1856
+ return
1857
+ groups.remove(digit)
1858
+ else:
1859
+ groups.add(digit)
1860
+ self.scene.set_enabled_geom_groups(groups)
1861
+ print(f"geom groups: {sorted(groups)}")
1862
+
1863
+ def _request_capture(self):
1864
+ """Defer the grab to the render loop so we capture the clean render+HUD frame (before the
1865
+ control panel / scrub bar are drawn), not the window with its chrome."""
1866
+ self._capture_pending = True
1867
+
1868
+ def _save_capture(self, w, h):
1869
+ """Read the current framebuffer, save a timestamped PNG under ~/Pictures/diffneusim/, and
1870
+ reveal it in the OS file browser (Finder on macOS)."""
1871
+ from PIL import Image
1872
+ data = self.ctx.screen.read(components=3, alignment=1)
1873
+ img = np.flipud(np.frombuffer(data, np.uint8).reshape(h, w, 3))
1874
+ out_dir = pathlib.Path.home() / "Pictures" / "diffneusim"
1875
+ out_dir.mkdir(parents=True, exist_ok=True)
1876
+ stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
1877
+ out = out_dir / f"{self.orig_path.stem}_{stamp}.png"
1878
+ Image.fromarray(img).save(out)
1879
+ print(f"capture -> {out}")
1880
+ self._reveal_in_file_browser(out)
1881
+
1882
+ @staticmethod
1883
+ def _reveal_in_file_browser(path: pathlib.Path):
1884
+ """Select the file in the OS file browser: Finder (macOS), Explorer (Windows), else open the
1885
+ folder (Linux). check=False so a non-zero exit never disturbs the viewer."""
1886
+ if sys.platform == "darwin":
1887
+ subprocess.run(["open", "-R", str(path)], check=False)
1888
+ elif sys.platform.startswith("win"):
1889
+ subprocess.run(["explorer", f"/select,{path}"], check=False)
1890
+ else:
1891
+ subprocess.run(["xdg-open", str(path.parent)], check=False)
1892
+
1893
+ def _ctrl_panel_active(self):
1894
+ return self._ctrl_visible and self.meta["kind"] == "dnmodel"
1895
+
1896
+ def on_mouse_press_event(self, x, y, button):
1897
+ self._note_input()
1898
+ self._last = (x, y)
1899
+ mx, my = x * self._px, y * self._px
1900
+ in_panel = self._panel_visible and self._panel.contains(mx, my)
1901
+ in_ctrl = self._ctrl_panel_active() and self._ctrl_panel.contains(mx, my)
1902
+ if self._edit_action and not in_panel and not in_ctrl: # click off any panel commits the open editor
1903
+ self._commit_edit()
1904
+ if in_panel:
1905
+ opt = self._panel.segmented_option_at(mx, my)
1906
+ if opt is not None: # clicked a specific muscle-mode pill
1907
+ self._commit_edit()
1908
+ self.scene.set_muscle_mode(opt); print(f"muscle render: {opt}")
1909
+ self._drag = None
1910
+ return
1911
+ vh = self._panel.value_hit(mx, my) # an editable value row (-/+ stepper or edit box)
1912
+ if vh is not None:
1913
+ zone, act = vh
1914
+ if zone == "edit":
1915
+ self._begin_edit(act)
1916
+ else:
1917
+ self._commit_edit(); self._nudge(act, zone == "inc")
1918
+ self._drag = None
1919
+ return
1920
+ i = self._panel.hit(mx, my) # a clickable row -> run its action
1921
+ if i >= 0:
1922
+ self._commit_edit()
1923
+ self._dispatch(self._panel._rows[i].action)
1924
+ self._drag = None
1925
+ return # click consumed by the panel (never orbits the view)
1926
+ if in_ctrl: # right-side joint/muscle panel: sliders + buttons
1927
+ sh = self._ctrl_panel.slider_hit(mx, my)
1928
+ if sh is not None:
1929
+ zone, act, frac, track = sh
1930
+ if zone == "edit": # click the value box -> type an exact number
1931
+ self._begin_edit(act)
1932
+ else: # click / drag the track -> set from fraction
1933
+ self._commit_edit(); self._set_slider(act, frac)
1934
+ self._drag = ("slider", act, track[0], track[1])
1935
+ return
1936
+ i = self._ctrl_panel.hit(mx, my)
1937
+ if i >= 0:
1938
+ self._commit_edit()
1939
+ self._dispatch(self._ctrl_panel._rows[i].action)
1940
+ self._drag = None
1941
+ return
1942
+ if y > self.wnd.size[1] * 0.94: # bottom strip = scrub bar
1943
+ self._drag = "scrub"; self._scrub_to(x)
1944
+ elif self._shift or button == self.wnd.mouse.right:
1945
+ self._drag = "pan"
1946
+ else: # LMB / MMB = orbit
1947
+ self._drag = "orbit"
1948
+
1949
+ def on_mouse_release_event(self, x, y, button):
1950
+ self._note_input()
1951
+ was_slider = isinstance(self._drag, tuple) and self._drag and self._drag[0] == "slider"
1952
+ self._drag = None
1953
+ if was_slider: # final apply next frame (drag now cleared -> full muscles)
1954
+ self._pose_dirty = True
1955
+
1956
+ def on_mouse_position_event(self, x, y, dx, dy):
1957
+ if dx or dy: # ignore zero-delta events (macOS activation churn)
1958
+ self._note_input() # so an untouched window settles to the idle rate
1959
+ self._mouse_xy = (x, y) # remembered so the wheel routes to the panel it's over
1960
+ mx, my = x * self._px, y * self._px
1961
+ self._hover_row = self._panel.hit(mx, my) if self._panel_visible else -1
1962
+ self._ctrl_hover = self._ctrl_panel.hit(mx, my) if self._ctrl_panel_active() else -1
1963
+
1964
+ def on_mouse_drag_event(self, x, y, dx, dy):
1965
+ self._note_input()
1966
+ if self._drag == "orbit":
1967
+ self.cam.orbit(-dx * 0.01, dy * 0.01)
1968
+ elif self._drag == "pan":
1969
+ self.cam.pan(dx, dy)
1970
+ elif self._drag == "scrub":
1971
+ self._scrub_to(x)
1972
+ elif isinstance(self._drag, tuple) and self._drag and self._drag[0] == "slider":
1973
+ _tag, act, tx0, tx1 = self._drag
1974
+ ax = self._ctrl_panel._anchor[0]
1975
+ frac = min(1.0, max(0.0, ((x * self._px) - ax - tx0) / max(1.0, tx1 - tx0)))
1976
+ self._set_slider(act, frac)
1977
+
1978
+ def on_mouse_scroll_event(self, x_offset, y_offset):
1979
+ self._note_input()
1980
+ mx, my = self._mouse_xy[0] * self._px, self._mouse_xy[1] * self._px
1981
+ if self._panel_visible and self._panel.contains(mx, my):
1982
+ p = self._panel # the left panel (the model picker): scroll it, don't zoom
1983
+ p.scroll = min(p.max_scroll, max(0.0, p.scroll - y_offset * 48.0))
1984
+ return
1985
+ if self._ctrl_panel_active() and self._ctrl_panel.contains(mx, my):
1986
+ cp = self._ctrl_panel # scroll the panel the cursor is over (don't zoom)
1987
+ cp.scroll = min(cp.max_scroll, max(0.0, cp.scroll - y_offset * 48.0))
1988
+ return
1989
+ self.cam.zoom(0.9 ** y_offset)
1990
+
1991
+ def _scrub_to(self, x):
1992
+ frac = np.clip((x / self.wnd.size[0] - 0.04) / 0.92, 0.0, 1.0)
1993
+ self.frame = frac * (self.clip.n_frames - 1)
1994
+ self.playing = False
1995
+
1996
+ @staticmethod
1997
+ def _digit(key, keys):
1998
+ for n in range(10):
1999
+ for name in (f"NUMBER_{n}", f"KEY_{n}", f"NUM_{n}", f"DIGIT_{n}"):
2000
+ if getattr(keys, name, None) == key:
2001
+ return n
2002
+ if key == ord(str(n)):
2003
+ return n
2004
+ return None
2005
+
2006
+ # Force the pyglet backend (installed on Mac + Windows; glfw is absent here). run_window_config
2007
+ # parses `args` for window flags, so pass ours explicitly instead of leaking into sys.argv.
2008
+ mglw.run_window_config(Viewer, args=["--window", "pyglet"])
2009
+
2010
+
2011
+ # ----------------------------------------------------------------------------- CLI
2012
+ def main():
2013
+ ap = argparse.ArgumentParser(description="Interactive .dnmodel / .dnrec viewer.")
2014
+ ap.add_argument("path", nargs="?", default=None,
2015
+ help="a .dnmodel/.dnrec file OR a registered model NAME (see --list); omit to open the "
2016
+ "default model and pick another in-viewer (Model row in the panel)")
2017
+ ap.add_argument("--model", default=None,
2018
+ help="registered model NAME to open (same as the positional arg; --list shows names)")
2019
+ ap.add_argument("--list", action="store_true", dest="list_models",
2020
+ help="print the model registry (models/*.dnmodel) and exit")
2021
+ ap.add_argument("--pose", default=None,
2022
+ help=".dnmodel only: pose/trajectory file (.txt/.npy/.npz) to view (overrides the *_qk.txt sibling)")
2023
+ ap.add_argument("--ref", nargs="?", const="__auto__", default=None,
2024
+ help=".dnmodel only: play the imitation REFERENCE motion on the model. Bare --ref = the "
2025
+ "model's training reference ($DN_REF or the per-model default); --ref PATH = a "
2026
+ "specific reference .npz. Plays through the normal playback controls (space/scrub/[ ]).")
2027
+ ap.add_argument("--shot", default=None, help="headless: render one frame to this PNG and exit (no window)")
2028
+ ap.add_argument("--selftest", default=None,
2029
+ help="open the window, render a few frames, save the window framebuffer to this PNG, then close")
2030
+ ap.add_argument("--frame", type=int, default=0, help="frame index for --shot / initial frame")
2031
+ ap.add_argument("--pick", action="store_true", help="window: open with the model picker showing")
2032
+ ap.add_argument("--sim", action="store_true",
2033
+ help=".dnmodel only: launch straight into live simulation (real engine; needs CUDA)")
2034
+ ap.add_argument("--hang", nargs="?", type=float, const=0.30, default=None, metavar="M",
2035
+ help=".dnmodel only (window): open with the model HUNG in the air -- its floating base "
2036
+ "pinned so the lowest point sits M metres above the floor (bare --hang = 0.30). "
2037
+ "Pairs with --sim to watch the muscles act without the model falling.")
2038
+ ap.add_argument("--bake", type=int, default=None, metavar="N",
2039
+ help=".dnmodel only: on launch, pre-compute N frames of physics through the real engine "
2040
+ "and replay them instantly (avoids slow live stepping; frames/steps are editable in-UI)")
2041
+ ap.add_argument("--width", type=int, default=1280)
2042
+ ap.add_argument("--height", type=int, default=720)
2043
+ # --shot framing pass-throughs (the same RenderOptions fields tools/viz/snapshot.py exposes)
2044
+ ap.add_argument("--muscles", choices=["auto", "off", "mtu", "capsule"], default="auto",
2045
+ help="--shot: muscle display; `off` is what a collider/bone shot wants")
2046
+ ap.add_argument("--geom-groups", default=None,
2047
+ help="--shot: comma list of geom groups (7 = the self-collision capsules)")
2048
+ ap.add_argument("--camera", default=None, help="--shot: yaw,pitch,dist[,zlift] (default = scene preset)")
2049
+ ap.add_argument("--dist-scale", type=float, default=1.0, help="--shot: extra zoom on the resolved distance")
2050
+ ap.add_argument("--no-hud", action="store_true", help="--shot: drop the caption/gizmo overlay")
2051
+ args, _unknown = ap.parse_known_args()
2052
+
2053
+ models = discover_models()
2054
+ if args.list_models:
2055
+ print("registered models (models/*.dnmodel):")
2056
+ for name, _p in models:
2057
+ print(f" {name}")
2058
+ return
2059
+ init_path = resolve_model(args.model or args.path, models) # name | path | None -> default
2060
+
2061
+ # --ref: play the imitation reference motion. A reference is a (T, nq) trajectory, so it feeds the same
2062
+ # pose_override path as --pose; bare --ref auto-resolves the model's training reference.
2063
+ pose = args.pose
2064
+ if args.ref is not None:
2065
+ assert args.pose is None, "pass only one of --pose / --ref"
2066
+ pose = _default_ref_for_model(init_path) if args.ref == "__auto__" else args.ref
2067
+ print(f"reference motion: {pose}")
2068
+
2069
+ if args.shot:
2070
+ # Compile the clip through the exact same path the window uses, then render offscreen.
2071
+ clip_path, _orig, _clip, meta = ClipSource().resolve(init_path, pose_override=pose)
2072
+ out = render_shot(clip_path, args.shot, frame=args.frame, width=args.width, height=args.height,
2073
+ muscles=args.muscles,
2074
+ geom_groups=[int(x) for x in args.geom_groups.split(",") if x.strip()]
2075
+ if args.geom_groups else None,
2076
+ camera=[float(x) for x in args.camera.split(",")] if args.camera else "auto",
2077
+ dist_scale=args.dist_scale, hud=not args.no_hud)
2078
+ print(f"wrote {out} ({meta['kind']} scene={meta['scene']} bodies={meta['n_bodies']} {meta['source']})")
2079
+ return
2080
+ _run_window(init_path, pose, args.width, args.height, args.frame,
2081
+ selftest_out=args.selftest, start_sim=args.sim, start_bake_frames=args.bake,
2082
+ start_hang=args.hang, start_picker=args.pick)
2083
+
2084
+
2085
+ if __name__ == "__main__":
2086
+ main()