nablaengine 1.0.2__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 (136) hide show
  1. nablaengine/__init__.py +4 -0
  2. nablaengine/_fixtures/README.md +19 -0
  3. nablaengine/_fixtures/data/mf_s0.npz +0 -0
  4. nablaengine/_fixtures/mjlab/LICENSE +27 -0
  5. nablaengine/_fixtures/mjlab/README.md +113 -0
  6. nablaengine/_fixtures/mjlab/g1_meta.json +32 -0
  7. nablaengine/_fixtures/mjlab/g1_train.mjb +0 -0
  8. nablaengine/_optional.py +30 -0
  9. nablaengine/_paths.py +38 -0
  10. nablaengine/actuators/__init__.py +169 -0
  11. nablaengine/actuators/bam.py +306 -0
  12. nablaengine/actuators/bam_params/LICENSE +202 -0
  13. nablaengine/actuators/bam_params/xl330/m6.json +19 -0
  14. nablaengine/boxbox.py +259 -0
  15. nablaengine/ccd.py +1122 -0
  16. nablaengine/checks.py +376 -0
  17. nablaengine/cuda.py +483 -0
  18. nablaengine/dist_query.py +628 -0
  19. nablaengine/dual.py +223 -0
  20. nablaengine/dyn_query.py +685 -0
  21. nablaengine/engines.py +114 -0
  22. nablaengine/envs/__init__.py +24 -0
  23. nablaengine/envs/brax.py +165 -0
  24. nablaengine/envs/convert.py +771 -0
  25. nablaengine/envs/dmc.py +523 -0
  26. nablaengine/envs/env.py +233 -0
  27. nablaengine/envs/kin.py +371 -0
  28. nablaengine/envs/ops.py +134 -0
  29. nablaengine/envs/rewards.py +57 -0
  30. nablaengine/fixtures.py +243 -0
  31. nablaengine/forest_engine/__init__.py +0 -0
  32. nablaengine/forest_engine/adjoint.py +1726 -0
  33. nablaengine/forest_engine/adjoint_contact.py +493 -0
  34. nablaengine/forest_engine/bam_hooks.py +248 -0
  35. nablaengine/forest_engine/body_params.py +1007 -0
  36. nablaengine/forest_engine/capacity_diag.py +116 -0
  37. nablaengine/forest_engine/ccd_coop.py +250 -0
  38. nablaengine/forest_engine/chol_blk.py +80 -0
  39. nablaengine/forest_engine/contact_forces.py +142 -0
  40. nablaengine/forest_engine/contact_vjp.py +462 -0
  41. nablaengine/forest_engine/convex.py +1331 -0
  42. nablaengine/forest_engine/cylinder.py +73 -0
  43. nablaengine/forest_engine/dist_device.py +923 -0
  44. nablaengine/forest_engine/dyn_device.py +696 -0
  45. nablaengine/forest_engine/ellipsoid.py +179 -0
  46. nablaengine/forest_engine/elliptic.py +272 -0
  47. nablaengine/forest_engine/equality.py +842 -0
  48. nablaengine/forest_engine/floss.py +148 -0
  49. nablaengine/forest_engine/foot_offset.py +368 -0
  50. nablaengine/forest_engine/free_gyro.py +288 -0
  51. nablaengine/forest_engine/host.py +530 -0
  52. nablaengine/forest_engine/kdof64.py +127 -0
  53. nablaengine/forest_engine/kinematics.py +320 -0
  54. nablaengine/forest_engine/margin.py +167 -0
  55. nablaengine/forest_engine/margin_convex.py +326 -0
  56. nablaengine/forest_engine/midphase.py +439 -0
  57. nablaengine/forest_engine/model_hooks.py +913 -0
  58. nablaengine/forest_engine/motor_hooks.py +50 -0
  59. nablaengine/forest_engine/muscle.py +485 -0
  60. nablaengine/forest_engine/nb128.py +118 -0
  61. nablaengine/forest_engine/nb64.py +163 -0
  62. nablaengine/forest_engine/noslip.py +1124 -0
  63. nablaengine/forest_engine/nv128.py +1944 -0
  64. nablaengine/forest_engine/object_size.py +283 -0
  65. nablaengine/forest_engine/replay_guard.py +40 -0
  66. nablaengine/forest_engine/root_spread.py +126 -0
  67. nablaengine/forest_engine/solref.py +74 -0
  68. nablaengine/forest_engine/source.py +1464 -0
  69. nablaengine/forest_engine/sparse_pattern.py +527 -0
  70. nablaengine/forest_engine/spatial.py +1045 -0
  71. nablaengine/forest_engine/step.py +3083 -0
  72. nablaengine/forest_engine/surrogate.py +498 -0
  73. nablaengine/forest_engine/tape.py +199 -0
  74. nablaengine/forest_engine/tendon.py +845 -0
  75. nablaengine/forest_engine/terrain.py +1059 -0
  76. nablaengine/forest_engine/world_forces.py +166 -0
  77. nablaengine/forest_engine/world_params.py +230 -0
  78. nablaengine/g1_engine/__init__.py +0 -0
  79. nablaengine/g1_engine/adjoint.py +1661 -0
  80. nablaengine/g1_engine/adjoint_contact.py +577 -0
  81. nablaengine/g1_engine/bam_hooks.py +596 -0
  82. nablaengine/g1_engine/condim4.py +245 -0
  83. nablaengine/g1_engine/contact_forces.py +500 -0
  84. nablaengine/g1_engine/cylccd.py +1158 -0
  85. nablaengine/g1_engine/cylinder.py +216 -0
  86. nablaengine/g1_engine/elliptic.py +565 -0
  87. nablaengine/g1_engine/exact_replay.py +61 -0
  88. nablaengine/g1_engine/host.py +358 -0
  89. nablaengine/g1_engine/kinematics.py +320 -0
  90. nablaengine/g1_engine/mesh.py +305 -0
  91. nablaengine/g1_engine/mesh_tables.py +79 -0
  92. nablaengine/g1_engine/model_hooks.py +919 -0
  93. nablaengine/g1_engine/motor_hooks.py +70 -0
  94. nablaengine/g1_engine/replay_guard.py +55 -0
  95. nablaengine/g1_engine/source.py +1107 -0
  96. nablaengine/g1_engine/sphbox.py +93 -0
  97. nablaengine/g1_engine/step.py +3716 -0
  98. nablaengine/g1_engine/tape.py +173 -0
  99. nablaengine/g1_engine/world_params.py +447 -0
  100. nablaengine/identity.py +401 -0
  101. nablaengine/jax_ffi.py +2536 -0
  102. nablaengine/model/__init__.py +1 -0
  103. nablaengine/model/capability.py +694 -0
  104. nablaengine/model/fields.py +317 -0
  105. nablaengine/model/gravcomp.py +64 -0
  106. nablaengine/model/invweight.py +145 -0
  107. nablaengine/motor.py +143 -0
  108. nablaengine/object_geometry.py +609 -0
  109. nablaengine/params.py +258 -0
  110. nablaengine/provenance.py +196 -0
  111. nablaengine/reference/__init__.py +0 -0
  112. nablaengine/reference/adjoint_groups.py +226 -0
  113. nablaengine/reference/jax64.py +690 -0
  114. nablaengine/reference/warp_physics.py +262 -0
  115. nablaengine/sensors/__init__.py +4 -0
  116. nablaengine/sensors/cameras.py +285 -0
  117. nablaengine/sensors/data/LIVOX_MID360_LICENSE +21 -0
  118. nablaengine/sensors/data/livox_mid360.npz +0 -0
  119. nablaengine/sensors/g1.py +521 -0
  120. nablaengine/sensors/jax_rays.py +364 -0
  121. nablaengine/sensors/optix_rays.py +725 -0
  122. nablaengine/sensors/raycore.py +630 -0
  123. nablaengine/sensors/raygrad.py +374 -0
  124. nablaengine/sensors/raygrad_cuda.py +191 -0
  125. nablaengine/sensors/robot_mesh.py +273 -0
  126. nablaengine/sensors/torch_rays.py +275 -0
  127. nablaengine/terrain.py +424 -0
  128. nablaengine/torch_ffi.py +1328 -0
  129. nablaengine/workdir.py +37 -0
  130. nablaengine-1.0.2.dist-info/METADATA +236 -0
  131. nablaengine-1.0.2.dist-info/RECORD +136 -0
  132. nablaengine-1.0.2.dist-info/WHEEL +5 -0
  133. nablaengine-1.0.2.dist-info/licenses/LICENSE +202 -0
  134. nablaengine-1.0.2.dist-info/licenses/NOTICE +23 -0
  135. nablaengine-1.0.2.dist-info/licenses/THIRD_PARTY_NOTICES.md +176 -0
  136. nablaengine-1.0.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1059 @@
