From f9fd18b5aa7b5e427943d4d60472b260c0d41eed Mon Sep 17 00:00:00 2001 From: trung09122002 Date: Sat, 3 Oct 2026 19:13:50 +0700 Subject: [PATCH] sim: camera ve bang GPU (lib tuy chon vslam_sim_gl, EGL + GLES3 + assimp) -- anh IR co texture that + depth khop tung pixel, vslam_node --sim-gl, tool vslam_render_preview --- README.md | 3 +- app/CMakeLists.txt | 5 + app/src/main.cc | 3 + app/src/runtime.cc | 23 + app/src/runtime.h | 3 + libs/CMakeLists.txt | 8 + libs/vslam_sim/CMakeLists.txt | 1 + .../include/vslam/sim_camera_renderer.h | 51 ++ libs/vslam_sim/include/vslam/sim_source.h | 7 + libs/vslam_sim/src/sim_source.cc | 113 ++- libs/vslam_sim_gl/CMakeLists.txt | 38 + .../include/vslam/sim_gl_renderer.h | 69 ++ libs/vslam_sim_gl/src/sim_gl_renderer.cc | 704 ++++++++++++++++++ test/CMakeLists.txt | 4 + test/test_sim_gl.cc | 182 +++++ tools/CMakeLists.txt | 10 + tools/vslam_render_preview.cc | 127 ++++ 17 files changed, 1329 insertions(+), 22 deletions(-) create mode 100644 libs/vslam_sim/include/vslam/sim_camera_renderer.h create mode 100644 libs/vslam_sim_gl/CMakeLists.txt create mode 100644 libs/vslam_sim_gl/include/vslam/sim_gl_renderer.h create mode 100644 libs/vslam_sim_gl/src/sim_gl_renderer.cc create mode 100644 test/test_sim_gl.cc create mode 100644 tools/vslam_render_preview.cc diff --git a/README.md b/README.md index 72c9b99..932fbb2 100644 --- a/README.md +++ b/README.md @@ -162,7 +162,8 @@ Dinh vi lai co **camera** (VPR + PnP, chot khi trung LiDAR): them `--slam-reloc- - Luc xoay, cu 30 do chup mot anh; chot SOM khi anh va LiDAR cung chi mot cho. Log ghi `bang camera+LiDAR` hoac `bang LiDAR`. Vi du do 02/10 (mot cho, mot ban do): camera+LiDAR chot sau ~3 s, LiDAR-only sau ~13 s. -- Chua chay duoc trong mo phong: camera mo phong chi co depth, khong co anh. +- Trong mo phong: build them `-DVSLAM_SIM_WITH_GL=ON` (may co GPU) va chay `--sim --sim-gl` -- camera ve + bang GPU co anh IR (texture lay tu `~/gazebo_models/aws_hospital`). Khong co co nay thi chi co depth. Xong thi tra lai hai dich vu: diff --git a/app/CMakeLists.txt b/app/CMakeLists.txt index e21ad2f..051408a 100644 --- a/app/CMakeLists.txt +++ b/app/CMakeLists.txt @@ -38,6 +38,11 @@ endif() if(VSLAM_WITH_REALSENSE) target_compile_definitions(vslam_node PRIVATE VSLAM_HAVE_REALSENSE=1) endif() +# Ve camera mo phong bang GPU (--sim-gl). Lib tuy chon, chi may dev co GPU. +if(TARGET vslam_sim_gl) + target_link_libraries(vslam_node PRIVATE vslam_sim_gl) + target_compile_definitions(vslam_node PRIVATE VSLAM_HAVE_SIM_GL=1) +endif() if(VSLAM_WITH_CANOPEN) target_compile_definitions(vslam_node PRIVATE VSLAM_HAVE_CANOPEN=1) endif() diff --git a/app/src/main.cc b/app/src/main.cc index 9e81b26..ad87d0b 100644 --- a/app/src/main.cc +++ b/app/src/main.cc @@ -57,6 +57,8 @@ void Usage(const char* argv0) { " system.yaml gamepad.enabled. DEV mac dinh lay\n" " tu system.yaml (/dev/input/js0)\n" " --no-gamepad tat tay cam du system.yaml co bat\n" + " --sim-gl ve camera mo phong bang GPU: depth + anh IR co\n" + " texture (can --world, build VSLAM_SIM_WITH_GL=ON)\n" " --sim-glass-at X dat buc KINH ngang hanh lang o x = X m.\n" " LiDAR/depth KHONG thay; chi sieu am + bumper.\n" " --max-speed V ghi de tran toc do (m/s). CHI CHO MO PHONG --\n" @@ -163,6 +165,7 @@ int main(int argc, char** argv) { } else if (a == "--no-gamepad") opts.gamepad_override = -1; else if (a == "--sim-glass-at") opts.sim_glass_at = std::atof(next().c_str()); + else if (a == "--sim-gl") opts.sim_gl = true; else if (a == "--max-speed") opts.max_speed_override = std::atof(next().c_str()); else if (a == "--slam") opts.force_slam = true; else if (a == "--slam-db") { opts.slam_db = next(); opts.have_slam_db = true; } diff --git a/app/src/runtime.cc b/app/src/runtime.cc index 6f43421..357bae0 100644 --- a/app/src/runtime.cc +++ b/app/src/runtime.cc @@ -18,6 +18,9 @@ #include "vslam/node_constants.h" #include "vslam/replay_source.h" #include "vslam/sim_source.h" +#ifdef VSLAM_HAVE_SIM_GL +#include "vslam/sim_gl_renderer.h" +#endif #ifdef VSLAM_HAVE_SLAM #include "vslam/occupancy_export.h" #include @@ -84,6 +87,26 @@ StatusResponse Runtime::OpenSource() { const StatusResponse st = source_->sim->Open(); if (!st.ok()) return st; + if (opts_.sim_gl) { + // Ve camera bang GPU: depth + anh IR tu mesh co texture that. Context + // GPU tao o khung dau tien, tren luong vong mo phong. + if (opts_.world_path.empty()) { + return StatusResponse::Error(StatusCode::kInvalidArgument, + "--sim-gl can --world (ve tu mesh cua world)"); + } +#ifdef VSLAM_HAVE_SIM_GL + std::string err; + auto r = CreateGlCameraRenderer(source_->sim->world(), DefaultGlRendererConfig(), &err); + if (!r) { + return StatusResponse::Error(StatusCode::kFailedPrecondition, "--sim-gl: " + err); + } + source_->sim->SetCameraRenderer(r); +#else + return StatusResponse::Error(StatusCode::kFailedPrecondition, + "--sim-gl: node build KHONG co -DVSLAM_SIM_WITH_GL=ON"); +#endif + } + if (opts_.sim_glass_at != 0.0) { // Buc kinh chan ngang hanh lang. Phai danh dau o DA BI CHIEM, nen // chen tuong truoc roi moi danh dau la kinh. diff --git a/app/src/runtime.h b/app/src/runtime.h index b117d8e..def3867 100644 --- a/app/src/runtime.h +++ b/app/src/runtime.h @@ -90,6 +90,9 @@ struct RuntimeOptions { // Kinh vo hinh voi LiDAR va depth; chi sieu am thay. Dung de chay nhanh // US_BLOCKED va BUMPER cua FSM -- hai nhanh chua bao gio chay end-to-end. double sim_glass_at = 0.0; + // Ve camera mo phong bang GPU (vslam_sim_gl): depth + anh IR co texture. + // Can --world va node build voi -DVSLAM_SIM_WITH_GL=ON. + bool sim_gl = false; bool force_slam = false; // --slam: ghi de slam.yaml enabled bool have_slam_db = false; // --slam-db "" nghia la DB trong RAM std::string slam_db; diff --git a/libs/CMakeLists.txt b/libs/CMakeLists.txt index 221cbba..e260576 100644 --- a/libs/CMakeLists.txt +++ b/libs/CMakeLists.txt @@ -45,3 +45,11 @@ endif() if(VSLAM_BUILD_SIM) add_subdirectory(vslam_sim) endif() + +# Ve anh camera mo phong bang GPU (anh IR + depth tu mesh co texture that). +# TUY CHON, chi may dev co GPU: sim van chay khong co no (depth raycast CPU, +# khong co anh IR). +option(VSLAM_SIM_WITH_GL "Ve camera mo phong bang GPU (EGL + GLES3 + assimp)" OFF) +if(VSLAM_BUILD_SIM AND VSLAM_SIM_WITH_GL) + add_subdirectory(vslam_sim_gl) +endif() diff --git a/libs/vslam_sim/CMakeLists.txt b/libs/vslam_sim/CMakeLists.txt index af73ac4..7857c5c 100644 --- a/libs/vslam_sim/CMakeLists.txt +++ b/libs/vslam_sim/CMakeLists.txt @@ -9,6 +9,7 @@ find_package(yaml-cpp REQUIRED) vslam_add_library(vslam_sim PUBLIC_HDRS sim_source.h + sim_camera_renderer.h occupancy_map_io.h gazebo_world.h PUBLIC_DEPS diff --git a/libs/vslam_sim/include/vslam/sim_camera_renderer.h b/libs/vslam_sim/include/vslam/sim_camera_renderer.h new file mode 100644 index 0000000..21e6313 --- /dev/null +++ b/libs/vslam_sim/include/vslam/sim_camera_renderer.h @@ -0,0 +1,51 @@ +#ifndef VSLAM_SIM_CAMERA_RENDERER_H +#define VSLAM_SIM_CAMERA_RENDERER_H + +// Ve anh camera cho bo mo phong. +// +// Interface nay KHONG phu thuoc do hoa: vslam_sim chi biet no, con cai dat GPU +// (EGL + OpenGL ES, texture that cua model) nam o lib TUY CHON vslam_sim_gl. +// Nho vay bo mo phong van build va chay tren Jetson / CI khong co GPU -- khi +// khong co renderer thi camera mo phong ve depth bang raycast CPU nhu cu va +// khong co anh IR. + +#include +#include +#include + +namespace vslam { + +// Tu the va noi suy cua MOT khung anh. +// +// Frame QUANG HOC theo quy uoc anh (giong RealSense va depth cua sim): +X +// phai, +Y xuong, +Z toi truoc. Pixel (u, v) co TAM tai toa do nguyen, kieu +// OpenCV: tia qua pixel u di theo ((u - cx) / fx, (v - cy) / fy, 1). +struct SimCameraView { + // Hang-chinh. Cot j la truc j cua frame quang hoc, viet trong world. + double R_wc[9] = {1, 0, 0, 0, 1, 0, 0, 0, 1}; + double t_wc[3] = {0, 0, 0}; // tam camera trong world, m + double fx = 0, fy = 0, cx = 0, cy = 0; + int width = 0, height = 0; + double near_m = 0.05, far_m = 30.0; +}; + +class SimCameraRenderer { + public: + virtual ~SimCameraRenderer() = default; + + // Ve mot khung. `ir`: width*height byte, anh xam, HANG TREN CUNG TRUOC. + // `depth_z`: width*height float, Z-DEPTH (hinh chieu len truc quang) theo + // met; 0 = tia khong trung gi. Tra false neu khong ve duoc. + // + // ⚠️ Context GPU gan voi LUONG tao ra no: moi lan goi phai tren CUNG mot + // luong (luong vong mo phong). + virtual bool Render(const SimCameraView& view, std::vector* ir, + std::vector* depth_z) = 0; + + // Mo ta ngan cho log, vd "NVIDIA GeForce RTX 4060 (EGL, GLES 3.2)". + virtual std::string Describe() const = 0; +}; + +} // namespace vslam + +#endif // VSLAM_SIM_CAMERA_RENDERER_H diff --git a/libs/vslam_sim/include/vslam/sim_source.h b/libs/vslam_sim/include/vslam/sim_source.h index 95791c7..757924a 100644 --- a/libs/vslam_sim/include/vslam/sim_source.h +++ b/libs/vslam_sim/include/vslam/sim_source.h @@ -42,6 +42,7 @@ #include "vslam/clock.h" #include "vslam/gazebo_world.h" +#include "vslam/sim_camera_renderer.h" #include "vslam/driver_interfaces.h" #include "vslam/vslam_common.h" @@ -366,6 +367,12 @@ class SimSource { using GroundTruthCallback = std::function; void SetGroundTruthCallback(GroundTruthCallback cb, double rate_hz = 0.0); + // Ve camera bang renderer ngoai (GPU, vslam_sim_gl): depth VA anh IR + // (`CameraFrame::infra1`) tu mesh co texture, thay raycast CPU. null = raycast + // CPU nhu cu, khong co anh IR. Goi truoc Run(); renderer duoc goi tren luong + // vong mo phong. + void SetCameraRenderer(std::shared_ptr r); + // Danh dau mot vung hinh chu nhat (toa do THE GIOI, met) la KINH. // // O kinh phai la o BI CHIEM trong ban do (data >= 50) -- kinh la vat can diff --git a/libs/vslam_sim/src/sim_source.cc b/libs/vslam_sim/src/sim_source.cc index efe8285..12c6adf 100644 --- a/libs/vslam_sim/src/sim_source.cc +++ b/libs/vslam_sim/src/sim_source.cc @@ -224,6 +224,12 @@ struct SimSource::Impl { // dung chung se bi khung sau ghi de giua chung. std::shared_ptr>> depth_pool = BufferPool>::Create(8); + + // Renderer GPU tuy chon (SetCameraRenderer). null = raycast CPU, khong co IR. + std::shared_ptr renderer; + std::vector gl_ir; + std::vector gl_depth; + bool gl_fail_logged = false; std::shared_ptr clock; // Trang thai that cua robot. @@ -1052,6 +1058,61 @@ struct SimSource::Impl { cz_w += rz; } + // Huong (don vi) trong THE GIOI cua mot huong trong frame quang hoc. + // Quang hoc -> than robot: +Z_quang = +X_than, +X_quang = -Y_than, + // +Y_quang = -Z_than. Roi chuc xuong `camera_pitch`, roi xoay theo than. + // Raycast CPU va renderer GPU dung CHUNG ham nay, nen tia cua hai duong + // trung nhau tung pixel. + auto to_world = [&](double bx0, double by0, double bz0, double* wx, double* wy, + double* wz) { + if (terrain_on) { + // Chuc camera tren than (quanh y than), roi xoay theo than. + const double mx = bx0 * ccp + bz0 * csp; + const double mz = -bx0 * csp + bz0 * ccp; + R_body.Apply(mx, by0, mz, wx, wy, wz); + } else { + // Nghieng ngang cua than (roll) truoc, roi chuc xuong (pitch). + const double by1 = by0 * cr_b - bz0 * sr_b; + const double bz1 = by0 * sr_b + bz0 * cr_b; + const double px = bx0 * cp + bz1 * sp; + *wz = -bx0 * sp + bz1 * cp; + const double py = by1; + + *wx = px * cy_r - py * sy_r; + *wy = px * sy_r + py * cy_r; + } + }; + + // Renderer GPU: ve CA khung mot lan (depth + IR), vong lap ben duoi chi + // ap nhieu. Ve hong thi khung nay quay ve raycast CPU. + bool use_gl = false; + if (renderer) { + SimCameraView view; + // Cot j cua R_wc = truc j cua frame quang hoc trong world. + double ax[3][3]; + to_world(0.0, -1.0, 0.0, &ax[0][0], &ax[0][1], &ax[0][2]); // +X quang + to_world(0.0, 0.0, -1.0, &ax[1][0], &ax[1][1], &ax[1][2]); // +Y quang + to_world(1.0, 0.0, 0.0, &ax[2][0], &ax[2][1], &ax[2][2]); // +Z quang + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) view.R_wc[i * 3 + j] = ax[j][i]; + } + view.t_wc[0] = cx_w; + view.t_wc[1] = cy_w; + view.t_wc[2] = cz_w; + view.fx = fx; + view.fy = fy; + view.cx = ppx; + view.cy = ppy; + view.width = static_cast(w); + view.height = static_cast(h); + view.far_m = std::max(cfg.depth_far, 1.0) + 1.0; + use_gl = renderer->Render(view, &gl_ir, &gl_depth); + if (!use_gl && !gl_fail_logged) { + gl_fail_logged = true; + VSLAM_WARN("sim: renderer GPU ve hong -- camera quay ve raycast CPU, KHONG co anh IR"); + } + } + // Khong dung mot `normal_distribution` chung: sigma phu thuoc KHOANG // CACH cua tung diem anh, nen phan phoi duoc dung ngay trong vong lap. std::uniform_real_distribution uni01(0.0, 1.0); @@ -1064,28 +1125,16 @@ struct SimSource::Impl { const double oz = 1.0; const double inv = 1.0 / std::sqrt(ox * ox + oy * oy + oz * oz); - // Quang hoc -> than robot: +Z_quang = +X_than, +X_quang = -Y_than, - // +Y_quang = -Z_than. Roi chuc xuong `camera_pitch`, roi xoay theo yaw. - const double bx0 = oz * inv, by0 = -ox * inv, bz0 = -oy * inv; - double wx, wy, pz; - if (terrain_on) { - // Chuc camera tren than (quanh y than), roi xoay theo than. - const double mx = bx0 * ccp + bz0 * csp; - const double mz = -bx0 * csp + bz0 * ccp; - R_body.Apply(mx, by0, mz, &wx, &wy, &pz); + double d; + if (use_gl) { + // GPU tra thang Z-DEPTH; 0 = khong trung gi. + const float zg = gl_depth[static_cast(v) * w + u]; + d = zg > 0.0f ? static_cast(zg) : std::numeric_limits::infinity(); } else { - // Nghieng ngang cua than (roll) truoc, roi chuc xuong (pitch). - const double by1 = by0 * cr_b - bz0 * sr_b; - const double bz1 = by0 * sr_b + bz0 * cr_b; - const double px = bx0 * cp + bz1 * sp; - pz = -bx0 * sp + bz1 * cp; - const double py = by1; - - wx = px * cy_r - py * sy_r; - wy = px * sy_r + py * cy_r; + double wx, wy, pz; + to_world(oz * inv, -ox * inv, -oy * inv, &wx, &wy, &pz); + d = RaycastDepth(cx_w, cy_w, cz_w, wx, wy, pz, cfg.depth_far); } - - double d = RaycastDepth(cx_w, cy_w, cz_w, wx, wy, pz, cfg.depth_far); uint16_t mm = 0; // 0 = khong do duoc, dung quy uoc cua RealSense // Depth dropout: D410 that mat diem o be mat toi, be mat bong, va o @@ -1110,7 +1159,9 @@ struct SimSource::Impl { // dung ra phang o z=0 bi cliff_detect khop thanh z0 = -0.254 m, // doc +0.114 -- va 87/1903 tia trong cua so roi duoi nguong, tuc // BAO VUC GIA tren san hoan toan phang, MAD 0.037 van lot cong. - d *= inv; + // + // GPU da tra Z-depth roi -- nhan them la sai lan nua. + if (!use_gl) d *= inv; // Nhieu depth theo MO HINH STEREO, khong phai hang so. // @@ -1173,6 +1224,21 @@ struct SimSource::Impl { img->depth_scale = 0.001f; img->data = depth_buf.data(); img->keep_alive = buf; + if (use_gl) { + // Anh IR cung kich thuoc, cung K va cung stamp voi depth -- giong + // RealSense: hai anh IR va depth thang hang tung pixel. + auto ibuf = depth_pool->Acquire(); + ibuf->assign(gl_ir.begin(), gl_ir.end()); + auto ir = std::make_shared(); + ir->header = img->header; + ir->width = w; + ir->height = h; + ir->step = w; + ir->format = PixelFormat::kMono8; + ir->data = ibuf->data(); + ir->keep_alive = ibuf; + out->infra1 = ir; + } out->header = img->header; out->depth = img; @@ -1656,6 +1722,11 @@ void SimSource::SetFloorRamp(double x0, double y0, double x1, double y1, bool SimSource::terrain_active() const { return impl_->terrain_on; } +void SimSource::SetCameraRenderer(std::shared_ptr r) { + impl_->renderer = std::move(r); + impl_->gl_fail_logged = false; +} + void SimSource::SetGroundTruthCallback(GroundTruthCallback cb, double rate_hz) { impl_->gt_cb = std::move(cb); impl_->gt_period = rate_hz > 0.0 ? 1.0 / rate_hz : 0.0; diff --git a/libs/vslam_sim_gl/CMakeLists.txt b/libs/vslam_sim_gl/CMakeLists.txt new file mode 100644 index 0000000..fd762fd --- /dev/null +++ b/libs/vslam_sim_gl/CMakeLists.txt @@ -0,0 +1,38 @@ +# Ve anh camera mo phong bang GPU: EGL KHONG man hinh + OpenGL ES 3, mesh hien +# thi va texture THAT cua model (assimp), anh tu OpenCV. +# +# TUY CHON (-DVSLAM_SIM_WITH_GL=ON), chi cho may dev co GPU: vslam_sim KHONG +# phu thuoc lib nay -- no chi biet interface SimCameraRenderer +# (vslam/sim_camera_renderer.h). Jetson va CI van build sim nhu cu. +# +# Khong dung find_package(assimp): goi libassimp-dev 5.0.1 cua Ubuntu 20.04 +# co file cmake tro sai ten thu vien. Tim thang thu vien va header thi chac. + +find_package(OpenCV REQUIRED COMPONENTS core imgproc imgcodecs) +find_library(VSLAM_EGL_LIB EGL) +find_library(VSLAM_GLES_LIB GLESv2) +find_library(VSLAM_ASSIMP_LIB assimp) +find_path(VSLAM_EGL_INC EGL/egl.h) +find_path(VSLAM_GLES_INC GLES3/gl3.h) +find_path(VSLAM_ASSIMP_INC assimp/scene.h) +foreach(v VSLAM_EGL_LIB VSLAM_GLES_LIB VSLAM_ASSIMP_LIB VSLAM_EGL_INC VSLAM_GLES_INC VSLAM_ASSIMP_INC) + if(NOT ${v}) + message(FATAL_ERROR "VSLAM_SIM_WITH_GL=ON nhung thieu ${v}. Ubuntu: " + "apt install libegl-dev libgles-dev libassimp-dev") + endif() +endforeach() + +vslam_add_library(vslam_sim_gl + PUBLIC_HDRS + sim_gl_renderer.h + PUBLIC_DEPS + vslam_sim + vslam_common + FIND_DEPS + vslam_sim + vslam_common +) +target_include_directories(vslam_sim_gl SYSTEM PRIVATE + ${VSLAM_EGL_INC} ${VSLAM_GLES_INC} ${VSLAM_ASSIMP_INC} ${OpenCV_INCLUDE_DIRS}) +target_link_libraries(vslam_sim_gl PRIVATE + ${VSLAM_EGL_LIB} ${VSLAM_GLES_LIB} ${VSLAM_ASSIMP_LIB} ${OpenCV_LIBS}) diff --git a/libs/vslam_sim_gl/include/vslam/sim_gl_renderer.h b/libs/vslam_sim_gl/include/vslam/sim_gl_renderer.h new file mode 100644 index 0000000..c161305 --- /dev/null +++ b/libs/vslam_sim_gl/include/vslam/sim_gl_renderer.h @@ -0,0 +1,69 @@ +#ifndef VSLAM_SIM_GL_RENDERER_H +#define VSLAM_SIM_GL_RENDERER_H + +// Ve anh camera mo phong bang GPU: EGL KHONG man hinh + OpenGL ES 3, mesh +// HIEN THI cua world voi texture THAT cua model (assimp: OBJ/MTL, COLLADA). +// +// ================== VI SAO CAN ================== +// Raycast CPU cua bo mo phong chi ra DEPTH, tren tuong ep tu luoi 2D: khong co +// anh, va hinh hoc chi la 2.5D. VO/VIO (F2M, DM-VIO) can ANH co van that de +// bam diem, va can depth KHOP voi anh do. Ve ca hai tu CUNG mot mesh trong +// MOT luot GPU thi chung khop tung pixel. +// +// ================== GIOI HAN (noi ro) ================== +// * Anh "IR" la do sang texture * chieu sang don gian (ambient + den chieu +// theo huong camera), emitter TAT: khong co cham laser, khong rolling +// shutter, khong nhoe chuyen dong, khong tu dong phoi sang. Anh sach hon +// camera that -- ket qua VO trong sim LAC QUAN. +// * Model khong co texture (tuong/san tu sinh) duoc phu mot texture anh +// that theo toa do the gioi (triplanar). Van that, nhung khong dung nghia. +// * Chi xet yaw cua model (giong bo doc world): do doc phai nam san trong +// dinh mesh. +// +// ⚠️ Context GPU tao LUOI o lan Render() dau tien, tren luong goi, va moi lan +// goi sau phai tren CUNG luong do (luong vong mo phong). + +#include +#include + +#include "vslam/gazebo_world.h" +#include "vslam/sim_camera_renderer.h" + +namespace vslam { + +struct GlRendererConfig { + // Texture cho model KHONG co texture: dia hinh (`vslam_terrain_*`) va vat + // khac. Phu theo toa do THE GIOI (triplanar), moi lan lap `texture_tile_m` + // met. Rong = mau dac (khong co van -- VO se khong bam duoc). + std::string fallback_floor_texture; + std::string fallback_wall_texture; + double texture_tile_m = 2.0; + // Chieu sang anh IR: ambient + den chieu dat tai camera (emitter TAT). + double ambient = 0.55; + double headlight = 0.45; + // Cho phep renderer PHAN MEM (Mesa llvmpipe). Mac dinh tu choi: may co ca + // driver Mesa, va chon nham thiet bi la cham ~100 lan ma khong bao loi. + bool allow_software = false; +}; + +// Cau hinh mac dinh: texture cho model khong co texture lay tu bo model AWS +// tren may (~/gazebo_models/aws_hospital): san/doc = anh THAM that, vat khac = +// anh VAI rem that -- ca hai lap duoc, co van cho VO bam. Bien moi truong +// VSLAM_SIM_FLOOR_TEXTURE / VSLAM_SIM_WALL_TEXTURE ghi de (duong dan anh). +// Khong tim thay anh nao thi de rong (mau dac) va log canh bao. +GlRendererConfig DefaultGlRendererConfig(); + +// Nap mesh + texture cua `world` NGAY (CPU), dua len GPU o lan Render() dau. +// Tra nullptr va dien `error` neu khong nap duoc mesh nao. +std::shared_ptr CreateGlCameraRenderer(const GazeboWorld& world, + const GlRendererConfig& cfg, + std::string* error); + +// Hop bao he WORLD cua mesh HIEN THI cua mot model, doc bang assimp voi CUNG +// quy uoc nhu renderer (ti le ``, yaw, tinh tien). Cho bai kiem so voi +// bo doc world cua vslam_sim. false neu khong doc duoc. +bool AssimpModelBounds(const WorldModel& m, double mn[3], double mx[3]); + +} // namespace vslam + +#endif // VSLAM_SIM_GL_RENDERER_H diff --git a/libs/vslam_sim_gl/src/sim_gl_renderer.cc b/libs/vslam_sim_gl/src/sim_gl_renderer.cc new file mode 100644 index 0000000..f5d3af2 --- /dev/null +++ b/libs/vslam_sim_gl/src/sim_gl_renderer.cc @@ -0,0 +1,704 @@ +#include "vslam/sim_gl_renderer.h" + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "vslam/log.h" + +namespace vslam { +namespace { + +// --------------------------------------------------------------------------- +// Du lieu phia CPU: nap mot lan luc tao, khong can context GPU. +// --------------------------------------------------------------------------- + +struct CpuTexture { + int w = 0, h = 0; + std::vector rgba; // hang DUOI cung truoc -- quy uoc texture GL +}; + +struct CpuMesh { + std::vector v; // moi dinh: x y z nx ny nz u v, he WORLD + std::vector idx; + int tex = -1; // chi so CpuTexture; -1 = mau dac + bool triplanar = false; // phu texture theo toa do world (model khong UV) + float color[3] = {0.7f, 0.7f, 0.7f}; +}; + +std::string DirOf(const std::string& p) { + const size_t s = p.rfind('/'); + return s == std::string::npos ? std::string(".") : p.substr(0, s); +} + +// Nap anh texture. Lat DOC: OBJ va COLLADA dat v = 0 o DAY anh, con anh doc +// tu file thi hang tren cung truoc. +int LoadTexture(const std::string& path, std::map* cache, + std::vector* out) { + auto it = cache->find(path); + if (it != cache->end()) return it->second; + cv::Mat img = cv::imread(path, cv::IMREAD_COLOR); + if (img.empty()) { + VSLAM_WARN("sim_gl: khong doc duoc texture " << path << " -- dung mau dac"); + (*cache)[path] = -1; + return -1; + } + // 2048 la du cho anh 640x480 nhin vat cach vai met; texture 8K cua vai + // model chi ton bo nho GPU va thoi gian nap. + const int kMax = 2048; + if (img.cols > kMax || img.rows > kMax) { + const double s = static_cast(kMax) / std::max(img.cols, img.rows); + cv::resize(img, img, cv::Size(), s, s, cv::INTER_AREA); + } + cv::Mat rgba; + cv::cvtColor(img, rgba, cv::COLOR_BGR2RGBA); + cv::flip(rgba, rgba, 0); + CpuTexture t; + t.w = rgba.cols; + t.h = rgba.rows; + t.rgba.assign(rgba.data, rgba.data + rgba.total() * 4); + out->push_back(std::move(t)); + const int id = static_cast(out->size()) - 1; + (*cache)[path] = id; + return id; +} + +// Doc mesh HIEN THI cua mot model bang assimp, bien doi sang world theo CUNG +// thu tu voi bo doc world (gazebo_world.cc): ti le `` -> yaw -> tinh tien. +// `meshes`/`textures` co the null (chi lay hop bao). +bool LoadModel(const WorldModel& m, const GlRendererConfig* cfg, + std::map* tex_cache, std::vector* textures, + std::vector* meshes, double mn[3], double mx[3]) { + const std::string& path = !m.visual_obj.empty() ? m.visual_obj : m.collision_obj; + if (path.empty()) return false; + Assimp::Importer imp; + // Bo cua COLLADA, y nhu bo doc world: file cua bo model AWS khai + // Y_UP nhung du lieu (hoac node goc) DA la Z-up. Don vi va bien doi + // node thi giu -- PreTransformVertices nuong ca hai vao dinh. + imp.SetPropertyBool(AI_CONFIG_IMPORT_COLLADA_IGNORE_UP_DIRECTION, true); + const aiScene* sc = + imp.ReadFile(path, aiProcess_Triangulate | aiProcess_GenSmoothNormals | + aiProcess_PreTransformVertices | + aiProcess_JoinIdenticalVertices); + if (sc == nullptr || sc->mRootNode == nullptr) { + VSLAM_WARN("sim_gl: assimp khong doc duoc " << path << ": " << imp.GetErrorString()); + return false; + } + const double cyw = std::cos(m.yaw), syw = std::sin(m.yaw); + const std::string dir = DirOf(path); + for (int k = 0; k < 3; ++k) { mn[k] = 1e18; mx[k] = -1e18; } + bool any = false; + + for (unsigned mi = 0; mi < sc->mNumMeshes; ++mi) { + const aiMesh* am = sc->mMeshes[mi]; + if (am->mNumVertices == 0 || am->mNumFaces == 0) continue; + CpuMesh cm; + if (meshes != nullptr && am->mMaterialIndex < sc->mNumMaterials) { + const aiMaterial* mat = sc->mMaterials[am->mMaterialIndex]; + aiColor3D kd(0.7f, 0.7f, 0.7f); + if (mat->Get(AI_MATKEY_COLOR_DIFFUSE, kd) == AI_SUCCESS) { + cm.color[0] = kd.r; cm.color[1] = kd.g; cm.color[2] = kd.b; + } + aiString tp; + if (mat->GetTextureCount(aiTextureType_DIFFUSE) > 0 && + mat->GetTexture(aiTextureType_DIFFUSE, 0, &tp) == AI_SUCCESS) { + std::string t = tp.C_Str(); + // '*' dau = texture nhung trong file -- bo model nay khong dung. + if (!t.empty() && t[0] != '*') { + std::replace(t.begin(), t.end(), '\\', '/'); + cm.tex = LoadTexture(t[0] == '/' ? t : dir + "/" + t, tex_cache, textures); + } + } + } + const bool has_uv = am->HasTextureCoords(0); + if (meshes != nullptr && cfg != nullptr && (cm.tex < 0 || !has_uv)) { + // Khong co texture (tuong/san tu sinh): phu anh that theo toa do world. + const std::string& fb = m.terrain ? cfg->fallback_floor_texture + : cfg->fallback_wall_texture; + if (!fb.empty()) { + cm.tex = LoadTexture(fb, tex_cache, textures); + cm.triplanar = cm.tex >= 0; + } + } + + cm.v.reserve(static_cast(am->mNumVertices) * 8); + for (unsigned k = 0; k < am->mNumVertices; ++k) { + const aiVector3D& p = am->mVertices[k]; + const double px = p.x * m.sx, py = p.y * m.sy, pz = p.z * m.sz; + const double wx = px * cyw - py * syw + m.x; + const double wy = px * syw + py * cyw + m.y; + const double wz = pz + m.z; + double nx = 0.0, ny = 0.0, nz = 1.0; + if (am->HasNormals()) { + // Ti le KHONG deu: phap tuyen chia (khong nhan) cho ti le, roi chuan hoa. + const double ax = am->mNormals[k].x / m.sx; + const double ay = am->mNormals[k].y / m.sy; + const double az = am->mNormals[k].z / m.sz; + const double rx = ax * cyw - ay * syw, ry = ax * syw + ay * cyw; + const double n = std::sqrt(rx * rx + ry * ry + az * az); + if (n > 1e-12) { nx = rx / n; ny = ry / n; nz = az / n; } + } + const float u = has_uv ? am->mTextureCoords[0][k].x : 0.0f; + const float w = has_uv ? am->mTextureCoords[0][k].y : 0.0f; + const float vals[8] = {static_cast(wx), static_cast(wy), + static_cast(wz), static_cast(nx), + static_cast(ny), static_cast(nz), u, w}; + cm.v.insert(cm.v.end(), vals, vals + 8); + mn[0] = std::min(mn[0], wx); mx[0] = std::max(mx[0], wx); + mn[1] = std::min(mn[1], wy); mx[1] = std::max(mx[1], wy); + mn[2] = std::min(mn[2], wz); mx[2] = std::max(mx[2], wz); + any = true; + } + for (unsigned f = 0; f < am->mNumFaces; ++f) { + const aiFace& face = am->mFaces[f]; + if (face.mNumIndices != 3) continue; // diem / doan sau Triangulate + cm.idx.push_back(face.mIndices[0]); + cm.idx.push_back(face.mIndices[1]); + cm.idx.push_back(face.mIndices[2]); + } + if (meshes != nullptr && !cm.idx.empty()) meshes->push_back(std::move(cm)); + } + return any; +} + +// --------------------------------------------------------------------------- +// Shader. Mot luot ve ra HAI anh: do sang IR (attachment 0) va Z-depth +// (attachment 1, float) -- cung mesh, cung pixel, nen khop tung diem. +// --------------------------------------------------------------------------- + +const char* kVertex = R"(#version 300 es +layout(location = 0) in vec3 aPos; +layout(location = 1) in vec3 aNrm; +layout(location = 2) in vec2 aUv; +uniform mat4 uProj; +uniform mat4 uView; +out vec3 vWorld; +out vec3 vNrm; +out vec2 vUv; +out float vZ; +void main() { + vWorld = aPos; + vNrm = aNrm; + vUv = aUv; + vec4 pc = uView * vec4(aPos, 1.0); + vZ = -pc.z; // Z-depth: camera GL nhin theo -z + gl_Position = uProj * pc; +} +)"; + +const char* kFragment = R"(#version 300 es +precision highp float; +in vec3 vWorld; +in vec3 vNrm; +in vec2 vUv; +in float vZ; +uniform sampler2D uTex; +uniform int uHasTex; +uniform int uTriplanar; +uniform float uTriScale; +uniform vec3 uColor; +uniform vec3 uCamPos; +uniform float uAmbient; +uniform float uHeadlight; +layout(location = 0) out vec4 oIr; +layout(location = 1) out vec4 oDepth; +vec3 Tri(vec3 p, vec3 n) { + vec3 w = abs(n); + w /= (w.x + w.y + w.z + 1e-6); + vec3 a = texture(uTex, p.yz * uTriScale).rgb; + vec3 b = texture(uTex, p.xz * uTriScale).rgb; + vec3 c = texture(uTex, p.xy * uTriScale).rgb; + return a * w.x + b * w.y + c * w.z; +} +void main() { + vec3 n = normalize(vNrm); + vec3 base = uColor; + if (uHasTex == 1) { + base = (uTriplanar == 1) ? Tri(vWorld, n) : texture(uTex, vUv).rgb; + } + // Den chieu dat tai camera; abs() vi vai mesh co phap tuyen nguoc. + vec3 l = normalize(uCamPos - vWorld); + float lit = uAmbient + uHeadlight * abs(dot(n, l)); + float g = clamp(dot(base, vec3(0.299, 0.587, 0.114)) * lit, 0.0, 1.0); + oIr = vec4(g, g, g, 1.0); + oDepth = vec4(vZ, 0.0, 0.0, 1.0); +} +)"; + +GLuint Compile(GLenum type, const char* src, std::string* err) { + const GLuint s = glCreateShader(type); + glShaderSource(s, 1, &src, nullptr); + glCompileShader(s); + GLint ok = 0; + glGetShaderiv(s, GL_COMPILE_STATUS, &ok); + if (!ok) { + char log[2048] = {0}; + glGetShaderInfoLog(s, sizeof(log), nullptr, log); + *err = log; + glDeleteShader(s); + return 0; + } + return s; +} + +bool IsSoftware(const char* renderer) { + if (renderer == nullptr) return true; + const std::string r = renderer; + return r.find("llvmpipe") != std::string::npos || + r.find("softpipe") != std::string::npos || + r.find("SwiftShader") != std::string::npos; +} + +// Ma tran 4x4 COT-chinh (quy uoc GL). +struct Mat4 { + float m[16]; +}; + +class GlCameraRenderer : public SimCameraRenderer { + public: + GlCameraRenderer(std::vector meshes, std::vector textures, + GlRendererConfig cfg) + : meshes_(std::move(meshes)), textures_(std::move(textures)), cfg_(std::move(cfg)) {} + + ~GlCameraRenderer() override { + // Tren luong khac thi chi huy context: tai nguyen GL di theo no. KHONG + // eglTerminate -- display cua thiet bi dung chung giua cac renderer. + if (ctx_ != EGL_NO_CONTEXT && std::this_thread::get_id() == thread_) { + eglMakeCurrent(dpy_, surf_, surf_, ctx_); + for (const Gpu& g : gpu_) { + glDeleteVertexArrays(1, &g.vao); + glDeleteBuffers(1, &g.vbo); + glDeleteBuffers(1, &g.ibo); + } + if (!gl_tex_.empty()) glDeleteTextures(static_cast(gl_tex_.size()), gl_tex_.data()); + DropFbo(); + if (prog_ != 0) glDeleteProgram(prog_); + eglMakeCurrent(dpy_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); + } + if (ctx_ != EGL_NO_CONTEXT) eglDestroyContext(dpy_, ctx_); + if (surf_ != EGL_NO_SURFACE) eglDestroySurface(dpy_, surf_); + } + + bool Render(const SimCameraView& view, std::vector* ir, + std::vector* depth_z) override { + if (!init_tried_) { + init_tried_ = true; + thread_ = std::this_thread::get_id(); + ok_ = InitGpu(); + // Du lieu CPU khong can nua: GPU da giu ban sao. + meshes_.clear(); + meshes_.shrink_to_fit(); + textures_.clear(); + textures_.shrink_to_fit(); + } + if (!ok_) return false; + if (std::this_thread::get_id() != thread_) { + VSLAM_ERROR("sim_gl: Render() goi tu luong khac luong tao context -- bo khung"); + return false; + } + if (view.width <= 0 || view.height <= 0) return false; + if (eglGetCurrentContext() != ctx_) eglMakeCurrent(dpy_, surf_, surf_, ctx_); + if (!EnsureFbo(view.width, view.height)) return false; + + const int w = view.width, h = view.height; + glBindFramebuffer(GL_FRAMEBUFFER, fbo_); + glViewport(0, 0, w, h); + const GLenum bufs[2] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1}; + glDrawBuffers(2, bufs); + const float c0[4] = {0.0f, 0.0f, 0.0f, 1.0f}; + const float c1[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + const float one = 1.0f; + glClearBufferfv(GL_COLOR, 0, c0); + glClearBufferfv(GL_COLOR, 1, c1); + glClearBufferfv(GL_DEPTH, 0, &one); + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_LESS); + glDisable(GL_CULL_FACE); // vai mesh quay mat nguoc, ve ca hai mat + + Mat4 proj, viewm; + Projection(view, &proj); + ViewMatrix(view, &viewm); + glUseProgram(prog_); + glUniformMatrix4fv(loc_proj_, 1, GL_FALSE, proj.m); + glUniformMatrix4fv(loc_view_, 1, GL_FALSE, viewm.m); + glUniform3f(loc_campos_, static_cast(view.t_wc[0]), + static_cast(view.t_wc[1]), static_cast(view.t_wc[2])); + glUniform1f(loc_amb_, static_cast(cfg_.ambient)); + glUniform1f(loc_head_, static_cast(cfg_.headlight)); + glUniform1f(loc_triscale_, static_cast(1.0 / std::max(0.05, cfg_.texture_tile_m))); + glUniform1i(loc_tex_, 0); + glActiveTexture(GL_TEXTURE0); + for (const Gpu& g : gpu_) { + glUniform3f(loc_color_, g.color[0], g.color[1], g.color[2]); + glUniform1i(loc_hastex_, g.tex >= 0 ? 1 : 0); + glUniform1i(loc_tri_, g.triplanar ? 1 : 0); + if (g.tex >= 0) glBindTexture(GL_TEXTURE_2D, gl_tex_[static_cast(g.tex)]); + glBindVertexArray(g.vao); + glDrawElements(GL_TRIANGLES, g.count, GL_UNSIGNED_INT, nullptr); + } + glBindVertexArray(0); + + rgba_.resize(static_cast(w) * h * 4); + rgbaf_.resize(static_cast(w) * h * 4); + glReadBuffer(GL_COLOR_ATTACHMENT0); + glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, rgba_.data()); + glReadBuffer(GL_COLOR_ATTACHMENT1); + glReadPixels(0, 0, w, h, GL_RGBA, GL_FLOAT, rgbaf_.data()); + const GLenum e = glGetError(); + if (e != GL_NO_ERROR) { + VSLAM_ERROR("sim_gl: loi GL 0x" << std::hex << e << std::dec << " khi ve"); + return false; + } + + // glReadPixels tra hang DUOI cung truoc; anh thi hang TREN truoc. + ir->resize(static_cast(w) * h); + depth_z->resize(static_cast(w) * h); + for (int r = 0; r < h; ++r) { + const size_t src = static_cast(h - 1 - r) * w; + const size_t dst = static_cast(r) * w; + for (int c = 0; c < w; ++c) { + (*ir)[dst + c] = rgba_[(src + c) * 4]; + (*depth_z)[dst + c] = rgbaf_[(src + c) * 4]; + } + } + return true; + } + + std::string Describe() const override { return describe_; } + + private: + struct Gpu { + GLuint vao = 0, vbo = 0, ibo = 0; + GLsizei count = 0; + int tex = -1; + bool triplanar = false; + float color[3] = {0.7f, 0.7f, 0.7f}; + }; + + bool InitGpu() { + auto query_devices = + reinterpret_cast(eglGetProcAddress("eglQueryDevicesEXT")); + auto get_display = reinterpret_cast( + eglGetProcAddress("eglGetPlatformDisplayEXT")); + if (query_devices == nullptr || get_display == nullptr) { + VSLAM_ERROR("sim_gl: EGL thieu EGL_EXT_device_enumeration / platform_device"); + return false; + } + EGLDeviceEXT devs[16]; + EGLint n = 0; + if (!query_devices(16, devs, &n) || n <= 0) { + VSLAM_ERROR("sim_gl: khong co thiet bi EGL nao"); + return false; + } + std::string rejected; + for (EGLint i = 0; i < n; ++i) { + EGLDisplay d = get_display(EGL_PLATFORM_DEVICE_EXT, devs[i], nullptr); + EGLint maj = 0, min = 0; + if (d == EGL_NO_DISPLAY || !eglInitialize(d, &maj, &min)) continue; + if (!eglBindAPI(EGL_OPENGL_ES_API)) continue; + const EGLint cattr[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE, + EGL_OPENGL_ES3_BIT, EGL_NONE}; + EGLConfig conf; + EGLint nc = 0; + if (!eglChooseConfig(d, cattr, &conf, 1, &nc) || nc < 1) continue; + const EGLint xattr[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE}; + EGLContext c = eglCreateContext(d, conf, EGL_NO_CONTEXT, xattr); + if (c == EGL_NO_CONTEXT) continue; + const EGLint pattr[] = {EGL_WIDTH, 16, EGL_HEIGHT, 16, EGL_NONE}; + EGLSurface s = eglCreatePbufferSurface(d, conf, pattr); + if (s == EGL_NO_SURFACE || !eglMakeCurrent(d, s, s, c)) { + if (s != EGL_NO_SURFACE) eglDestroySurface(d, s); + eglDestroyContext(d, c); + continue; + } + const char* rend = reinterpret_cast(glGetString(GL_RENDERER)); + const char* ext = reinterpret_cast(glGetString(GL_EXTENSIONS)); + const bool soft = IsSoftware(rend); + const bool fbuf = ext != nullptr && std::strstr(ext, "GL_EXT_color_buffer_float") != nullptr; + if ((soft && !cfg_.allow_software) || !fbuf) { + rejected += std::string(rend ? rend : "?") + (soft ? " (phan mem)" : " (thieu float FBO)") + "; "; + eglMakeCurrent(d, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); + eglDestroySurface(d, s); + eglDestroyContext(d, c); + continue; + } + dpy_ = d; + ctx_ = c; + surf_ = s; + describe_ = std::string(rend ? rend : "?") + " (EGL, " + + reinterpret_cast(glGetString(GL_VERSION)) + ")"; + break; + } + if (ctx_ == EGL_NO_CONTEXT) { + VSLAM_ERROR("sim_gl: khong co GPU dung duoc. Da bo: " << rejected + << "(allow_software = true de chay CHAM tren CPU)"); + return false; + } + + std::string err; + const GLuint vs = Compile(GL_VERTEX_SHADER, kVertex, &err); + if (vs == 0) { VSLAM_ERROR("sim_gl: vertex shader: " << err); return false; } + const GLuint fs = Compile(GL_FRAGMENT_SHADER, kFragment, &err); + if (fs == 0) { VSLAM_ERROR("sim_gl: fragment shader: " << err); return false; } + prog_ = glCreateProgram(); + glAttachShader(prog_, vs); + glAttachShader(prog_, fs); + glLinkProgram(prog_); + glDeleteShader(vs); + glDeleteShader(fs); + GLint linked = 0; + glGetProgramiv(prog_, GL_LINK_STATUS, &linked); + if (!linked) { + char log[2048] = {0}; + glGetProgramInfoLog(prog_, sizeof(log), nullptr, log); + VSLAM_ERROR("sim_gl: link shader: " << log); + return false; + } + loc_proj_ = glGetUniformLocation(prog_, "uProj"); + loc_view_ = glGetUniformLocation(prog_, "uView"); + loc_tex_ = glGetUniformLocation(prog_, "uTex"); + loc_hastex_ = glGetUniformLocation(prog_, "uHasTex"); + loc_tri_ = glGetUniformLocation(prog_, "uTriplanar"); + loc_triscale_ = glGetUniformLocation(prog_, "uTriScale"); + loc_color_ = glGetUniformLocation(prog_, "uColor"); + loc_campos_ = glGetUniformLocation(prog_, "uCamPos"); + loc_amb_ = glGetUniformLocation(prog_, "uAmbient"); + loc_head_ = glGetUniformLocation(prog_, "uHeadlight"); + + // Texture. + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + gl_tex_.resize(textures_.size(), 0); + if (!gl_tex_.empty()) glGenTextures(static_cast(gl_tex_.size()), gl_tex_.data()); + for (size_t i = 0; i < textures_.size(); ++i) { + glBindTexture(GL_TEXTURE_2D, gl_tex_[i]); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, textures_[i].w, textures_[i].h, 0, GL_RGBA, + GL_UNSIGNED_BYTE, textures_[i].rgba.data()); + glGenerateMipmap(GL_TEXTURE_2D); + // Mipmap + loc tuyen tinh: van o xa khong nhap nhay (aliasing) -- mot + // nguon "dac trung" gia ma VO se bam vao. + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + } + + // Mesh. + size_t tris = 0; + for (const CpuMesh& cm : meshes_) { + Gpu g; + g.tex = cm.tex; + g.triplanar = cm.triplanar; + std::copy(cm.color, cm.color + 3, g.color); + g.count = static_cast(cm.idx.size()); + glGenVertexArrays(1, &g.vao); + glBindVertexArray(g.vao); + glGenBuffers(1, &g.vbo); + glBindBuffer(GL_ARRAY_BUFFER, g.vbo); + glBufferData(GL_ARRAY_BUFFER, static_cast(cm.v.size() * sizeof(float)), + cm.v.data(), GL_STATIC_DRAW); + glGenBuffers(1, &g.ibo); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g.ibo); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, + static_cast(cm.idx.size() * sizeof(uint32_t)), cm.idx.data(), + GL_STATIC_DRAW); + const GLsizei stride = 8 * sizeof(float); + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, nullptr); + glEnableVertexAttribArray(1); + glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, stride, + reinterpret_cast(3 * sizeof(float))); + glEnableVertexAttribArray(2); + glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, stride, + reinterpret_cast(6 * sizeof(float))); + glBindVertexArray(0); + gpu_.push_back(g); + tris += cm.idx.size() / 3; + } + const GLenum e = glGetError(); + if (e != GL_NO_ERROR) { + VSLAM_ERROR("sim_gl: loi GL 0x" << std::hex << e << std::dec << " khi nap mesh"); + return false; + } + VSLAM_INFO("sim_gl: ve camera bang " << describe_ << " -- " << gpu_.size() << " mesh, " + << tris << " tam giac, " << gl_tex_.size() << " texture"); + return true; + } + + void DropFbo() { + if (fbo_ != 0) glDeleteFramebuffers(1, &fbo_); + if (rb_ir_ != 0) glDeleteRenderbuffers(1, &rb_ir_); + if (rb_depth_ != 0) glDeleteRenderbuffers(1, &rb_depth_); + if (rb_z_ != 0) glDeleteRenderbuffers(1, &rb_z_); + fbo_ = rb_ir_ = rb_depth_ = rb_z_ = 0; + fbo_w_ = fbo_h_ = 0; + } + + bool EnsureFbo(int w, int h) { + if (fbo_ != 0 && fbo_w_ == w && fbo_h_ == h) return true; + DropFbo(); + glGenFramebuffers(1, &fbo_); + glBindFramebuffer(GL_FRAMEBUFFER, fbo_); + glGenRenderbuffers(1, &rb_ir_); + glBindRenderbuffer(GL_RENDERBUFFER, rb_ir_); + glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, w, h); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rb_ir_); + glGenRenderbuffers(1, &rb_depth_); + glBindRenderbuffer(GL_RENDERBUFFER, rb_depth_); + glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA32F, w, h); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_RENDERBUFFER, rb_depth_); + glGenRenderbuffers(1, &rb_z_); + glBindRenderbuffer(GL_RENDERBUFFER, rb_z_); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, w, h); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb_z_); + const GLenum st = glCheckFramebufferStatus(GL_FRAMEBUFFER); + if (st != GL_FRAMEBUFFER_COMPLETE) { + VSLAM_ERROR("sim_gl: framebuffer khong day du (0x" << std::hex << st << std::dec << ")"); + DropFbo(); + return false; + } + fbo_w_ = w; + fbo_h_ = h; + return true; + } + + // Phep chieu tu noi suy pinhole. Tam pixel o toa do NGUYEN (kieu OpenCV), + // con GL lay mau o x + 0.5: cong 0.5 vao cx, cy de tia qua pixel u cua GL + // trung tia qua pixel u cua raycast CPU. + static void Projection(const SimCameraView& v, Mat4* P) { + const double W = v.width, H = v.height, n = v.near_m, f = v.far_m; + const double cx = v.cx + 0.5, cy = v.cy + 0.5; + std::fill(P->m, P->m + 16, 0.0f); + P->m[0] = static_cast(2.0 * v.fx / W); + P->m[5] = static_cast(2.0 * v.fy / H); + P->m[8] = static_cast(1.0 - 2.0 * cx / W); + P->m[9] = static_cast(2.0 * cy / H - 1.0); + P->m[10] = static_cast(-(f + n) / (f - n)); + P->m[11] = -1.0f; + P->m[14] = static_cast(-2.0 * f * n / (f - n)); + } + + // World -> camera GL (x phai, y LEN, nhin theo -z). Frame quang hoc (y + // XUONG, z truoc) doi sang GL bang diag(1, -1, -1). + static void ViewMatrix(const SimCameraView& v, Mat4* V) { + // R_gl_w = diag(1,-1,-1) * R_wc^T. Hang i cua R_wc^T = cot i cua R_wc. + double R[9]; + for (int i = 0; i < 3; ++i) { + const double s = i == 0 ? 1.0 : -1.0; + for (int j = 0; j < 3; ++j) R[i * 3 + j] = s * v.R_wc[j * 3 + i]; + } + double t[3]; + for (int i = 0; i < 3; ++i) { + t[i] = -(R[i * 3 + 0] * v.t_wc[0] + R[i * 3 + 1] * v.t_wc[1] + R[i * 3 + 2] * v.t_wc[2]); + } + std::fill(V->m, V->m + 16, 0.0f); + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) V->m[j * 4 + i] = static_cast(R[i * 3 + j]); + V->m[12 + i] = static_cast(t[i]); + } + V->m[15] = 1.0f; + } + + std::vector meshes_; + std::vector textures_; + GlRendererConfig cfg_; + + bool init_tried_ = false, ok_ = false; + std::thread::id thread_; + EGLDisplay dpy_ = EGL_NO_DISPLAY; + EGLContext ctx_ = EGL_NO_CONTEXT; + EGLSurface surf_ = EGL_NO_SURFACE; + GLuint prog_ = 0; + GLint loc_proj_ = -1, loc_view_ = -1, loc_tex_ = -1, loc_hastex_ = -1, loc_tri_ = -1; + GLint loc_triscale_ = -1, loc_color_ = -1, loc_campos_ = -1, loc_amb_ = -1, loc_head_ = -1; + std::vector gpu_; + std::vector gl_tex_; + GLuint fbo_ = 0, rb_ir_ = 0, rb_depth_ = 0, rb_z_ = 0; + int fbo_w_ = 0, fbo_h_ = 0; + std::vector rgba_; + std::vector rgbaf_; + std::string describe_ = "sim_gl (chua khoi tao)"; +}; + +} // namespace + +namespace { + +std::string TexturePath(const char* env, const char* home_rel) { + if (const char* e = std::getenv(env)) { + if (*e != '\0') return e; + } + const char* home = std::getenv("HOME"); + if (home == nullptr) return ""; + const std::string p = std::string(home) + "/gazebo_models/" + home_rel; + struct stat st; + if (::stat(p.c_str(), &st) != 0) { + VSLAM_WARN("sim_gl: khong thay texture " << p << " (dat " << env + << ") -- model khong co texture se la MAU DAC, VO khong bam duoc"); + return ""; + } + return p; +} + +} // namespace + +GlRendererConfig DefaultGlRendererConfig() { + GlRendererConfig c; + c.fallback_floor_texture = TexturePath( + "VSLAM_SIM_FLOOR_TEXTURE", + "aws_hospital/aws_robomaker_residential_Carpet_01/materials/textures/aws_Carpet_01.png"); + c.fallback_wall_texture = TexturePath( + "VSLAM_SIM_WALL_TEXTURE", + "aws_hospital/aws_robomaker_hospital_curtain_open_01/meshes/" + "aws_robomaker_hospital_curtain_open_01_visual.png"); + return c; +} + +std::shared_ptr CreateGlCameraRenderer(const GazeboWorld& world, + const GlRendererConfig& cfg, + std::string* error) { + std::vector meshes; + std::vector textures; + std::map cache; + size_t loaded = 0, failed = 0; + for (const WorldModel& m : world.models) { + double mn[3], mx[3]; + if (LoadModel(m, &cfg, &cache, &textures, &meshes, mn, mx)) { + loaded++; + } else { + failed++; + } + } + if (meshes.empty()) { + if (error != nullptr) *error = "khong nap duoc mesh hien thi nao tu world"; + return nullptr; + } + VSLAM_INFO("sim_gl: nap " << loaded << " model (" << failed << " khong doc duoc), " + << meshes.size() << " mesh, " << textures.size() << " texture"); + return std::make_shared(std::move(meshes), std::move(textures), cfg); +} + +bool AssimpModelBounds(const WorldModel& m, double mn[3], double mx[3]) { + return LoadModel(m, nullptr, nullptr, nullptr, nullptr, mn, mx); +} + +} // namespace vslam diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 1acacb0..7c7e235 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -92,6 +92,10 @@ if(VSLAM_BUILD_SIM) vslam_add_test(test_sim_terrain LIBS vslam_sim vslam_drivers vslam_common) # IMU mo phong (mo hinh dong hoc, phat thua, tre, bias) va su that 6-DoF. vslam_add_test(test_sim_imu LIBS vslam_sim vslam_drivers vslam_common) + # Ve camera bang GPU (lib tuy chon). May khong co GPU thi cac bai SKIP. + if(TARGET vslam_sim_gl) + vslam_add_test(test_sim_gl LIBS vslam_sim_gl vslam_sim vslam_drivers vslam_common) + endif() if(VSLAM_BUILD_ODOMETRY) # Test TICH HOP: sim -> encoder -> wheel_odom -> EKF, do sai so so voi # ground truth. Day la bai L2 cua repo cu viet lai khong ROS. diff --git a/test/test_sim_gl.cc b/test/test_sim_gl.cc new file mode 100644 index 0000000..f41326d --- /dev/null +++ b/test/test_sim_gl.cc @@ -0,0 +1,182 @@ +// Ve camera mo phong bang GPU (vslam_sim_gl). +// +// May khong co GPU dung duoc (CI, container) thi cac bai nay SKIP, khong do: +// renderer GPU la tuy chon, va bo mo phong van chay bang raycast CPU. +// +// Khoa: +// * depth GPU dung khoang cach toi mm (tia qua pixel giua); +// * hop bao mesh doc bang assimp khop bo doc world cua vslam_sim (OBJ met, +// OBJ cm + , COLLADA co , COLLADA khai Y_UP) -- lech quy +// uoc la anh va luoi chiem dung noi hai chuyen khac nhau; +// * bo mo phong dung renderer: co anh IR cung kich thuoc depth, va depth GPU +// KHOP depth raycast CPU tren san / doc / tuong. + +#include + +#include +#include +#include +#include +#include +#include + +#include "vslam/gazebo_world.h" +#include "vslam/sim_gl_renderer.h" +#include "vslam/sim_source.h" + +using namespace vslam; + +namespace { + +std::string WorldDir() { + const char* e = std::getenv("VSLAM_TEST_DATA_DIR"); + return (e != nullptr ? std::string(e) : std::string("test/data")) + "/world"; +} + +GazeboWorld Load(const std::string& name) { + GazeboWorld w; + const StatusResponse st = + LoadGazeboWorld(WorldDir() + "/" + name, {WorldDir() + "/models"}, &w); + EXPECT_TRUE(st.ok()) << st.message; + return w; +} + +// Camera dat tai (x, y, z), nhin theo yaw, khong chuc. +SimCameraView View(double x, double y, double z, double yaw, int w, int h, double fx) { + const double cy = std::cos(yaw), sy = std::sin(yaw); + SimCameraView v; + // Cot: X quang = phai = -trai, Y quang = xuong, Z quang = truoc. + const double cols[3][3] = {{sy, -cy, 0.0}, {0.0, 0.0, -1.0}, {cy, sy, 0.0}}; + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) v.R_wc[i * 3 + j] = cols[j][i]; + } + v.t_wc[0] = x; v.t_wc[1] = y; v.t_wc[2] = z; + v.width = w; v.height = h; + v.fx = v.fy = fx; + v.cx = w / 2.0; v.cy = h / 2.0; + return v; +} + +// Renderer cho world, hoac nullptr (kem ly do) neu may khong ve duoc. +std::shared_ptr MakeRenderer(const GazeboWorld& w, std::string* why) { + GlRendererConfig cfg = DefaultGlRendererConfig(); + auto r = CreateGlCameraRenderer(w, cfg, why); + if (!r) return nullptr; + std::vector ir; + std::vector d; + if (!r->Render(View(0, 0, 1, 0, 8, 8, 4.0), &ir, &d)) { + *why = "khong co GPU dung duoc (xem log sim_gl)"; + return nullptr; + } + return r; +} + +} // namespace + +TEST(SimGl, DepthDungKhoangCachToiMm) { + // mini.world: hop box_m 2.0 x 1.0 x 0.5 m tam o goc. Mesh CHI co day, nap + // va hai mat +-y (khong co mat +-x), nen nhin vao mat y = -0.5: camera o + // y = -2.5, cao giua hop, nhin +y -- pixel giua thay mat do o Z = 2.0. + const GazeboWorld w = Load("mini.world"); + std::string why; + auto r = MakeRenderer(w, &why); + if (!r) GTEST_SKIP() << why; + std::vector ir; + std::vector d; + const int W = 160, H = 120; + ASSERT_TRUE(r->Render(View(0.0, -2.5, 0.25, M_PI / 2, W, H, 120.0), &ir, &d)); + ASSERT_EQ(d.size(), static_cast(W) * H); + EXPECT_NEAR(d[static_cast(H / 2) * W + W / 2], 2.0, 1e-3); + // Goc tren trai nhin len troi: khong trung gi. + EXPECT_EQ(d[0], 0.0f); + EXPECT_EQ(ir[0], 0); +} + +TEST(SimGl, HopBaoAssimpKhopBoDocWorld) { + const GazeboWorld w = Load("mini.world"); + WorldMeshes ref; + ASSERT_TRUE(ExportWorldMeshes(w, /*visual=*/true, &ref).ok()); + size_t checked = 0; + for (const WorldMeshInstance& in : ref.instances) { + // Hop bao THE GIOI cua the hien theo bo doc world: tam giac he model + // (da ap ) -> yaw -> tinh tien. + const WorldMeshGeom& g = ref.geoms[in.geom]; + double rmn[3] = {1e18, 1e18, 1e18}, rmx[3] = {-1e18, -1e18, -1e18}; + const double c = std::cos(in.yaw), s = std::sin(in.yaw); + for (size_t k = 0; k + 2 < g.tri.size(); k += 3) { + const double p[3] = {g.tri[k] * c - g.tri[k + 1] * s + in.x, + g.tri[k] * s + g.tri[k + 1] * c + in.y, g.tri[k + 2] + in.z}; + for (int a = 0; a < 3; ++a) { rmn[a] = std::min(rmn[a], p[a]); rmx[a] = std::max(rmx[a], p[a]); } + } + // The hien tuong ung trong world (cung ten model, cung vi tri). + for (const WorldModel& m : w.models) { + if (m.model_name != g.model_name || std::fabs(m.x - in.x) > 1e-6 || + std::fabs(m.y - in.y) > 1e-6) { + continue; + } + double amn[3], amx[3]; + ASSERT_TRUE(AssimpModelBounds(m, amn, amx)) << m.name; + for (int a = 0; a < 3; ++a) { + EXPECT_NEAR(amn[a], rmn[a], 0.01) << m.name << " truc " << a; + EXPECT_NEAR(amx[a], rmx[a], 0.01) << m.name << " truc " << a; + } + checked++; + break; + } + } + EXPECT_GE(checked, 4u) << "phai kiem du OBJ met, OBJ cm, DAE matrix, DAE Y_UP"; +} + +TEST(SimGl, BoMoPhongCoAnhIrVaDepthKhopRaycastCpu) { + // Cung tu the tren world doc: mot sim ve bang GPU, mot sim raycast CPU. Tat + // nhieu depth de so thang. Hinh hoc CPU la 2.5D (tuong ep tu luoi) nen chi + // so TRUNG VI -- san, mat doc va tuong phai khop toi vai cm. + auto make = [](bool gpu, std::string* why, CameraFrame* out) -> bool { + SimConfig c; + c.speed = 0.0; + c.world_path = WorldDir() + "/ramp.world"; + c.world_model_paths = {WorldDir() + "/models"}; + c.enable_depth_camera = true; + c.depth_disparity_noise_px = 0.0; + c.depth_noise_floor = 0.0; + c.camera_z = 0.445; + c.camera_x = 0.095; + c.camera_pitch = 0.0; + c.wheel_radius = 0.0865; + c.start_x = -1.5; + SimSource sim(c); + if (!sim.Open().ok()) { *why = "sim khong mo duoc"; return false; } + if (gpu) { + auto r = MakeRenderer(sim.world(), why); + if (!r) return false; + sim.SetCameraRenderer(r); + } + bool have = false; + sim.camera()->SetCallback([&](const CameraFrame& f) { *out = f; have = true; }); + sim.camera()->Open(); + sim.RunFor(0.1); + if (!have) *why = "khong co khung camera"; + return have; + }; + std::string why; + CameraFrame gpu, cpu; + if (!make(true, &why, &gpu)) GTEST_SKIP() << why; + ASSERT_TRUE(make(false, &why, &cpu)) << why; + + ASSERT_TRUE(gpu.infra1 != nullptr) << "renderer GPU phai cho anh IR"; + EXPECT_TRUE(cpu.infra1 == nullptr) << "raycast CPU khong co anh IR"; + ASSERT_EQ(gpu.infra1->width, gpu.depth->width); + ASSERT_EQ(gpu.infra1->height, gpu.depth->height); + + const size_t n = static_cast(gpu.depth->width) * gpu.depth->height; + std::vector diff; + for (size_t i = 0; i < n; ++i) { + const uint16_t a = static_cast(gpu.depth->data[2 * i] | (gpu.depth->data[2 * i + 1] << 8)); + const uint16_t b = static_cast(cpu.depth->data[2 * i] | (cpu.depth->data[2 * i + 1] << 8)); + if (a == 0 || b == 0) continue; + diff.push_back(std::fabs(static_cast(a) - b) * 0.001); + } + ASSERT_GT(diff.size(), n / 4) << "qua it diem co depth o ca hai"; + std::nth_element(diff.begin(), diff.begin() + diff.size() / 2, diff.end()); + EXPECT_LT(diff[diff.size() / 2], 0.02) << "trung vi |depth GPU - depth CPU|"; +} diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index dfe7fbe..fbf93ce 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -57,6 +57,16 @@ if(VSLAM_BUILD_SLAM) endif() endif() +# vslam_render_preview: ve MOT khung camera mo phong bang GPU ra PNG, de nhin +# texture/depth truoc khi tin. Chi khi co lib tuy chon vslam_sim_gl. +if(TARGET vslam_sim_gl) + find_package(OpenCV REQUIRED COMPONENTS core imgproc imgcodecs) + add_executable(vslam_render_preview vslam_render_preview.cc) + target_include_directories(vslam_render_preview SYSTEM PRIVATE ${OpenCV_INCLUDE_DIRS}) + target_link_libraries(vslam_render_preview + PRIVATE vslam_sim_gl vslam_sim vslam_common ${OpenCV_LIBS}) +endif() + # vslam_record: ghi .vsr tu bo mo phong theo kich ban co ten. Hat giong co # dinh => cung kich ban cho cung file, byte giong byte -- dieu kien de # regress.sh so ket qua duoc. diff --git a/tools/vslam_render_preview.cc b/tools/vslam_render_preview.cc new file mode 100644 index 0000000..a98eecf --- /dev/null +++ b/tools/vslam_render_preview.cc @@ -0,0 +1,127 @@ +// vslam_render_preview -- ve MOT khung camera mo phong bang GPU ra file PNG. +// +// vslam_render_preview --world W.world [--models DIR]... --x X --y Y --yaw R +// [--z 0.445] [--pitch 0] [--w 640] [--h 480] +// [--hfov-deg 69 | --fx F] --out PREFIX +// +// Ra: PREFIX_ir.png (anh xam 8 bit), PREFIX_depth.png (16 bit, mm -- dung +// quy uoc RealSense), PREFIX_depth_vis.png (to mau de nhin). In GPU dang dung, +// ti le diem co depth, do sang/do tuong phan anh IR. +// +// Dung de NHIN truoc khi tin: texture co len khong, depth co khop hinh khong, +// camera co dung huong khong. `--z` la do cao camera so voi z = 0 cua world +// (cong them san neu dung tren san cao). `--pitch` duong = chuc xuong. + +#include +#include +#include +#include +#include + +#include +#include + +#include "vslam/gazebo_world.h" +#include "vslam/sim_gl_renderer.h" + +int main(int argc, char** argv) { + std::string world, out; + std::vector models; + double x = 0, y = 0, z = 0.445, yaw = 0, pitch = 0, hfov_deg = 69.0, fx = 0; + int w = 640, h = 480; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : ""; }; + if (a == "--world") world = next(); + else if (a == "--models") models.push_back(next()); + else if (a == "--x") x = std::atof(next().c_str()); + else if (a == "--y") y = std::atof(next().c_str()); + else if (a == "--z") z = std::atof(next().c_str()); + else if (a == "--yaw") yaw = std::atof(next().c_str()); + else if (a == "--pitch") pitch = std::atof(next().c_str()); + else if (a == "--w") w = std::atoi(next().c_str()); + else if (a == "--h") h = std::atoi(next().c_str()); + else if (a == "--hfov-deg") hfov_deg = std::atof(next().c_str()); + else if (a == "--fx") fx = std::atof(next().c_str()); + else if (a == "--out") out = next(); + else { + std::fprintf(stderr, "tham so la: %s (xem dau file)\n", a.c_str()); + return 2; + } + } + if (world.empty() || out.empty()) { + std::fprintf(stderr, "can --world va --out\n"); + return 2; + } + + vslam::GazeboWorld gw; + vslam::StatusResponse st = vslam::LoadGazeboWorld(world, models, &gw); + if (!st.ok()) { + std::fprintf(stderr, "world: %s\n", st.message.c_str()); + return 1; + } + std::string err; + auto r = vslam::CreateGlCameraRenderer(gw, vslam::DefaultGlRendererConfig(), &err); + if (!r) { + std::fprintf(stderr, "renderer: %s\n", err.c_str()); + return 1; + } + + // Than: Rz(yaw) * Ry(pitch). Quang hoc: X = -Y than, Y = -Z than, Z = X than. + const double cy = std::cos(yaw), sy = std::sin(yaw), cp = std::cos(pitch), sp = std::sin(pitch); + const double fwd[3] = {cy * cp, sy * cp, -sp}; + const double left[3] = {-sy, cy, 0.0}; + const double up[3] = {cy * sp, sy * sp, cp}; + vslam::SimCameraView v; + for (int i = 0; i < 3; ++i) { + v.R_wc[i * 3 + 0] = -left[i]; + v.R_wc[i * 3 + 1] = -up[i]; + v.R_wc[i * 3 + 2] = fwd[i]; + } + v.t_wc[0] = x; + v.t_wc[1] = y; + v.t_wc[2] = z; + v.width = w; + v.height = h; + v.fx = fx > 0 ? fx : (w / 2.0) / std::tan(hfov_deg * M_PI / 360.0); + v.fy = v.fx; + v.cx = w / 2.0; + v.cy = h / 2.0; + + std::vector ir; + std::vector depth; + if (!r->Render(v, &ir, &depth)) { + std::fprintf(stderr, "ve hong (xem log)\n"); + return 1; + } + + cv::Mat im_ir(h, w, CV_8UC1, ir.data()); + cv::Mat im_d(h, w, CV_16UC1); + size_t valid = 0; + double dmin = 1e9, dmax = 0; + for (int rr = 0; rr < h; ++rr) { + for (int c = 0; c < w; ++c) { + const float d = depth[static_cast(rr) * w + c]; + im_d.at(rr, c) = d > 0 ? static_cast(std::min(65535.0f, d * 1000.0f)) : 0; + if (d > 0) { valid++; dmin = std::min(dmin, d); dmax = std::max(dmax, d); } + } + } + cv::Mat vis8, vis; + im_d.convertTo(vis8, CV_8UC1, 255.0 / std::max(1.0, dmax * 1000.0)); + cv::applyColorMap(vis8, vis, cv::COLORMAP_JET); + vis.setTo(cv::Scalar(0, 0, 0), im_d == 0); + cv::imwrite(out + "_ir.png", im_ir); + cv::imwrite(out + "_depth.png", im_d); + cv::imwrite(out + "_depth_vis.png", vis); + + cv::Scalar mean, sd; + cv::meanStdDev(im_ir, mean, sd, im_d > 0); + std::printf("%s\n", r->Describe().c_str()); + std::printf("depth: %.1f%% diem co gia tri, %.3f..%.3f m | IR (vung co depth): " + "trung binh %.1f, do lech %.1f\n", + 100.0 * valid / (static_cast(w) * h), valid ? dmin : 0.0, dmax, + mean[0], sd[0]); + std::printf("ghi %s_ir.png, %s_depth.png, %s_depth_vis.png\n", out.c_str(), out.c_str(), + out.c_str()); + return 0; +}