Files
vslam_cpp/libs/vslam_sim/src/gazebo_world.cc

1089 lines
42 KiB
C++

#include "vslam/gazebo_world.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <functional>
#include <limits>
#include <vector>
#include <fstream>
#include <map>
#include <sstream>
#include <sys/stat.h>
#include <yaml-cpp/yaml.h>
#include "vslam/log.h"
namespace vslam {
namespace {
bool FileExists(const std::string& p) {
struct stat st;
return !p.empty() && ::stat(p.c_str(), &st) == 0 && S_ISREG(st.st_mode);
}
bool DirExists(const std::string& p) {
struct stat st;
return !p.empty() && ::stat(p.c_str(), &st) == 0 && S_ISDIR(st.st_mode);
}
std::string ReadFile(const std::string& p) {
std::ifstream f(p);
if (!f) return "";
std::ostringstream o;
o << f.rdbuf();
return o.str();
}
// Lay noi dung cua the <tag> DAU TIEN tu vi tri `from`. Tra chuoi rong neu
// khong co. `end_out` nhan vi tri ngay sau the dong.
//
// Du cho cau truc rat deu cua SDF; khong nham lam mot parser XML tong quat.
std::string Tag(const std::string& s, const std::string& tag, size_t from,
size_t* end_out = nullptr) {
const std::string open = "<" + tag + ">";
const std::string close = "</" + tag + ">";
const size_t a = s.find(open, from);
if (a == std::string::npos) return "";
const size_t b = s.find(close, a);
if (b == std::string::npos) return "";
if (end_out) *end_out = b + close.size();
return s.substr(a + open.size(), b - a - open.size());
}
std::string Trim(const std::string& s) {
const size_t a = s.find_first_not_of(" \t\r\n");
if (a == std::string::npos) return "";
const size_t b = s.find_last_not_of(" \t\r\n");
return s.substr(a, b - a + 1);
}
// "x y z roll pitch yaw" -> sau so. Thieu thi de 0.
void ParsePose(const std::string& s, WorldModel* m) {
std::istringstream in(s);
double v[6] = {0, 0, 0, 0, 0, 0};
for (int i = 0; i < 6 && (in >> v[i]); ++i) {}
m->x = v[0]; m->y = v[1]; m->z = v[2];
m->roll = v[3]; m->pitch = v[4]; m->yaw = v[5];
}
std::vector<std::string> DefaultModelPaths() {
std::vector<std::string> out;
if (const char* env = std::getenv("GAZEBO_MODEL_PATH")) {
std::string s(env), cur;
std::istringstream in(s);
while (std::getline(in, cur, ':')) if (!cur.empty()) out.push_back(cur);
}
if (const char* home = std::getenv("HOME")) {
// Cho mac dinh cua Gazebo, va cho ma repo nay that su de model.
out.push_back(std::string(home) + "/.gazebo/models");
out.push_back(std::string(home) + "/gazebo_models/aws_hospital_fuel");
out.push_back(std::string(home) + "/gazebo_models/aws_hospital");
}
return out;
}
// `model://Ten` hoac `model://Ten/meshes/x.obj` -> duong dan tuyet doi.
std::string ResolveModelUri(const std::string& uri,
const std::vector<std::string>& roots,
std::string* root_used) {
const std::string prefix = "model://";
if (uri.compare(0, prefix.size(), prefix) != 0) return "";
const std::string rel = uri.substr(prefix.size());
for (const std::string& r : roots) {
const std::string p = r + "/" + rel;
if (FileExists(p) || DirExists(p)) {
if (root_used) *root_used = r;
return p;
}
}
return "";
}
} // namespace
StatusResponse LoadGazeboWorld(const std::string& world_path,
const std::vector<std::string>& model_paths,
GazeboWorld* out, size_t* skipped) {
const std::string src = ReadFile(world_path);
if (src.empty()) {
return StatusResponse::Error(
StatusCode::kNotFound,
"khong doc duoc file world: " + world_path);
}
std::vector<std::string> roots = model_paths;
if (roots.empty()) roots = DefaultModelPaths();
// Bo cac thu muc khong ton tai -- de thong bao loi ben duoi khong liet ke
// mot dong duong dan vo nghia.
roots.erase(std::remove_if(roots.begin(), roots.end(),
[](const std::string& p) { return !DirExists(p); }),
roots.end());
if (roots.empty()) {
return StatusResponse::Error(
StatusCode::kNotFound,
"khong tim thay thu muc model nao. Dat GAZEBO_MODEL_PATH, hoac de "
"model o ~/.gazebo/models.");
}
out->world_path = world_path;
out->models.clear();
size_t skip = 0;
// Quet tung the <model name="...">.
size_t pos = 0;
const std::string kModelOpen = "<model name=";
while ((pos = src.find(kModelOpen, pos)) != std::string::npos) {
const size_t name_a = src.find('"', pos);
const size_t name_b = name_a == std::string::npos
? std::string::npos : src.find('"', name_a + 1);
if (name_b == std::string::npos) break;
WorldModel m;
m.name = src.substr(name_a + 1, name_b - name_a - 1);
// Khoi cua model nay ket thuc o </model> gan nhat.
const size_t block_end = src.find("</model>", name_b);
if (block_end == std::string::npos) break;
const std::string block = src.substr(name_b, block_end - name_b);
const std::string uri = Trim(Tag(block, "uri", 0));
ParsePose(Tag(block, "pose", 0), &m);
pos = block_end + 8;
if (uri.empty()) { skip++; continue; }
m.model_name = uri.substr(uri.rfind('/') + 1);
m.terrain = m.model_name.rfind(kTerrainModelPrefix, 0) == 0;
std::string root;
const std::string dir = ResolveModelUri(uri, roots, &root);
if (dir.empty()) {
// `ground_plane` va `sun` la built-in cua Gazebo, khong co tren dia.
// Bo qua chung la DUNG, khong phai loi.
skip++;
continue;
}
if (std::find(out->model_roots.begin(), out->model_roots.end(), root) ==
out->model_roots.end()) {
out->model_roots.push_back(root);
}
// model.sdf tro toi mesh. Lay ca visual lan collision: chung thuong la
// cung mot file, nhung khi khac nhau thi collision la ban da giam da
// giac -- dung cai do de raster hoa se nhanh hon nhieu.
const std::string sdf = ReadFile(dir + "/model.sdf");
if (!sdf.empty()) {
size_t vp = sdf.find("<visual");
if (vp != std::string::npos) {
const std::string u = Trim(Tag(sdf, "uri", vp));
m.visual_obj = ResolveModelUri(u, roots, nullptr);
}
size_t cp = sdf.find("<collision");
if (cp != std::string::npos) {
const std::string u = Trim(Tag(sdf, "uri", cp));
m.collision_obj = ResolveModelUri(u, roots, nullptr);
}
// `<scale>` nam trong khoi <mesh>. Lay cua collision truoc, khong co
// thi cua visual -- hai cai hau nhu luon giong nhau.
{
size_t sp = (cp != std::string::npos) ? cp : vp;
if (sp != std::string::npos) {
const std::string sc = Trim(Tag(sdf, "scale", sp));
std::istringstream in(sc);
double v[3] = {1, 1, 1};
int n = 0;
while (n < 3 && (in >> v[n])) n++;
if (n == 3) { m.sx = v[0]; m.sy = v[1]; m.sz = v[2]; }
else if (n == 1) { m.sx = m.sy = m.sz = v[0]; }
}
}
}
// Khong co collision rieng thi dung visual -- van tot hon la bo qua han
// mot buc tuong.
if (m.collision_obj.empty()) m.collision_obj = m.visual_obj;
if (m.visual_obj.empty()) m.visual_obj = m.collision_obj;
// ⚠️ File world nay co san pose HONG.
//
// `StorageRack_1` mang `<pose>9.07 -10.36 -7.57769e+08 ...>`: mot vat da
// roi xuyen san trong mot phien Gazebo nao do roi world duoc luu lai.
// Gazebo cung khong hien chung -- chung o cach mat dat 757 nghin km.
//
// Khong loc thi luoi van dung (tam giac roi ngoai dai z) nhung khung 3D
// cap phat instance cho vat khong bao gio thay duoc, va moi phep tinh bao
// loi deu vo nghia.
if (std::fabs(m.x) > 1000.0 || std::fabs(m.y) > 1000.0 ||
std::fabs(m.z) > 1000.0) {
VSLAM_WARN("world: bo model " << m.name << " -- pose vo ly ("
<< m.x << ", " << m.y << ", " << m.z << ")");
skip++;
continue;
}
out->models.push_back(std::move(m));
}
if (skipped) *skipped = skip;
VSLAM_INFO("world " << world_path << ": " << out->models.size()
<< " model phan giai duoc"
<< (skip ? ", bo qua " + std::to_string(skip) +
" (ground_plane/sun la built-in)"
: ""));
if (out->models.empty()) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
world_path + ": khong phan giai duoc model nao");
}
return StatusResponse::Ok();
}
// ---------------------------------------------------------------------------
// Raster hoa
// ---------------------------------------------------------------------------
namespace {
struct Tri { double x[3], y[3], z[3]; };
// Ma tran 4x4 hang-chinh, chi dung cho phep bien doi affine cua COLLADA.
struct Mat4 {
double m[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
};
Mat4 MatMul(const Mat4& a, const Mat4& b) {
Mat4 r;
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j) {
double s = 0;
for (int k = 0; k < 4; ++k) s += a.m[i * 4 + k] * b.m[k * 4 + j];
r.m[i * 4 + j] = s;
}
return r;
}
void MatApply(const Mat4& t, double* x, double* y, double* z) {
const double px = *x, py = *y, pz = *z;
*x = t.m[0] * px + t.m[1] * py + t.m[2] * pz + t.m[3];
*y = t.m[4] * px + t.m[5] * py + t.m[6] * pz + t.m[7];
*z = t.m[8] * px + t.m[9] * py + t.m[10] * pz + t.m[11];
}
Mat4 MakeTranslate(double x, double y, double z) {
Mat4 t;
t.m[3] = x; t.m[7] = y; t.m[11] = z;
return t;
}
// Quay quanh truc (ax,ay,az) mot goc `deg` DO -- COLLADA dung do, khong radian.
Mat4 MakeRotate(double ax, double ay, double az, double deg) {
const double n = std::sqrt(ax * ax + ay * ay + az * az);
Mat4 t;
if (n < 1e-12) return t;
ax /= n; ay /= n; az /= n;
const double a = deg * M_PI / 180.0, c = std::cos(a), s = std::sin(a), k = 1 - c;
t.m[0] = c + ax*ax*k; t.m[1] = ax*ay*k - az*s; t.m[2] = ax*az*k + ay*s;
t.m[4] = ay*ax*k + az*s; t.m[5] = c + ay*ay*k; t.m[6] = ay*az*k - ax*s;
t.m[8] = az*ax*k - ay*s; t.m[9] = az*ay*k + ax*s; t.m[10] = c + az*az*k;
return t;
}
Mat4 MakeScale(double x, double y, double z) {
Mat4 t;
t.m[0] = x; t.m[5] = y; t.m[10] = z;
return t;
}
std::vector<double> ParseFloats(const std::string& s) {
std::vector<double> v;
std::istringstream in(s);
double d;
while (in >> d) v.push_back(d);
return v;
}
// Lay gia tri thuoc tinh `attr` cua the bat dau tai `tag_pos`.
std::string Attr(const std::string& s, size_t tag_pos, const std::string& attr) {
const size_t end = s.find('>', tag_pos);
if (end == std::string::npos) return "";
const size_t a = s.find(attr + "=\"", tag_pos);
if (a == std::string::npos || a > end) return "";
const size_t b = a + attr.size() + 2;
const size_t c = s.find('"', b);
if (c == std::string::npos) return "";
return s.substr(b, c - b);
}
// Doc tam giac tu file COLLADA (.dae).
//
// ⚠️ QUY UOC NAM TRONG TUNG FILE, KHONG PHAI TOAN CUC.
//
// Cac mesh `.obj` cua bo model nay la Z-UP, don vi MET. Nhung `.dae` cua
// tuong/san lai la:
// <unit meter="0.01" name="centimeter"/>
// <up_axis>Y_UP</up_axis>
// Ap mot quy uoc chung cho ca hai lam luoi ra la RAC ma van "trong nhu co du
// lieu": da do mot lan ra luoi 5235x5942 o (262 x 297 m) cho mot toa nha chi
// rong 25 x 51 m.
//
// Ho tro tap con thuc su xuat hien trong bo model AWS: <polylist> va
// <triangles>, input co offset, va phep bien doi cua <node> (translate /
// rotate truc-goc theo DO / scale).
// So duoi file KHONG phan biet hoa thuong.
//
// ⚠️ Bo model nay tron ca `.dae` lan `.DAE`: 15 model `aws_robomaker_
// residential_*` va `warehouse_*` dung chu hoa. So phan biet hoa thuong lam
// chung roi vao bo doc OBJ va HONG IM LANG -- khong loi, khong canh bao, chi
// la sofa/tu lanh/tranh tuong bien mat khoi ca khung 3D LAN luoi chiem dung.
bool IsDae(const std::string& p) {
if (p.size() < 4) return false;
const std::string e = p.substr(p.size() - 4);
return (e[0] == '.') && (e[1] == 'd' || e[1] == 'D') &&
(e[2] == 'a' || e[2] == 'A') && (e[3] == 'e' || e[3] == 'E');
}
bool ReadDaeTriangles(const std::string& path, std::vector<Tri>* out) {
const std::string s = ReadFile(path);
if (s.empty()) return false;
// --- don vi va truc len ---
double unit = 1.0;
{
const size_t u = s.find("<unit");
if (u != std::string::npos) {
const std::string v = Attr(s, u, "meter");
if (!v.empty()) unit = std::atof(v.c_str());
}
}
// --- source id -> mang float ---
std::map<std::string, std::vector<double>> sources;
for (size_t p = 0; (p = s.find("<source", p)) != std::string::npos;) {
const std::string id = Attr(s, p, "id");
size_t fa = s.find("<float_array", p);
const size_t next_src = s.find("<source", p + 1);
if (fa != std::string::npos && (next_src == std::string::npos || fa < next_src)) {
const size_t open_end = s.find('>', fa);
const size_t close = s.find("</float_array>", open_end);
if (open_end != std::string::npos && close != std::string::npos && !id.empty()) {
sources[id] = ParseFloats(s.substr(open_end + 1, close - open_end - 1));
}
}
p += 7;
}
// --- vertices id -> source id cua POSITION ---
std::map<std::string, std::string> vert_to_src;
for (size_t p = 0; (p = s.find("<vertices", p)) != std::string::npos;) {
const std::string id = Attr(s, p, "id");
const size_t in = s.find("<input", p);
const size_t close = s.find("</vertices>", p);
if (in != std::string::npos && close != std::string::npos && in < close) {
std::string src = Attr(s, in, "source");
if (!src.empty() && src[0] == '#') src.erase(0, 1);
if (!id.empty()) vert_to_src[id] = src;
}
p += 9;
}
// --- phep bien doi cua node, theo id geometry duoc instance ben trong ---
std::map<std::string, Mat4> geom_xform;
for (size_t p = 0; (p = s.find("<node", p)) != std::string::npos;) {
const size_t node_end = s.find("</node>", p);
const size_t limit = node_end == std::string::npos ? s.size() : node_end;
Mat4 t;
// Thu tu ap la thu tu XUAT HIEN trong file -- COLLADA quy dinh vay.
//
// ⚠️ `<matrix>` KHONG the bo qua. Bo model nay co hai ho file: ho xuat tu
// Blender dung translate/rotate/scale, ho xuat tu 3ds Max dung MOT the
// `<matrix>`. Bo qua the do lam ti le sai tu 10x den 100x ma khong mot
// canh bao nao -- da do sofa ra 24.4 m va buc tranh ra 5 cm, ca hai trong
// file khai `<unit meter="0.01">` y het cac file dung.
for (size_t q = p; q < limit;) {
const size_t tr = s.find("<translate", q), ro = s.find("<rotate", q),
sc = s.find("<scale", q), mx = s.find("<matrix", q);
size_t nxt = std::min({tr == std::string::npos ? limit : tr,
ro == std::string::npos ? limit : ro,
sc == std::string::npos ? limit : sc,
mx == std::string::npos ? limit : mx});
if (nxt >= limit) break;
const size_t oe = s.find('>', nxt), ce = s.find('<', oe + 1);
const std::vector<double> v = ParseFloats(s.substr(oe + 1, ce - oe - 1));
if (nxt == tr && v.size() >= 3) t = MatMul(t, MakeTranslate(v[0], v[1], v[2]));
else if (nxt == ro && v.size() >= 4) t = MatMul(t, MakeRotate(v[0], v[1], v[2], v[3]));
else if (nxt == sc && v.size() >= 3) t = MatMul(t, MakeScale(v[0], v[1], v[2]));
else if (nxt == mx && v.size() >= 16) {
// COLLADA ghi ma tran theo HANG, cung quy uoc voi Mat4 o day.
Mat4 mm;
for (int i = 0; i < 16; ++i) mm.m[i] = v[static_cast<size_t>(i)];
t = MatMul(t, mm);
}
q = ce;
}
for (size_t g = p; (g = s.find("<instance_geometry", g)) != std::string::npos &&
g < limit;) {
std::string url = Attr(s, g, "url");
if (!url.empty() && url[0] == '#') url.erase(0, 1);
if (!url.empty()) geom_xform[url] = t;
g += 18;
}
p += 5;
}
// --- geometry -> tam giac ---
size_t before = out->size();
for (size_t p = 0; (p = s.find("<geometry", p)) != std::string::npos;) {
const std::string gid = Attr(s, p, "id");
const size_t gend = s.find("</geometry>", p);
const size_t limit = gend == std::string::npos ? s.size() : gend;
Mat4 xf;
auto it = geom_xform.find(gid);
if (it != geom_xform.end()) xf = it->second;
// ⚠️ `<up_axis>` cua bo model nay PHAI BI BO QUA.
//
// Moi file deu khai `<up_axis>Y_UP`, nhung do la noi ve he toa do cua bo
// XUAT, khong phai cua du lieu trong file. Bo xuat nay da nuong phep doi
// truc vao node goc, va chi nuong KHI CAN:
//
// walls_collision ID3 : dinh (56.12, 3.00, 25.12) -- Y-up that
// node co `0 1 0 90` + `0 0 1 -270` de doi truc
// walls_visual ID43: dinh (25.12, 56.12, 3.00) -- DA la Z-up
// node RONG, khong can doi gi
//
// Cung mot buc tuong, hai file, hai cach. Ap them `<up_axis>` lam cai thu
// hai bi lat: buc tuong 3 m thanh mot thanh DUNG DUNG cao 56 m giua san.
//
// Tung thu doan theo ma tran node ("node don vi thi lat") -- sai chinh o
// ID43. Node don vi o day nghia la "khong can doi", khong phai "chua doi".
for (size_t q = p; q < limit;) {
const size_t pl = s.find("<polylist", q), trg = s.find("<triangles", q);
size_t prim = std::min(pl == std::string::npos ? limit : pl,
trg == std::string::npos ? limit : trg);
if (prim >= limit) break;
const bool is_poly = (prim == pl);
const size_t pend = s.find(is_poly ? "</polylist>" : "</triangles>", prim);
if (pend == std::string::npos) break;
// Tim input VERTEX va stride (offset lon nhat + 1).
int vert_off = -1, stride = 1;
std::string vsrc;
for (size_t i = prim; (i = s.find("<input", i)) != std::string::npos && i < pend;) {
const std::string off = Attr(s, i, "offset");
if (!off.empty()) stride = std::max(stride, std::atoi(off.c_str()) + 1);
if (Attr(s, i, "semantic") == "VERTEX") {
vert_off = off.empty() ? 0 : std::atoi(off.c_str());
vsrc = Attr(s, i, "source");
if (!vsrc.empty() && vsrc[0] == '#') vsrc.erase(0, 1);
}
i += 6;
}
if (vert_off < 0) { q = pend; continue; }
auto vt = vert_to_src.find(vsrc);
const std::string psrc = vt != vert_to_src.end() ? vt->second : vsrc;
auto ps = sources.find(psrc);
if (ps == sources.end()) { q = pend; continue; }
const std::vector<double>& pos = ps->second;
std::vector<double> vcount;
if (is_poly) {
const size_t vc = s.find("<vcount>", prim);
if (vc != std::string::npos && vc < pend) {
const size_t e = s.find("</vcount>", vc);
vcount = ParseFloats(s.substr(vc + 8, e - vc - 8));
}
}
const size_t pp = s.find("<p>", prim);
if (pp == std::string::npos || pp > pend) { q = pend; continue; }
const size_t pe = s.find("</p>", pp);
const std::vector<double> idx = ParseFloats(s.substr(pp + 3, pe - pp - 3));
auto vertex = [&](size_t n, double* x, double* y, double* z) {
const size_t vi = static_cast<size_t>(idx[n * stride + vert_off]) * 3;
if (vi + 2 >= pos.size()) return false;
// ⚠️ THU TU: ap ma tran node TRUOC, roi moi doi don vi.
//
// `<translate>` cua node nam trong CUNG don vi cua file (o day la
// centimet). Nhan `unit` vao dinh truoc roi ap mot translate tinh
// bang cm se coi 5000 cm thanh 5000 MET -- da do mot lan ra luoi
// 263 x 146 m cho mot toa nha 25 x 51 m.
double px = pos[vi], py = pos[vi + 1], pz = pos[vi + 2];
MatApply(xf, &px, &py, &pz);
px *= unit; py *= unit; pz *= unit;
// Y_UP -> Z_UP cua ROS: (x, y, z)_dae -> (x, -z, y)
*x = px; *y = py; *z = pz;
return true;
};
const size_t nvert = stride > 0 ? idx.size() / stride : 0;
if (is_poly && !vcount.empty()) {
size_t base = 0;
for (double cd : vcount) {
const size_t c = static_cast<size_t>(cd);
for (size_t k = 2; k < c && base + k < nvert; ++k) {
Tri t;
bool ok = vertex(base, &t.x[0], &t.y[0], &t.z[0]) &&
vertex(base + k - 1, &t.x[1], &t.y[1], &t.z[1]) &&
vertex(base + k, &t.x[2], &t.y[2], &t.z[2]);
if (ok) out->push_back(t);
}
base += c;
}
} else {
for (size_t k = 0; k + 2 < nvert; k += 3) {
Tri t;
bool ok = vertex(k, &t.x[0], &t.y[0], &t.z[0]) &&
vertex(k + 1, &t.x[1], &t.y[1], &t.z[1]) &&
vertex(k + 2, &t.x[2], &t.y[2], &t.z[2]);
if (ok) out->push_back(t);
}
}
q = pend;
}
p = limit;
}
return out->size() > before;
}
// Doc tam giac tu file OBJ. Chi can `v` va `f`; bo qua vt/vn/usemtl.
//
// OBJ danh chi so tu 1 va cho phep chi so AM (tinh nguoc tu cuoi). Bo qua
// chi so am se lam mot so mesh mat mat -- xu ly ca hai.
bool ReadObjTriangles(const std::string& path, std::vector<Tri>* out) {
std::ifstream f(path);
if (!f) return false;
std::vector<std::array<double, 3>> v;
std::string line;
while (std::getline(f, line)) {
if (line.size() < 2) continue;
if (line[0] == 'v' && line[1] == ' ') {
std::istringstream in(line.substr(2));
std::array<double, 3> p{0, 0, 0};
in >> p[0] >> p[1] >> p[2];
v.push_back(p);
} else if (line[0] == 'f' && line[1] == ' ') {
std::istringstream in(line.substr(2));
std::string tok;
std::vector<int> idx;
while (in >> tok) {
// "a", "a/b", "a//c", "a/b/c" -- chi lay phan truoc dau '/'.
const size_t slash = tok.find('/');
const std::string num = slash == std::string::npos ? tok : tok.substr(0, slash);
if (num.empty()) continue;
int i = std::atoi(num.c_str());
if (i > 0) i -= 1;
else if (i < 0) i = static_cast<int>(v.size()) + i;
else continue;
if (i >= 0 && i < static_cast<int>(v.size())) idx.push_back(i);
}
// Quat va n-giac: chia thanh quat tam giac.
for (size_t k = 2; k < idx.size(); ++k) {
Tri t;
const int a = idx[0], b = idx[k - 1], c = idx[k];
t.x[0] = v[a][0]; t.y[0] = v[a][1]; t.z[0] = v[a][2];
t.x[1] = v[b][0]; t.y[1] = v[b][1]; t.z[1] = v[b][2];
t.x[2] = v[c][0]; t.y[2] = v[c][1]; t.z[2] = v[c][2];
out->push_back(t);
}
}
}
return true;
}
} // namespace
StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
const WorldRasterOptions& opt,
OccupancyGrid* out) {
return RasterizeGazeboWorld(world, opt, out, nullptr);
}
StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
const WorldRasterOptions& opt,
OccupancyGrid* out, WorldTerrain* terrain) {
if (!(opt.resolution > 0.0)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"resolution phai duong");
}
// --- Luot 1: bao loi ---
double minx = 1e18, maxx = -1e18, miny = 1e18, maxy = -1e18;
size_t n_tri = 0, n_mesh = 0;
struct Loaded { const WorldModel* m; std::vector<Tri> tris; };
std::vector<Loaded> loaded;
loaded.reserve(world.models.size());
for (const WorldModel& m : world.models) {
if (m.collision_obj.empty()) continue;
Loaded L;
L.m = &m;
// Chon bo doc theo DUOI FILE: bo model nay tron ca .obj lan .dae, va moi
// dinh dang mang quy uoc rieng (xem ghi chu o ReadDaeTriangles).
const std::string& cp = m.collision_obj;
const bool ok = IsDae(cp) ? ReadDaeTriangles(cp, &L.tris)
: ReadObjTriangles(cp, &L.tris);
if (!ok) {
VSLAM_WARN("world: khong doc duoc mesh " << cp << " cua model "
<< m.model_name << " -- vat the nay VANG MAT khoi luoi");
continue;
}
if (L.tris.empty()) continue;
n_mesh++;
n_tri += L.tris.size();
const double cy = std::cos(m.yaw), sny = std::sin(m.yaw);
for (Tri& t : L.tris) {
for (int k = 0; k < 3; ++k) {
// Ti le TRUOC khi quay va tinh tien -- `<scale>` la cua mesh, khong
// phai cua the gioi.
t.x[k] *= m.sx; t.y[k] *= m.sy; t.z[k] *= m.sz;
// Bo doc da tra ve he ROS (Z-len, met) roi -- KHONG doi truc them o
// day. Quy uoc nam trong TUNG FILE (.obj Z-up met, .dae Y-up cm), va
// ap them mot phep doi chung se lam hong dung mot nua so mesh.
const double wx = t.x[k], wy = t.y[k], wz = t.z[k];
// Chi xet yaw: roll/pitch cua do dac dat tren san gan nhu luon 0, va
// xoay day du se lam ham nay dai gap doi ma khong doi ket qua.
const double rx = wx * cy - wy * sny;
const double ry = wx * sny + wy * cy;
t.x[k] = rx + m.x;
t.y[k] = ry + m.y;
t.z[k] = wz + m.z;
minx = std::min(minx, t.x[k]); maxx = std::max(maxx, t.x[k]);
miny = std::min(miny, t.y[k]); maxy = std::max(maxy, t.y[k]);
}
}
loaded.push_back(std::move(L));
}
if (loaded.empty()) {
return StatusResponse::Error(StatusCode::kNotFound,
"khong doc duoc mesh va cham nao tu world");
}
minx -= opt.pad; maxx += opt.pad;
miny -= opt.pad; maxy += opt.pad;
const double res = opt.resolution;
const uint32_t w = static_cast<uint32_t>(std::ceil((maxx - minx) / res));
const uint32_t h = static_cast<uint32_t>(std::ceil((maxy - miny) / res));
out->resolution = static_cast<float>(res);
out->width = w;
out->height = h;
out->origin = Pose{};
out->origin.position.x = minx;
out->origin.position.y = miny;
// Bat dau la TRONG, khong phai chua biet: the gioi nay do ta dung nen moi
// o deu da biet -- cai chua duoc quet la chuyen cua ban do SLAM.
out->data.assign(static_cast<size_t>(w) * h, 0);
// --- Luot 1.5: dia hinh -> do cao san ---
//
// Do cao mat tren tai TAM o, noi suy trong tam giac. Tam giac dung thang
// (suy bien tren mat bang) la mat ben cua doc/bac, khong dinh nghia san nen
// bo qua. Chong nhau thi lay CAO NHAT: mot hop kin co ca mat day lan mat tren.
const size_t n_cells = static_cast<size_t>(w) * h;
std::vector<float> ground(n_cells, 0.0f);
std::vector<uint8_t> covered(n_cells, 0);
size_t n_terrain_models = 0, n_terrain_cells = 0;
for (const Loaded& L : loaded) {
if (!L.m->terrain) continue;
n_terrain_models++;
for (const Tri& t : L.tris) {
const double ax = t.x[0], ay = t.y[0];
const double bx = t.x[1], by = t.y[1];
const double cx = t.x[2], cy = t.y[2];
const double den = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy);
if (std::fabs(den) < 1e-12) continue;
const int cx0 = std::max(0, static_cast<int>((std::min({ax, bx, cx}) - minx) / res));
const int cx1 = std::min(static_cast<int>(w) - 1,
static_cast<int>((std::max({ax, bx, cx}) - minx) / res));
const int cy0 = std::max(0, static_cast<int>((std::min({ay, by, cy}) - miny) / res));
const int cy1 = std::min(static_cast<int>(h) - 1,
static_cast<int>((std::max({ay, by, cy}) - miny) / res));
for (int gy = cy0; gy <= cy1; ++gy) {
for (int gx = cx0; gx <= cx1; ++gx) {
const double px = minx + (gx + 0.5) * res;
const double py = miny + (gy + 0.5) * res;
const double l1 = ((by - cy) * (px - cx) + (cx - bx) * (py - cy)) / den;
const double l2 = ((cy - ay) * (px - cx) + (ax - cx) * (py - cy)) / den;
const double l3 = 1.0 - l1 - l2;
if (l1 < -1e-9 || l2 < -1e-9 || l3 < -1e-9) continue;
const float z = static_cast<float>(l1 * t.z[0] + l2 * t.z[1] + l3 * t.z[2]);
const size_t idx = static_cast<size_t>(gy) * w + gx;
if (!covered[idx]) {
covered[idx] = 1;
ground[idx] = z;
n_terrain_cells++;
} else if (z > ground[idx]) {
ground[idx] = z;
}
}
}
}
}
// O khong co dia hinh la san 0, nen min/max luon tinh ca 0. World phang:
// fmin = fmax = 0 va luot 2 duoi day y het truoc.
float fmin = 0.0f, fmax = 0.0f;
for (float f : ground) { fmin = std::min(fmin, f); fmax = std::max(fmax, f); }
// --- Luot 2: to tam giac VAT CAN trong dai do cao, tinh tu san cuc bo ---
std::vector<float> top(n_cells, 0.0f);
size_t n_used = 0;
for (const Loaded& L : loaded) {
if (L.m->terrain) continue; // dia hinh la san, khong phai vat can
for (const Tri& t : L.tris) {
// Tam giac nam hoan toan ngoai dai thi bo. Cat dung tam giac la thua:
// mesh day dac nen mot tam giac bien bi bo van con hang xom phu.
//
// Day la phep loc THO theo dai cua ca ban do; dai dung cua tung o kiem
// ben duoi, theo san cua chinh o do.
const double tz0 = std::min({t.z[0], t.z[1], t.z[2]});
const double tz1 = std::max({t.z[0], t.z[1], t.z[2]});
if (tz1 < fmin + opt.z_min || tz0 > fmax + opt.z_max) continue;
n_used++;
// Bao loi cua tam giac, roi kiem tung o bang toa do trong tam.
const double bx0 = std::min({t.x[0], t.x[1], t.x[2]});
const double bx1 = std::max({t.x[0], t.x[1], t.x[2]});
const double by0 = std::min({t.y[0], t.y[1], t.y[2]});
const double by1 = std::max({t.y[0], t.y[1], t.y[2]});
const int cx0 = std::max(0, static_cast<int>((bx0 - minx) / res));
const int cx1 = std::min(static_cast<int>(w) - 1,
static_cast<int>((bx1 - minx) / res));
const int cy0 = std::max(0, static_cast<int>((by0 - miny) / res));
const int cy1 = std::min(static_cast<int>(h) - 1,
static_cast<int>((by1 - miny) / res));
const double ax = t.x[0], ay = t.y[0];
const double bx = t.x[1], by = t.y[1];
const double cx = t.x[2], cy = t.y[2];
const double den = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy);
const bool degenerate = std::fabs(den) < 1e-12;
for (int gy = cy0; gy <= cy1; ++gy) {
for (int gx = cx0; gx <= cx1; ++gx) {
const double px = minx + (gx + 0.5) * res;
const double py = miny + (gy + 0.5) * res;
bool inside;
if (degenerate) {
// Tam giac suy bien (canh rat mong) van phai to, neu khong mot
// buc tuong mong se thung lo.
inside = true;
} else {
const double l1 = ((by - cy) * (px - cx) + (cx - bx) * (py - cy)) / den;
const double l2 = ((cy - ay) * (px - cx) + (ax - cx) * (py - cy)) / den;
const double l3 = 1.0 - l1 - l2;
inside = l1 >= -1e-9 && l2 >= -1e-9 && l3 >= -1e-9;
}
if (inside) {
const size_t idx = static_cast<size_t>(gy) * w + gx;
// Dai z cua RIENG o nay. World phang: san 0, trung phep loc tho
// o tren nen khong bo them o nao.
const double f = ground[idx];
if (tz1 < f + opt.z_min || tz0 > f + opt.z_max) continue;
out->data[idx] = 100;
if (tz1 > top[idx]) top[idx] = static_cast<float>(tz1);
}
}
}
}
}
size_t occ = 0;
for (int8_t v : out->data) if (v >= 50) occ++;
VSLAM_INFO("world -> luoi: " << w << "x" << h << " @ " << res << " m/o, goc ("
<< minx << ", " << miny << "), " << n_mesh << " mesh, " << n_tri
<< " tam giac (" << n_used << " trong dai z ["
<< opt.z_min << ", " << opt.z_max << "]), " << occ << " o bi chiem");
if (n_terrain_models > 0) {
VSLAM_INFO("world -> dia hinh: " << n_terrain_models << " model, "
<< n_terrain_cells << " o, san tu " << fmin << " den " << fmax
<< " m; dai z cua vat can tinh tu san cuc bo");
}
if (terrain != nullptr) {
terrain->floor_z = std::move(ground);
terrain->wall_top = std::move(top);
terrain->terrain_cells = n_terrain_cells;
terrain->floor_min = fmin;
terrain->floor_max = fmax;
}
return StatusResponse::Ok();
}
// ---------------------------------------------------------------------------
StatusResponse BuildWorldSegments(const GazeboWorld& world,
const WorldRasterOptions& opt,
const OccupancyGrid& grid,
WorldSegments* out,
const std::vector<float>* floor_z) {
if (out == nullptr) {
return StatusResponse::Error(StatusCode::kInvalidArgument, "out == null");
}
out->seg.clear();
out->cell_items.clear();
out->cell_start.assign(static_cast<size_t>(grid.width) * grid.height + 1, 0);
out->width = grid.width;
out->height = grid.height;
out->resolution = grid.resolution;
out->origin_x = grid.origin.position.x;
out->origin_y = grid.origin.position.y;
const double res = grid.resolution;
const double ox = out->origin_x, oy = out->origin_y;
const int W = static_cast<int>(grid.width), H = static_cast<int>(grid.height);
// San cuc bo tai mot diem, de dai z truot theo dia hinh. Khong co ban do
// san thi la 0 -- y het truoc.
const bool have_floor =
floor_z != nullptr && floor_z->size() == static_cast<size_t>(W) * H;
auto floor_at = [&](double x, double y) -> double {
if (!have_floor) return 0.0;
const int fx = static_cast<int>(std::floor((x - ox) / res));
const int fy = static_cast<int>(std::floor((y - oy) / res));
if (fx < 0 || fy < 0 || fx >= W || fy >= H) return 0.0;
return (*floor_z)[static_cast<size_t>(fy) * grid.width + fx];
};
// --- Gom doan tu canh cua tam giac trong dai z ---
//
// Lay CA BA canh cua moi tam giac. Canh nam trong long vat the (vd canh cua
// tam giac mat tren chieu xuong) khong gay hai: chung luon nam XA hon mat
// truoc doc theo tia, va phep cat lay t NHO NHAT.
std::map<std::string, std::vector<Tri>> cache;
for (const WorldModel& m : world.models) {
if (m.collision_obj.empty()) continue;
if (m.terrain) continue; // dia hinh la san: tia cham no o raycast 3D
auto it = cache.find(m.model_name);
if (it == cache.end()) {
std::vector<Tri> tris;
const bool ok = IsDae(m.collision_obj)
? ReadDaeTriangles(m.collision_obj, &tris)
: ReadObjTriangles(m.collision_obj, &tris);
if (!ok) tris.clear();
it = cache.emplace(m.model_name, std::move(tris)).first;
}
if (it->second.empty()) continue;
const double cy = std::cos(m.yaw), sny = std::sin(m.yaw);
for (const Tri& t0 : it->second) {
double X[3], Y[3], Z[3];
for (int k = 0; k < 3; ++k) {
const double sx = t0.x[k] * m.sx, sy = t0.y[k] * m.sy;
X[k] = sx * cy - sy * sny + m.x;
Y[k] = sx * sny + sy * cy + m.y;
Z[k] = t0.z[k] * m.sz + m.z;
}
const double zlo = std::min({Z[0], Z[1], Z[2]});
const double zhi = std::max({Z[0], Z[1], Z[2]});
const double f = floor_at((X[0] + X[1] + X[2]) / 3.0, (Y[0] + Y[1] + Y[2]) / 3.0);
if (zhi < f + opt.z_min || zlo > f + opt.z_max) continue;
for (int e = 0; e < 3; ++e) {
const int a = e, b = (e + 1) % 3;
out->seg.push_back(static_cast<float>(X[a]));
out->seg.push_back(static_cast<float>(Y[a]));
out->seg.push_back(static_cast<float>(X[b]));
out->seg.push_back(static_cast<float>(Y[b]));
}
}
}
const size_t n_seg = out->seg.size() / 4;
if (n_seg == 0) {
return StatusResponse::Error(StatusCode::kNotFound,
"khong dung duoc doan nao tu mesh va cham");
}
// --- Chi muc CSR: hai luot, dem roi dien ---
//
// Moi doan duoc ghi vao MOI O no cat qua, di bang DDA supercover. Dung bao
// loi cua doan se re hon nhung mot buc tuong cheo dai 5 m se dinh vao hang
// nghin o no khong he cham.
auto walk = [&](size_t s, const std::function<void(int, int)>& visit) {
double ax = out->seg[s * 4], ay = out->seg[s * 4 + 1];
double bx = out->seg[s * 4 + 2], by = out->seg[s * 4 + 3];
double px = (ax - ox) / res, py = (ay - oy) / res;
const double qx = (bx - ox) / res, qy = (by - oy) / res;
int cx = static_cast<int>(std::floor(px));
int cyi = static_cast<int>(std::floor(py));
const int ex = static_cast<int>(std::floor(qx));
const int ey = static_cast<int>(std::floor(qy));
const double dx = qx - px, dy = qy - py;
const int sx = dx > 0 ? 1 : (dx < 0 ? -1 : 0);
const int sy = dy > 0 ? 1 : (dy < 0 ? -1 : 0);
const double inf = std::numeric_limits<double>::infinity();
const double tdx = dx != 0.0 ? std::fabs(1.0 / dx) : inf;
const double tdy = dy != 0.0 ? std::fabs(1.0 / dy) : inf;
double tmx = dx != 0.0 ? ((dx > 0 ? (cx + 1 - px) : (px - cx)) * tdx) : inf;
double tmy = dy != 0.0 ? ((dy > 0 ? (cyi + 1 - py) : (py - cyi)) * tdy) : inf;
for (int guard = 0; guard < 4096; ++guard) {
if (cx >= 0 && cyi >= 0 && cx < W && cyi < H) visit(cx, cyi);
if (cx == ex && cyi == ey) break;
if (tmx < tmy) { tmx += tdx; cx += sx; }
else { tmy += tdy; cyi += sy; }
if (tmx > 1.0 && tmy > 1.0) {
if (cx >= 0 && cyi >= 0 && cx < W && cyi < H) visit(cx, cyi);
break;
}
}
};
for (size_t s = 0; s < n_seg; ++s) {
walk(s, [&](int cx, int cyi) {
out->cell_start[static_cast<size_t>(cyi) * grid.width + cx + 1]++;
});
}
for (size_t i = 1; i < out->cell_start.size(); ++i) {
out->cell_start[i] += out->cell_start[i - 1];
}
out->cell_items.assign(out->cell_start.back(), 0);
std::vector<uint32_t> fill(out->cell_start.begin(), out->cell_start.end() - 1);
for (size_t s = 0; s < n_seg; ++s) {
walk(s, [&](int cx, int cyi) {
out->cell_items[fill[static_cast<size_t>(cyi) * grid.width + cx]++] =
static_cast<uint32_t>(s);
});
}
VSLAM_INFO("world -> doan: " << n_seg << " doan, " << out->cell_items.size()
<< " muc chi muc (" << (out->seg.size() * 4 +
out->cell_items.size() * 4) / 1048576.0
<< " MB)");
return StatusResponse::Ok();
}
// ---------------------------------------------------------------------------
StatusResponse ExportWorldMeshes(const GazeboWorld& world, bool visual,
WorldMeshes* out) {
if (out == nullptr) {
return StatusResponse::Error(StatusCode::kInvalidArgument, "out == null");
}
out->geoms.clear();
out->instances.clear();
std::map<std::string, uint32_t> by_model;
for (const WorldModel& m : world.models) {
const std::string& path = visual && !m.visual_obj.empty() ? m.visual_obj
: m.collision_obj;
if (path.empty()) continue;
// Gop theo TEN MODEL, khong theo duong dan mesh: `<scale>` den tu
// model.sdf nen hai model dung chung mot file mesh van co the khac ti le.
uint32_t gid = 0;
auto it = by_model.find(m.model_name);
if (it != by_model.end()) {
gid = it->second;
} else {
std::vector<Tri> tris;
const bool ok = IsDae(path) ? ReadDaeTriangles(path, &tris)
: ReadObjTriangles(path, &tris);
if (!ok || tris.empty()) {
VSLAM_WARN("world: khong doc duoc mesh " << path << " cua model "
<< m.model_name << " -- vat the nay VANG MAT khoi khung 3D");
continue;
}
WorldMeshGeom g;
g.model_name = m.model_name;
g.tri.reserve(tris.size() * 9);
for (const Tri& t : tris) {
for (int k = 0; k < 3; ++k) {
g.tri.push_back(static_cast<float>(t.x[k] * m.sx));
g.tri.push_back(static_cast<float>(t.y[k] * m.sy));
g.tri.push_back(static_cast<float>(t.z[k] * m.sz));
}
}
gid = static_cast<uint32_t>(out->geoms.size());
by_model[m.model_name] = gid;
out->geoms.push_back(std::move(g));
}
WorldMeshInstance inst;
inst.geom = gid;
inst.x = static_cast<float>(m.x);
inst.y = static_cast<float>(m.y);
inst.z = static_cast<float>(m.z);
inst.yaw = static_cast<float>(m.yaw);
out->instances.push_back(inst);
}
if (out->geoms.empty()) {
return StatusResponse::Error(StatusCode::kNotFound,
"khong doc duoc mesh nao tu world");
}
return StatusResponse::Ok();
}
size_t ApplyModelColors(const std::string& json_path, WorldMeshes* io) {
if (io == nullptr) return 0;
// JSON la tap con cua YAML, nen yaml-cpp doc duoc thang -- khong keo them
// mot bo doc JSON vao `vslam_sim` chi vi mot bang 69 dong.
YAML::Node root;
try {
root = YAML::LoadFile(json_path);
} catch (const std::exception& e) {
VSLAM_WARN("world: khong doc duoc bang mau " << json_path << " (" << e.what()
<< ") -- moi vat the se mang mau mac dinh");
return 0;
}
size_t n = 0;
for (WorldMeshGeom& g : io->geoms) {
const YAML::Node c = root[g.model_name];
if (!c || !c.IsSequence() || c.size() < 3) continue;
g.r = static_cast<uint8_t>(c[0].as<int>());
g.g = static_cast<uint8_t>(c[1].as<int>());
g.b = static_cast<uint8_t>(c[2].as<int>());
n++;
}
return n;
}
namespace {
void PutU32(std::string* o, uint32_t v) {
// Little-endian tuong minh: trinh duyet doc bang DataView voi littleEndian
// = true, nen khong duoc phu thuoc endianness cua may chu.
o->push_back(static_cast<char>(v & 0xFF));
o->push_back(static_cast<char>((v >> 8) & 0xFF));
o->push_back(static_cast<char>((v >> 16) & 0xFF));
o->push_back(static_cast<char>((v >> 24) & 0xFF));
}
void PutF32(std::string* o, float f) {
uint32_t u = 0;
std::memcpy(&u, &f, 4);
PutU32(o, u);
}
} // namespace
void EncodeWorldMeshes(const WorldMeshes& in, std::string* out) {
if (out == nullptr) return;
out->clear(); // ⚠️ ghi de, KHONG noi them -- xem EncodeScanPayload
out->append("VSLW");
PutU32(out, 1);
PutU32(out, static_cast<uint32_t>(in.geoms.size()));
PutU32(out, static_cast<uint32_t>(in.instances.size()));
for (const WorldMeshGeom& g : in.geoms) {
PutU32(out, static_cast<uint32_t>(g.model_name.size()));
out->append(g.model_name);
out->push_back(static_cast<char>(g.r));
out->push_back(static_cast<char>(g.g));
out->push_back(static_cast<char>(g.b));
PutU32(out, static_cast<uint32_t>(g.tri.size() / 9));
for (float v : g.tri) PutF32(out, v);
}
for (const WorldMeshInstance& i : in.instances) {
PutU32(out, i.geom);
PutF32(out, i.x); PutF32(out, i.y); PutF32(out, i.z); PutF32(out, i.yaw);
}
}
} // namespace vslam