This commit is contained in:
trung09122002
2026-09-18 18:14:42 +07:00
commit 48bd5377dc
224 changed files with 37685 additions and 0 deletions

View File

@@ -0,0 +1,863 @@
#include "vslam/gazebo_world.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cstdlib>
#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);
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) {
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 2: to tam giac trong dai do cao ---
size_t n_used = 0;
for (const Loaded& L : loaded) {
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.
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 < opt.z_min || tz0 > 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) {
out->data[static_cast<size_t>(gy) * w + gx] = 100;
}
}
}
}
}
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");
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

View File

@@ -0,0 +1,248 @@
#include "vslam/occupancy_map_io.h"
#include <yaml-cpp/yaml.h>
#include <algorithm>
#include <cstdio>
#include <fstream>
#include <sstream>
#include <vector>
#include "vslam/log.h"
namespace vslam {
namespace {
std::string DirName(const std::string& path) {
const size_t slash = path.find_last_of('/');
return slash == std::string::npos ? std::string(".") : path.substr(0, slash);
}
// Doc PGM P5 (nhi phan 8 bit). Bo qua comment bat dau bang '#'.
bool ReadPgm(const std::string& path, uint32_t* w, uint32_t* h,
std::vector<uint8_t>* pixels, std::string* err) {
std::ifstream f(path, std::ios::binary);
if (!f) {
*err = "khong mo duoc " + path;
return false;
}
auto next_token = [&f]() -> std::string {
std::string tok;
while (f) {
const int c = f.get();
if (c == EOF) break;
if (c == '#') {
while (f && f.get() != '\n') {
}
continue;
}
if (std::isspace(c)) {
if (!tok.empty()) break;
continue;
}
tok.push_back(static_cast<char>(c));
}
return tok;
};
if (next_token() != "P5") {
*err = path + ": chi ho tro PGM P5 (nhi phan)";
return false;
}
*w = static_cast<uint32_t>(std::stoul(next_token()));
*h = static_cast<uint32_t>(std::stoul(next_token()));
const unsigned long maxval = std::stoul(next_token());
if (maxval > 255) {
*err = path + ": chi ho tro PGM 8 bit";
return false;
}
pixels->resize(static_cast<size_t>(*w) * (*h));
f.read(reinterpret_cast<char*>(pixels->data()),
static_cast<std::streamsize>(pixels->size()));
if (static_cast<size_t>(f.gcount()) != pixels->size()) {
*err = path + ": file anh cut";
return false;
}
return true;
}
} // namespace
StatusResponse LoadOccupancyMap(const std::string& yaml_path, MapLoadResult* out) {
// Kiem TON TAI truoc khi giao cho yaml-cpp.
//
// `YAML::LoadFile` tren mot file khong co nem `BadFile`, va `what()` cua no
// dung la chuoi "bad file" -- khong noi file nao, khong phan biet thieu voi
// hong, khong goi y gi. Nguoi dung go sai duong dan chi nhan duoc
// "hospital.yaml: bad file" roi dung do.
{
std::ifstream probe(yaml_path);
if (!probe) {
return StatusResponse::Error(
StatusCode::kNotFound,
"khong mo duoc ban do: " + yaml_path +
" (khong ton tai hoac khong co quyen doc). Xuat mot ban do tu DB "
"RTAB-Map bang: vslam_slam_bench --db X.db --localize "
"--export-only --export-map out.pgm");
}
}
YAML::Node node;
try {
node = YAML::LoadFile(yaml_path);
} catch (const YAML::Exception& e) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
yaml_path + ": YAML hong: " + e.what());
}
if (!node["image"] || !node["resolution"]) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
yaml_path + ": thieu 'image' hoac 'resolution'");
}
std::string image = node["image"].as<std::string>();
if (!image.empty() && image[0] != '/') image = DirName(yaml_path) + "/" + image;
out->image_path = image;
const double resolution = node["resolution"].as<double>();
double ox = 0.0, oy = 0.0;
if (node["origin"] && node["origin"].size() >= 2) {
ox = node["origin"][0].as<double>();
oy = node["origin"][1].as<double>();
}
const bool negate = node["negate"] ? node["negate"].as<int>() != 0 : false;
out->occupied_thresh =
node["occupied_thresh"] ? node["occupied_thresh"].as<double>() : 0.65;
out->free_thresh = node["free_thresh"] ? node["free_thresh"].as<double>() : 0.196;
uint32_t w = 0, h = 0;
std::vector<uint8_t> pixels;
std::string err;
if (!ReadPgm(image, &w, &h, &pixels, &err)) {
return StatusResponse::Error(StatusCode::kNotFound, err);
}
out->grid.width = w;
out->grid.height = h;
out->grid.resolution = static_cast<float>(resolution);
out->grid.origin.position.x = ox;
out->grid.origin.position.y = oy;
out->grid.data.resize(static_cast<size_t>(w) * h);
for (uint32_t y = 0; y < h; ++y) {
for (uint32_t x = 0; x < w; ++x) {
// PGM hang 0 o TREN CUNG; occupancy grid hang 0 o DUOI CUNG (goc o
// origin). Quen lat truc y la loi kinh dien khi doc map, va hau qua la
// ban do bi lat nguoc ma van "trong nhu that".
const uint8_t px = pixels[static_cast<size_t>(h - 1 - y) * w + x];
double occ = (255.0 - static_cast<double>(px)) / 255.0;
if (negate) occ = 1.0 - occ;
int8_t v;
if (occ > out->occupied_thresh) {
v = 100;
} else if (occ < out->free_thresh) {
v = 0;
} else {
v = -1; // chua biet
}
out->grid.data[static_cast<size_t>(y) * w + x] = v;
}
}
VSLAM_INFO("map: nap " << image << " -- " << w << "x" << h << " @ "
<< resolution << " m/o, goc (" << ox << ", " << oy << ")");
return StatusResponse::Ok();
}
StatusResponse SaveOccupancyMap(const OccupancyGrid& grid,
const std::string& yaml_path) {
std::string base = yaml_path;
const size_t dot = base.find_last_of('.');
if (dot != std::string::npos) base = base.substr(0, dot);
const std::string pgm_path = base + ".pgm";
std::ofstream img(pgm_path, std::ios::binary);
if (!img) {
return StatusResponse::Error(StatusCode::kUnavailable,
"khong ghi duoc " + pgm_path);
}
img << "P5\n# sinh boi vslam\n" << grid.width << " " << grid.height << "\n255\n";
for (uint32_t y = 0; y < grid.height; ++y) {
for (uint32_t x = 0; x < grid.width; ++x) {
const int8_t v = grid.data[static_cast<size_t>(grid.height - 1 - y) * grid.width + x];
const uint8_t px = v < 0 ? 205 : (v >= 50 ? 0 : 254);
img.put(static_cast<char>(px));
}
}
img.close();
std::ofstream y(yaml_path);
if (!y) {
return StatusResponse::Error(StatusCode::kUnavailable,
"khong ghi duoc " + yaml_path);
}
const size_t slash = pgm_path.find_last_of('/');
y << "image: " << (slash == std::string::npos ? pgm_path : pgm_path.substr(slash + 1))
<< "\nresolution: " << grid.resolution << "\norigin: [" << grid.origin.position.x
<< ", " << grid.origin.position.y << ", 0.0]\nnegate: 0\n"
<< "occupied_thresh: 0.65\nfree_thresh: 0.196\n";
VSLAM_INFO("map: da ghi " << yaml_path << " va " << pgm_path);
return StatusResponse::Ok();
}
OccupancyGrid MakeSyntheticWorld(uint32_t w, uint32_t h, float res) {
OccupancyGrid m;
m.width = w;
m.height = h;
m.resolution = res;
m.origin.position.x = -static_cast<double>(w) * res / 2.0;
m.origin.position.y = -static_cast<double>(h) * res / 2.0;
m.data.assign(static_cast<size_t>(w) * h, -1);
auto put = [&](uint32_t x, uint32_t y, int8_t v) {
if (x < w && y < h) m.data[static_cast<size_t>(y) * w + x] = v;
};
const uint32_t cy = h / 2;
const uint32_t half = std::max<uint32_t>(6, h / 24);
for (uint32_t x = w / 10; x < w - w / 10; ++x) {
for (uint32_t y = cy - half; y <= cy + half; ++y) put(x, y, 0);
put(x, cy - half - 1, 100);
put(x, cy + half + 1, 100);
}
// Bit hai dau hanh lang, neu khong thi raycast chay ra vo tan.
for (uint32_t y = cy - half - 1; y <= cy + half + 1; ++y) {
put(w / 10, y, 100);
put(w - w / 10 - 1, y, 100);
}
const uint32_t room = half * 3;
for (uint32_t rx = w / 6; rx + room < w - w / 10; rx += room + room / 2) {
for (int side = 0; side < 2; ++side) {
const uint32_t y0 = side == 0 ? cy + half + 2 : cy - half - 2 - room;
for (uint32_t x = rx; x < rx + room; ++x) {
for (uint32_t y = y0; y < y0 + room; ++y) put(x, y, 0);
}
for (uint32_t x = rx - 1; x <= rx + room; ++x) {
put(x, y0 - 1, 100);
put(x, y0 + room, 100);
}
for (uint32_t y = y0 - 1; y <= y0 + room; ++y) {
put(rx - 1, y, 100);
put(rx + room, y, 100);
}
const uint32_t door = rx + room / 2;
for (uint32_t x = door - 2; x <= door + 2; ++x) {
put(x, side == 0 ? y0 - 1 : y0 + room, 0);
}
}
}
return m;
}
} // namespace vslam

File diff suppressed because it is too large Load Diff