1
+ """Terrain builds on the forest engine (nablaengine.terrain; the tree engine's g1_engine.step.TERRAIN_DEVICE text)."""
2
+ import re
3
+
4
+ import mujoco
5
+ import numpy as np
6
+
7
+ from nablaengine.forest_engine import step
8
+
9
+ TERRAIN_GTYPE = 6
10
+
11
+
12
+ def _g1_step():
13
+ from nablaengine.g1_engine import step as g1_step
14
+ return g1_step
15
+
16
+
17
+ def _cfg(terrain):
18
+ return terrain[0] if isinstance(terrain, tuple) else terrain
19
+
20
+
21
+ def check(m, terrain):
22
+ """ValueError where a terrain build ((TerrainConfig, robot geoms)) does not fit the forest build of m."""
23
+ cfg, tg = terrain
24
+ geoms = step.collision_geoms(m)
25
+ if not tg:
26
+ raise ValueError("terrain build: no robot geom collides with the terrain")
27
+ if m.npair + len(tg) >= 65536:
28
+ raise ValueError(f"{m.npair} pairs and {len(tg)} terrain geoms: a forest terrain build holds fewer than 65536")
29
+ if len(geoms) + 1 > 255:
30
+ raise ValueError(f"{len(geoms)} collision geoms: a forest terrain build holds at most 254 (8-bit geom index)")
31
+ if step.broad_groups(m) is not None:
32
+ raise ValueError(f"terrain builds: at most {step.GROUP_PAIRS} model pairs (the broad phase's pair groups)")
33
+ ok = {int(mujoco.mjtGeom.mjGEOM_SPHERE), int(mujoco.mjtGeom.mjGEOM_CAPSULE), int(mujoco.mjtGeom.mjGEOM_BOX)}
34
+ for g, _, _ in tg:
35
+ if int(m.geom_type[g]) not in ok:
36
+ raise ValueError(f"terrain geom {m.geom(g).name}: spheres, capsules and boxes collide with the terrain")
37
+ if has_box_geoms(m, terrain) and cfg.mode == "native":
38
+ raise ValueError("box robot geoms against the terrain: the analytic heightfield mode only")
39
+
40
+
41
+ def has_box_geoms(m, terrain):
42
+ """Whether a box robot geom collides with the terrain (box_geom_hooks)."""
43
+ box = int(mujoco.mjtGeom.mjGEOM_BOX)
44
+ return any(int(m.geom_type[g]) == box for g, _, _ in terrain[1])
45
+
46
+
47
+ def com_words(m, terrain):
48
+ """Per-world com words of a terrain build: the forest's (COM offset, fixtures) and the object slots."""
49
+ from nablaengine import terrain as T
50
+ cfg = _cfg(terrain)
51
+ return (step.com_words(m) + (T.OBJ_WORDS + (T.OBJ_VEL_WORDS if cfg.object_velocity else 0)) * int(cfg.objects)
52
+ + (T.OBJ_MAT_WORDS * int(cfg.objects) if getattr(cfg, "object_material", False) else 0))
53
+
54
+
55
+ def const_layout(m, terrain):
56
+ """step.const_layout(m) with NTG more pairs (c_pword) and one more collision-geom row (the pseudo geom)."""
57
+ ntg, ng = len(terrain[1]), len(step.collision_geoms(m))
58
+ geom_syms = {s for s, _, _ in step.GEOM_LAYOUT} | {"c_ginvw"}
59
+ out = []
60
+ for s, k, n in step.const_layout(m):
61
+ if s == "c_pword":
62
+ n = n + ntg
63
+ elif s in geom_syms:
64
+ assert n % ng == 0, (s, n, ng)
65
+ n = n + n // ng
66
+ out.append((s, k, n))
67
+ return out
68
+
69
+
70
+ def pair_constants(m, foot_pairs, terrain):
71
+ """step.pair_constants(m, foot_pairs) in const_layout(m, terrain) order: after the model's pairs one virtual pair per
72
+ terrain geom (g1 = the terrain's pseudo geom, the last geom-table row; the geom's floor pair's parameter set,
73
+ condim and foot flag), and the pseudo geom's row (world body, type TERRAIN_GTYPE, at the origin, zero sizes and
74
+ bounds, inverse weight 0)."""
75
+ base = step.pair_constants(m, foot_pairs)
76
+ geoms = step.collision_geoms(m)
77
+ gid = {g: i for i, g in enumerate(geoms)}
78
+ sets = step.pair_param_sets(m)[1]
79
+ tg = len(geoms)
80
+ words = np.asarray([step.pair_word(tg, gid[g], sets[p], int(m.pair_dim[p]), int(ft), 0, 0)
81
+ for g, p, ft in terrain[1]], np.int64)
82
+ extra = {"c_pword": np.stack([words & 0xFFFF, words >> 16], 1).ravel(),
83
+ "c_gbody": [0], "c_gtype": [TERRAIN_GTYPE], "c_gsize": [0.0] * 3, "c_gpos": [0.0] * 3,
84
+ "c_gquat": [1.0, 0.0, 0.0, 0.0], "c_grbound": [0.0], "c_gaabb": [0.0] * 6, "c_ginvw": [0.0]}
85
+ parts, off = [], 0
86
+ for s, k, n in step.const_layout(m):
87
+ nf = 2 * n if k == "u" else n
88
+ parts.append(base[off:off + nf])
89
+ if s in extra:
90
+ parts.append(np.asarray(extra[s], np.float64).astype(np.float32))
91
+ off += nf
92
+ assert off == len(base), (off, len(base))
93
+ return np.concatenate(parts).astype(np.float32)
94
+
95
+
96
+ def defines(m, terrain):
97
+ """The terrain's #defines (the tree engine's step_header terrain block; COM_WORDS: the forest's com_words)."""
98
+ from nablaengine import terrain as T
99
+ cfg, tg = terrain
100
+ return (f"#define HAS_TERRAIN 1\n#define NTG {len(tg)} // robot geoms that collide with the terrain\n"
101
+ f"#define TERRAIN_FLOOR {int(cfg.floor)} // keep the model's floor plane pairs\n"
102
+ f"#define TERRAIN_CAP_PTS {int(cfg.cap_points)} // heightfield samples per capsule\n"
103
+ f"#define TERRAIN_HF_NATIVE {int(cfg.mode == 'native')} // heightfield contacts per prism\n"
104
+ f"#define TERRAIN_NOBJ {int(cfg.objects)} // per-world object slots (in com after the COM offset)\n"
105
+ f"#define OBJ_E0 {T.OBJ_E0} // the element index of object slot 0\n"
106
+ "#ifndef TERRAIN_SORT\n#define TERRAIN_SORT 1 // contacts sorted by (pair, element, slot)\n#endif\n"
107
+ + ("#define OBJ_VEL 1 // the object slots' velocities (com after the slots) enter their contacts\n"
108
+ if cfg.object_velocity else ""))
109
+
110
+
111
+ def _sub1(text, a, b, what):
112
+ if text.count(a) != 1:
113
+ raise RuntimeError(f"forest terrain {what}: anchor found {text.count(a)} times: {a[:70]!r}")
114
+ return text.replace(a, b)
115
+
116
+
117
+ def header(text, m, terrain):
118
+ """step.step_header(m, ...)'s text for a terrain build: NGEOMC + 1, c_pword with the virtual pairs, the geom
119
+ arrays with the pseudo geom's row, COM_WORDS with the object slots; the terrain's #defines first."""
120
+ p, g, ntg = m.npair, len(step.collision_geoms(m)), len(terrain[1])
121
+ text = _sub1(text, f"#define NGEOMC {g}\n", f"#define NGEOMC {g + 1} // (the terrain's pseudo geom last)\n",
122
+ "header")
123
+ text = _sub1(text, f"DKC unsigned int c_pword[{max(p, 1)}];",
124
+ f"DKC unsigned int c_pword[{p + ntg}]; // (terrain: NTG virtual pairs from NPAIR on)\n//", "header")
125
+ text = _sub1(text, f"DKC int c_gbody[{max(g, 1)}], c_gtype[{max(g, 1)}];",
126
+ "DKC int c_gbody[NGEOMC], c_gtype[NGEOMC];", "header")
127
+ text = _sub1(text, f"DKC float c_gsize[{max(g, 1) * 3}], c_gpos[{max(g, 1) * 3}], c_gquat[{max(g, 1) * 4}], "
128
+ f"c_grbound[{max(g, 1)}],\n c_gaabb[{max(g, 1) * 6}];",
129
+ "DKC float c_gsize[NGEOMC * 3], c_gpos[NGEOMC * 3], c_gquat[NGEOMC * 4], c_grbound[NGEOMC],\n"
130
+ " c_gaabb[NGEOMC * 6];", "header")
131
+ if step.fixture_groups(m):
132
+ a = f"__device__ const int c_fixg[{g}] = {{"
133
+ i = text.index(a)
134
+ j = text.index("};", i)
135
+ text = _sub1(text, text[i:j + 2], f"__device__ const int c_fixg[{g + 1}] = {{" + text[i + len(a):j] + ", -1};",
136
+ "header (fixtures)")
137
+ text = _sub1(text, f"#define COM_WORDS {step.com_words(m)}\n",f"#define COM_WORDS {com_words(m, terrain)} "
138
+ "// (the COM offset, then the terrain's object slots)\n", "header")
139
+ return defines(m, terrain) + text
140
+
141
+
142
+ SORT_DEVICE = r"""// A terrain build's contact order (forest_engine.terrain; the tree engine's terrain_sort_contacts with CPL contacts per
143
+ // lane): sorted by (pair, element, slot), ties in their order of arrival, so that the order, and hence the constraint
144
+ // rows and the solver's bits, depend only on the contact set; nothing moves when the contacts arrived sorted
145
+ template <class S>
146
+ __device__ void terrain_sort_contacts(S& s, int ncon, int lane) {
147
+ #if TERRAIN_SORT
148
+ __syncwarp();
149
+ unsigned long long key[CPL];
150
+ int rk[CPL];
151
+ bool moved = false;
152
+ #pragma unroll
153
+ for (int h = 0; h < CPL; h++) {
154
+ const int c = lane + 32 * h;
155
+ key[h] = c < ncon ? (unsigned long long)s.con_pair[c] << 32 | (unsigned long long)s.con_elem[c] << 8 |
156
+ (unsigned long long)s.con_slot[c]
157
+ : ~0ull;
158
+ rk[h] = 0;
159
+ }
160
+ for (int j = 0; j < ncon; j++) {
161
+ const unsigned long long kj = (unsigned long long)s.con_pair[j] << 32 | (unsigned long long)s.con_elem[j] << 8 |
162
+ (unsigned long long)s.con_slot[j];
163
+ #pragma unroll
164
+ for (int h = 0; h < CPL; h++) rk[h] += kj < key[h] || (kj == key[h] && j < lane + 32 * h);
165
+ }
166
+ #pragma unroll
167
+ for (int h = 0; h < CPL; h++) moved |= lane + 32 * h < ncon && rk[h] != lane + 32 * h;
168
+ if (!__any_sync(0xffffffffu, moved)) return;
169
+ int pr[CPL], dm[CPL];
170
+ unsigned char sl[CPL];
171
+ unsigned short el[CPL];
172
+ float di[CPL], mu[CPL], ps[CPL][3], fr[CPL][9];
173
+ #if TERRAIN_HF_NATIVE
174
+ unsigned aux[CPL];
175
+ #endif
176
+ #pragma unroll
177
+ for (int h = 0; h < CPL; h++) {
178
+ const int c = lane + 32 * h;
179
+ if (c < ncon) {
180
+ pr[h] = s.con_pair[c]; sl[h] = s.con_slot[c]; el[h] = s.con_elem[c]; dm[h] = s.con_dim[c];
181
+ di[h] = s.con_dist[c]; mu[h] = s.con_mu[c];
182
+ for (int k = 0; k < 3; k++) ps[h][k] = s.con_pos[c][k];
183
+ for (int k = 0; k < 9; k++) fr[h][k] = s.con_frame[c][k];
184
+ #if TERRAIN_HF_NATIVE
185
+ aux[h] = s.con_aux[c];
186
+ #endif
187
+ }
188
+ }
189
+ __syncwarp();
190
+ #pragma unroll
191
+ for (int h = 0; h < CPL; h++) {
192
+ if (lane + 32 * h < ncon) {
193
+ const int c = rk[h];
194
+ s.con_pair[c] = pr[h]; s.con_slot[c] = sl[h]; s.con_elem[c] = el[h]; s.con_dim[c] = dm[h];
195
+ s.con_dist[c] = di[h]; s.con_mu[c] = mu[h];
196
+ for (int k = 0; k < 3; k++) s.con_pos[c][k] = ps[h][k];
197
+ for (int k = 0; k < 9; k++) s.con_frame[c][k] = fr[h][k];
198
+ #if TERRAIN_HF_NATIVE
199
+ s.con_aux[c] = aux[h];
200
+ #endif
201
+ }
202
+ }
203
+ __syncwarp();
204
+ #endif
205
+ }
206
+
207
+ """
208
+
209
+
210
+ def device_text(src):
211
+ """The tree engine's TERRAIN_DEVICE with capbox_segs generated from the forest text src and the forest's
212
+ terrain_sort_contacts."""
213
+ g1 = _g1_step()
214
+ dev = g1.TERRAIN_DEVICE
215
+ a = dev.index("// permutation of a per-contact array: contact c (lanes c, c - 32) moves to rk[c / 32]")
216
+ b = dev.index("// the terrain's contacts of the robot geoms (virtual pairs NPAIR .. NPAIR + NTG - 1)")
217
+ dev = dev[:a] + SORT_DEVICE + dev[b:]
218
+ return g1.capbox_segs_source(src) + "\n" + dev.lstrip("\n") + "\n"
219
+
220
+
221
+ STEP_HOOKS = (
222
+ ("""template <class S>
223
+ __device__ DK_INL_COLLIDE void collide_pair(S& s, int pair) {""", None),
224
+ (""" unsigned char con_slot[MAXCON]; // which contact of its pair (tape): plane-capsule end, parallel capsule-capsule candidate
225
+ """,
226
+ """ unsigned char con_slot[MAXCON]; // which contact of its pair (tape): plane-capsule end, parallel capsule-capsule candidate
227
+ unsigned short con_elem[MAXCON]; // terrain builds: the contact's terrain element (add_contact's slot >> 8)
228
+ """),
229
+ (""" float con_mu[MAXCON];
230
+ unsigned char con_slot[MAXCON];
231
+ float *con_dist""",
232
+ """ float con_mu[MAXCON];
233
+ unsigned char con_slot[MAXCON];
234
+ unsigned short con_elem[MAXCON];
235
+ float *con_dist"""),
236
+ (""" s.con_slot[c] = (unsigned char)slot;
237
+ """,
238
+ """ s.con_slot[c] = (unsigned char)slot;
239
+ s.con_elem[c] = (unsigned short)(slot >> 8);
240
+ """),
241
+ (""" __stcs(rec + OFF_CON + i, __uint_as_float(e));
242
+ }
243
+ """,
244
+ """ __stcs(rec + OFF_CON + i, __uint_as_float(e));
245
+ }
246
+ if (rec) // tape (terrain): the contacts' terrain elements, 16 bits each
247
+ for (int i = lane; i < (MAXCON + 1) / 2; i += 32) {
248
+ const unsigned x0 = 2 * i < ncon ? (unsigned)s.con_elem[2 * i] : 0u;
249
+ const unsigned x1 = 2 * i + 1 < ncon ? (unsigned)s.con_elem[2 * i + 1] : 0u;
250
+ __stcs(rec + OFF_TELEM + i, __uint_as_float(x0 | x1 << 16));
251
+ }
252
+ """),
253
+ (""" if (PPLANE(pr)) {
254
+ #if FLOOR_G >= 0
255
+ const float* n = fn;""",
256
+ """ if (PPLANE(pr)) {
257
+ #if !TERRAIN_FLOOR
258
+ return false; // (terrain build: the terrain replaces the floor)
259
+ #endif
260
+ #if FLOOR_G >= 0
261
+ const float* n = fn;"""),
262
+ (""" for (int i = lane; i < ncand; i += 32) collide_pair(s, s.cand[i]);
263
+ """,
264
+ """ for (int i = lane; i < ncand; i += 32) collide_pair(s, s.cand[i]);
265
+ collide_terrain(s, lane);
266
+ """),
267
+ (""" int ncon = uniform_int(min(s.ncon, MAXCON), CON_BITS);
268
+ { // contact Jacobians:""",
269
+ """ int ncon = uniform_int(min(s.ncon, MAXCON), CON_BITS);
270
+ terrain_sort_contacts(s, ncon, lane);
271
+ { // contact Jacobians:"""),
272
+ )
273
+
274
+ STEP_NATIVE_HOOKS = (
275
+ (""" unsigned short con_elem[MAXCON]; // terrain builds: the contact's terrain element (add_contact's slot >> 8)
276
+ """,
277
+ """ unsigned short con_elem[MAXCON]; // terrain builds: the contact's terrain element (add_contact's slot >> 8)
278
+ unsigned con_aux[MAXCON]; // native heightfield contacts: the candidate id (HfCand.pid), else 0
279
+ """),
280
+ (""" unsigned short con_elem[MAXCON];
281
+ float *con_dist""",
282
+ """ unsigned short con_elem[MAXCON];
283
+ unsigned con_aux[MAXCON];
284
+ float *con_dist"""),
285
+ (""" s.con_elem[c] = (unsigned short)(slot >> 8);
286
+ s.con_dim[c] = PDIM(pair);
287
+ s.con_dist[c] = dist;
288
+ for (int k = 0; k < 3; k++) s.con_pos[c][k] = pos[k];
289
+ for (int k = 0; k < 9; k++) s.con_frame[c][k] = frame[k];
290
+ s.con_mu[c] = PFOOT(pair) ? s.fric : PMU(pair);
291
+ return true;""",
292
+ """ s.con_elem[c] = (unsigned short)(slot >> 8);
293
+ s.con_aux[c] = 0u;
294
+ s.con_dim[c] = PDIM(pair);
295
+ s.con_dist[c] = dist;
296
+ for (int k = 0; k < 3; k++) s.con_pos[c][k] = pos[k];
297
+ for (int k = 0; k < 9; k++) s.con_frame[c][k] = frame[k];
298
+ s.con_mu[c] = PFOOT(pair) ? s.fric : PMU(pair);
299
+ return true;"""),
300
+ (""" __stcs(rec + OFF_TELEM + i, __uint_as_float(x0 | x1 << 16));
301
+ }
302
+ """,
303
+ """ __stcs(rec + OFF_TELEM + i, __uint_as_float(x0 | x1 << 16));
304
+ }
305
+ if (rec) // tape (native heightfields): the contacts' candidate ids
306
+ for (int i = lane; i < MAXCON; i += 32) __stcs(rec + OFF_TAUX + i, __uint_as_float(i < ncon ? s.con_aux[i] : 0u));
307
+ """),
308
+ )
309
+
310
+
311
+ OBJ_VEL_SLOT = r"""// (forest_engine.terrain, OBJ_VEL) the slots moved to the substep's time (obj_advance), their motion words after
312
+ // them as in com; dk_objc: the world's slots in com
313
+ #define OBJ_VW 18 // motion words per slot: v, w, s, a, al, sd
314
+ __shared__ float dk_objk[TERRAIN_NOBJ * (15 + OBJ_VW)];
315
+ __shared__ const float* dk_objc;
316
+ __shared__ float dk_objt; // the substep's time t = k h (obj_advance)
317
+ // object slot e's motion words at the substep: v (3) at the slot's position, w (3), world; s (3) slot frame; a, al
318
+ // (world), sd (slot frame)
319
+ __device__ __forceinline__ const float* obj_vel(int e) { return dk_obj + 15 * TERRAIN_NOBJ + OBJ_VW * e; }
320
+ // R x for a slot's row-major rotation ob + 3
321
+ __device__ __forceinline__ void obj_rot(const float* ob, const float* x, float* y) {
322
+ for (int t = 0; t < 3; t++) y[t] = ob[3 + 3 * t] * x[0] + ob[4 + 3 * t] * x[1] + ob[5 + 3 * t] * x[2];
323
+ }
324
+ // the slot's surface velocity u and acceleration A at point p of a contact with normal n
325
+ __device__ __forceinline__ void obj_point_motion(int e, const float* p, const float* n, float* u, float* A) {
326
+ const float *ov = obj_vel(e), *ob = dk_obj + 15 * e;
327
+ const float r[3] = {p[0] - ob[0], p[1] - ob[1], p[2] - ob[2]};
328
+ float rs[3], rd[3];
329
+ cross(ov + 3, r, u);
330
+ obj_rot(ob, ov + 6, rs);
331
+ obj_rot(ob, ov + 15, rd);
332
+ const float rn = dot3(n, rs), dn = dot3(n, rd);
333
+ for (int t = 0; t < 3; t++) u[t] += ov[t] + rs[t] - n[t] * rn;
334
+ cross(ov + 12, r, A);
335
+ for (int t = 0; t < 3; t++) A[t] += ov[9 + t] + rd[t] - n[t] * dn;
336
+ }
337
+ // R' = exp([th]) R (Rodrigues; th = 0: R copied)
338
+ __device__ __forceinline__ void obj_rotate(const float* th3, const float* o, float* d) {
339
+ const float th = sqrtf(dot3(th3, th3));
340
+ if (!(th > 0.f)) {
341
+ for (int i = 0; i < 9; i++) d[i] = o[i];
342
+ return;
343
+ }
344
+ const float k[3] = {th3[0] / th, th3[1] / th, th3[2] / th}, sn = sinf(th), cs = 1.f - cosf(th);
345
+ const float Q[9] = {1.f - cs * (k[1] * k[1] + k[2] * k[2]), -sn * k[2] + cs * k[0] * k[1], sn * k[1] + cs * k[0] * k[2],
346
+ sn * k[2] + cs * k[0] * k[1], 1.f - cs * (k[0] * k[0] + k[2] * k[2]), -sn * k[0] + cs * k[1] * k[2],
347
+ -sn * k[1] + cs * k[0] * k[2], sn * k[0] + cs * k[1] * k[2], 1.f - cs * (k[0] * k[0] + k[1] * k[1])};
348
+ float R[9];
349
+ for (int i = 0; i < 3; i++)
350
+ for (int j = 0; j < 3; j++) R[3 * i + j] = Q[3 * i] * o[j] + Q[3 * i + 1] * o[3 + j] + Q[3 * i + 2] * o[6 + j];
351
+ for (int i = 0; i < 9; i++) d[i] = R[i];
352
+ }
353
+ // the world's slots at substep k (t = k h) into dk_objk, dk_obj pointed at it
354
+ __device__ __forceinline__ void obj_advance(int k, float h, int lane) {
355
+ __syncwarp();
356
+ const float t = k * h;
357
+ for (int e = lane; e < TERRAIN_NOBJ; e += 32) {
358
+ const float *o = dk_objc + 15 * e, *ov = dk_objc + 15 * TERRAIN_NOBJ + OBJ_VW * e;
359
+ float* d = dk_objk + 15 * e;
360
+ float* dv = dk_objk + 15 * TERRAIN_NOBJ + OBJ_VW * e;
361
+ const float kk = 0.5f * (float)(k * (k + 1)); // sum_{j<=k} j
362
+ for (int i = 0; i < 3; i++) d[i] = o[i] + (t * ov[i] + (h * h * kk) * ov[9 + i]);
363
+ const bool alz = ov[12] == 0.f && ov[13] == 0.f && ov[14] == 0.f;
364
+ if (alz) { // constant w: one rotation exp(t [w])
365
+ const float th3[3] = {t * ov[3], t * ov[4], t * ov[5]};
366
+ obj_rotate(th3, o + 3, d + 3);
367
+ } else { // R_k = exp(h [w_k]) ... exp(h [w_1]) R
368
+ for (int i = 0; i < 9; i++) d[3 + i] = o[3 + i];
369
+ for (int j = 1; j <= k; j++) {
370
+ const float th3[3] = {h * (ov[3] + (j * h) * ov[12]), h * (ov[4] + (j * h) * ov[13]), h * (ov[5] + (j * h) * ov[14])};
371
+ obj_rotate(th3, d + 3, d + 3);
372
+ }
373
+ }
374
+ for (int i = 12; i < 15; i++) d[i] = o[i];
375
+ for (int i = 0; i < 3; i++) {
376
+ dv[i] = ov[i] + t * ov[9 + i];
377
+ dv[3 + i] = ov[3 + i] + t * ov[12 + i];
378
+ dv[6 + i] = ov[6 + i] + t * ov[15 + i];
379
+ }
380
+ for (int i = 9; i < OBJ_VW; i++) dv[i] = ov[i];
381
+ }
382
+ if (lane == 0) { dk_obj = dk_objk; dk_objt = t; }
383
+ __syncwarp();
384
+ }
385
+ """
386
+ OBJ_VEL_FORWARD = (
387
+ (" con_jv(s, s.qvel, lane); // contact J qvel for the contact rows' velocities (its __syncwarp also publishes the "
388
+ "above)\n",
389
+ " con_jv(s, s.qvel, lane); // contact J qvel for the contact rows' velocities (its __syncwarp also publishes the "
390
+ "above)\n"
391
+ " for (int c = lane; c < ncon; c += 32) // (forest_engine.terrain, OBJ_VEL) relative to the object slot's surface\n"
392
+ " if (s.con_pair[c] >= NPAIR && s.con_elem[c] >= OBJ_E0) {\n"
393
+ " const int e = s.con_elem[c] - OBJ_E0;\n"
394
+ " float p[3], fr[9], u[3], A[3];\n"
395
+ " for (int t = 0; t < 3; t++) p[t] = s.con_pos[c][t];\n"
396
+ " for (int t = 0; t < 9; t++) fr[t] = s.con_frame[c][t];\n"
397
+ " obj_point_motion(e, p, fr, u, A);\n"
398
+ " for (int d = 0; d < 3; d++) s.con_dot[c][d] -= dot3(fr + 3 * d, u);\n"
399
+ "#if HAS_CONDIM4\n"
400
+ " s.con_dot[c][3] -= dot3(fr, obj_vel(e) + 3);\n"
401
+ "#endif\n"
402
+ " }\n"
403
+ " __syncwarp();\n"),
404
+ (" float D = efc_D(iw, imp);\n",
405
+ " float D = efc_D(iw, imp);\n"
406
+ " if (con && s.con_pair[c] >= NPAIR && s.con_elem[c] >= OBJ_E0 && bb != 0.f) { // (OBJ_VEL) the slot's acceleration\n"
407
+ " const int e = s.con_elem[c] - OBJ_E0;\n"
408
+ " float p[3], fr[9], u[3], A[3];\n"
409
+ " for (int t = 0; t < 3; t++) p[t] = s.con_pos[c][t];\n"
410
+ " for (int t = 0; t < 9; t++) fr[t] = s.con_frame[c][t];\n"
411
+ " obj_point_motion(e, p, fr, u, A);\n"
412
+ " for (int d = 0; d < 3; d++) s.con_dot[c][d] -= dot3(fr + 3 * d, A) / bb;\n"
413
+ "#if HAS_CONDIM4\n"
414
+ " s.con_dot[c][3] -= dot3(fr, obj_vel(e) + 12) / bb;\n"
415
+ "#endif\n"
416
+ " }\n"),
417
+ )
418
+ OBJ_VEL_HOST = (
419
+ (" if (lane == 0) s.oforce = k == nsub - 1 ? s.con_fo : nullptr; // the contact forces of the last substep\n",
420
+ " obj_advance(k, c_misc[0], lane); // (forest_engine.terrain, OBJ_VEL) the slots at the substep\n"
421
+ " if (lane == 0) s.oforce = k == nsub - 1 ? s.con_fo : nullptr; // the contact forces of the last substep\n",
422
+ 1),
423
+ (" load_fixtures(s, com, w, lane);\n if (lane == 0) {\n s.fric = fric[w];\n s.unsupported = k ? g.unsupported : 0;",
424
+ " load_fixtures(s, com, w, lane);\n"
425
+ " obj_advance(k, c_misc[0], lane); // (forest_engine.terrain, OBJ_VEL) the slots at the substep\n"
426
+ " if (lane == 0) {\n s.fric = fric[w];\n s.unsupported = k ? g.unsupported : 0;", 2),
427
+ )
428
+ OBJ_VEL_ADJ_KERNEL = (
429
+ (" const size_t r = (size_t)w * nsub + k;\n adj_substep(",
430
+ " const size_t r = (size_t)w * nsub + k;\n"
431
+ " obj_advance(k, c_misc[0], lane); // (forest_engine.terrain, OBJ_VEL) the slots at the substep\n"
432
+ " adj_substep(", 1),
433
+ )
434
+ OBJ_VEL_ADJOINT = (
435
+ ("#define CS_N (HAS_CONDIM4 ? 33 : 24)",
436
+ "#define CS_OV (HAS_CONDIM4 ? 33 : 24) // (forest_engine.terrain, OBJ_VEL) the slot's motion cotangents (18 + 6)\n"
437
+ "#define CS_N (CS_OV + 24)"),
438
+ (" float Wv[3], Wa[3], Wl[3], cot[13], fg[12]; // cot = (d bar, p bar, frame bar): adj_contact_geom's cotangent\n",
439
+ " const int oe = pair >= NPAIR && (slot >> 8) >= OBJ_E0 ? (slot >> 8) - OBJ_E0 : -1; // (OBJ_VEL) its slot\n"
440
+ " if (oe >= 0) { // (forest_engine.terrain, OBJ_VEL) relative to the slot's surface\n"
441
+ " float u[3], A[3];\n"
442
+ " obj_point_motion(oe, p, fr, u, A);\n"
443
+ " const float* ov = obj_vel(oe);\n"
444
+ " for (int t = 0; t < 3; t++) { Vv[t] -= u[t]; Ov[t] -= ov[3 + t]; Va[t] -= A[t]; Oa[t] -= ov[12 + t]; }\n"
445
+ " }\n"
446
+ " float Wv[3], Wa[3], Wl[3], cot[13], fg[12]; // cot = (d bar, p bar, frame bar): adj_contact_geom's cotangent\n"),
447
+ (" cot[1] = cot[2] = cot[3] = 0.f;\n contact_pbar_motion(Wv, Wa, Wl, Ov, Oa, Ol, cot + 1);\n",
448
+ " float og[24]; // (OBJ_VEL) the slot's motion cotangents (18), then the pose partials' contact parts (6)\n"
449
+ "#pragma unroll\n"
450
+ " for (int t = 0; t < 24; t++) og[t] = 0.f;\n"
451
+
452
+ " if (oe >= 0) {\n"
453
+ " const float *ov = obj_vel(oe), *ob = dk_obj + 15 * oe;\n"
454
+ " float rs[3], rd[3], r[3], x[3];\n"
455
+ " obj_rot(ob, ov + 6, rs);\n"
456
+ " obj_rot(ob, ov + 15, rd);\n"
457
+ " for (int t = 0; t < 3; t++) r[t] = p[t] - ob[t];\n"
458
+ " const float rn = dot3(fr, rs), dn = dot3(fr, rd), wn = dot3(fr, Wv), an = dot3(fr, Wa);\n"
459
+ " for (int t = 0; t < 3; t++) cot[4 + t] += rn * Wv[t] + wn * rs[t] + dn * Wa[t] + an * rd[t]; // n bar\n"
460
+
461
+ " float wt[3], at[3];\n"
462
+ " for (int t = 0; t < 3; t++) { og[t] = Wv[t]; og[9 + t] = Wa[t]; wt[t] = Wv[t] - fr[t] * wn; at[t] = Wa[t] - fr[t] * an; }\n"
463
+ " cross(r, Wv, og + 3);\n"
464
+
465
+ " cross(r, Wa, og + 12);\n"
466
+ "#if HAS_CONDIM4\n"
467
+ " for (int t = 0; t < 3; t++) { og[3 + t] += AWv[t]; og[12 + t] += AWa[t]; }\n"
468
+ "#endif\n"
469
+ " for (int j = 0; j < 3; j++) {\n"
470
+ " og[6 + j] = ob[3 + j] * wt[0] + ob[6 + j] * wt[1] + ob[9 + j] * wt[2];\n"
471
+ " og[15 + j] = ob[3 + j] * at[0] + ob[6 + j] * at[1] + ob[9 + j] * at[2];\n"
472
+ " }\n"
473
+ " cross(rs, wt, x); // the rotation partial's surface terms (og[21 ..] completed below)\n"
474
+ " for (int t = 0; t < 3; t++) og[21 + t] = -x[t];\n"
475
+ " cross(rd, at, x);\n"
476
+ " for (int t = 0; t < 3; t++) og[21 + t] -= x[t];\n"
477
+ " }\n"
478
+ " cot[1] = cot[2] = cot[3] = 0.f;\n contact_pbar_motion(Wv, Wa, Wl, Ov, Oa, Ol, cot + 1);\n"
479
+ ),
480
+ (" for (int t = 0; t < 12; t++) cs[12 + t] = fg[t];\n",
481
+ " for (int t = 0; t < 12; t++) cs[12 + t] = fg[t];\n"
482
+ " if (oe >= 0) { // (OBJ_VEL) the slot pose's partials without the robot geom's terms\n"
483
+ " const float *ov = obj_vel(oe), *ob = dk_obj + 15 * oe;\n"
484
+ " float x[3], y[3], nb[3], r[3];\n"
485
+ " cross(Wv, ov + 3, x);\n"
486
+ " cross(Wa, ov + 12, y);\n"
487
+ " for (int t = 0; t < 3; t++) { og[18 + t] = cot[1 + t] + x[t] + y[t]; r[t] = p[t] - ob[t]; }\n"
488
+ " make_frame_vjp(fr, cot + 4, nb);\n"
489
+ " cross(fr, nb, x);\n"
490
+ " cross(r, cot + 1, y);\n"
491
+ " for (int t = 0; t < 3; t++) og[21 + t] += x[t] + y[t];\n"
492
+ " }\n"
493
+ "#pragma unroll\n"
494
+ " for (int t = 0; t < 24; t++) cs[CS_OV + t] = og[t]; // (OBJ_VEL)\n"),
495
+ )
496
+ OBJ_VEL_GRAD = (
497
+ (" float qbar[NQ], vbar[NV], ubar[NU]; // cotangents of the substep's output, then of its input; ctrl (summed)\n",
498
+ " float qbar[NQ], vbar[NV], ubar[NU]; // cotangents of the substep's output, then of its input; ctrl (summed)\n"
499
+ " float ovbar[OBJ_VW * TERRAIN_NOBJ]; // (forest_engine.terrain, OBJ_VEL) the slots' motion cotangents (summed)\n"),
500
+ (" for (int i = lane; i < NU; i += 32) s.ubar[i] = 0.f;\n",
501
+ " for (int i = lane; i < NU; i += 32) s.ubar[i] = 0.f;\n"
502
+ " for (int i = lane; i < OBJ_VW * TERRAIN_NOBJ; i += 32) s.ovbar[i] = 0.f; // (OBJ_VEL)\n"),
503
+ (" APROF(APROF_CONTACT_ROWS);\n",
504
+ " APROF(APROF_CONTACT_ROWS);\n"
505
+ " { // (forest_engine.terrain, OBJ_VEL) the batch's object contacts' slot motion cotangents (after cb_coop)\n"
506
+ " const int oe = cb >= 0 && pair >= NPAIR && (slot >> 8) >= OBJ_E0 ? (slot >> 8) - OBJ_E0 : -1;\n"
507
+ " float g[18];\n"
508
+ " const float t = dk_objt, tq = 0.5f * t * (t + c_misc[0]); // d v_k / d a, d pos_k / d a\n"
509
+ "#pragma unroll\n"
510
+ " for (int q = 0; q < 9; q++) { g[q] = cw[CS_OV + q]; g[9 + q] = cw[CS_OV + 9 + q] + t * cw[CS_OV + q]; }\n"
511
+ " if (oe >= 0 && t > 0.f) { // the slot's motion within the step through the contact geometry\n"
512
+ " const float *ov = obj_vel(oe), *ob = dk_obj + 15 * oe, *X = s.X[c_gbody[PG2(pair)]];\n"
513
+ " float xs[3], ts[3], r[3], u[3];\n"
514
+ " for (int i = 0; i < 3; i++) { xs[i] = cw[CS_OV + 18 + i] - cw[18 + i]; r[i] = X[i] - ob[i]; }\n"
515
+ " cross(r, cw + 18, u);\n"
516
+ " for (int i = 0; i < 3; i++) ts[i] = cw[CS_OV + 21 + i] - cw[21 + i] - u[i];\n"
517
+ " const float w0[3] = {ov[3] - t * ov[12], ov[4] - t * ov[13], ov[5] - t * ov[14]}; // the step's w\n"
518
+ " const float ph[3] = {t * w0[0], t * w0[1], t * w0[2]}, th2 = dot3(ph, ph), th = sqrtf(th2);\n"
519
+ " const float ca = th < 1e-3f ? 0.5f - th2 / 24.f : (1.f - cosf(th)) / th2;\n"
520
+ " const float cb3 = th < 1e-3f ? 1.f / 6.f - th2 / 120.f : (th - sinf(th)) / (th2 * th);\n"
521
+ " float a1[3], a2[3];\n"
522
+ " cross(ph, ts, a1);\n"
523
+ " cross(ph, a1, a2);\n"
524
+ " for (int i = 0; i < 3; i++) {\n"
525
+ " const float jt = ts[i] - ca * a1[i] + cb3 * a2[i];\n"
526
+ " g[i] -= t * xs[i]; g[9 + i] -= tq * xs[i]; g[3 + i] -= t * jt; g[12 + i] -= tq * jt;\n"
527
+ " }\n"
528
+ " }\n"
529
+ " unsigned om = __ballot_sync(0xffffffffu, oe >= 0);\n"
530
+ " while (om) { // slot by slot (uniform: om is the warp's)\n"
531
+ " const int k = __shfl_sync(0xffffffffu, oe, __ffs(om) - 1);\n"
532
+ " const bool mine = oe == k;\n"
533
+ " om &= ~__ballot_sync(0xffffffffu, mine);\n"
534
+ "#pragma unroll\n"
535
+ " for (int q = 0; q < 18; q++) {\n"
536
+ " float sv = mine ? g[q] : 0.f;\n"
537
+ " for (int o = 16; o > 0; o >>= 1) sv += __shfl_xor_sync(0xffffffffu, sv, o);\n"
538
+ " if (lane == 0) s.ovbar[OBJ_VW * k + q] += sv;\n"
539
+ " }\n"
540
+ " }\n"
541
+ " }\n"),
542
+ )
543
+
544
+
545
+ MAT_DECL = r"""// (forest_engine.terrain, OBJ_MAT / TER_MAT) contact materials of the object slots (OBJ_MW words each in com after
546
+ // the slots and their motion words; dk_omat: the world's, set with dk_obj) and of the static terrain's elements (g_tmat:
547
+ // TER_MW words each, the boxes then the heightfields, set with the terrain; null: none)
548
+ #define OBJ_MAT_ON @OBJ@
549
+ #define TER_MAT_ON @TER@
550
+ #define OBJ_MW 7
551
+ #define TER_MW 8
552
+ #if OBJ_MAT_ON
553
+ __shared__ const float* dk_omat;
554
+ __device__ __forceinline__ const float* obj_mat(int e) { return dk_omat + OBJ_MW * e; }
555
+ #endif
556
+ #if TER_MAT_ON
557
+ __device__ const float* g_tmat;
558
+ #endif
559
+ // the material of a contact of pair with terrain element e into *p: 0 none (the pair's parameters), 1 its friction
560
+ // mixed by max, 2 its friction, solref and solimp (an object slot's: 2)
561
+ __device__ __forceinline__ int el_mat(int pair, int e, const float** p) {
562
+ *p = nullptr;
563
+ if (pair < NPAIR) return 0;
564
+ #if OBJ_MAT_ON
565
+ if (e >= OBJ_E0) { *p = obj_mat(e - OBJ_E0); return 2; }
566
+ #endif
567
+ #if TER_MAT_ON
568
+ if (e < OBJ_E0 && g_tmat) {
569
+ const float* q = g_tmat + TER_MW * e;
570
+ const int md = (int)q[7];
571
+ if (md == 1 || md == 2) { *p = q; return md; }
572
+ }
573
+ #endif
574
+ return 0;
575
+ }
576
+
577
+ """
578
+ _MAT_DECL_AT = ("// slot: which contact of the pair this is (the tape's contact table, tape.py): the end e of a plane-capsule "
579
+ "pair\n")
580
+ _MAT_MU = " s.con_mu[c] = PFOOT(pair) ? s.fric : PMU(pair);\n"
581
+ _MAT_MU_NEW = (" s.con_mu[c] = el_mu(pair, slot >> 8, PFOOT(pair) ? s.fric : PMU(pair)); // (forest_engine.terrain, "
582
+ "OBJ_MAT / TER_MAT)\n")
583
+ _EL_MU_AT = " return 0;\n}\n\n"
584
+ _EL_MU = """ return 0;
585
+ }
586
+ // (forest_engine.terrain, OBJ_MAT / TER_MAT) the friction of a new contact of pair with element e, mu the pair's (or
587
+ // the foot pair's per-world friction): an override's mu, max(mu, the element's) for mode 1, else mu
588
+ __device__ __noinline__ float el_mu(int pair, int e, float mu) {
589
+ const float* em;
590
+ const int md = el_mat(pair, e, &em);
591
+ return md == 2 ? em[0] : (md == 1 ? fmaxf(mu, em[0]) : mu);
592
+ }
593
+
594
+ """
595
+ _MAT_KB = " float k, bb, imp;\n kbimp(sref, simp, pos, h, &k, &bb, &imp);\n"
596
+ _MAT_KB_NEW = """ float omsi[5]; // (forest_engine.terrain, OBJ_MAT / TER_MAT) an overriding material's impedance
597
+ if (con) {
598
+ const float* em;
599
+ if (el_mat(s.con_pair[c], s.con_elem[c], &em) == 2) {
600
+ for (int t = 0; t < 4; t++) omsi[t] = em[3 + t];
601
+ omsi[4] = simp[4];
602
+ sref = em + 1;
603
+ simp = omsi;
604
+ }
605
+ }
606
+ """
607
+ _MAT_ADJ_MU = " const float mu = PFOOT(pair) ? s.fric : PMU(pair);\n"
608
+ _MAT_ADJ_MU_NEW = """ const int om_e = pair >= NPAIR && (slot >> 8) >= OBJ_E0 ? (slot >> 8) - OBJ_E0 : -1; // (OBJ_MAT) its slot
609
+ const float* em; // (OBJ_MAT / TER_MAT) the element's material and mode (el_mat)
610
+ const int em_md = el_mat(pair, slot >> 8, &em);
611
+ const float mu_b = PFOOT(pair) ? s.fric : PMU(pair);
612
+ const float mu = em_md == 2 ? em[0] : (em_md == 1 ? fmaxf(mu_b, em[0]) : mu_b);
613
+ const bool em_mu = em_md == 2 || (em_md == 1 && em[0] > mu_b); // (the friction is the element's)
614
+ (void)om_e; (void)em_mu;
615
+ """
616
+ _MAT_ADJ_SEL = """ float omsi[5]; // (forest_engine.terrain, OBJ_MAT / TER_MAT) an overriding material's impedance
617
+ if (em_md == 2) {
618
+ for (int t = 0; t < 4; t++) omsi[t] = em[3 + t];
619
+ omsi[4] = simp[4];
620
+ sref = em + 1;
621
+ simp = omsi;
622
+ }
623
+ """
624
+ _MAT_ADJ_IMP_P = " adj_row_impedance(sref, simp, d, contact_invw(pair, mu), ri);\n"
625
+ _MAT_ADJ_IMP = " adj_row_impedance(PSOLREF(pair), PSOLIMP(pair), d, contact_invw(pair, mu), ri);\n"
626
+ _MAT_PB = " cot[1] = cot[2] = cot[3] = 0.f;\n contact_pbar_motion(Wv, Wa, Wl, Ov, Oa, Ol, cot + 1);\n"
627
+ _MAT_PARTIALS = (" if (om_e >= 0 && zone) // (OBJ_MAT) the slot material's partials (P sign)\n"
628
+ " contact_param_vjp(Vv, Va, Vl, fr, mu, dim, zone, d, D, k, b, imp, contact_invw(pair, mu), sref, simp, mg);\n")
629
+ _MAT_REDUCE = """ { // (forest_engine.terrain, OBJ_MAT) the batch's object contacts' material cotangents, slot by slot (a warp sum)
630
+ const int oe = cb >= 0 && pair >= NPAIR && (slot >> 8) >= OBJ_E0 ? (slot >> 8) - OBJ_E0 : -1;
631
+ unsigned om = __ballot_sync(0xffffffffu, oe >= 0);
632
+ while (om) { // (uniform: om is the warp's)
633
+ const int k = __shfl_sync(0xffffffffu, oe, __ffs(om) - 1);
634
+ const bool mine = oe == k;
635
+ om &= ~__ballot_sync(0xffffffffu, mine);
636
+ #pragma unroll
637
+ for (int q = 0; q < 7; q++) { // contact_param_vjp's (tc, dr, dmin, dmax, width, mid, mu) -> the words' order
638
+ float sv = mine ? mg[q] : 0.f;
639
+ for (int o = 16; o > 0; o >>= 1) sv += __shfl_xor_sync(0xffffffffu, sv, o);
640
+ if (lane == 0) s.omg[OBJ_MW * k + (q == 6 ? 0 : q + 1)] -= sv; // (the gradient is -P)
641
+ }
642
+ }
643
+ }
644
+ """
645
+
646
+
647
+ def material_engine(src, m, terrain):
648
+ """The final engine text (adjoint.cuda_source, after world_params / world_forces / velocity_grad_out) with the
649
+ contact materials of the object slots (TerrainConfig.object_material, OBJ_MAT) and of the static terrain's elements
650
+ (TerrainConfig.terrain_material, TER_MAT); else unchanged."""
651
+ cfg = _cfg(terrain) if terrain is not None else None
652
+ objm, term = (bool(getattr(cfg, "object_material", False)), bool(getattr(cfg, "terrain_material", False))) \
653
+ if cfg is not None else (False, False)
654
+ sand = bool(getattr(cfg, "terrain_sand", False)) if cfg is not None else False
655
+ if not (objm or term or sand):
656
+ return src
657
+ what = "TerrainConfig." + ("object_material" if objm else "terrain_material")
658
+ if (objm or term) and "#define HAS_CONDIM4 1" in src:
659
+ raise ValueError(f"{what}: not with condim-4 (torsional) contact pairs")
660
+ if (objm or term) and int(m.opt.cone) == int(mujoco.mjtCone.mjCONE_ELLIPTIC):
661
+ raise ValueError(f"{what}: the pyramidal cone only")
662
+ from nablaengine.g1_engine import world_params as G
663
+ decl = MAT_DECL.replace("@OBJ@", str(int(objm))).replace("@TER@", str(int(term or sand)))
664
+ if sand:
665
+ from nablaengine.forest_engine import foot_offset as _fo
666
+ decl = _sub1(decl, "#define TER_MW 8\n", f"#define TER_MW {_fo.sand_words(cfg)} // (with the sand fields: "
667
+ "TerrainConfig.terrain_sand)\n", "TER_MW (terrain_sand)")
668
+ src = _sub1(src, _MAT_DECL_AT, decl + _MAT_DECL_AT, "forward (contact material)")
669
+ if not (objm or term):
670
+ return src
671
+ if src.count(_MAT_MU) != 2:
672
+ raise RuntimeError(f"forest terrain (contact material): contact friction sites {src.count(_MAT_MU)}, expected 2")
673
+ src = src.replace(_MAT_MU, _MAT_MU_NEW)
674
+ src = _sub1(src, decl, decl.replace(_EL_MU_AT, _EL_MU), "forward (contact material: el_mu)")
675
+ src = _sub1(src, _MAT_KB, _MAT_KB_NEW + _MAT_KB, "forward (contact material impedance)")
676
+ if G.DIRECT_SOLREF[0][0] in src:
677
+ src = _sub1(src, G.DIRECT_SOLREF[0][0], G.DIRECT_SOLREF[0][1], "kbimp (contact material)")
678
+ src = _sub1(src, _MAT_ADJ_MU, _MAT_ADJ_MU_NEW, "adjoint (contact material mu)")
679
+ if _MAT_ADJ_IMP_P in src:
680
+ src = _sub1(src, _MAT_ADJ_IMP_P, _MAT_ADJ_SEL + _MAT_ADJ_IMP_P, "adjoint (contact material impedance)")
681
+ else:
682
+ src = _sub1(src, _MAT_ADJ_IMP, " const float *sref = PSOLREF(pair), *simp = PSOLIMP(pair);\n" + _MAT_ADJ_SEL
683
+ + _MAT_ADJ_IMP_P, "adjoint (contact material impedance)")
684
+ pf = " if (PFOOT(pair) && zone) { // the foot pair's parameters (world_params)\n"
685
+ if pf in src:
686
+ src = _sub1(src, pf, pf.replace("zone) {", "zone && em_md != 2) {"), "adjoint (contact material, foot "
687
+ "parameters)")
688
+ src = _sub1(src, _MAT_PB, " if (PFOOT(pair) && zone && em_mu) pp[6] = 0.f; // (OBJ_MAT / TER_MAT)\n" + _MAT_PB,
689
+ "adjoint (contact material, foot friction)")
690
+ if not objm:
691
+ return src
692
+ head = "__device__ __forceinline__ float adj_contact_one(Adj& s, int c, int pair, int slot, unsigned zone,"
693
+ if "void contact_param_vjp(" not in src:
694
+ src = _sub1(src, head, G.PARTIALS_DEVICE.lstrip("\n") + head, "adjoint (object material partials)")
695
+ sig = " float* dbg"
696
+ i = src.index(head)
697
+ j = src.index(sig, i)
698
+ if j - i > 400:
699
+ raise RuntimeError("forest terrain (object material): adj_contact_one's dbg parameter")
700
+ src = src[:j] + sig + ", float* mg" + src[j + len(sig):]
701
+ src = _sub1(src, "adj_contact_one(s, c, pair, slot, zone, cw, dbg", "adj_contact_one(s, c, pair, slot, zone, cw, dbg, mg",
702
+ "adjoint (object material call)")
703
+ src = _sub1(src, _MAT_PB, _MAT_PARTIALS + _MAT_PB, "adjoint (object material partials)")
704
+ cw = " float cw[CS_N]; // the lane's contact (adj_contact_one), read by the body lanes by shuffles\n"
705
+ src = _sub1(src, cw, cw + " float mg[7] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; // (OBJ_MAT) its slot material's "
706
+ "partials\n", "adjoint (object material words)")
707
+ src = _sub1(src, " APROF(APROF_CONTACT_ROWS);\n", " APROF(APROF_CONTACT_ROWS);\n" + _MAT_REDUCE,
708
+ "adjoint (object material reduction)")
709
+ ub = " float qbar[NQ], vbar[NV], ubar[NU]; // cotangents of the substep's output, then of its input; ctrl (summed)\n"
710
+ src = _sub1(src, ub, ub + " float omg[OBJ_MW * TERRAIN_NOBJ]; // (forest_engine.terrain, OBJ_MAT) the slots' material "
711
+ "cotangents (summed)\n", "adjoint (object material state)")
712
+ z = " for (int i = lane; i < NU; i += 32) s.ubar[i] = 0.f;\n"
713
+ src = _sub1(src, z, z + " for (int i = lane; i < OBJ_MW * TERRAIN_NOBJ; i += 32) s.omg[i] = 0.f; // (OBJ_MAT)\n",
714
+ "adjoint (object material zero)")
715
+ return material_grad_out(src, terrain)
716
+
717
+
718
+ def material_grad_out(src, terrain):
719
+ """k_adjoint's gctrl rows with the slots' material cotangents last (after ctrl's, the parameters' and the motion
720
+ words')."""
721
+ vel = _cfg(terrain).object_velocity
722
+ pw = "NPARAM" in src and "gctrl[(size_t)w * (NU + NPARAM + 1" in src
723
+ x = "NU" + (" + NPARAM + 1" if pw else "") + (" + OBJ_VW * TERRAIN_NOBJ" if vel else "")
724
+ old = "gctrl[(size_t)w * NU + " if x == "NU" else f"gctrl[(size_t)w * ({x}) + "
725
+ new = f"gctrl[(size_t)w * ({x} + OBJ_MW * TERRAIN_NOBJ) + "
726
+ n = src.count(old)
727
+ if n < 1:
728
+ raise RuntimeError(f"forest terrain (object material): k_adjoint's gctrl rows not found ({old!r})")
729
+ src = src.replace(old, new)
730
+ a = " if (lane == 0) info[w] = s.flags;\n"
731
+ return _sub1(src, a, " __syncwarp();\n for (int i = lane; i < OBJ_MW * TERRAIN_NOBJ; i += 32) "
732
+ f"gctrl[(size_t)w * ({x} + OBJ_MW * TERRAIN_NOBJ) + {x} + i] = s.omg[i]; // (OBJ_MAT)\n" + a,
733
+ "adjoint (object material cotangents)")
734
+
735
+
736
+ def velocity_grad_out(src, terrain):
737
+ """k_adjoint's gctrl rows with the slots' motion cotangents last (TerrainConfig.object_velocity; on the final
738
+ text: after world_params' row width NU + NPARAM + 1); else unchanged."""
739
+ if terrain is None or not _cfg(terrain).object_velocity:
740
+ return src
741
+ a = " for (int i = lane; i < NU; i += 32) gctrl[(size_t)w * NU + i] = s.ubar[i];\n"
742
+ if a in src:
743
+ return _sub1(src, a, " for (int i = lane; i < NU; i += 32) gctrl[(size_t)w * (NU + OBJ_VW * TERRAIN_NOBJ) + i] = "
744
+ "s.ubar[i];\n __syncwarp();\n for (int i = lane; i < OBJ_VW * TERRAIN_NOBJ; i += 32) "
745
+ "gctrl[(size_t)w * (NU + OBJ_VW * TERRAIN_NOBJ) + NU + i] = s.ovbar[i]; // (OBJ_VEL)\n",
746
+ "adjoint (object velocity cotangents)")
747
+ p = "gctrl[(size_t)w * (NU + NPARAM + 1) + "
748
+ if src.count(p) != 2:
749
+ raise RuntimeError(f"forest terrain: k_adjoint's gctrl rows not found ({src.count(p)} parameter writes)")
750
+ src = src.replace(p, "gctrl[(size_t)w * (NU + NPARAM + 1 + OBJ_VW * TERRAIN_NOBJ) + ")
751
+ a = "NU + i] = s.gpw[i];\n"
752
+ return _sub1(src, a, a + " __syncwarp();\n for (int i = lane; i < OBJ_VW * TERRAIN_NOBJ; i += 32) gctrl[(size_t)w * "
753
+ "(NU + NPARAM + 1 + OBJ_VW * TERRAIN_NOBJ) + NU + NPARAM + 1 + i] = s.ovbar[i]; // (OBJ_VEL)\n",
754
+ "adjoint (object velocity cotangents)")
755
+
756
+
757
+ def _apply(src, hooks, what):
758
+ for a, b in hooks:
759
+ src = _sub1(src, a, b, what)
760
+ return src
761
+
762
+
763
+ def step_source(src, terrain, m=None):
764
+ """The forest's STEP_DEVICE + STEP_KERNEL (src) with the terrain's device code and hooks (m: the model, for box
765
+ robot geoms' CCD text, box_ccd_device)."""
766
+ dev = device_text(src)
767
+ if m is not None and has_box_geoms(m, terrain):
768
+ dev = box_ccd_device(m) + dev
769
+ if _cfg(terrain).object_velocity:
770
+ dev = dev + OBJ_VEL_SLOT
771
+ src = _apply(src, [(a, dev + a if b is None else b) for a, b in STEP_HOOKS], "forward")
772
+ if _cfg(terrain).object_velocity:
773
+ src = _apply(src, OBJ_VEL_FORWARD, "forward (object velocity)")
774
+ if _cfg(terrain).mode == "native":
775
+ src = _apply(src, STEP_NATIVE_HOOKS, "forward (native)")
776
+ if m is not None and step.has_defer(m):
777
+ src = _apply(src, DEFER_ENGINE_HOOKS, "forward (Hand)")
778
+ if m is not None and sorted_build(m):
779
+ src = _apply(src, SORT_ELEM_HOOKS, "forward (sort_contacts)")
780
+ if _cfg(terrain).mode == "native":
781
+ src = _apply(src, SORT_AUX_HOOKS, "forward (sort_contacts, native)")
782
+ return src
783
+
784
+
785
+ def sorted_build(m):
786
+ """Whether the forest build of m sorts its contacts by (pair, slot) after the collision (step.sort_contacts: the
787
+ split forward's deferred pairs, step.has_defer; the collision mid-phase, midphase.enabled)."""
788
+ from nablaengine.forest_engine import midphase
789
+ return step.has_defer(m) or midphase.enabled(m)
790
+
791
+
792
+ SORT_ELEM_HOOKS = (
793
+ (""" unsigned char sl[CPL];
794
+ float mu[CPL], ds[CPL], ps[CPL][3], fr[CPL][9];
795
+ """, """ unsigned char sl[CPL];
796
+ float mu[CPL], ds[CPL], ps[CPL][3], fr[CPL][9];
797
+ unsigned short el[CPL]; // (forest_engine.terrain: the terrain element)
798
+ """),
799
+ (""" pr[h] = s.con_pair[c]; sl[h] = s.con_slot[c]; dm[h] = s.con_dim[c]; mu[h] = s.con_mu[c]; ds[h] = s.con_dist[c];
800
+ """, """ pr[h] = s.con_pair[c]; sl[h] = s.con_slot[c]; dm[h] = s.con_dim[c]; mu[h] = s.con_mu[c]; ds[h] = s.con_dist[c];
801
+ el[h] = s.con_elem[c];
802
+ """),
803
+ (""" s.con_pair[r] = pr[h]; s.con_slot[r] = sl[h]; s.con_dim[r] = dm[h]; s.con_mu[r] = mu[h]; s.con_dist[r] = ds[h];
804
+ """, """ s.con_pair[r] = pr[h]; s.con_slot[r] = sl[h]; s.con_dim[r] = dm[h]; s.con_mu[r] = mu[h]; s.con_dist[r] = ds[h];
805
+ s.con_elem[r] = el[h];
806
+ """),
807
+ )
808
+ SORT_AUX_HOOKS = (
809
+ (""" unsigned short el[CPL]; // (forest_engine.terrain: the terrain element)
810
+ """, """ unsigned short el[CPL]; // (forest_engine.terrain: the terrain element)
811
+ unsigned ax[CPL]; // (the native candidate id)
812
+ """),
813
+ (""" el[h] = s.con_elem[c];
814
+ """, """ el[h] = s.con_elem[c];
815
+ ax[h] = s.con_aux[c];
816
+ """),
817
+ (""" s.con_elem[r] = el[h];
818
+ """, """ s.con_elem[r] = el[h];
819
+ s.con_aux[r] = ax[h];
820
+ """),
821
+ )
822
+
823
+ DEFER_ENGINE_HOOKS = (
824
+ (""" float gx[NGEOMC][3], gq[NGEOMC][4]; // k_pre_a's geom poses, for k_ccd
825
+ unsigned char con_slot[MAXCON];
826
+ """, """ float gx[NGEOMC][3], gq[NGEOMC][4]; // k_pre_a's geom poses, for k_ccd
827
+ unsigned char con_slot[MAXCON];
828
+ unsigned short con_elem[MAXCON]; // (forest_engine.terrain: the contacts' terrain elements)
829
+ #if TERRAIN_HF_NATIVE
830
+ unsigned con_aux[MAXCON];
831
+ #endif
832
+ """),
833
+ )
834
+ DEFER_HOST_HOOKS = (
835
+ (""" s.con_pair[c] = g.con_pair[c]; s.con_slot[c] = g.con_slot[c]; s.con_dim[c] = g.con_dim[c];
836
+ s.con_mu[c] = g.con_mu[c];
837
+ """, """ s.con_pair[c] = g.con_pair[c]; s.con_slot[c] = g.con_slot[c]; s.con_dim[c] = g.con_dim[c];
838
+ s.con_mu[c] = g.con_mu[c];
839
+ s.con_elem[c] = g.con_elem[c]; // (forest_engine.terrain)
840
+ #if TERRAIN_HF_NATIVE
841
+ s.con_aux[c] = g.con_aux[c];
842
+ #endif
843
+ """),
844
+ (""" g.con_pair[c] = s.con_pair[c]; g.con_slot[c] = s.con_slot[c]; g.con_dim[c] = s.con_dim[c];
845
+ g.con_mu[c] = s.con_mu[c];
846
+ """, """ g.con_pair[c] = s.con_pair[c]; g.con_slot[c] = s.con_slot[c]; g.con_dim[c] = s.con_dim[c];
847
+ g.con_mu[c] = s.con_mu[c];
848
+ g.con_elem[c] = s.con_elem[c]; // (forest_engine.terrain)
849
+ #if TERRAIN_HF_NATIVE
850
+ g.con_aux[c] = s.con_aux[c];
851
+ #endif
852
+ """),
853
+ (""" g.con_pair[c] = pair; g.con_slot[c] = (unsigned char)o.slot[j]; g.con_dim[c] = PDIM(pair);
854
+ """, """ g.con_pair[c] = pair; g.con_slot[c] = (unsigned char)o.slot[j]; g.con_dim[c] = PDIM(pair);
855
+ g.con_elem[c] = 0; // (forest_engine.terrain: a model pair)
856
+ #if TERRAIN_HF_NATIVE
857
+ g.con_aux[c] = 0u;
858
+ #endif
859
+ """),
860
+ )
861
+
862
+
863
+ _COM_LOAD = " if (lane < 3) s.com[lane] = com[(size_t)w * COM_WORDS + lane];\n"
864
+ _OBJ_PTR = (" dk_obj = com + (size_t)w * COM_WORDS + 3 + 7 * NFIX; // the world's object slots (terrain objects, "
865
+ "forest_engine.terrain)\n")
866
+ OBJECT_HOOKS = {"host": ((_COM_LOAD, _COM_LOAD + _OBJ_PTR, 3),),
867
+ "adjoint": ((_COM_LOAD, _COM_LOAD + _OBJ_PTR, 1),),
868
+ "kinematics": ()}
869
+
870
+
871
+ _CF_KSUB = " if (lane == 0) { // (contact_forces: the table carries the forces, oforce stays null)\n"
872
+
873
+
874
+ def object_hooks(src, hooks, terrain, m=None):
875
+ """src with OBJECT_HOOKS[hooks] (step.OBJECT_*_HOOKS) for a terrain build with object slots, else unchanged; m (the
876
+ model; hooks "host"): with deferred pairs (step.has_defer) also DEFER_HOST_HOOKS."""
877
+ if m is not None and hooks == "host" and step.has_defer(m):
878
+ src = _apply(src, DEFER_HOST_HOOKS, "host (deferred pairs)")
879
+ if not _cfg(terrain).objects:
880
+ return src
881
+ vel, mat = _cfg(terrain).object_velocity, getattr(_cfg(terrain), "object_material", False)
882
+ ptr = _OBJ_PTR + (" dk_objc = dk_obj; // (OBJ_VEL: obj_advance's source)\n" if vel else "")
883
+ if mat:
884
+ from nablaengine import terrain as T
885
+ off = (T.OBJ_WORDS + (T.OBJ_VEL_WORDS if vel else 0)) * int(_cfg(terrain).objects)
886
+ ptr += f" dk_omat = dk_obj + {off}; // the world's slot materials (forest_engine.terrain, OBJ_MAT)\n"
887
+ extra = {"host": OBJ_VEL_HOST, "adjoint": OBJ_VEL_ADJ_KERNEL, "kinematics": ()}[hooks] if vel else ()
888
+ for a, b, n in tuple((a, b.replace(_OBJ_PTR, ptr), n) for a, b, n in OBJECT_HOOKS[hooks]) + extra:
889
+ if src.count(a) == 0 and a == OBJ_VEL_HOST[0][0] and src.count(_CF_KSUB) == 1:
890
+ a, b = _CF_KSUB, b.replace(OBJ_VEL_HOST[0][0], _CF_KSUB)
891
+ if src.count(a) != n:
892
+ raise RuntimeError(f"forest object hook anchor found {src.count(a)} times, expected {n}: {a[:70]!r}")
893
+ src = src.replace(a, b)
894
+ return src
895
+
896
+
897
+ def _adj_hooks():
898
+ from nablaengine.dual import DUAL_DEVICE
899
+ from nablaengine.g1_engine import adjoint as g1_adj, adjoint_contact as g1_ac
900
+ return (
901
+ ("// adj_contact_geom for contact (pair, slot) of the engine's pair table",
902
+ DUAL_DEVICE + g1_adj.capbox_dual_source() + g1_adj.CBTER_DIR_VJP_TREE + g1_ac.TERRAIN_DEVICE.lstrip("\n")
903
+ + "\n// adj_contact_geom for contact (pair, slot) of the engine's pair table"),
904
+ (" if (!cot) return br;\n const float* pb = cot + 1;\n",
905
+ " if (!cot) return br;\n" + g1_adj.ADJ_CAPBOX_DUAL_TREE + " const float* pb = cot + 1;\n"),
906
+ (""" int g1 = PG1(pair), g2 = PG2(pair);
907
+ return adj_contact_geom(""",
908
+ """ if (pair >= NPAIR) // a terrain contact (forest_engine.terrain)
909
+ return adj_terrain_geom(slot, 0u, c_gtype[PG2(pair)], c_gsize + 3 * PG2(pair), gx[PG2(pair)], gq[PG2(pair)], dist,
910
+ pos, fr, nu, cot, gb);
911
+ int g1 = PG1(pair), g2 = PG2(pair);
912
+ return adj_contact_geom("""),
913
+ (""" unsigned con[MAXCON]; // the record's contact table: pair | slot << 16
914
+ """,
915
+ """ unsigned con[MAXCON]; // the record's contact table: pair | slot << 16
916
+ unsigned telem[(MAXCON + 1) / 2]; // the contacts' terrain elements, 16 bits each (terrain build)
917
+ """),
918
+ (""" for (int i = lane; i < MAXCON; i += 32) s.con[i] = __float_as_uint(__ldcs(rec + OFF_CON + i));
919
+ """,
920
+ """ for (int i = lane; i < MAXCON; i += 32) s.con[i] = __float_as_uint(__ldcs(rec + OFF_CON + i));
921
+ for (int i = lane; i < (MAXCON + 1) / 2; i += 32) s.telem[i] = __float_as_uint(__ldcs(rec + OFF_TELEM + i));
922
+ """),
923
+ (""" const int pair = e & 0xFFFFu, slot = e >> 16, dim = on ? PDIM(pair) : 0;""",
924
+ """ const unsigned x = on ? (s.telem[c >> 1] >> (16 * (c & 1))) & 0xFFFFu : 0u; // (terrain: the element)
925
+ const int pair = e & 0xFFFFu, slot = (int)(e >> 16 | x << 8), dim = on ? PDIM(pair) : 0;"""),
926
+ )
927
+
928
+
929
+ ADJ_NATIVE_HOOKS = (
930
+ (""" unsigned telem[(MAXCON + 1) / 2]; // the contacts' terrain elements, 16 bits each (terrain build)
931
+ """,
932
+ """ unsigned telem[(MAXCON + 1) / 2]; // the contacts' terrain elements, 16 bits each (terrain build)
933
+ unsigned taux[MAXCON]; // native heightfield contacts: the candidate ids
934
+ """),
935
+ (""" for (int i = lane; i < (MAXCON + 1) / 2; i += 32) s.telem[i] = __float_as_uint(__ldcs(rec + OFF_TELEM + i));
936
+ """,
937
+ """ for (int i = lane; i < (MAXCON + 1) / 2; i += 32) s.telem[i] = __float_as_uint(__ldcs(rec + OFF_TELEM + i));
938
+ for (int i = lane; i < MAXCON; i += 32) s.taux[i] = __float_as_uint(__ldcs(rec + OFF_TAUX + i));
939
+ """),
940
+ ("""// a geom's pose cotangent (xbar, tbar = gb + 6 j of adj_contact_geom) onto its body's:""",
941
+ """// adj_pair_geom with a terrain contact's candidate id
942
+ __device__ __forceinline__ int adj_pair_geom_aux(int pair, int slot, unsigned aux, const float (*gx)[3],
943
+ const float (*gq)[4], float* dist, float* pos, float* fr, float* nu,
944
+ const float* cot, float* gb) {
945
+ if (pair >= NPAIR)
946
+ return adj_terrain_geom(slot, aux, c_gtype[PG2(pair)], c_gsize + 3 * PG2(pair), gx[PG2(pair)], gq[PG2(pair)], dist,
947
+ pos, fr, nu, cot, gb);
948
+ return adj_pair_geom(pair, slot, gx, gq, dist, pos, fr, nu, cot, gb);
949
+ }
950
+
951
+ // a geom's pose cotangent (xbar, tbar = gb + 6 j of adj_contact_geom) onto its body's:"""),
952
+ ("""adj_pair_geom(pair, slot, s.gx, s.gq, &d, p, fr, &nu, nullptr, nullptr)""",
953
+ """adj_pair_geom_aux(pair, slot, s.taux[c], s.gx, s.gq, &d, p, fr, &nu, nullptr, nullptr)"""),
954
+ ("""adj_pair_geom(pair, slot, s.gx, s.gq, &d2, p2, fr2, &nu2, cot, gb)""",
955
+ """adj_pair_geom_aux(pair, slot, s.taux[c], s.gx, s.gq, &d2, p2, fr2, &nu2, cot, gb)"""),
956
+ )
957
+
958
+
959
+ def adjoint_source(src, terrain):
960
+ """The forest's contact adjoint (adjoint_contact.source(m) + ADJ_DEVICE + ADJ_KERNEL) with the terrain contacts and
961
+ the object pointer."""
962
+ src = _apply(src, _adj_hooks(), "adjoint")
963
+ if _cfg(terrain).object_velocity:
964
+ src = _apply(src, OBJ_VEL_ADJOINT + OBJ_VEL_GRAD, "adjoint (object velocity)")
965
+ if _cfg(terrain).mode == "native":
966
+ src = _apply(src, ADJ_NATIVE_HOOKS, "adjoint (native)")
967
+ return object_hooks(src, "adjoint", terrain)
968
+
969
+
970
+ def coop_dispatch(src):
971
+ """capbox_coop_hooks' dispatch for a terrain build: the terrain capsule-box contacts (g1_engine.model_hooks.
972
+ tree_coop_dispatch's terrain part: pair >= NPAIR, the capsule's 6 directions) and, if the model has its own
973
+ sphere-box / capsule-box pairs (forest_engine.model_hooks.CB_COOP_DISPATCH in src), theirs (pair < NPAIR, 12
974
+ directions) in one cb_coop_dir."""
975
+ from nablaengine.g1_engine import model_hooks as g1_hooks
976
+ from nablaengine.forest_engine import model_hooks as fh
977
+ ter = g1_hooks.tree_coop_dispatch(False, True)
978
+ if fh.CB_COOP_DISPATCH not in src:
979
+ return ter
980
+ sig = " const float* rec) {\n"
981
+ p0, p1 = "#define CB_COOP_PAIR(pair, slot) (", ") // (model_hooks.tree_coop_dispatch)\n"
982
+ head, tcond = ter[:ter.index(p0)], ter[ter.index(p0) + len(p0):ter.index(p1)]
983
+ tbody = ter[ter.index(sig) + len(sig):ter.rindex(" return 0.f;\n}\n")]
984
+ f = fh.CB_COOP_DISPATCH
985
+ f0, f1 = "#define CB_COOP_PAIR(pair, slot) ", "\n#define CB_COOP_WIDE"
986
+ fcond = f[len(f0):f.index(f1)]
987
+ fsig = "const float* rec) {\n"
988
+ fbody = f[f.index(fsig) + len(fsig):f.rindex("}\n")]
989
+ assert f.startswith(f0) and tbody.startswith(" if (pair >= NPAIR) {"), (f[:40], tbody[:40])
990
+ return (head + f"#define CB_COOP_PAIR(pair, slot) (((pair) < NPAIR && {fcond}) || {tcond}) "
991
+ "// (forest_engine.terrain.coop_dispatch)\n"
992
+ "#define CB_COOP_WIDE(pair, slot) ((pair) < NPAIR) // (the model's pairs: both geoms' 12 directions; "
993
+ "terrain: the capsule's 6)\n"
994
+ "// (forest_engine.terrain.coop_dispatch) direction j's gb[j] of contact (pair, slot), rec: cot[0..3], nbar\n"
995
+ "__device__ __forceinline__ float cb_coop_dir(const float (*gx)[3], const float (*gq)[4], int pair, int slot,"
996
+ " int j,\n" + sig + tbody + fbody + "}\n\n")
997
+
998
+
999
+ def coop_hooks(src):
1000
+ """The cooperative pass over the terrain capsule-box contacts' pose directions (DK_CAPBOX_COOP;
1001
+ g1_engine.model_hooks.capbox_coop_hooks with coop_dispatch), on the full text after model_hooks: the tree engine's
1002
+ cb_coop (g1_engine.model_hooks.TREE_COOP_DEV, tree_coop_dev: the batch's directions spread evenly over the warp,
1003
+ ceil(6 n / 32) dual replays for n terrain contacts, geom_to_body_vjp once per contact; each direction the same
1004
+ cb_coop_dir on the same inputs as the earlier packing CAPBOX_COOP_DEV, so the same gradients bit for bit). A model
1005
+ whose own pairs already have the pass (sphere-box / capsule-box pairs: forest_engine.model_hooks' capbox_coop_hooks
1006
+ with CAPBOX_COOP_DEV) gets its dispatch replaced by coop_dispatch's (both kinds in one cb_coop_dir) and its cb_coop
1007
+ by tree_coop_dev(True) (contacts with 12 directions); the forest's builds without terrain keep CAPBOX_COOP_DEV."""
1008
+ from nablaengine.g1_engine import model_hooks as g1_hooks
1009
+ from nablaengine.forest_engine import model_hooks as fh
1010
+ disp = coop_dispatch(src)
1011
+ if fh.CB_COOP_DISPATCH in src:
1012
+ for a, b in ((fh.CB_COOP_DISPATCH, disp), (g1_hooks.CAPBOX_COOP_DEV, g1_hooks.tree_coop_dev(True))):
1013
+ if src.count(a) != 1:
1014
+ raise RuntimeError(f"forest terrain coop: the model's pass found {src.count(a)} times: {a[:70]!r}")
1015
+ src = src.replace(a, b)
1016
+ return src
1017
+ if "CB_COOP_PAIR" in src:
1018
+ raise RuntimeError("forest terrain coop: a cooperative pass with an unknown dispatch")
1019
+ for a, b, n in g1_hooks.capbox_coop_hooks(disp, g1_hooks.tree_coop_dev(False)):
1020
+ if src.count(a) != n:
1021
+ raise RuntimeError(f"forest terrain coop hook anchor found {src.count(a)} times, expected {n}: {a[:70]!r}")
1022
+ src = src.replace(a, b)
1023
+ return src
1024
+
1025
+
1026
+ def box_ccd_device(m):
1027
+ """The forward's text for box robot geoms against terrain boxes (the tree engine's, model_hooks.box_box_hook):
1028
+ nablaengine.ccd's native box-box CCD (ccd_box_box; its CSink struct is the forest's, step.py) with its #defines
1029
+ (ccd.header) and boxes_separated (the separating-axis prefilter)."""
1030
+ import re as _re
1031
+ from nablaengine import ccd
1032
+ from nablaengine.g1_engine import model_hooks as g1_hooks
1033
+ dev, n = _re.subn(r"#define SINK_MAX 8\nstruct CSink \{.*?\};\n", "", ccd.DEVICE, count=1, flags=_re.S)
1034
+ if n != 1:
1035
+ raise RuntimeError("forest terrain: no CSink struct in nablaengine.ccd's text")
1036
+ wrap = g1_hooks.box_box_hook()[1][len(ccd.DEVICE):]
1037
+ sep = wrap[:wrap.index("template <class S>\n__device__ void box_box(")]
1038
+ assert "__device__ bool boxes_separated(" in sep
1039
+ return ("// box robot geoms against the terrain (forest_engine.terrain.box_ccd_device: nablaengine.ccd's box-box CCD, in\n"
1040
+ "// namespace tccd: its vector helpers are named as the forest's own)\n"
1041
+ + ccd.header(m) + "namespace tccd {\n" + dev + "} // namespace tccd\nusing tccd::ccd_box_box;\n" + sep)
1042
+
1043
+
1044
+ def box_geom_hooks(src, m, terrain):
1045
+ """Box robot geoms against the terrain (the tree engine's g1_engine.model_hooks.TERRAIN_BOX_GEOMS on the full text:
1046
+ against a terrain box or object slot MuJoCo Warp's native CCD, ccd_box_box, and its VJP ccd_box_box_vjp; against a
1047
+ heightfield the box's 8 corners as sample points), with ccd.ADJ_DEVICE before adj_contact_geom. Unchanged unless a
1048
+ box robot geom collides with the terrain."""
1049
+ if not has_box_geoms(m, terrain):
1050
+ return src
1051
+ from nablaengine import ccd
1052
+ from nablaengine.g1_engine import model_hooks as g1_hooks
1053
+ head = "__device__ __noinline__ int adj_contact_geom("
1054
+ adj = "namespace tccd {\n" + ccd.ADJ_DEVICE + "} // namespace tccd\nusing tccd::ccd_box_box_vjp;\n"
1055
+ for a, b, n in ((head, adj + head, 1),) + g1_hooks.TERRAIN_BOX_GEOMS:
1056
+ if src.count(a) != n:
1057
+ raise RuntimeError(f"forest terrain box hook anchor found {src.count(a)} times, expected {n}: {a[:70]!r}")
1058
+ src = src.replace(a, b)
1059
+ return src