update
This commit is contained in:
275
tools/cut_world.py
Normal file
275
tools/cut_world.py
Normal file
@@ -0,0 +1,275 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Cat mot world Gazebo theo truc y: giu phan y < --y-max, bo han phan con lai.
|
||||
|
||||
Dung de co mot ban do VUA -- lon hon nha hang (12x10 m), nho hon ca benh vien
|
||||
(25x51 m) -- quet tron duoc trong 10-15 phut.
|
||||
|
||||
Ba buoc:
|
||||
1. LOC MODEL: giu khoi `<model name="...">` co pose y < y-max - margin.
|
||||
Bo doc world (libs/vslam_sim/src/gazebo_world.cc) tach khoi tu
|
||||
`<model name="` den `</model>` GAN NHAT, lay `<uri>` va `<pose>` DAU TIEN
|
||||
-- script nay loc dung theo cach tach do.
|
||||
2. CAT MESH (--clip): tuong va san cua benh vien la MOT mesh .dae cho ca toa
|
||||
nha. Khong sua .dae (de hong) -- lay CHINH tam giac ma bo doc world tao ra
|
||||
(`vslam_world_export --meshes`), cat o y = y-max (tam giac vat qua duong
|
||||
cat bi cat doi chinh xac, nen tuong doc chay suot toa nha van con phan
|
||||
phia nam), ghi thanh model .obj moi va thay vao world.
|
||||
3. TUONG CHAN: duong cat di qua loi hanh lang, nen chen
|
||||
resources/models/vslam_tuong_cat o y = y-max de bit lai.
|
||||
|
||||
Tai tao resources/worlds/hospital_nam.world (chay tu goc repo):
|
||||
|
||||
GAZEBO_MODEL_PATH=$PWD/resources/models ./build/tools/vslam_world_export \\
|
||||
--world ../vSLAM_ws/src/robot_sim/worlds/hospital.world --meshes /tmp/c.bin
|
||||
GAZEBO_MODEL_PATH=$PWD/resources/models ./build/tools/vslam_world_export \\
|
||||
--world ../vSLAM_ws/src/robot_sim/worlds/hospital.world --meshes /tmp/v.bin \\
|
||||
--meshes-visual
|
||||
python3 tools/cut_world.py \\
|
||||
--in ../vSLAM_ws/src/robot_sim/worlds/hospital.world \\
|
||||
--out resources/worlds/hospital_nam.world --y-max -10.12 \\
|
||||
--meshes-bin /tmp/c.bin --meshes-visual-bin /tmp/v.bin \\
|
||||
--clip aws_robomaker_hospital_floor_01_walls=vslam_hospital_nam_walls \\
|
||||
--clip aws_robomaker_hospital_floor_01_floor=vslam_hospital_nam_floor \\
|
||||
--colors resources/model_colors.json
|
||||
|
||||
Chay node voi GAZEBO_MODEL_PATH=$PWD/resources/models de tim thay cac model moi.
|
||||
|
||||
y = -10.12 chon tu ban do raster hoa (vslam_world_export): duong ngang o do chi
|
||||
cat 7.7 m san trong (cac loi hanh lang), con lai trung tuong co san.
|
||||
|
||||
⚠️ Chay lai tools/gen_model_colors.py se ghi de model_colors.json va mat mau
|
||||
cua model moi -- chay lai script nay sau do.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
|
||||
WALL_BLOCK = """ <model name="vslam_tuong_cat_1">
|
||||
<include>
|
||||
<uri>model://vslam_tuong_cat</uri>
|
||||
<static>true</static>
|
||||
<pose>{x} {y} 0 0 0 0</pose>
|
||||
</include>
|
||||
</model>
|
||||
"""
|
||||
|
||||
CLIP_BLOCK = """ <model name="{name}_1">
|
||||
<include>
|
||||
<uri>model://{name}</uri>
|
||||
<static>true</static>
|
||||
<pose>0 0 0 0 0 0</pose>
|
||||
</include>
|
||||
</model>
|
||||
"""
|
||||
|
||||
MODEL_CONFIG = """<?xml version="1.0" ?>
|
||||
<model>
|
||||
<name>{name}</name>
|
||||
<version>1.0</version>
|
||||
<sdf version="1.6">model.sdf</sdf>
|
||||
<author>
|
||||
<name>vslam_cpp</name>
|
||||
<email></email>
|
||||
</author>
|
||||
<description>
|
||||
{src} cat o y <= {y_max}, toa do THE GIOI (dat model o goc).
|
||||
Sinh boi tools/cut_world.py -- dung sua tay.
|
||||
</description>
|
||||
</model>
|
||||
"""
|
||||
|
||||
MODEL_SDF = """<?xml version="1.0" ?>
|
||||
<sdf version="1.6">
|
||||
<model name="{name}">
|
||||
<link name="link">
|
||||
<visual name="visual">
|
||||
<geometry>
|
||||
<mesh>
|
||||
<uri>model://{name}/meshes/visual.obj</uri>
|
||||
</mesh>
|
||||
</geometry>
|
||||
</visual>
|
||||
<collision name="collision">
|
||||
<geometry>
|
||||
<mesh>
|
||||
<uri>model://{name}/meshes/collision.obj</uri>
|
||||
</mesh>
|
||||
</geometry>
|
||||
</collision>
|
||||
</link>
|
||||
<static>1</static>
|
||||
</model>
|
||||
</sdf>
|
||||
"""
|
||||
|
||||
|
||||
def read_meshes(path):
|
||||
"""Doc khoi "VSLW" cua EncodeWorldMeshes (gazebo_world.h).
|
||||
|
||||
Tra ve (geoms, instances): geoms[i] = (ten, [9 float moi tam giac] trong he
|
||||
MODEL), instances = [(geom, x, y, z, yaw)].
|
||||
"""
|
||||
b = open(path, "rb").read()
|
||||
if b[:4] != b"VSLW":
|
||||
sys.exit(f"{path}: khong phai khoi VSLW")
|
||||
_, ng, ni = struct.unpack_from("<III", b, 4)
|
||||
o = 16
|
||||
geoms = []
|
||||
for _ in range(ng):
|
||||
(n,) = struct.unpack_from("<I", b, o)
|
||||
o += 4
|
||||
name = b[o:o + n].decode()
|
||||
o += n + 3 # bo qua r,g,b
|
||||
(nt,) = struct.unpack_from("<I", b, o)
|
||||
o += 4
|
||||
geoms.append((name, struct.unpack_from(f"<{nt * 9}f", b, o)))
|
||||
o += nt * 9 * 4
|
||||
insts = []
|
||||
for _ in range(ni):
|
||||
insts.append(struct.unpack_from("<Iffff", b, o))
|
||||
o += 20
|
||||
return geoms, insts
|
||||
|
||||
|
||||
def clip_poly(poly, y_max):
|
||||
"""Sutherland-Hodgman voi mot nua mat phang y <= y_max. Giu thu tu dinh."""
|
||||
out = []
|
||||
for i, cur in enumerate(poly):
|
||||
prev = poly[i - 1]
|
||||
cin, pin = cur[1] <= y_max, prev[1] <= y_max
|
||||
if cin != pin:
|
||||
t = (y_max - prev[1]) / (cur[1] - prev[1])
|
||||
out.append(tuple(p + t * (c - p) for p, c in zip(prev, cur)))
|
||||
if cin:
|
||||
out.append(cur)
|
||||
return out
|
||||
|
||||
|
||||
def world_triangles(geoms, insts, model_name, y_max):
|
||||
"""Moi the hien cua `model_name` -> tam giac TOA DO THE GIOI, da cat."""
|
||||
idx = [i for i, g in enumerate(geoms) if g[0] == model_name]
|
||||
if not idx:
|
||||
sys.exit(f"khong co mesh '{model_name}' trong file .bin")
|
||||
tris = []
|
||||
for g, x, y, z, yaw in insts:
|
||||
if g not in idx:
|
||||
continue
|
||||
c, s = math.cos(yaw), math.sin(yaw)
|
||||
t = geoms[g][1]
|
||||
for k in range(0, len(t), 9):
|
||||
poly = [(c * t[k + 3 * j] - s * t[k + 3 * j + 1] + x,
|
||||
s * t[k + 3 * j] + c * t[k + 3 * j + 1] + y,
|
||||
t[k + 3 * j + 2] + z) for j in range(3)]
|
||||
poly = clip_poly(poly, y_max)
|
||||
for j in range(2, len(poly)): # quat tam giac
|
||||
tris.append((poly[0], poly[j - 1], poly[j]))
|
||||
return tris
|
||||
|
||||
|
||||
def write_obj(path, tris, header):
|
||||
with open(path, "w") as f:
|
||||
f.write(f"# {header}\n# Z-UP, don vi MET, toa do THE GIOI. Sinh boi tools/cut_world.py.\n")
|
||||
for tri in tris:
|
||||
for p in tri:
|
||||
f.write(f"v {p[0]:.4f} {p[1]:.4f} {p[2]:.4f}\n")
|
||||
for i in range(len(tris)):
|
||||
f.write(f"f {3 * i + 1} {3 * i + 2} {3 * i + 3}\n")
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
ap.add_argument("--in", dest="src", required=True, help="world goc")
|
||||
ap.add_argument("--out", required=True, help="world da cat")
|
||||
ap.add_argument("--y-max", type=float, required=True,
|
||||
help="giu phan y < y-max; tuong chan dat o y-max")
|
||||
ap.add_argument("--margin", type=float, default=0.3,
|
||||
help="model co pose trong khoang nay quanh duong cat bi bo (m)")
|
||||
ap.add_argument("--keep", action="append", default=[],
|
||||
help="uri chua chuoi nay thi LUON giu nguyen (khong cat)")
|
||||
ap.add_argument("--clip", action="append", default=[],
|
||||
help="MODEL=MOI: cat mesh MODEL, ghi thanh model MOI, thay vao world")
|
||||
ap.add_argument("--meshes-bin", help="vslam_world_export --meshes (va cham)")
|
||||
ap.add_argument("--meshes-visual-bin", help="vslam_world_export --meshes --meshes-visual")
|
||||
ap.add_argument("--models-dir", default="resources/models",
|
||||
help="noi ghi model moi")
|
||||
ap.add_argument("--colors", help="model_colors.json: chep mau MODEL sang MOI")
|
||||
ap.add_argument("--wall-x", type=float, default=0.0,
|
||||
help="tam x cua tuong chan (mesh rong 27.4 m quanh tam)")
|
||||
a = ap.parse_args()
|
||||
|
||||
clips = dict(c.split("=", 1) for c in a.clip)
|
||||
if clips and not (a.meshes_bin and a.meshes_visual_bin):
|
||||
sys.exit("--clip can ca --meshes-bin lan --meshes-visual-bin")
|
||||
|
||||
# --- 2. Cat mesh, ghi model moi ---
|
||||
if clips:
|
||||
col = read_meshes(a.meshes_bin)
|
||||
vis = read_meshes(a.meshes_visual_bin)
|
||||
for src_name, new_name in clips.items():
|
||||
d = os.path.join(a.models_dir, new_name)
|
||||
os.makedirs(os.path.join(d, "meshes"), exist_ok=True)
|
||||
for kind, data in (("collision", col), ("visual", vis)):
|
||||
tris = world_triangles(*data, src_name, a.y_max)
|
||||
write_obj(os.path.join(d, "meshes", kind + ".obj"), tris,
|
||||
f"{src_name} ({kind}) cat o y <= {a.y_max}: {len(tris)} tam giac")
|
||||
print(f"{new_name}/{kind}.obj: {len(tris)} tam giac")
|
||||
with open(os.path.join(d, "model.config"), "w") as f:
|
||||
f.write(MODEL_CONFIG.format(name=new_name, src=src_name, y_max=a.y_max))
|
||||
with open(os.path.join(d, "model.sdf"), "w") as f:
|
||||
f.write(MODEL_SDF.format(name=new_name))
|
||||
if a.colors:
|
||||
colors = json.load(open(a.colors))
|
||||
for src_name, new_name in clips.items():
|
||||
if src_name in colors:
|
||||
colors[new_name] = colors[src_name]
|
||||
with open(a.colors, "w") as f:
|
||||
json.dump(colors, f, indent=0, sort_keys=True)
|
||||
f.write("\n") # giu dung dinh dang gen_model_colors.py ghi ra
|
||||
|
||||
# --- 1 + 3. Loc model, thay model da cat, chen tuong chan ---
|
||||
src = open(a.src).read()
|
||||
if src.count("</world>") != 1:
|
||||
sys.exit("world phai co dung mot </world>")
|
||||
kept, dropped, replaced = [], [], []
|
||||
|
||||
def filt(m):
|
||||
body = m.group(2)
|
||||
uri = re.search(r"<uri>([^<]+)</uri>", body)
|
||||
pose = re.search(r"<pose>([^<]+)</pose>", body)
|
||||
# Khong co uri: bo doc world cung bo qua, de nguyen cho Gazebo that.
|
||||
if uri is None:
|
||||
kept.append(m.group(1))
|
||||
return m.group(0)
|
||||
model = uri.group(1).split("://", 1)[-1].split("/", 1)[0]
|
||||
if model in clips:
|
||||
replaced.append(m.group(1))
|
||||
return CLIP_BLOCK.format(name=clips[model])
|
||||
if any(k in uri.group(1) for k in a.keep):
|
||||
kept.append(m.group(1))
|
||||
return m.group(0)
|
||||
y = float(pose.group(1).split()[1]) if pose else 0.0
|
||||
if y < a.y_max - a.margin:
|
||||
kept.append(m.group(1))
|
||||
return m.group(0)
|
||||
dropped.append(m.group(1))
|
||||
return ""
|
||||
|
||||
# Non-greedy toi </model> GAN NHAT -- dung cach gazebo_world.cc tach khoi.
|
||||
out = re.sub(r'[ \t]*<model name="([^"]+)">(.*?)</model>[ \t]*\n?', filt, src,
|
||||
flags=re.S)
|
||||
out = re.sub(r"[ \t]*</world>",
|
||||
lambda _: WALL_BLOCK.format(x=a.wall_x, y=a.y_max) + " </world>",
|
||||
out, count=1)
|
||||
with open(a.out, "w") as f:
|
||||
f.write(out)
|
||||
print(f"giu {len(kept)}, thay {len(replaced)} (da cat mesh), bo {len(dropped)} model; "
|
||||
f"tuong chan o y = {a.y_max}")
|
||||
print(f"-> {a.out}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user