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,630 @@
1
+ """The ray-casting library: CUDA source, build (nvcc, cached), and the scene data layout.
2
+
3
+ One thread per (world, ray). A ray is given in a per-world sensor frame (pos (B, 3), rot (B, 3, 3) row major): origin
4
+ pos + rot off, direction rot dir (dir unit, off / dir (N, 3)); it is cast against
5
+ terrain the static boxes and heightfields of a nablaengine.terrain.Terrain (pack(cell): its 2-D broad-phase grid),
6
+ walked cell by cell along the ray (2-D DDA), stopping at the first cell whose exit lies beyond the nearest
7
+ hit; heightfields by a DDA over their cells (two triangles per cell, MuJoCo Warp's ray_hfield split along
8
+ the (c, r)-(c+1, r+1) diagonal) plus their base box and side walls, as ray_hfield;
9
+ floor optionally the plane z = floor_z;
10
+ objects per-world boxes (B, K, 15: pos, rot row major, half sizes; half size 0 = absent);
11
+ robot triangle meshes, one per robot geom, each with a BVH (bvh.py), posed per world by its body's pose (xpos
12
+ (B, nbody, 3), xquat (B, nbody, 4)) and the geom's local pose; meshes of exclude_body are skipped (the
13
+ sensor's own body, as mjlab's RayCastSensor exclude_parent_body).
14
+ Output per ray: dist (the nearest hit's distance along the ray, -1 for none or beyond max_distance), id (int32: ID_*
15
+ category | index; -1 none) and the world normal. Ray-box and ray-triangle tests follow MuJoCo Warp's ray.py
16
+ (ray_box, _ray_triangle; github.com/google-deepmind/mujoco_warp, Apache License 2.0) for the terrain and objects; the
17
+ robot's triangles use the two-sided Moller-Trumbore test (MuJoCo's mju_rayMesh also tests every face from both sides)."""
18
+ import hashlib
19
+ import os
20
+ import subprocess
21
+ from pathlib import Path
22
+
23
+ ID_BOX, ID_HFIELD, ID_FLOOR, ID_OBJECT, ID_ROBOT = 0 << 24, 1 << 24, 2 << 24, 3 << 24, 4 << 24
24
+ ID_MASK = (1 << 24) - 1
25
+
26
+ SOURCE = r"""
27
+ #include <cuda_runtime.h>
28
+ #include <math.h>
29
+ #define TR_MINVAL 1e-15f
30
+ #define TR_INF 1e30f
31
+ #define ID_BOX 0
32
+ #define ID_HFIELD (1 << 24)
33
+ #define ID_FLOOR (2 << 24)
34
+ #define ID_OBJECT (3 << 24)
35
+ #define ID_ROBOT (4 << 24)
36
+ #define MP 12 // floats per (world, mesh geom) in mpose
37
+ #ifdef RAY_STATS // counters (debug): grid cells, box tests, heightfield calls, heightfield cells, rays
38
+ __device__ unsigned long long g_rstat[8];
39
+ #define RSTAT(k, n) atomicAdd(&g_rstat[k], (unsigned long long)(n))
40
+ #else
41
+ #define RSTAT(k, n) do {} while (0)
42
+ #endif
43
+ extern "C" int dk_rays_stats(unsigned long long* o, int reset) {
44
+ #ifdef RAY_STATS
45
+ cudaMemcpyFromSymbol(o, g_rstat, sizeof(g_rstat));
46
+ if (reset) { unsigned long long z[8] = {0}; cudaMemcpyToSymbol(g_rstat, z, sizeof(z)); }
47
+ return 0;
48
+ #else
49
+ (void)o; (void)reset;
50
+ return -1;
51
+ #endif
52
+ }
53
+ #ifndef RAY_BLOCK
54
+ #define RAY_BLOCK 128 // threads per block of the ray kernels
55
+ #endif
56
+ #ifndef STATIC_MINB
57
+ #define STATIC_MINB 1 // k_rays_static's __launch_bounds__ minimum blocks per SM (a register cap when > 1)
58
+ #endif
59
+ #ifndef ROBOT_MINB
60
+ #define ROBOT_MINB 1 // k_rays_robot's __launch_bounds__ minimum blocks per SM (a register cap when > 1)
61
+ #endif
62
+ #ifndef HF_PAD
63
+ #define HF_PAD 0 // heightfield cells tested around the DDA's: 0 the cell alone, 1 its 3 x 3 block
64
+ #endif
65
+
66
+ struct Scene {
67
+ // terrain (nablaengine.terrain.Terrain.pack): boxes (nbox, 15), heightfield headers (nhf, 16) / ints (nhf, 4) / data,
68
+ // grid [x0, y0, 1 / cell, nx, ny, nbox], cell_start (nx ny + 1), cell_items; grid null: no terrain
69
+ const float *box, *hfh, *hfd, *grid, *cellz; // cellz: the top of each grid cell's elements
70
+ const int *hfi, *cstart, *citems;
71
+ int has_floor;
72
+ float floor_z;
73
+ float zmax; // the terrain's highest point (cellz's maximum): the rays' parts above it skip the grid
74
+ // per-world objects (B, nobj, 15)
75
+ int nobj;
76
+ const float* obj;
77
+ // robot meshes: per mesh geom (body, local pos 3, local quat 4, bounding-sphere centre 3, radius) = 12 floats, its
78
+ // root node; BVH nodes: lo 3, hi 3 (float), ints (left, right) or (-(first tri) - 1, count); triangles 9 floats
79
+ int nmesh, nbody, exclude_body;
80
+ const float* mgeom;
81
+ const int* mroot;
82
+ const float* nodeb;
83
+ const int* nodei;
84
+ const float* tri;
85
+ const float *xpos, *xquat; // (B, nbody, 3 / 4)
86
+ float* mpose; // work: (B, nmesh, MP) each mesh geom's world position, quaternion, its bounding sphere's centre
87
+ // from the sensor origin and the cosine of its angular radius from there (k_mesh_cull)
88
+ unsigned* mmask; // work: (B, 2) the mesh geoms that can meet the sensor's ray cone (bit g)
89
+ };
90
+
91
+ __device__ __forceinline__ float dot3(const float* a, const float* b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; }
92
+ __device__ __forceinline__ void cross(const float* a, const float* b, float* o) {
93
+ o[0] = a[1] * b[2] - a[2] * b[1]; o[1] = a[2] * b[0] - a[0] * b[2]; o[2] = a[0] * b[1] - a[1] * b[0];
94
+ }
95
+ __device__ __forceinline__ void mv3(const float* A, const float* v, float* o) {
96
+ for (int i = 0; i < 3; i++) o[i] = A[3 * i] * v[0] + A[3 * i + 1] * v[1] + A[3 * i + 2] * v[2];
97
+ }
98
+ __device__ __forceinline__ void mtv3(const float* A, const float* v, float* o) {
99
+ for (int i = 0; i < 3; i++) o[i] = A[i] * v[0] + A[3 + i] * v[1] + A[6 + i] * v[2];
100
+ }
101
+ __device__ __forceinline__ void qrot(const float* q, const float* v, float* o) { // o = q v q^-1
102
+ float u[3] = {q[1], q[2], q[3]}, t[3], c[3];
103
+ cross(u, v, t);
104
+ for (int k = 0; k < 3; k++) t[k] *= 2.f;
105
+ cross(u, t, c);
106
+ for (int k = 0; k < 3; k++) o[k] = v[k] + q[0] * t[k] + c[k];
107
+ }
108
+ __device__ __forceinline__ void qrot_inv(const float* q, const float* v, float* o) {
109
+ const float qc[4] = {q[0], -q[1], -q[2], -q[3]};
110
+ qrot(qc, v, o);
111
+ }
112
+ __device__ __forceinline__ void qmul(const float* a, const float* b, float* o) {
113
+ o[0] = a[0] * b[0] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3];
114
+ o[1] = a[0] * b[1] + a[1] * b[0] + a[2] * b[3] - a[3] * b[2];
115
+ o[2] = a[0] * b[2] - a[1] * b[3] + a[2] * b[0] + a[3] * b[1];
116
+ o[3] = a[0] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[0];
117
+ }
118
+ __device__ __forceinline__ float tr_div(float x, float y) { return x / (y != 0.f ? y : TR_MINVAL); }
119
+
120
+ __device__ __forceinline__ float tr_quad(float a, float b, float c) {
121
+ float det = b * b - a * c;
122
+ if (det < TR_MINVAL) return -1.f;
123
+ det = sqrtf(det);
124
+ const float den = tr_div(1.f, a), x0 = (-b - det) * den, x1 = (-b + det) * den;
125
+ return x0 >= 0.f ? x0 : (x1 >= 0.f ? x1 : -1.f);
126
+ }
127
+
128
+ // ray_box (MuJoCo Warp): all[6] per side solutions (or -1), nrm world
129
+ __device__ float tr_box(const float* pos, const float* R, const float* sz, const float* pnt, const float* vec, float* all,
130
+ float* nrm) {
131
+ for (int i = 0; i < 6; i++) all[i] = -1.f;
132
+ for (int k = 0; k < 3; k++) nrm[k] = 0.f;
133
+ float dif[3] = {pnt[0] - pos[0], pnt[1] - pos[1], pnt[2] - pos[2]};
134
+ if (tr_quad(dot3(vec, vec), dot3(vec, dif), dot3(dif, dif) - dot3(sz, sz)) < 0.f) return -1.f;
135
+ float lp[3], lv[3];
136
+ mtv3(R, dif, lp);
137
+ mtv3(R, vec, lv);
138
+ float x = -1.f;
139
+ int fa = -1, fs = -1;
140
+ for (int i = 0; i < 3; i++) {
141
+ if (!(fabsf(lv[i]) > TR_MINVAL)) continue;
142
+ for (int side = -1; side < 2; side += 2) {
143
+ const float sol = (float(side) * sz[i] - lp[i]) / lv[i];
144
+ if (sol >= 0.f) {
145
+ const int i0 = i == 0 ? 1 : 0, i1 = i == 2 ? 1 : 2;
146
+ const float p0 = lp[i0] + sol * lv[i0], p1 = lp[i1] + sol * lv[i1];
147
+ if (fabsf(p0) <= sz[i0] && fabsf(p1) <= sz[i1]) {
148
+ if (x < 0.f || sol < x) { x = sol; fa = i; fs = side; }
149
+ all[2 * i + (side + 1) / 2] = sol;
150
+ }
151
+ }
152
+ }
153
+ }
154
+ if (x >= 0.f) {
155
+ float nl[3] = {0.f, 0.f, 0.f};
156
+ nl[fa] = float(fs);
157
+ mv3(R, nl, nrm);
158
+ }
159
+ return x;
160
+ }
161
+
162
+ // _ray_triangle (MuJoCo Warp; local frame; b0, b1: the orthogonal basis of the ray direction)
163
+ __device__ float tr_tri(const float* v0, const float* v1, const float* v2, const float* pnt, const float* vec,
164
+ const float* b0, const float* b1, float* nrm) {
165
+ float d0[3], d1[3], d2[3];
166
+ for (int k = 0; k < 3; k++) { d0[k] = v0[k] - pnt[k]; d1[k] = v1[k] - pnt[k]; d2[k] = v2[k] - pnt[k]; }
167
+ const float p00 = dot3(d0, b0), p01 = dot3(d0, b1), p10 = dot3(d1, b0), p11 = dot3(d1, b1), p20 = dot3(d2, b0),
168
+ p21 = dot3(d2, b1);
169
+ if ((p00 > 0.f && p10 > 0.f && p20 > 0.f) || (p00 < 0.f && p10 < 0.f && p20 < 0.f) ||
170
+ (p01 > 0.f && p11 > 0.f && p21 > 0.f) || (p01 < 0.f && p11 < 0.f && p21 < 0.f))
171
+ return -1.f;
172
+ const float A00 = p00 - p20, A10 = p10 - p20, A01 = p01 - p21, A11 = p11 - p21, bb0 = -p20, bb1 = -p21;
173
+ const float det = A00 * A11 - A10 * A01;
174
+ if (fabsf(det) < TR_MINVAL) return -1.f;
175
+ const float t0 = (A11 * bb0 - A10 * bb1) / det, t1 = (-A01 * bb0 + A00 * bb1) / det;
176
+ if (t0 < 0.f || t1 < 0.f || t0 + t1 > 1.f) return -1.f;
177
+ float e0[3], e1[3], e2[3], n[3];
178
+ for (int k = 0; k < 3; k++) { e0[k] = v0[k] - v2[k]; e1[k] = v1[k] - v2[k]; e2[k] = pnt[k] - v2[k]; }
179
+ cross(e0, e1, n);
180
+ const float den = dot3(vec, n);
181
+ if (fabsf(den) < TR_MINVAL) return -1.f;
182
+ const float dist = -dot3(e2, n) / den, il = rsqrtf(dot3(n, n));
183
+ for (int k = 0; k < 3; k++) nrm[k] = n[k] * il;
184
+ return dist >= 0.f ? dist : -1.f;
185
+ }
186
+
187
+ // ray_hfield with a DDA over the heightfield's cells: the base box, the top box, the triangles of the cells the ray
188
+ // crosses inside the top box (in ray order, stopping after the first cell with a hit within it), the side walls
189
+ #ifndef HF_NOINLINE
190
+ #define HF_NOINLINE 0
191
+ #endif
192
+ #if HF_NOINLINE
193
+ __device__ __noinline__
194
+ #else
195
+ __device__
196
+ #endif
197
+ float tr_hfield(const Scene& S, int j, const float* pnt, const float* vec, float* nrm) {
198
+ const float* hh = S.hfh + 16 * j;
199
+ const int* hi = S.hfi + 4 * j;
200
+ const float *pos = hh, *R = hh + 3, *size = hh + 12, *hd = S.hfd + hi[2];
201
+ const int nrow = hi[0], ncol = hi[1];
202
+ const float col[3] = {R[2], R[5], R[8]};
203
+ const float bs = size[3] * 0.5f, ts = size[2] * 0.5f;
204
+ float bsz[3] = {size[0], size[1], bs}, tsz[3] = {size[0], size[1], ts}, bpos[3], tpos[3], allb[6], all[6], nb[3],
205
+ nt[3];
206
+ for (int k = 0; k < 3; k++) { bpos[k] = pos[k] - col[k] * bs; tpos[k] = pos[k] + col[k] * ts; }
207
+ float x = tr_box(bpos, R, bsz, pnt, vec, allb, nb);
208
+ const float top = tr_box(tpos, R, tsz, pnt, vec, all, nt);
209
+ if (top < 0.f) { for (int k = 0; k < 3; k++) nrm[k] = nb[k]; return x; }
210
+ float dif[3] = {pnt[0] - pos[0], pnt[1] - pos[1], pnt[2] - pos[2]}, lp[3], lv[3];
211
+ mtv3(R, dif, lp);
212
+ mtv3(R, vec, lv);
213
+ const float sg = lv[2] >= 0.f ? 1.f : -1.f, a = -1.f / (sg + lv[2]), b = lv[0] * lv[1] * a;
214
+ const float b0[3] = {1.f + sg * lv[0] * lv[0] * a, sg * b, -sg * lv[0]}, b1[3] = {b, sg + lv[1] * lv[1] * a, -lv[1]};
215
+ float s0 = 0.f, s1 = top;
216
+ for (int i = 0; i < 6; i++)
217
+ if (all[i] > s1) { s0 = top; s1 = all[i]; }
218
+ const float dx = tr_div(2.f * size[0], float(ncol - 1)), dy = tr_div(2.f * size[1], float(nrow - 1));
219
+ float nl[3] = {0.f, 0.f, 0.f};
220
+ if (x >= 0.f) mtv3(R, nb, nl);
221
+ { // DDA from s0 to s1 in cell coordinates u = (lp + s lv + size) / d
222
+ const float ux = tr_div(lp[0] + s0 * lv[0] + size[0], dx), uy = tr_div(lp[1] + s0 * lv[1] + size[1], dy);
223
+ int c = min(max(int(floorf(ux)), 0), ncol - 2), r = min(max(int(floorf(uy)), 0), nrow - 2);
224
+ const float gx = tr_div(lv[0], dx), gy = tr_div(lv[1], dy); // cell units per unit s
225
+ const int stx = gx > 0.f ? 1 : -1, sty = gy > 0.f ? 1 : -1;
226
+ const float tdx = fabsf(gx) > TR_MINVAL ? 1.f / fabsf(gx) : TR_INF, tdy = fabsf(gy) > TR_MINVAL ? 1.f / fabsf(gy) : TR_INF;
227
+ float tnx = fabsf(gx) > TR_MINVAL ? s0 + ((gx > 0.f ? float(c + 1) : float(c)) - ux) / gx : TR_INF;
228
+ float tny = fabsf(gy) > TR_MINVAL ? s0 + ((gy > 0.f ? float(r + 1) : float(r)) - uy) / gy : TR_INF;
229
+ for (int it = 0; it < ncol + nrow + 4; it++) {
230
+ // this cell, and (HF_PAD 1) its 8 neighbours as MuJoCo Warp's 1-cell pad against rounding at the cell borders
231
+ float best = -1.f, bn[3];
232
+ for (int rr = max(r - HF_PAD, 0); rr <= min(r + HF_PAD, nrow - 2); rr++)
233
+ for (int cc = max(c - HF_PAD, 0); cc <= min(c + HF_PAD, ncol - 2); cc++) {
234
+ const float x0 = dx * float(cc) - size[0], x1 = dx * float(cc + 1) - size[0];
235
+ const float y0 = dy * float(rr) - size[1], y1 = dy * float(rr + 1) - size[1];
236
+ const float h00 = hd[rr * ncol + cc] * size[2], h10 = hd[rr * ncol + cc + 1] * size[2];
237
+ const float h11 = hd[(rr + 1) * ncol + cc + 1] * size[2], h01 = hd[(rr + 1) * ncol + cc] * size[2];
238
+ const float va[3] = {x0, y0, h00}, vb[3] = {x1, y0, h10}, vc[3] = {x1, y1, h11}, vd[3] = {x0, y1, h01};
239
+ float nt2[3];
240
+ float sol = tr_tri(va, vb, vc, lp, lv, b0, b1, nt2);
241
+ if (sol >= 0.f && (best < 0.f || sol < best)) { best = sol; for (int k = 0; k < 3; k++) bn[k] = nt2[k]; }
242
+ sol = tr_tri(va, vc, vd, lp, lv, b0, b1, nt2);
243
+ if (sol >= 0.f && (best < 0.f || sol < best)) { best = sol; for (int k = 0; k < 3; k++) bn[k] = nt2[k]; }
244
+ }
245
+ RSTAT(3, 1);
246
+ if (best >= 0.f && (x < 0.f || best < x)) { x = best; for (int k = 0; k < 3; k++) nl[k] = bn[k]; }
247
+ const float texit = fminf(tnx, tny);
248
+ if (x >= 0.f && x <= texit) break; // the hits of later cells lie beyond this cell's exit
249
+ if (texit > s1) break;
250
+ if (tnx < tny) { c += stx; tnx += tdx; } else { r += sty; tny += tdy; }
251
+ if (c < 0 || c > ncol - 2 || r < 0 || r > nrow - 2) break;
252
+ }
253
+ }
254
+ for (int i = 0; i < 4; i++) {
255
+ if (!(all[i] >= 0.f && (all[i] < x || x < 0.f))) continue;
256
+ const float z = tr_div(lp[2] + all[i] * lv[2], size[2]);
257
+ float y, y0, z0, z1;
258
+ if (i < 2) {
259
+ y = tr_div(lp[1] + all[i] * lv[1] + size[1], dy);
260
+ y0 = fmaxf(0.f, fminf(float(nrow - 2), floorf(y)));
261
+ const int k0 = int(rintf(y0)), k1 = int(rintf(y0 + 1.f));
262
+ z0 = i == 1 ? hd[k0 * ncol + ncol - 1] : hd[k0 * ncol];
263
+ z1 = i == 1 ? hd[k1 * ncol + ncol - 1] : hd[k1 * ncol];
264
+ } else {
265
+ y = tr_div(lp[0] + all[i] * lv[0] + size[0], dx);
266
+ y0 = fmaxf(0.f, fminf(float(ncol - 2), floorf(y)));
267
+ const int k0 = int(rintf(y0)), k1 = int(rintf(y0 + 1.f));
268
+ z0 = i == 3 ? hd[k0 + (nrow - 1) * ncol] : hd[k0];
269
+ z1 = i == 3 ? hd[k1 + (nrow - 1) * ncol] : hd[k1];
270
+ }
271
+ if (z < z0 * (y0 + 1.f - y) + z1 * (y - y0)) {
272
+ x = all[i];
273
+ nl[0] = float(i == 1) - float(i == 0); nl[1] = float(i == 3) - float(i == 2); nl[2] = 0.f;
274
+ }
275
+ }
276
+ if (x >= 0.f) mv3(R, nl, nrm);
277
+ else for (int k = 0; k < 3; k++) nrm[k] = 0.f;
278
+ return x;
279
+ }
280
+
281
+ __device__ __forceinline__ void take(float d, int id, const float* n, float* best, int* bid, float* bn) {
282
+ if (d >= 0.f && (*best < 0.f || d < *best)) { *best = d; *bid = id; for (int k = 0; k < 3; k++) bn[k] = n[k]; }
283
+ }
284
+
285
+ // the terrain along the ray (2-D DDA over the broad-phase grid; up to maxd)
286
+ __device__ void cast_terrain(const Scene& S, const float* p, const float* v, float maxd, float* best, int* bid,
287
+ float* bn) {
288
+ const float x0 = S.grid[0], y0 = S.grid[1], ic = S.grid[2];
289
+ const int nx = int(S.grid[3]), ny = int(S.grid[4]), nbox = int(S.grid[5]);
290
+ // the ray's part over the grid rectangle
291
+ float t0 = 0.f, t1 = maxd;
292
+ const float lo[2] = {x0, y0}, hi[2] = {x0 + nx / ic, y0 + ny / ic};
293
+ for (int k = 0; k < 2; k++) {
294
+ if (fabsf(v[k]) < TR_MINVAL) { if (p[k] < lo[k] || p[k] > hi[k]) return; continue; }
295
+ float a = (lo[k] - p[k]) / v[k], b = (hi[k] - p[k]) / v[k];
296
+ if (a > b) { const float t = a; a = b; b = t; }
297
+ t0 = fmaxf(t0, a); t1 = fminf(t1, b);
298
+ }
299
+ // and below the terrain's top
300
+ if (v[2] < -TR_MINVAL) t0 = fmaxf(t0, (p[2] - S.zmax) / -v[2]);
301
+ else if (p[2] > S.zmax) return;
302
+ else if (v[2] > TR_MINVAL) t1 = fminf(t1, (S.zmax - p[2]) / v[2]);
303
+ if (t0 > t1) return;
304
+ const float ux = (p[0] + t0 * v[0] - x0) * ic, uy = (p[1] + t0 * v[1] - y0) * ic;
305
+ int c = min(max(int(floorf(ux)), 0), nx - 1), r = min(max(int(floorf(uy)), 0), ny - 1);
306
+ const float gx = v[0] * ic, gy = v[1] * ic;
307
+ const int stx = gx > 0.f ? 1 : -1, sty = gy > 0.f ? 1 : -1;
308
+ const float tdx = fabsf(gx) > TR_MINVAL ? 1.f / fabsf(gx) : TR_INF, tdy = fabsf(gy) > TR_MINVAL ? 1.f / fabsf(gy) : TR_INF;
309
+ float tnx = fabsf(gx) > TR_MINVAL ? t0 + ((gx > 0.f ? float(c + 1) : float(c)) - ux) / gx : TR_INF;
310
+ float tny = fabsf(gy) > TR_MINVAL ? t0 + ((gy > 0.f ? float(r + 1) : float(r)) - uy) / gy : TR_INF;
311
+ float tin = t0;
312
+ int seen[4] = {-1, -1, -1, -1}, nseen = 0; // heightfields already cast (each in many cells: once per ray)
313
+ for (int it = 0; it < nx + ny + 2; it++) {
314
+ const float texit0 = fminf(fminf(tnx, tny), t1);
315
+ // the cell's elements unless the ray stays above their top over the cell
316
+ const bool above = fminf(p[2] + tin * v[2], p[2] + texit0 * v[2]) > S.cellz[r * nx + c];
317
+ RSTAT(0, 1);
318
+ if (!above)
319
+ for (int k = S.cstart[r * nx + c]; k < S.cstart[r * nx + c + 1]; k++) {
320
+ const int e = S.citems[k];
321
+ float all[6], nn[3], d;
322
+ if (e < nbox) { RSTAT(1, 1); const float* b = S.box + 15 * e; d = tr_box(b, b + 3, b + 12, p, v, all, nn); take(d, ID_BOX + e, nn, best, bid, bn); }
323
+ else {
324
+ const int j = e - nbox;
325
+ if (j == seen[0] || j == seen[1] || j == seen[2] || j == seen[3]) continue;
326
+ seen[nseen & 3] = j;
327
+ nseen++;
328
+ RSTAT(2, 1);
329
+ d = tr_hfield(S, j, p, v, nn);
330
+ take(d, ID_HFIELD + j, nn, best, bid, bn);
331
+ }
332
+ }
333
+ const float texit = fminf(tnx, tny);
334
+ if (*best >= 0.f && *best <= texit) return;
335
+ if (texit > t1) return;
336
+ tin = texit;
337
+ if (tnx < tny) { c += stx; tnx += tdx; } else { r += sty; tny += tdy; }
338
+ if (c < 0 || c >= nx || r < 0 || r >= ny) return;
339
+ }
340
+ }
341
+
342
+ // per (world, mesh geom): its world pose into mpose, and whether its bounding sphere meets the sensor's ray cone
343
+ // (apex pos, axis R e_x, half angle with cos ch / sin sh, length maxd) into mmask
344
+ // offmax: the largest ray offset from the sensor origin (the angular test's sphere is inflated by it)
345
+ __global__ void k_mesh_cull(Scene S, int B, const float* pos, const float* rot, float ch, float sh, float maxd,
346
+ float offmax) {
347
+ const int tid = blockIdx.x * blockDim.x + threadIdx.x;
348
+ if (tid >= B * S.nmesh) return;
349
+ const int w = tid / S.nmesh, g = tid % S.nmesh;
350
+ const float* mg = S.mgeom + 12 * g;
351
+ const int body = int(mg[0]);
352
+ const float* bx = S.xpos + ((size_t)w * S.nbody + body) * 3;
353
+ const float* bq = S.xquat + ((size_t)w * S.nbody + body) * 4;
354
+ float gq[4], gp[3], t[3], c[3];
355
+ qmul(bq, mg + 4, gq);
356
+ qrot(bq, mg + 1, t);
357
+ for (int k = 0; k < 3; k++) gp[k] = bx[k] + t[k];
358
+ float* o = S.mpose + (size_t)tid * MP;
359
+ for (int k = 0; k < 3; k++) o[k] = gp[k];
360
+ for (int k = 0; k < 4; k++) o[3 + k] = gq[k];
361
+ qrot(gq, mg + 8, t);
362
+ for (int k = 0; k < 3; k++) c[k] = gp[k] + t[k] - pos[3 * w + k]; // the sphere centre from the apex
363
+ { // the angular test of the rays: a unit direction v can meet the (inflated) sphere only if v . c >= cos |c|
364
+ const float ri = mg[11] + offmax, dc = sqrtf(dot3(c, c));
365
+ for (int k = 0; k < 3; k++) o[8 + k] = c[k];
366
+ o[11] = dc > ri ? sqrtf(fmaxf(dc * dc - ri * ri, 0.f)) / dc : -2.f; // cos of the angular radius; inside: always
367
+ }
368
+ const float ax[3] = {rot[9 * w], rot[9 * w + 3], rot[9 * w + 6]}, rad = mg[11];
369
+ const float along = dot3(c, ax), d2 = dot3(c, c), perp = sqrtf(fmaxf(d2 - along * along, 0.f));
370
+ // sphere vs cone: the distance from the centre to the cone surface (Eberly) below the radius, or the centre inside
371
+ bool keep = d2 <= rad * rad || (along * ch + perp * sh >= -rad && perp * ch - along * sh <= rad);
372
+ keep = keep && along <= maxd + rad && sqrtf(d2) <= maxd + rad;
373
+ if (dot3(c, c) > (maxd + rad) * (maxd + rad)) keep = false;
374
+ if (body == S.exclude_body) keep = false;
375
+ if (keep) atomicOr(S.mmask + 2 * w + (g >> 5), 1u << (g & 31));
376
+ }
377
+
378
+ // the robot's mesh geoms that can meet the ray cone (mmask), each in its frame (mpose), their BVH (two-sided
379
+ // Moller-Trumbore), nearest child first
380
+ __device__ void cast_robot(const Scene& S, int w, const float* p, const float* v, float* best, int* bid, float* bn) {
381
+ for (int h = 0; h < 2; h++) {
382
+ unsigned bits = S.mmask[2 * w + h];
383
+ while (bits) {
384
+ const int g = 32 * h + __ffs(bits) - 1;
385
+ bits &= bits - 1u;
386
+ const float* mg = S.mgeom + 12 * g;
387
+ const float* mp = S.mpose + ((size_t)w * S.nmesh + g) * MP;
388
+ { // the angular test (k_mesh_cull): the direction against the sphere's cone from the sensor origin
389
+ const float vc = v[0] * mp[8] + v[1] * mp[9] + v[2] * mp[10];
390
+ const float cc = sqrtf(mp[8] * mp[8] + mp[9] * mp[9] + mp[10] * mp[10]);
391
+ if (vc < mp[11] * cc) continue;
392
+ }
393
+ const float gq[4] = {mp[3], mp[4], mp[5], mp[6]};
394
+ float dif[3] = {p[0] - mp[0], p[1] - mp[1], p[2] - mp[2]}, lp[3], lv[3];
395
+ qrot_inv(gq, dif, lp);
396
+ qrot_inv(gq, v, lv);
397
+ { // bounding sphere (centre mg[8..10], radius mg[11], mesh frame)
398
+ float dc[3] = {lp[0] - mg[8], lp[1] - mg[9], lp[2] - mg[10]};
399
+ const float bb = dot3(dc, lv), cc = dot3(dc, dc) - mg[11] * mg[11];
400
+ if (cc > 0.f && (bb > 0.f || bb * bb - cc < 0.f)) continue;
401
+ const float tnear = -bb - sqrtf(fmaxf(bb * bb - cc, 0.f));
402
+ if (*best >= 0.f && tnear > *best) continue;
403
+ }
404
+ const float iv[3] = {1.f / lv[0], 1.f / lv[1], 1.f / lv[2]};
405
+ int stack[32], sp = 0; // (median-split BVH depth: about log2(triangles / LEAF) + 1 < 20)
406
+ stack[sp++] = S.mroot[g];
407
+ float hit = -1.f, hn[3] = {0.f, 0.f, 0.f};
408
+ while (sp) {
409
+ const int nd = stack[--sp];
410
+ const float* nb = S.nodeb + 6 * nd;
411
+ float tmin = 0.f, tmax = *best >= 0.f ? *best : TR_INF;
412
+ if (hit >= 0.f) tmax = fminf(tmax, hit);
413
+ for (int k = 0; k < 3; k++) {
414
+ float a = (nb[k] - lp[k]) * iv[k], b = (nb[3 + k] - lp[k]) * iv[k];
415
+ if (a > b) { const float t = a; a = b; b = t; }
416
+ tmin = fmaxf(tmin, a); tmax = fminf(tmax, b);
417
+ }
418
+ if (tmin > tmax) continue;
419
+ const int l = S.nodei[2 * nd], rr = S.nodei[2 * nd + 1];
420
+ if (l >= 0) { // push the farther child first (by the children's box centres along the ray)
421
+ const float *bl = S.nodeb + 6 * l, *br = S.nodeb + 6 * rr;
422
+ float dl = 0.f, dr = 0.f;
423
+ for (int k = 0; k < 3; k++) { dl += (bl[k] + bl[3 + k]) * lv[k]; dr += (br[k] + br[3 + k]) * lv[k]; }
424
+ if (sp + 2 <= 32) {
425
+ if (dl <= dr) { stack[sp++] = rr; stack[sp++] = l; } else { stack[sp++] = l; stack[sp++] = rr; }
426
+ }
427
+ continue;
428
+ }
429
+ for (int i = -l - 1, e = -l - 1 + rr; i < e; i++) {
430
+ const float* T = S.tri + 9 * i;
431
+ float e1[3], e2[3], pv[3], tv[3], qv[3];
432
+ for (int k = 0; k < 3; k++) { e1[k] = T[3 + k] - T[k]; e2[k] = T[6 + k] - T[k]; }
433
+ cross(lv, e2, pv);
434
+ const float det = dot3(e1, pv);
435
+ if (fabsf(det) < 1e-12f) continue;
436
+ const float id = 1.f / det;
437
+ for (int k = 0; k < 3; k++) tv[k] = lp[k] - T[k];
438
+ const float u = dot3(tv, pv) * id;
439
+ if (u < 0.f || u > 1.f) continue;
440
+ cross(tv, e1, qv);
441
+ const float vv = dot3(lv, qv) * id;
442
+ if (vv < 0.f || u + vv > 1.f) continue;
443
+ const float tt = dot3(e2, qv) * id;
444
+ if (tt >= 0.f && (hit < 0.f || tt < hit) && (*best < 0.f || tt < *best)) { hit = tt; cross(e1, e2, hn); }
445
+ }
446
+ }
447
+ if (hit >= 0.f) {
448
+ float nw[3];
449
+ qrot(gq, hn, nw);
450
+ const float il = rsqrtf(fmaxf(dot3(nw, nw), 1e-30f)), sgn = dot3(nw, v) > 0.f ? -1.f : 1.f;
451
+ for (int k = 0; k < 3; k++) nw[k] *= il * sgn;
452
+ take(hit, ID_ROBOT + g, nw, best, bid, bn);
453
+ }
454
+ }
455
+ }
456
+ }
457
+
458
+ __device__ __forceinline__ void world_ray(int w, int n, const float* pos, const float* rot, const float* off,
459
+ const float* dir, float* p, float* v) {
460
+ const float *P = pos + 3 * w, *R = rot + 9 * w;
461
+ float t[3];
462
+ mv3(R, off + 3 * n, t);
463
+ for (int k = 0; k < 3; k++) p[k] = P[k] + t[k];
464
+ mv3(R, dir + 3 * n, v);
465
+ }
466
+
467
+ // pass 1: the terrain, the floor and the objects (dist -1 for none or beyond maxd)
468
+ __global__ void __launch_bounds__(RAY_BLOCK, STATIC_MINB) k_rays_static(Scene S, int B, int N, const float* pos, const float* rot, const float* off,
469
+ const float* dir, float maxd, float* dist, int* oid, float* onrm, int dpw) {
470
+ const long long tid = (long long)blockIdx.x * blockDim.x + threadIdx.x;
471
+ if (tid >= (long long)B * N) return;
472
+ const int w = int(tid / N), n = int(tid % N);
473
+ if (dpw) { off += (size_t)w * N * 3; dir += (size_t)w * N * 3; } // per-world rays (B, N, 3)
474
+ float p[3], v[3];
475
+ world_ray(w, n, pos, rot, off, dir, p, v);
476
+ float best = -1.f, bn[3] = {0.f, 0.f, 0.f};
477
+ int bid = -1;
478
+ RSTAT(4, 1);
479
+ if (S.grid) cast_terrain(S, p, v, maxd, &best, &bid, bn);
480
+ if (S.has_floor && fabsf(v[2]) > TR_MINVAL) {
481
+ const float d = (S.floor_z - p[2]) / v[2], nf[3] = {0.f, 0.f, 1.f};
482
+ take(d, ID_FLOOR, nf, &best, &bid, bn);
483
+ }
484
+ for (int k = 0; k < S.nobj; k++) {
485
+ const float* b = S.obj + ((size_t)w * S.nobj + k) * 15;
486
+ if (!(b[12] > 0.f)) continue;
487
+ float all[6], nn[3];
488
+ take(tr_box(b, b + 3, b + 12, p, v, all, nn), ID_OBJECT + k, nn, &best, &bid, bn);
489
+ }
490
+ if (best > maxd) { best = -1.f; bid = -1; }
491
+ dist[tid] = best;
492
+ oid[tid] = bid;
493
+ if (onrm) for (int k = 0; k < 3; k++) onrm[3 * tid + k] = best >= 0.f ? bn[k] : 0.f;
494
+ }
495
+
496
+ // pass 2: the robot's meshes nearer than pass 1's hit (or maxd)
497
+ __global__ void __launch_bounds__(RAY_BLOCK, ROBOT_MINB) k_rays_robot(Scene S, int B, int N, const float* pos, const float* rot, const float* off,
498
+ const float* dir, float maxd, float* dist, int* oid, float* onrm, int dpw) {
499
+ const long long tid = (long long)blockIdx.x * blockDim.x + threadIdx.x;
500
+ if (tid >= (long long)B * N) return;
501
+ const int w = int(tid / N), n = int(tid % N);
502
+ if (!S.mmask[2 * w] && !S.mmask[2 * w + 1]) return;
503
+ if (dpw) { off += (size_t)w * N * 3; dir += (size_t)w * N * 3; }
504
+ float p[3], v[3];
505
+ world_ray(w, n, pos, rot, off, dir, p, v);
506
+ const float d0 = dist[tid];
507
+ float best = d0 >= 0.f ? d0 : maxd, bn[3] = {0.f, 0.f, 0.f};
508
+ int bid = d0 >= 0.f ? oid[tid] : -1;
509
+ cast_robot(S, w, p, v, &best, &bid, bn);
510
+ if (bid >= ID_ROBOT && bid != (d0 >= 0.f ? oid[tid] : -1)) {
511
+ dist[tid] = best;
512
+ oid[tid] = bid;
513
+ if (onrm) for (int k = 0; k < 3; k++) onrm[3 * tid + k] = bn[k];
514
+ }
515
+ }
516
+
517
+ // cone: cos and sin of the half angle of a cone from the sensor origin along its x axis that holds every ray (the mesh
518
+ // culling; offsets must be small against the meshes' distances, as a camera's zeros); dpw: off / dir are per world
519
+ // (B, N, 3) instead of shared (N, 3)
520
+ extern "C" int dk_scene_rays_pw(cudaStream_t st, const Scene* S, int B, int N, const float* pos, const float* rot,
521
+ const float* off, const float* dir, float maxd, float ch, float sh, float offmax,
522
+ float* dist, int* id, float* nrm, int dpw) {
523
+ const long long n = (long long)B * N;
524
+ if (n == 0) return 0;
525
+ if (S->nmesh) {
526
+ if (S->nmesh > 64) return -1;
527
+ cudaMemsetAsync(S->mmask, 0, sizeof(unsigned) * 2 * B, st);
528
+ k_mesh_cull<<<(B * S->nmesh + 127) / 128, 128, 0, st>>>(*S, B, pos, rot, ch, sh, maxd, offmax);
529
+ }
530
+ const unsigned nb = (unsigned)((n + RAY_BLOCK - 1) / RAY_BLOCK);
531
+ k_rays_static<<<nb, RAY_BLOCK, 0, st>>>(*S, B, N, pos, rot, off, dir, maxd, dist, id, nrm, dpw);
532
+ if (S->nmesh) k_rays_robot<<<nb, RAY_BLOCK, 0, st>>>(*S, B, N, pos, rot, off, dir, maxd, dist, id, nrm, dpw);
533
+ return (int)cudaGetLastError();
534
+ }
535
+ extern "C" int dk_scene_rays(cudaStream_t st, const Scene* S, int B, int N, const float* pos, const float* rot,
536
+ const float* off, const float* dir, float maxd, float ch, float sh, float offmax,
537
+ float* dist, int* id, float* nrm) {
538
+ return dk_scene_rays_pw(st, S, B, N, pos, rot, off, dir, maxd, ch, sh, offmax, dist, id, nrm, 0);
539
+ }
540
+ extern "C" int dk_scene_size() { return (int)sizeof(Scene); }
541
+ """
542
+
543
+
544
+ FFI_SOURCE = r"""
545
+ #include "xla/ffi/api/ffi.h"
546
+ namespace ffi = xla::ffi;
547
+ #define DK_MAX_DEV 16
548
+ static Scene g_scene[DK_MAX_DEV];
549
+ static bool g_have[DK_MAX_DEV];
550
+ extern "C" int dk_rays_set_scene(int dev, const Scene* s) {
551
+ if (dev < 0 || dev >= DK_MAX_DEV) return -1;
552
+ g_scene[dev] = *s;
553
+ g_have[dev] = true;
554
+ return 0;
555
+ }
556
+ static ffi::Error bad(const char* m) { return ffi::Error(ffi::ErrorCode::kInvalidArgument, m); }
557
+ using BufF = ffi::Buffer<ffi::F32>;
558
+ using RetF = ffi::Result<ffi::Buffer<ffi::F32>>;
559
+ using RetI = ffi::Result<ffi::Buffer<ffi::S32>>;
560
+ static ffi::Error scene_rays_impl(cudaStream_t st, BufF pos, BufF rot, BufF off, BufF dir, BufF xpos, BufF xquat,
561
+ BufF obj, float maxd, float ch, float sh, float offmax, int32_t robot,
562
+ int32_t exclude_body,
563
+ RetF dist, RetI id, RetF nrm, RetF mpose, RetI mmask) {
564
+ int dev = 0;
565
+ cudaGetDevice(&dev);
566
+ if (dev < 0 || dev >= DK_MAX_DEV || !g_have[dev]) return bad("no scene on this device (jax_rays.setup)");
567
+ Scene S = g_scene[dev];
568
+ if (!robot) S.nmesh = 0; // (the height scan: the terrain alone)
569
+ S.exclude_body = exclude_body; // (a LiDAR: its own body's meshes)
570
+ const auto dp = pos.dimensions(), dd = off.dimensions(), dx = xpos.dimensions(), dob = obj.dimensions();
571
+ const auto dr = dir.dimensions();
572
+ const int dpw = dd.size() == 3; // per-world rays: off / dir (B, N, 3)
573
+ if (dp.size() != 2 || dp[1] != 3 || dd.size() < 2 || dd.size() > 3 || dd[dd.size() - 1] != 3 ||
574
+ dr.size() != dd.size() || (dpw && dd[0] != dp[0]))
575
+ return bad("pos (B, 3), off / dir (N, 3) or (B, N, 3)");
576
+ for (size_t k = 0; k < dd.size(); k++)
577
+ if (dr[k] != dd[k]) return bad("off and dir: the same shape");
578
+ const int64_t B = dp[0], N = dd[dd.size() - 2];
579
+ if (B * N > INT_MAX) return bad("too many rays");
580
+ if (dx.size() != 3 || dx[0] != B || dx[2] != 3 || dob.size() != 3 || dob[0] != B || dob[2] != 15)
581
+ return bad("xpos (B, nbody, 3), objects (B, K, 15)");
582
+ if (S.nmesh && dx[1] != S.nbody) return bad("xpos: the scene's body count");
583
+ S.xpos = xpos.typed_data();
584
+ S.xquat = xquat.typed_data();
585
+ S.nobj = (int)dob[1];
586
+ S.obj = dob[1] ? obj.typed_data() : nullptr;
587
+ S.mpose = mpose->typed_data();
588
+ S.mmask = reinterpret_cast<unsigned*>(mmask->typed_data());
589
+ int rc = dk_scene_rays_pw(st, &S, (int)B, (int)N, pos.typed_data(), rot.typed_data(), off.typed_data(),
590
+ dir.typed_data(), maxd, ch, sh, offmax, dist->typed_data(), id->typed_data(),
591
+ nrm->typed_data(), dpw);
592
+ return rc ? ffi::Error(ffi::ErrorCode::kInternal, "dk_scene_rays") : ffi::Error::Success();
593
+ }
594
+ XLA_FFI_DEFINE_HANDLER_SYMBOL(DkSceneRays, scene_rays_impl,
595
+ ffi::Ffi::Bind().Ctx<ffi::PlatformStream<cudaStream_t>>()
596
+ .Arg<BufF>().Arg<BufF>().Arg<BufF>().Arg<BufF>().Arg<BufF>().Arg<BufF>().Arg<BufF>()
597
+ .Attr<float>("max_distance").Attr<float>("cone_cos").Attr<float>("cone_sin")
598
+ .Attr<float>("offset_max")
599
+ .Attr<int32_t>("robot").Attr<int32_t>("exclude_body")
600
+ .Ret<BufF>().Ret<ffi::Buffer<ffi::S32>>().Ret<BufF>().Ret<BufF>()
601
+ .Ret<ffi::Buffer<ffi::S32>>());
602
+ """
603
+
604
+
605
+ def cache_dir():
606
+ d = Path(os.environ.get("DK_CACHE_DIR") or Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache")
607
+ / "nablaengine")
608
+ d.mkdir(parents=True, exist_ok=True)
609
+ return d
610
+
611
+
612
+ def build(arch, include=None):
613
+ """The shared library (nvcc -shared, the CUDA runtime static) for architecture arch (sm_XY), cached by source;
614
+ include: XLA's FFI headers (jax.ffi.include_dir()) for the JAX variant with the handler DkSceneRays."""
615
+ from nablaengine import cuda
616
+ nvcc = cuda.nvcc()
617
+ flags = ["-O3", f"-arch={arch}", "-std=c++17", "-shared", "-Xcompiler", "-fPIC", "-cudart", "static"]
618
+ flags += os.environ.get("DK_RAYS_FLAGS", "").split()
619
+ text = SOURCE if include is None else SOURCE.replace("#include <math.h>\n", "#include <math.h>\n#include <climits>\n") + FFI_SOURCE
620
+ if include is not None:
621
+ flags.append(f"-I{include}")
622
+ key = hashlib.sha256((text + " ".join(flags) + nvcc).encode()).hexdigest()[:20]
623
+ out = cache_dir() / f"libdk_rays{'_jax' if include else ''}_{arch}_{key}.so"
624
+ if not out.exists():
625
+ src = out.with_suffix(".cu")
626
+ src.write_text(text)
627
+ tmp = out.with_suffix(f".tmp{os.getpid()}.so")
628
+ subprocess.run([nvcc, *flags, "-o", str(tmp), str(src)], check=True)
629
+ os.replace(tmp, out)
630
+ return out