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
This commit is contained in:
704
libs/vslam_sim_gl/src/sim_gl_renderer.cc
Normal file
704
libs/vslam_sim_gl/src/sim_gl_renderer.cc
Normal file
@@ -0,0 +1,704 @@
|
||||
#include "vslam/sim_gl_renderer.h"
|
||||
|
||||
#include <EGL/egl.h>
|
||||
#include <EGL/eglext.h>
|
||||
#include <GLES3/gl3.h>
|
||||
|
||||
#include <assimp/Importer.hpp>
|
||||
#include <assimp/config.h>
|
||||
#include <assimp/postprocess.h>
|
||||
#include <assimp/scene.h>
|
||||
|
||||
#include <opencv2/imgcodecs.hpp>
|
||||
#include <opencv2/imgproc.hpp>
|
||||
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#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<uint8_t> rgba; // hang DUOI cung truoc -- quy uoc texture GL
|
||||
};
|
||||
|
||||
struct CpuMesh {
|
||||
std::vector<float> v; // moi dinh: x y z nx ny nz u v, he WORLD
|
||||
std::vector<uint32_t> 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<std::string, int>* cache,
|
||||
std::vector<CpuTexture>* 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<double>(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<int>(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 `<scale>` -> yaw -> tinh tien.
|
||||
// `meshes`/`textures` co the null (chi lay hop bao).
|
||||
bool LoadModel(const WorldModel& m, const GlRendererConfig* cfg,
|
||||
std::map<std::string, int>* tex_cache, std::vector<CpuTexture>* textures,
|
||||
std::vector<CpuMesh>* 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 <up_axis> 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 <unit> 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<size_t>(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<float>(wx), static_cast<float>(wy),
|
||||
static_cast<float>(wz), static_cast<float>(nx),
|
||||
static_cast<float>(ny), static_cast<float>(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<CpuMesh> meshes, std::vector<CpuTexture> 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<GLsizei>(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<uint8_t>* ir,
|
||||
std::vector<float>* 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<float>(view.t_wc[0]),
|
||||
static_cast<float>(view.t_wc[1]), static_cast<float>(view.t_wc[2]));
|
||||
glUniform1f(loc_amb_, static_cast<float>(cfg_.ambient));
|
||||
glUniform1f(loc_head_, static_cast<float>(cfg_.headlight));
|
||||
glUniform1f(loc_triscale_, static_cast<float>(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<size_t>(g.tex)]);
|
||||
glBindVertexArray(g.vao);
|
||||
glDrawElements(GL_TRIANGLES, g.count, GL_UNSIGNED_INT, nullptr);
|
||||
}
|
||||
glBindVertexArray(0);
|
||||
|
||||
rgba_.resize(static_cast<size_t>(w) * h * 4);
|
||||
rgbaf_.resize(static_cast<size_t>(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<size_t>(w) * h);
|
||||
depth_z->resize(static_cast<size_t>(w) * h);
|
||||
for (int r = 0; r < h; ++r) {
|
||||
const size_t src = static_cast<size_t>(h - 1 - r) * w;
|
||||
const size_t dst = static_cast<size_t>(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<PFNEGLQUERYDEVICESEXTPROC>(eglGetProcAddress("eglQueryDevicesEXT"));
|
||||
auto get_display = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(
|
||||
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<const char*>(glGetString(GL_RENDERER));
|
||||
const char* ext = reinterpret_cast<const char*>(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<const char*>(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<GLsizei>(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<GLsizei>(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<GLsizeiptr>(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<GLsizeiptr>(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<const void*>(3 * sizeof(float)));
|
||||
glEnableVertexAttribArray(2);
|
||||
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, stride,
|
||||
reinterpret_cast<const void*>(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<float>(2.0 * v.fx / W);
|
||||
P->m[5] = static_cast<float>(2.0 * v.fy / H);
|
||||
P->m[8] = static_cast<float>(1.0 - 2.0 * cx / W);
|
||||
P->m[9] = static_cast<float>(2.0 * cy / H - 1.0);
|
||||
P->m[10] = static_cast<float>(-(f + n) / (f - n));
|
||||
P->m[11] = -1.0f;
|
||||
P->m[14] = static_cast<float>(-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<float>(R[i * 3 + j]);
|
||||
V->m[12 + i] = static_cast<float>(t[i]);
|
||||
}
|
||||
V->m[15] = 1.0f;
|
||||
}
|
||||
|
||||
std::vector<CpuMesh> meshes_;
|
||||
std::vector<CpuTexture> 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> gpu_;
|
||||
std::vector<GLuint> gl_tex_;
|
||||
GLuint fbo_ = 0, rb_ir_ = 0, rb_depth_ = 0, rb_z_ = 0;
|
||||
int fbo_w_ = 0, fbo_h_ = 0;
|
||||
std::vector<uint8_t> rgba_;
|
||||
std::vector<float> 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<SimCameraRenderer> CreateGlCameraRenderer(const GazeboWorld& world,
|
||||
const GlRendererConfig& cfg,
|
||||
std::string* error) {
|
||||
std::vector<CpuMesh> meshes;
|
||||
std::vector<CpuTexture> textures;
|
||||
std::map<std::string, int> 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<GlCameraRenderer>(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
|
||||
Reference in New Issue
Block a user