Repository navigation
Expand file tree
/
Copy pathbind_render.cpp
More file actions
338 lines (319 loc) · 21.7 KB
/
Copy pathbind_render.cpp
File metadata and controls
338 lines (319 loc) · 21.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
// The rendering layer: Canvas (window / headless surface), GLRenderer (draws a
// scene and reads pixels back as numpy), OrbitControls, and TransformControls.
#include "bindings.hpp"
#include <pybind11/functional.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include "threepp/cameras/Camera.hpp"
#include "threepp/canvas/Canvas.hpp"
#include "threepp/constants.hpp"
#include "threepp/controls/OrbitControls.hpp"
#include "threepp/controls/TransformControls.hpp"
#include "threepp/core/Object3D.hpp"
#include "threepp/helpers/DepthSensor.hpp"
#include "threepp/input/KeyFromName.hpp"
#include "threepp/helpers/LidarModel.hpp"
#include "threepp/helpers/LidarTypes.hpp"
#include "threepp/input/KeyListener.hpp"
#include "threepp/math/Color.hpp"
#include "threepp/renderers/GLRenderer.hpp"
#include "threepp/scenes/Scene.hpp"
#include <cctype>
#include <cstring>
#include <sstream>
#include <string>
using namespace threepp;
namespace threepp_py {
// Resolve a Python renderer object to the backend-neutral threepp::Renderer&.
// Accepts the GLRenderer binding or the Vulkan facade (whose underlying native
// renderer is recovered via py_vulkan_native_renderer); raises a clear TypeError
// for anything else. Lets renderer-taking helpers (DepthSensor) be backend-neutral.
static Renderer& as_renderer(const py::handle& h) {
if (Renderer* vk = py_vulkan_native_renderer(h)) return *vk;
return h.cast<GLRenderer&>();
}
// keyFromName lives in the library (threepp/input/KeyFromName.hpp) - one
// mapping shared with the player's keyboard provider, so the names a script
// was written against mean the same key on every surface.
void init_render(py::module_& m) {
// Tone-mapping operator (maps HDR/linear radiance to displayable range).
// Default is NoToneMapping (clips >1); ACESFilmic/Neutral give a filmic
// roll-off that keeps HDR highlights and IBL reflections from blowing out.
py::enum_<ToneMapping>(m, "ToneMapping")
.value("NoToneMapping", ToneMapping::None)
.value("Linear", ToneMapping::Linear)
.value("Reinhard", ToneMapping::Reinhard)
.value("Cineon", ToneMapping::Cineon)
.value("ACESFilmic", ToneMapping::ACESFilmic)
.value("Neutral", ToneMapping::Neutral)
// AgX (Sobotka / three.js AgXToneMapping): the gentlest
// highlight roll-off of the set. Vulkan renderers only.
.value("AgX", ToneMapping::AgX);
// ---- LIDAR value types (helpers/LidarTypes.hpp + LidarModel.hpp) -----
// Pure data structs shared by the GL LidarSensor and the Vulkan
// PathTracedLidarSensor. Bound here (always-compiled, GL-safe) as plain
// value types; the scan itself is a separate, renderer-side step.
py::class_<LidarBeam>(m, "LidarBeam")
.def(py::init([](const Vector3& origin, const Vector3& direction) {
return LidarBeam{origin, direction};
}), py::arg("origin") = Vector3(), py::arg("direction") = Vector3())
.def_readwrite("origin", &LidarBeam::origin)
.def_readwrite("direction", &LidarBeam::direction);
py::class_<LidarReturn>(m, "LidarReturn")
.def(py::init<>())
.def_readwrite("position", &LidarReturn::position)
.def_readwrite("normal", &LidarReturn::normal)
.def_readwrite("distance", &LidarReturn::distance)
.def_readwrite("intensity", &LidarReturn::intensity)
.def_readwrite("hit_instance_id", &LidarReturn::hitInstanceId)
.def_readwrite("return_no", &LidarReturn::returnNo)
.def("__repr__", [](const LidarReturn& r) {
std::ostringstream o;
o << "LidarReturn(distance=" << r.distance << ", intensity=" << r.intensity
<< ", hit_instance_id=" << r.hitInstanceId << ", return_no=" << r.returnNo << ")";
return o.str();
});
py::class_<LidarParams>(m, "LidarParams")
.def(py::init<>())
.def_readwrite("max_range", &LidarParams::maxRange)
.def_readwrite("laser_power", &LidarParams::laserPower)
.def_readwrite("reference_range", &LidarParams::referenceRange)
.def_readwrite("atmospheric_extinction", &LidarParams::atmosphericExtinction)
.def_readwrite("detector_threshold", &LidarParams::detectorThreshold)
.def_readwrite("max_returns", &LidarParams::maxReturns)
.def_readwrite("samples_per_beam", &LidarParams::samplesPerBeam)
.def_readwrite("beam_divergence_mrad", &LidarParams::beamDivergenceMrad)
.def_readwrite("medium_surface_y", &LidarParams::mediumSurfaceY)
.def_readwrite("medium_extinction", &LidarParams::mediumExtinction)
.def_readwrite("medium_albedo", &LidarParams::mediumAlbedo)
.def_readwrite("medium_anisotropy", &LidarParams::mediumAnisotropy);
py::class_<LidarModel>(m, "LidarModel")
.def(py::init<>())
.def_readwrite("elevation_angles", &LidarModel::elevationAngles)
.def_readwrite("azimuth_resolution", &LidarModel::azimuthResolution)
.def_readwrite("azimuth_min", &LidarModel::azimuthMin)
.def_readwrite("azimuth_max", &LidarModel::azimuthMax)
.def_static("vlp16", &LidarModel::VLP16, "Velodyne VLP-16: 16 beams, +/-15deg elevation.")
.def_static("hdl32e", &LidarModel::HDL32E, "Velodyne HDL-32E: 32 beams, -30.67..+10.67deg.")
.def_static("os1_64", &LidarModel::OS1_64, "Ouster OS1-64: 64 beams, +/-22.5deg elevation.")
.def_static("os0_128", &LidarModel::OS0_128, "Ouster OS0-128: 128 beams, +/-45deg elevation.")
.def("__repr__", [](const LidarModel& lm) {
std::ostringstream o;
o << "LidarModel(beams=" << lm.elevationAngles.size()
<< ", azimuth_resolution=" << lm.azimuthResolution << ")";
return o.str();
});
// ---- Canvas ----------------------------------------------------------
// A GLFW window (or a hidden surface when headless=True). Construction is
// exposed as keyword arguments rather than the fluent Parameters builder.
py::class_<Canvas>(m, "Canvas")
.def(py::init([](const std::string& title, int width, int height, int antialiasing,
bool vsync, bool resizable, bool headless) {
Canvas::Parameters p;
p.title(title);
if (width > 0 && height > 0) p.size(width, height);
p.antialiasing(antialiasing).vsync(vsync).resizable(resizable).headless(headless);
return std::make_unique<Canvas>(p);
}),
py::arg("title") = "threepp", py::arg("width") = -1, py::arg("height") = -1,
py::arg("antialiasing") = 4, py::arg("vsync") = true,
py::arg("resizable") = true, py::arg("headless") = false)
.def("animate", &Canvas::animate, py::arg("callback"),
"Run the render loop, calling callback() every frame until the window closes.")
.def("animate_once", &Canvas::animateOnce, py::arg("callback"),
"Render a single frame; returns False when the app should quit.")
.def("size", [](const Canvas& c) {
auto s = c.size();
return py::make_tuple(s.width(), s.height());
})
.def("aspect", &Canvas::aspect)
.def_property_readonly("graphics_api", [](const Canvas& c) {
switch (c.graphicsApi()) {
case GraphicsAPI::Vulkan: return "Vulkan";
default: return "OpenGL";
}
})
.def("set_size", [](Canvas& c, int w, int h) { c.setSize({w, h}); }, py::arg("width"), py::arg("height"))
.def("on_window_resize", [](Canvas& c, const std::function<void(int, int)>& cb) {
c.onWindowResize([cb](WindowSize s) { cb(s.width(), s.height()); });
}, py::arg("callback"),
"Register callback(width, height), called when the window is resized. Use it to "
"update the camera aspect (+ update_projection_matrix) and the renderer size.")
.def("is_key_down", [](const Canvas& c, const std::string& key) { return c.isKeyDown(keyFromName(key)); },
py::arg("key"),
"Poll whether a key is currently held — e.g. 'W','A','S','D','SPACE','UP','LEFT'. "
"Query per-frame for continuous controls (WASD driving); never sticks.")
.def("is_open", &Canvas::isOpen)
.def("close", &Canvas::close);
// ---- GLRenderer ------------------------------------------------------
py::class_<GLRenderer>(m, "GLRenderer")
.def(py::init([](Canvas& canvas) { return std::make_unique<GLRenderer>(canvas); }),
py::arg("canvas"), py::keep_alive<1, 2>())
.def("render", &GLRenderer::render, py::arg("scene"), py::arg("camera"))
.def("set_size", [](GLRenderer& r, int w, int h) { r.setSize({w, h}); }, py::arg("width"), py::arg("height"))
.def("set_pixel_ratio", &GLRenderer::setPixelRatio, py::arg("value"))
.def("set_clear_color", &GLRenderer::setClearColor, py::arg("color"), py::arg("alpha") = 1.f)
.def("set_viewport", [](GLRenderer& r, int x, int y, int width, int height) { r.setViewport(x, y, width, height); },
py::arg("x"), py::arg("y"), py::arg("width"), py::arg("height"))
.def("set_scissor", [](GLRenderer& r, int x, int y, int width, int height) { r.setScissor(x, y, width, height); },
py::arg("x"), py::arg("y"), py::arg("width"), py::arg("height"))
.def("set_scissor_test", &GLRenderer::setScissorTest, py::arg("enabled"))
.def("clear", &GLRenderer::clear, py::arg("color") = true, py::arg("depth") = true, py::arg("stencil") = true)
.def_readwrite("auto_clear", &GLRenderer::autoClear)
.def_readwrite("sort_objects", &GLRenderer::sortObjects)
.def_readwrite("check_shader_errors", &GLRenderer::checkShaderErrors)
.def_readwrite("tone_mapping", &GLRenderer::toneMapping)
.def_readwrite("tone_mapping_exposure", &GLRenderer::toneMappingExposure)
.def_property("shadow_map_enabled",
[](GLRenderer& r) { return r.shadowMap().enabled; },
[](GLRenderer& r, bool v) { r.shadowMap().enabled = v; })
.def("size", [](const GLRenderer& r) {
auto s = r.size();
return py::make_tuple(s.width(), s.height());
})
// Read the current framebuffer as a (H, W, 3) uint8 numpy array.
// OpenGL reads bottom-up; flip=True (default) returns the usual
// top-down image orientation.
.def("read_pixels", [](GLRenderer& r, bool flip) {
auto s = r.size();
const int w = s.width(), h = s.height();
std::vector<unsigned char> buf = r.readRGBPixels();
py::array_t<uint8_t> arr({static_cast<py::ssize_t>(h),
static_cast<py::ssize_t>(w),
static_cast<py::ssize_t>(3)});
const size_t rowBytes = static_cast<size_t>(w) * 3;
auto* dst = arr.mutable_data();
if (buf.size() >= rowBytes * static_cast<size_t>(h)) {
for (int row = 0; row < h; ++row) {
const auto srcRow = static_cast<size_t>(flip ? (h - 1 - row) : row);
std::memcpy(dst + static_cast<size_t>(row) * rowBytes,
buf.data() + srcRow * rowBytes, rowBytes);
}
}
return arr;
}, py::arg("flip") = true)
.def("save_frame", [](GLRenderer& r, const std::string& path) { r.writeFramebuffer(path); }, py::arg("path"));
// ---- DepthSensor (helpers/DepthSensor.hpp) ---------------------------
// A GPU depth-render sensor: renders the scene from its own viewpoint, linearizes
// depth, reads it back, and reprojects to a world-space point cloud (optionally with
// per-point sRGB color). It is an Object3D — aim it with position/rotation/quaternion/
// look_at, then scan() with a GLRenderer. scan() refreshes the sensor's world matrix
// first, so it works whether or not the sensor was added to the scene.
auto pts_to_numpy = [](const std::vector<Vector3>& cloud) {
py::array_t<float> pts({static_cast<py::ssize_t>(cloud.size()), static_cast<py::ssize_t>(3)});
auto* d = pts.mutable_data();
for (size_t i = 0; i < cloud.size(); ++i) {
d[i * 3 + 0] = cloud[i].x; d[i * 3 + 1] = cloud[i].y; d[i * 3 + 2] = cloud[i].z;
}
return pts;
};
py::class_<DepthSensor, Object3D, Sensor, std::shared_ptr<DepthSensor>>(m, "DepthSensor")
.def(py::init([](float fov_y, unsigned int width, unsigned int height, float near, float far) {
return std::make_shared<DepthSensor>(fov_y, width, height, near, far);
}), py::arg("fov_y"), py::arg("width"), py::arg("height"),
py::arg("near") = 0.1f, py::arg("far") = 100.f,
"Depth sensor with a vertical FOV (deg), output resolution, and the near/far "
"RANGE bounds (m) it reports in -- a blind sphere of radius near out to a max "
"range of far, inclusive at both ends and identical on GL and Vulkan. These are "
"ranges, not view-space clip planes: an off-axis surface is judged by its "
"distance, not by its depth along the view axis.")
// `range_noise` stays a float — the sigma is the knob every
// caller actually turns (sliders, episode randomization) — with
// the full seeded model beside it as `noise`.
.def_property(
"range_noise",
[](const DepthSensor& s) { return s.rangeNoise.stddev; },
[](DepthSensor& s, float v) { s.rangeNoise.stddev = v; },
"Gaussian range-noise std-dev in metres (0 = perfect sensor). "
"Shorthand for noise.stddev.")
.def_readwrite("noise", &DepthSensor::rangeNoise,
"The full RangeNoiseModel (stddev, stddev_per_metre, bias, seed). "
"Set `seed` to make a captured dataset replayable; the stream re-seeds "
"on the next scan when the seed changes.")
.def_property_readonly("last_scan_time", &DepthSensor::lastScanTime,
"Sim time (s) stamped on the most recent scan — the timestamp to "
"record alongside the cloud. Register the sensor with a PhysxWorld "
"or drive `sim_time` yourself; see threepp.Sensor.")
.def_property_readonly("scan_due", &DepthSensor::scanDue,
"True when the rate gate says a scan is due (always true unless "
"rate_hz is set and the sensor is registered with a PhysxWorld).")
.def("reset_noise", &DepthSensor::resetNoise,
"Re-seed the noise stream from noise.seed and clear last_scan_time — call between "
"episodes so two runs with the same seed produce the same clouds.")
.def_property_readonly("width", &DepthSensor::width)
.def_property_readonly("height", &DepthSensor::height)
.def_property_readonly("fov", &DepthSensor::fov)
.def_property_readonly("near", &DepthSensor::near)
.def_property_readonly("far", &DepthSensor::far)
.def("scan", [pts_to_numpy](DepthSensor& self, const py::object& renderer, Scene& scene) {
self.updateWorldMatrix(true, true); // sync sensor + child camera pose
std::vector<Vector3> cloud;
self.scan(as_renderer(renderer), scene, cloud);
return pts_to_numpy(cloud);
}, py::arg("renderer"), py::arg("scene"),
"Depth scan -> (N,3) float32 world-space hit points (N = points that hit within far). "
"Works with a GLRenderer (raster depth) or a VulkanRenderer (path-traced through the "
"renderer's acceleration structure -- render() the scene at least once first).")
.def("scan_rgbd", [pts_to_numpy](DepthSensor& self, const py::object& renderer, Scene& scene) {
self.updateWorldMatrix(true, true);
std::vector<Vector3> cloud;
std::vector<Color> colors;
self.scan(as_renderer(renderer), scene, cloud, colors);
py::array_t<float> col({static_cast<py::ssize_t>(colors.size()), static_cast<py::ssize_t>(3)});
auto* c = col.mutable_data();
for (size_t i = 0; i < colors.size(); ++i) {
c[i * 3 + 0] = colors[i].r; c[i * 3 + 1] = colors[i].g; c[i * 3 + 2] = colors[i].b;
}
return py::make_tuple(pts_to_numpy(cloud), col);
}, py::arg("renderer"), py::arg("scene"),
"RGB-D scan -> (points (N,3) float32 world-space, colors (N,3) float32 in [0,1]). On GL the "
"colors are sampled sRGB; on Vulkan they are LIDAR intensity as greyscale.");
// ---- TransformControls -----------------------------------------------
py::class_<TransformControls, Object3D, std::shared_ptr<TransformControls>>(m, "TransformControls")
.def(py::init([](Camera& camera, Canvas& canvas) {
return std::make_shared<TransformControls>(camera, canvas);
}),
py::arg("camera"), py::arg("canvas"),
py::keep_alive<1, 2>(), py::keep_alive<1, 3>())
.def_readwrite("enabled", &TransformControls::enabled)
.def_readwrite("show_x", &TransformControls::showX)
.def_readwrite("show_y", &TransformControls::showY)
.def_readwrite("show_z", &TransformControls::showZ)
.def("set_mode", &TransformControls::setMode, py::arg("mode"),
"Mode: 'translate' | 'rotate' | 'scale'")
.def("set_space", &TransformControls::setSpace, py::arg("space"),
"Space: 'world' | 'local'")
.def("get_space", &TransformControls::getSpace)
.def("set_size", &TransformControls::setSize, py::arg("size"))
.def("set_translation_snap", &TransformControls::setTranslationSnap, py::arg("snap"))
.def("set_rotation_snap", &TransformControls::setRotationSnap, py::arg("snap"))
.def("set_scale_snap", &TransformControls::setScaleSnap, py::arg("snap"))
.def_property_readonly("dragging", &TransformControls::isDragging,
"True while the user is actively dragging the gizmo.")
.def("attach", [](TransformControls& self, const py::handle& obj) -> TransformControls& {
return self.attach(*as_object3d(obj));
}, py::arg("object"), py::return_value_policy::reference,
"Attach the gizmo to an Object3D. Add the TransformControls itself to the scene.")
.def("detach", &TransformControls::detach, py::return_value_policy::reference);
// ---- OrbitControls ---------------------------------------------------
py::class_<OrbitControls>(m, "OrbitControls")
.def(py::init([](Camera& camera, Canvas& canvas) {
return std::make_unique<OrbitControls>(camera, canvas);
}),
py::arg("camera"), py::arg("canvas"), py::keep_alive<1, 2>(), py::keep_alive<1, 3>())
.def_readwrite("enabled", &OrbitControls::enabled)
.def_readwrite("target", &OrbitControls::target)
.def_readwrite("min_distance", &OrbitControls::minDistance)
.def_readwrite("max_distance", &OrbitControls::maxDistance)
.def_readwrite("enable_damping", &OrbitControls::enableDamping)
.def_readwrite("damping_factor", &OrbitControls::dampingFactor)
.def_readwrite("enable_zoom", &OrbitControls::enableZoom)
.def_readwrite("zoom_speed", &OrbitControls::zoomSpeed)
.def_readwrite("enable_rotate", &OrbitControls::enableRotate)
.def_readwrite("rotate_speed", &OrbitControls::rotateSpeed)
.def_readwrite("enable_pan", &OrbitControls::enablePan)
.def_readwrite("auto_rotate", &OrbitControls::autoRotate)
.def_readwrite("auto_rotate_speed", &OrbitControls::autoRotateSpeed)
.def("update", &OrbitControls::update);
}
}// namespace threepp_py