Update utils.py
Browse files
utils.py
CHANGED
|
@@ -1,783 +1,783 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import json
|
| 3 |
-
from copy import deepcopy
|
| 4 |
-
import re
|
| 5 |
-
import ast
|
| 6 |
-
import numpy as np
|
| 7 |
-
from scipy.spatial.transform import Rotation as R
|
| 8 |
-
import uuid
|
| 9 |
-
import xml.etree.ElementTree as ET
|
| 10 |
-
|
| 11 |
-
BLOCKPROPERTYPATH=R"Besiege_blocks_markov.json"
|
| 12 |
-
|
| 13 |
-
FLIP_SENSITIVE_BLOCKS = ["2","46"]
|
| 14 |
-
def are_quaternions_similar(q1, angle_threshold=1e-3):
|
| 15 |
-
|
| 16 |
-
q2 = np.array([0, -0.7071068, 0, 0.7071068])
|
| 17 |
-
# 将四元数转换为旋转对象
|
| 18 |
-
r1 = R.from_quat(q1)
|
| 19 |
-
r2 = R.from_quat(q2)
|
| 20 |
-
|
| 21 |
-
# 计算两个旋转之间的夹角差异
|
| 22 |
-
relative_rotation = r1.inv() * r2
|
| 23 |
-
angle = relative_rotation.magnitude()
|
| 24 |
-
|
| 25 |
-
# 如果角度差异小于阈值,则认为两个四元数大致相同
|
| 26 |
-
return angle < angle_threshold
|
| 27 |
-
def generate_guid():
|
| 28 |
-
"""生成一个唯一的GUID"""
|
| 29 |
-
return str(uuid.uuid4())
|
| 30 |
-
|
| 31 |
-
def add_rotations(q1, q2):
|
| 32 |
-
"""叠加两个旋转四元数"""
|
| 33 |
-
r1 = R.from_quat(q1) # 从四元数创建旋转对象
|
| 34 |
-
r2 = R.from_quat(q2) # 从四元数创建旋转对象
|
| 35 |
-
r_combined = r1 * r2 # 叠加旋转
|
| 36 |
-
return r_combined.as_quat() # 返回四元数 (xyzw 格式)
|
| 37 |
-
def read_txt(path):
|
| 38 |
-
"""读取文本文件内容"""
|
| 39 |
-
with open(path, "r", encoding="utf-8") as file:
|
| 40 |
-
return file.read()
|
| 41 |
-
|
| 42 |
-
def write_file(path, content):
|
| 43 |
-
"""将内容写入文本文件"""
|
| 44 |
-
with open(path, 'w', encoding='utf-8') as file:
|
| 45 |
-
file.write(content)
|
| 46 |
-
def extract_json_from_string(input_string: str,return_raw_str=False):
|
| 47 |
-
if isinstance(input_string,list):
|
| 48 |
-
return input_string
|
| 49 |
-
if os.path.exists(input_string):
|
| 50 |
-
input_content = read_txt(input_string)
|
| 51 |
-
else:
|
| 52 |
-
input_content = deepcopy(input_string)
|
| 53 |
-
match = re.search(r"```json(.*?)```", input_content, re.DOTALL)
|
| 54 |
-
if match:
|
| 55 |
-
json_content = match.group(1).strip()
|
| 56 |
-
try:
|
| 57 |
-
if return_raw_str:
|
| 58 |
-
return json.loads(json_content),json_content
|
| 59 |
-
return json.loads(json_content)
|
| 60 |
-
except json.JSONDecodeError:
|
| 61 |
-
pass
|
| 62 |
-
|
| 63 |
-
try:
|
| 64 |
-
if return_raw_str:
|
| 65 |
-
return json.loads(input_content),input_content
|
| 66 |
-
return json.loads(input_content)
|
| 67 |
-
except json.JSONDecodeError:
|
| 68 |
-
try:
|
| 69 |
-
if return_raw_str:
|
| 70 |
-
return json.loads(input_content),input_content
|
| 71 |
-
return ast.literal_eval(input_content)
|
| 72 |
-
except (ValueError, SyntaxError):
|
| 73 |
-
if return_raw_str:
|
| 74 |
-
return None,""
|
| 75 |
-
return None
|
| 76 |
-
|
| 77 |
-
def get_relative_pos_list(bp_oldpos,ref_p,ref_r,scale=1,decimals=None):
|
| 78 |
-
bp_newpos = []
|
| 79 |
-
|
| 80 |
-
if ref_r.shape[0] != 3 or ref_r.shape[1] != 3:
|
| 81 |
-
ref_r = R.from_quat(ref_r).as_matrix() # 如果是四元数,转换为旋转矩阵
|
| 82 |
-
|
| 83 |
-
for point in bp_oldpos:
|
| 84 |
-
point_lp = ref_p+np.dot(ref_r, point*scale)
|
| 85 |
-
bp_newpos.append(tuple(point_lp))
|
| 86 |
-
bp_newpos = np.array(bp_newpos)#可建造点局部位置
|
| 87 |
-
|
| 88 |
-
if decimals!=None:
|
| 89 |
-
bp_newpos = np.round(bp_newpos,decimals=decimals)
|
| 90 |
-
|
| 91 |
-
return bp_newpos
|
| 92 |
-
|
| 93 |
-
def get_bbox(manu_lp,manu_lr,scale,bc_gc,bbox_size,gp,gr):
|
| 94 |
-
|
| 95 |
-
if manu_lr.shape[0] != 3 or manu_lr.shape[1] != 3:
|
| 96 |
-
manu_lr = R.from_quat(manu_lr).as_matrix()
|
| 97 |
-
if gr.shape[0] != 3 or gr.shape[1] != 3:
|
| 98 |
-
gr = R.from_quat(gr).as_matrix()
|
| 99 |
-
|
| 100 |
-
half_bbox_size = np.array(bbox_size) / 2.0
|
| 101 |
-
bbox_lp = []
|
| 102 |
-
for z in [-1, 1]:
|
| 103 |
-
for x in [-1, 1]:
|
| 104 |
-
for y in [-1, 1]:
|
| 105 |
-
point = (manu_lp+bc_gc) + (x * half_bbox_size[0], y * half_bbox_size[1], z * half_bbox_size[2])
|
| 106 |
-
bc_point = point-manu_lp
|
| 107 |
-
point_lp = manu_lp+np.dot(manu_lr, bc_point*scale)
|
| 108 |
-
bbox_lp.append(tuple(point_lp))
|
| 109 |
-
bbox_lp = np.array(bbox_lp)#碰撞盒顶点相对位置
|
| 110 |
-
|
| 111 |
-
bbox_gp = get_relative_pos_list(bbox_lp,gp,gr,decimals=2)
|
| 112 |
-
return bbox_lp,bbox_gp
|
| 113 |
-
|
| 114 |
-
def compute_normal_vector(vertices, bp):
|
| 115 |
-
bp = np.round(bp, decimals=3)
|
| 116 |
-
|
| 117 |
-
# 计算每个维度的最小和最大坐标值
|
| 118 |
-
min_coords = np.min(vertices, axis=0)
|
| 119 |
-
max_coords = np.max(vertices, axis=0)
|
| 120 |
-
|
| 121 |
-
# 初始化法向量
|
| 122 |
-
normal = np.zeros(3)
|
| 123 |
-
# epsilon = 5e-4 # 容差范围,还算严格
|
| 124 |
-
epsilon = 0.005 # 容差范围
|
| 125 |
-
|
| 126 |
-
# 检查点是否在x方向的面上
|
| 127 |
-
if abs(bp[0] - min_coords[0]) < epsilon:
|
| 128 |
-
normal = np.array([-1, 0, 0]) # 左面法向量
|
| 129 |
-
elif abs(bp[0] - max_coords[0]) < epsilon:
|
| 130 |
-
normal = np.array([1, 0, 0]) # 右面法向量
|
| 131 |
-
# 检查y方向
|
| 132 |
-
elif abs(bp[1] - min_coords[1]) < epsilon:
|
| 133 |
-
normal = np.array([0, -1, 0]) # 下面法向量
|
| 134 |
-
elif abs(bp[1] - max_coords[1]) < epsilon:
|
| 135 |
-
normal = np.array([0, 1, 0]) # 上面法向量
|
| 136 |
-
# 检查z方向
|
| 137 |
-
elif abs(bp[2] - min_coords[2]) < epsilon:
|
| 138 |
-
normal = np.array([0, 0, -1]) # 后面法向量
|
| 139 |
-
elif abs(bp[2] - max_coords[2]) < epsilon:
|
| 140 |
-
normal = np.array([0, 0, 1]) # 前面法向量
|
| 141 |
-
else:
|
| 142 |
-
raise ValueError("点不在长方体的任何一个面上")
|
| 143 |
-
|
| 144 |
-
return normal
|
| 145 |
-
|
| 146 |
-
def get_mybuildingpoints(bc_bp,manu_lp,manu_lr,gp,gr,bc_gc,bbox_size,scale=1):
|
| 147 |
-
|
| 148 |
-
bp_ori = np.array(bc_bp)
|
| 149 |
-
bp_lp = get_relative_pos_list(bp_ori,manu_lp,manu_lr,scale=scale)
|
| 150 |
-
bp_gp = get_relative_pos_list(bp_lp,gp,gr,decimals=2)
|
| 151 |
-
bbox_lp,bbox_gp = get_bbox(manu_lp,manu_lr,scale,bc_gc,bbox_size,gp,gr)
|
| 152 |
-
|
| 153 |
-
my_building_points = bp_gp.copy()
|
| 154 |
-
my_building_points_buildrotation=[]
|
| 155 |
-
# print(f"bp_gp:{bp_gp}")
|
| 156 |
-
|
| 157 |
-
for i in range(len(my_building_points)):
|
| 158 |
-
# print(f"bp_lp:{bp_lp[i]}")
|
| 159 |
-
# print(f"bbox_lp:{bbox_lp}")
|
| 160 |
-
normal_vector_l = compute_normal_vector(bbox_lp,bp_lp[i])
|
| 161 |
-
rotated_initvec = np.array([0,0,1])
|
| 162 |
-
building_points_rot_quat = rotation_quaternion(rotated_initvec,normal_vector_l)
|
| 163 |
-
my_building_points_buildrotation.append(building_points_rot_quat) #这个是对的
|
| 164 |
-
my_building_points_buildrotation = np.array(my_building_points_buildrotation)
|
| 165 |
-
|
| 166 |
-
return my_building_points,my_building_points_buildrotation
|
| 167 |
-
|
| 168 |
-
def rotation_quaternion(v_from, v_to):
|
| 169 |
-
"""计算从 v_from 到 v_to 的旋转四元数 (xyzw 格式)"""
|
| 170 |
-
v_from = v_from / np.linalg.norm(v_from) # 单位化
|
| 171 |
-
v_to = v_to / np.linalg.norm(v_to) # 单位化
|
| 172 |
-
|
| 173 |
-
# 计算旋转轴和旋转角
|
| 174 |
-
cross = np.cross(v_from, v_to)
|
| 175 |
-
dot = np.dot(v_from, v_to)
|
| 176 |
-
|
| 177 |
-
if np.allclose(cross, 0) and np.allclose(dot, 1):
|
| 178 |
-
return np.array([0, 0, 0, 1]) # 无需旋转
|
| 179 |
-
elif np.allclose(cross, 0) and np.allclose(dot, -1):
|
| 180 |
-
# 特殊情况:v_from 和 v_to 反方向
|
| 181 |
-
# 选择一个垂直于 v_from 的轴作为旋转轴
|
| 182 |
-
if np.isclose(v_from[0], 0) and np.isclose(v_from[1], 0):
|
| 183 |
-
axis = np.array([0, 1, 0]) # 如果 v_from 在 z 轴上,选择 y 轴作为旋转轴
|
| 184 |
-
else:
|
| 185 |
-
axis = np.cross(v_from, np.array([0, 1, 0])) # 选择垂直于 v_from 和 y 轴的向量
|
| 186 |
-
axis = axis / np.linalg.norm(axis)
|
| 187 |
-
angle = np.pi
|
| 188 |
-
else:
|
| 189 |
-
angle = np.arccos(dot)
|
| 190 |
-
axis = cross / np.linalg.norm(cross)
|
| 191 |
-
|
| 192 |
-
# 生成四元数
|
| 193 |
-
q = R.from_rotvec(axis * angle).as_quat() # xyzw格式
|
| 194 |
-
return q
|
| 195 |
-
|
| 196 |
-
def format_json(input_json):
|
| 197 |
-
try:
|
| 198 |
-
new_clean_json=[]
|
| 199 |
-
for json_info in input_json:
|
| 200 |
-
new_clean_dict={}
|
| 201 |
-
if int(json_info["id"]) not in [7,9]:
|
| 202 |
-
new_clean_dict["id"]=str(json_info["id"])
|
| 203 |
-
new_clean_dict["order_id"]=int(json_info["order_id"])
|
| 204 |
-
new_clean_dict["parent"]=int(json_info["parent"])
|
| 205 |
-
new_clean_dict["bp_id"]=int(json_info["bp_id"])
|
| 206 |
-
else:
|
| 207 |
-
new_clean_dict["id"]=str(json_info["id"])
|
| 208 |
-
new_clean_dict["order_id"]=int(json_info["order_id"])
|
| 209 |
-
new_clean_dict["parent_a"]=int(json_info["parent_a"])
|
| 210 |
-
new_clean_dict["bp_id_a"]=int(json_info["bp_id_a"])
|
| 211 |
-
new_clean_dict["parent_b"]=int(json_info["parent_b"])
|
| 212 |
-
new_clean_dict["bp_id_b"]=int(json_info["bp_id_b"])
|
| 213 |
-
new_clean_json.append(new_clean_dict)
|
| 214 |
-
return new_clean_json
|
| 215 |
-
except:
|
| 216 |
-
return input_json
|
| 217 |
-
|
| 218 |
-
def convert_to_numpy(data):
|
| 219 |
-
no_globalrt = True
|
| 220 |
-
for info in data:
|
| 221 |
-
if "GlobalPosition" in info:
|
| 222 |
-
info["GlobalPosition"] = np.array(info["GlobalPosition"])
|
| 223 |
-
info["GlobalRotation"] = np.array(info["GlobalRotation"])
|
| 224 |
-
no_globalrt = False
|
| 225 |
-
else:
|
| 226 |
-
|
| 227 |
-
keys_to_convert = ["corners", "building_center", "scale","manu_lr","manu_lp","bp_lr"]
|
| 228 |
-
for key in keys_to_convert:
|
| 229 |
-
if key in info:
|
| 230 |
-
info[key] = np.array(info[key])
|
| 231 |
-
|
| 232 |
-
new_data = [{"GlobalPosition":np.array([0,5.05,0]),"GlobalRotation":np.array([0,0,0,1])}]
|
| 233 |
-
if no_globalrt:
|
| 234 |
-
new_data.extend(data)
|
| 235 |
-
return new_data
|
| 236 |
-
|
| 237 |
-
return data # 返回原始数据
|
| 238 |
-
|
| 239 |
-
def get_3d_from_llm(block_sizes, input_info, gp, gr, log=False):
|
| 240 |
-
info = deepcopy(input_info)
|
| 241 |
-
for block in info:
|
| 242 |
-
order_id = int(block["order_id"])
|
| 243 |
-
block_id = str(block["id"])
|
| 244 |
-
|
| 245 |
-
# Handle scale
|
| 246 |
-
if "scale" not in block:
|
| 247 |
-
block["scale"] = np.array([1,1,1])
|
| 248 |
-
else:
|
| 249 |
-
print(f"警告!{order_id}改变了scale!使用初始值")
|
| 250 |
-
block["scale"] = np.array([1,1,1])
|
| 251 |
-
|
| 252 |
-
# Handle rotations
|
| 253 |
-
if "bp_lr" not in block:
|
| 254 |
-
if "manu_lr" not in block:
|
| 255 |
-
block["bp_lr"] = np.array([0,0,0,1])
|
| 256 |
-
elif "manu_lr" in block and str(block.get("parent", "")) not in ("-1", ""):
|
| 257 |
-
print(f"警告!{order_id}有manu_lr但不是根节点!旋转使用初始值")
|
| 258 |
-
block["bp_lr"] = np.array([0,0,0,1])
|
| 259 |
-
block.pop("manu_lr", None)
|
| 260 |
-
|
| 261 |
-
block_info = block_sizes[block_id]
|
| 262 |
-
parent = int(block.get("parent", -1))
|
| 263 |
-
|
| 264 |
-
# Handle parent cases
|
| 265 |
-
if parent == -1:
|
| 266 |
-
if block_id not in ("0","7", "9"):
|
| 267 |
-
print("警告!发现了非起始方块的无父节点块")
|
| 268 |
-
|
| 269 |
-
if block_id in ("7", "9"):
|
| 270 |
-
parent_a, parent_b = int(block["parent_a"]), int(block["parent_b"])
|
| 271 |
-
bp_id_a, bp_id_b = int(block["bp_id_a"]), int(block["bp_id_b"])
|
| 272 |
-
block["bp_lr"] = np.array([0,0,0,1])
|
| 273 |
-
block["manu_lr"] = add_rotations(
|
| 274 |
-
info[parent_a]["my_building_points_buildrotation"][bp_id_a],
|
| 275 |
-
block["bp_lr"]
|
| 276 |
-
)
|
| 277 |
-
block["manu_lp_a"] = info[parent_a]["my_building_points"][bp_id_a] - gp
|
| 278 |
-
block["manu_lp_b"] = info[parent_b]["my_building_points"][bp_id_b] - gp
|
| 279 |
-
else:
|
| 280 |
-
if "manu_lr" not in block:
|
| 281 |
-
block["manu_lr"] = np.array([0,0,0,1])
|
| 282 |
-
block["manu_lp"] = np.array([0,0,0])
|
| 283 |
-
else:
|
| 284 |
-
print("警告!发现了某个方块的manu_lr和manu_lp")
|
| 285 |
-
if block["manu_lr"].shape != (3, 3):
|
| 286 |
-
block["manu_lr"] = R.from_matrix(block["manu_lr"]).as_quat()
|
| 287 |
-
else:
|
| 288 |
-
try:
|
| 289 |
-
bp_id = int(block["bp_id"])
|
| 290 |
-
parent_rot = info[parent]["my_building_points_buildrotation"][bp_id]
|
| 291 |
-
block["manu_lr"] = add_rotations(parent_rot, block["bp_lr"])
|
| 292 |
-
block["manu_lp"] = info[parent]["my_building_points"][bp_id] - gp
|
| 293 |
-
except Exception:
|
| 294 |
-
print(f"警告!parent:{parent},order_id{order_id}的my_building_points或my_building_points_buildrotation不存在")
|
| 295 |
-
# print(info[parent])
|
| 296 |
-
pass
|
| 297 |
-
|
| 298 |
-
if block_id not in ("7", "9"):
|
| 299 |
-
if block_id in FLIP_SENSITIVE_BLOCKS:
|
| 300 |
-
block["flip"] = are_quaternions_similar(block["manu_lr"])
|
| 301 |
-
|
| 302 |
-
bc_bp = block_info['bc_bp']
|
| 303 |
-
bc_gc = block_info['bc_gc']
|
| 304 |
-
bbox_size = block_info['bbox_size']
|
| 305 |
-
|
| 306 |
-
if block_id == "30":
|
| 307 |
-
bc_gc = [0,0,0.5]
|
| 308 |
-
bbox_size = [1,1,1]
|
| 309 |
-
|
| 310 |
-
building_points, build_rotation = get_mybuildingpoints(
|
| 311 |
-
bc_bp, block["manu_lp"], block["manu_lr"], gp, gr,
|
| 312 |
-
bc_gc, bbox_size, scale=block["scale"]
|
| 313 |
-
)
|
| 314 |
-
block["my_building_points"] = building_points
|
| 315 |
-
block["my_building_points_buildrotation"] = build_rotation
|
| 316 |
-
|
| 317 |
-
if log:
|
| 318 |
-
print(f"block_id:{block_id}\nscale:{block['scale']}\nbc_gc:{bc_gc}\n"
|
| 319 |
-
f"bbox_size:{bbox_size}\nmanu_lp:{block['manu_lp']}\n"
|
| 320 |
-
f"manu_lr:{block['manu_lr']}\nmy_building_points:{building_points}\n"
|
| 321 |
-
f"my_building_points_buildrotation:{build_rotation}")
|
| 322 |
-
|
| 323 |
-
return info
|
| 324 |
-
|
| 325 |
-
def llm2xml_filetree(block_details, block_sizes_path, selected_menu=None):
|
| 326 |
-
with open(block_sizes_path, 'r', encoding='utf-8') as file:
|
| 327 |
-
block_sizes = json.load(file)
|
| 328 |
-
|
| 329 |
-
global_rt = block_details.pop(0)
|
| 330 |
-
gp, gr_quat = global_rt["GlobalPosition"], global_rt["GlobalRotation"]
|
| 331 |
-
gr_matrix = R.from_quat(gr_quat).as_matrix()
|
| 332 |
-
|
| 333 |
-
blocks_to_delete = set() # 使用集合以避免重复添加和快速查找
|
| 334 |
-
blocks_to_delete_feedback = []
|
| 335 |
-
|
| 336 |
-
#先对block_details做一个整体格式检查
|
| 337 |
-
linear = {"id","order_id","parent_a", "bp_id_a", "parent_b", "bp_id_b"}
|
| 338 |
-
non_linear = {"id","order_id", "parent", "bp_id"}
|
| 339 |
-
for i, block in enumerate(block_details):
|
| 340 |
-
if not (set(block.keys()) == linear or set(block.keys()) == non_linear):
|
| 341 |
-
blocks_to_delete.add(i)
|
| 342 |
-
blocks_to_delete_feedback.append(
|
| 343 |
-
f"警告:块(orderID {i})结构非法"
|
| 344 |
-
)
|
| 345 |
-
|
| 346 |
-
order_id_map = {int(b["order_id"]): b for b in block_details} # 方便快速查找父块
|
| 347 |
-
|
| 348 |
-
for i,block in enumerate(block_details):
|
| 349 |
-
is_linear = False
|
| 350 |
-
parent_order_a=-1
|
| 351 |
-
parent_order_b=-1
|
| 352 |
-
|
| 353 |
-
#检查一下value的格式
|
| 354 |
-
format_error = False
|
| 355 |
-
for k,v in block.items():
|
| 356 |
-
if k =="id":
|
| 357 |
-
if not isinstance(v,str):
|
| 358 |
-
if isinstance(v,int):
|
| 359 |
-
v = str(v)
|
| 360 |
-
else:
|
| 361 |
-
format_error = True
|
| 362 |
-
|
| 363 |
-
if k in["order_id","parent_a", "bp_id_a", "parent_b", "bp_id_b", "parent", "bp_id"]:
|
| 364 |
-
if not isinstance(v,int):
|
| 365 |
-
if isinstance(v,str):
|
| 366 |
-
try:
|
| 367 |
-
v = int(v)
|
| 368 |
-
except:
|
| 369 |
-
format_error = True
|
| 370 |
-
|
| 371 |
-
if format_error:
|
| 372 |
-
|
| 373 |
-
blocks_to_delete.add(i)
|
| 374 |
-
blocks_to_delete_feedback.append(f"警告:order{i}json格式非法")
|
| 375 |
-
continue
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
#先检查起始方块:
|
| 379 |
-
if i==0:
|
| 380 |
-
block_type = str(block["id"])
|
| 381 |
-
order_id = int(block["order_id"])
|
| 382 |
-
parent_order = int(block.get("parent", -2))
|
| 383 |
-
bp_id = int(block.get("bp_id", -2))
|
| 384 |
-
if any([block_type!="0",order_id!=0]):
|
| 385 |
-
blocks_to_delete.add(i)
|
| 386 |
-
blocks_to_delete_feedback.append(f"警告:起始方块非法")
|
| 387 |
-
continue
|
| 388 |
-
if any([parent_order!=-1,bp_id!=-1]):
|
| 389 |
-
#起始方块不规范,parent bpid改成-1 -1
|
| 390 |
-
block["parent"]=-1
|
| 391 |
-
block["bp_id"]=-1
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
order_id = int(block["order_id"])
|
| 395 |
-
parent_order = int(block.get("parent", -1))
|
| 396 |
-
if parent_order==-1 and order_id!=0:
|
| 397 |
-
is_linear = True
|
| 398 |
-
parent_order_a = int(block.get("parent_a", -1))
|
| 399 |
-
parent_order_b = int(block.get("parent_b", -1))
|
| 400 |
-
parents = [parent_order_a,parent_order_b]
|
| 401 |
-
else:
|
| 402 |
-
parents = [parent_order]
|
| 403 |
-
# 检查1: 父块是否已被标记为非法
|
| 404 |
-
if any(order in blocks_to_delete for order in parents):
|
| 405 |
-
blocks_to_delete.add(order_id)
|
| 406 |
-
blocks_to_delete_feedback.append(f"警告:块(orderID {order_id})的父块(orderID {parent_order})非法,因此也被标记为非法。")
|
| 407 |
-
continue
|
| 408 |
-
# 检查2: 父块的连接点(bp_id)是否有效
|
| 409 |
-
for i_th_parent,parent_order in enumerate(parents):
|
| 410 |
-
parent_block = order_id_map.get(parent_order)
|
| 411 |
-
if parent_block:
|
| 412 |
-
parent_block_id = str(parent_block["id"])
|
| 413 |
-
if i_th_parent==0:
|
| 414 |
-
bp_id = int(block.get("bp_id",block.get("bp_id_a",-1)))
|
| 415 |
-
elif i_th_parent==1:
|
| 416 |
-
bp_id = int(block.get("bp_id_b",-1))
|
| 417 |
-
else:
|
| 418 |
-
bp_id=-1
|
| 419 |
-
if parent_block_id in block_sizes and bp_id >= len(block_sizes[parent_block_id]["bc_bp"]):
|
| 420 |
-
blocks_to_delete.add(order_id)
|
| 421 |
-
blocks_to_delete_feedback.append(f"警告:块(orderID {order_id})的父块(ID {parent_block_id})不存在可建造点{bp_id}。")
|
| 422 |
-
continue
|
| 423 |
-
|
| 424 |
-
# 检查3: 双父块(线性块)的特殊处理
|
| 425 |
-
if (not is_linear) and str(block.get("id")) in ["7", "9"]:
|
| 426 |
-
blocks_to_delete.add(order_id)
|
| 427 |
-
blocks_to_delete_feedback.append(f"警告:块(orderID {order_id})是线性块但不存在双parent属性。")
|
| 428 |
-
continue
|
| 429 |
-
elif is_linear and (str(block.get("id")) not in ["7", "9"]):
|
| 430 |
-
blocks_to_delete.add(order_id)
|
| 431 |
-
blocks_to_delete_feedback.append(f"警告:块(orderID {order_id})存在双parent属性但不是线性块。")
|
| 432 |
-
continue
|
| 433 |
-
|
| 434 |
-
# print(blocks_to_delete_feedback)
|
| 435 |
-
|
| 436 |
-
if blocks_to_delete:
|
| 437 |
-
# 从 block_details 中过滤掉要删除的块
|
| 438 |
-
block_details = [b for b in block_details if int(b["order_id"]) not in blocks_to_delete]
|
| 439 |
-
|
| 440 |
-
# --- 计算 3D 位置并构建 XML 风格列表 ---
|
| 441 |
-
processed_details = get_3d_from_llm(block_sizes, block_details, gp, gr_matrix, log=False)
|
| 442 |
-
# print(block_details)
|
| 443 |
-
xml_block_details = [{"GlobalPosition": gp, "GlobalRotation": gr_quat}]
|
| 444 |
-
for block in processed_details:
|
| 445 |
-
xml_info = {
|
| 446 |
-
"id": block["id"],
|
| 447 |
-
"order_id": block["order_id"],
|
| 448 |
-
"guid": generate_guid()
|
| 449 |
-
}
|
| 450 |
-
|
| 451 |
-
if str(block["id"]) in ["7", "9"]: # 线性块
|
| 452 |
-
xml_info["Transform"] = {"Position": block["manu_lp_a"], "Rotation": np.array([0,0,0,1]), "Scale": block["scale"]}
|
| 453 |
-
xml_info["end-position"] = block["manu_lp_b"] - block["manu_lp_a"]
|
| 454 |
-
else: # 普通块
|
| 455 |
-
manu_lr = R.from_matrix(block["manu_lr"]).as_quat() if block["manu_lr"].shape == (3, 3) else block["manu_lr"]
|
| 456 |
-
xml_info["Transform"] = {"Position": block["manu_lp"], "Rotation": manu_lr, "Scale": block["scale"]}
|
| 457 |
-
if "flip" in block: # 轮子属性
|
| 458 |
-
xml_info.update({"flip": block["flip"], "auto": True, "autobrake": False})
|
| 459 |
-
if selected_menu and "special_props" in selected_menu:
|
| 460 |
-
xml_info["WheelDoubleSpeed"] = "WheelDoubleSpeed" in selected_menu["special_props"]
|
| 461 |
-
|
| 462 |
-
xml_block_details.append(xml_info)
|
| 463 |
-
|
| 464 |
-
# print("\n".join(blocks_to_delete_feedback))
|
| 465 |
-
|
| 466 |
-
return xml_block_details, processed_details, "\n".join(blocks_to_delete_feedback)
|
| 467 |
-
|
| 468 |
-
def facing(q_in):
|
| 469 |
-
q_z_pos = np.array([0, 0, 0, 1])
|
| 470 |
-
q_z_neg = np.array([0, 1, 0, 0])
|
| 471 |
-
q_x_neg = np.array([0, -0.7071068, 0, 0.7071068])
|
| 472 |
-
q_x_pos = np.array([0, 0.7071068, 0, 0.7071068])
|
| 473 |
-
q_y_pos = np.array([-0.7071068,0, 0,0.7071068])
|
| 474 |
-
q_y_neg = np.array([0.7071068,0, 0,0.7071068])
|
| 475 |
-
|
| 476 |
-
angle_threshold = 1e-3
|
| 477 |
-
rots = [q_z_pos,q_z_neg,q_x_neg,q_x_pos,q_y_pos,q_y_neg]
|
| 478 |
-
facing = ["z+","z-","x-","x+","y+","y-"]
|
| 479 |
-
# 将四元数转换为旋转对象
|
| 480 |
-
r1 = R.from_quat(q_in)
|
| 481 |
-
for q2 in range(len(rots)):
|
| 482 |
-
r2 = R.from_quat(rots[q2])
|
| 483 |
-
|
| 484 |
-
# 计算两个旋转之间的夹角差异
|
| 485 |
-
relative_rotation = r1.inv() * r2
|
| 486 |
-
angle = relative_rotation.magnitude()
|
| 487 |
-
|
| 488 |
-
# 如果角度差异小于阈值,则认为两个四元数大致相同
|
| 489 |
-
if(angle < angle_threshold):
|
| 490 |
-
return facing[q2]
|
| 491 |
-
|
| 492 |
-
return "Error!未找到正确方向"
|
| 493 |
-
|
| 494 |
-
def check_overlap_or_connection(cube1, cube2):
|
| 495 |
-
def get_bounds(vertices):
|
| 496 |
-
x_min = min(v[0] for v in vertices)
|
| 497 |
-
x_max = max(v[0] for v in vertices)
|
| 498 |
-
y_min = min(v[1] for v in vertices)
|
| 499 |
-
y_max = max(v[1] for v in vertices)
|
| 500 |
-
z_min = min(v[2] for v in vertices)
|
| 501 |
-
z_max = max(v[2] for v in vertices)
|
| 502 |
-
return x_min, x_max, y_min, y_max, z_min, z_max
|
| 503 |
-
|
| 504 |
-
x1_min, x1_max, y1_min, y1_max, z1_min, z1_max = get_bounds(cube1)
|
| 505 |
-
x2_min, x2_max, y2_min, y2_max, z2_min, z2_max = get_bounds(cube2)
|
| 506 |
-
|
| 507 |
-
if x1_max <= x2_min or x2_max <= x1_min:
|
| 508 |
-
return False
|
| 509 |
-
if y1_max <= y2_min or y2_max <= y1_min:
|
| 510 |
-
return False
|
| 511 |
-
if z1_max <= z2_min or z2_max <= z1_min:
|
| 512 |
-
return False
|
| 513 |
-
|
| 514 |
-
x_overlap = x1_min < x2_max and x2_min < x1_max
|
| 515 |
-
y_overlap = y1_min < y2_max and y2_min < y1_max
|
| 516 |
-
z_overlap = z1_min < z2_max and z2_min < z1_max
|
| 517 |
-
|
| 518 |
-
return x_overlap and y_overlap and z_overlap
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
def check_overlap(block_details,vis=True,corners_parent_llm_parent=None,
|
| 522 |
-
language="zh"):
|
| 523 |
-
|
| 524 |
-
def overlap_log(id1,id2):
|
| 525 |
-
head1 = "方块order_id"
|
| 526 |
-
head2 = "和方块order_id"
|
| 527 |
-
overlap_head = "重叠"
|
| 528 |
-
return f"{head1} {id1} {head2} {id2} {overlap_head}\n"
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
overlaps = []
|
| 532 |
-
connections = []
|
| 533 |
-
# 检查每对方块是否重叠
|
| 534 |
-
overlaps_info=""
|
| 535 |
-
# print(len(block_details))
|
| 536 |
-
# print(len(corners_parent_llm_parent))
|
| 537 |
-
for i in range(len(block_details)):
|
| 538 |
-
# print(block_details[i])
|
| 539 |
-
for j in range(i + 1, len(block_details)):
|
| 540 |
-
if "GlobalPosition" in block_details[i] or "GlobalPosition" in block_details[j]:continue
|
| 541 |
-
# if np.all(block_details[i] == 0) or np.all(block_details[j] == 0): continue
|
| 542 |
-
if "corners" in block_details[i] and "corners" in block_details[j]:
|
| 543 |
-
corners1, id1 = (block_details[i]["corners"],i)
|
| 544 |
-
corners2, id2 = (block_details[j]["corners"],j)
|
| 545 |
-
else:
|
| 546 |
-
corners1 = block_details[i]
|
| 547 |
-
id1 = i
|
| 548 |
-
corners2 = block_details[j]
|
| 549 |
-
id2 = j
|
| 550 |
-
|
| 551 |
-
#print(f"方块order_id {id1} 和方块order_id {id2}")
|
| 552 |
-
results = check_overlap_or_connection(corners1, corners2)
|
| 553 |
-
if results=="connected":
|
| 554 |
-
#print(f"方块order_id {id1} 和方块order_id {id2} 相交")
|
| 555 |
-
connections.append((id1, id2, corners1, corners2))
|
| 556 |
-
elif results:
|
| 557 |
-
if corners_parent_llm_parent !=None:
|
| 558 |
-
id1_type = str(corners_parent_llm_parent[id1][0])
|
| 559 |
-
id1_order = str(corners_parent_llm_parent[id1][1])
|
| 560 |
-
id1_parent_order = str(corners_parent_llm_parent[id1][2])
|
| 561 |
-
id2_type = str(corners_parent_llm_parent[id2][0])
|
| 562 |
-
id2_order = str(corners_parent_llm_parent[id2][1])
|
| 563 |
-
id2_parent_order = str(corners_parent_llm_parent[id2][2])
|
| 564 |
-
if id1_order==id2_parent_order:
|
| 565 |
-
if str(id1_type)=="30":#如果1是2的父节点,并且1是容器
|
| 566 |
-
pass
|
| 567 |
-
else:
|
| 568 |
-
|
| 569 |
-
overlaps_info+=overlap_log(id1,id2)
|
| 570 |
-
overlaps.append((id1, id2, corners1, corners2))
|
| 571 |
-
elif id2_order==id1_parent_order:
|
| 572 |
-
if str(id2_type)=="30":#如果2是1的父节点,并且2是容器
|
| 573 |
-
pass
|
| 574 |
-
else:
|
| 575 |
-
overlaps_info+=overlap_log(id1,id2)
|
| 576 |
-
overlaps.append((id1, id2, corners1, corners2))
|
| 577 |
-
else:
|
| 578 |
-
overlaps_info+=overlap_log(id1,id2)
|
| 579 |
-
overlaps.append((id1, id2, corners1, corners2))
|
| 580 |
-
else:
|
| 581 |
-
overlaps_info+=overlap_log(id1,id2)
|
| 582 |
-
overlaps.append((id1, id2, corners1, corners2))
|
| 583 |
-
|
| 584 |
-
if overlaps:
|
| 585 |
-
# print(f"共发现 {len(overlaps)} 处重叠。")
|
| 586 |
-
found_head = "共发现"
|
| 587 |
-
overlaps_head="处重叠"
|
| 588 |
-
overlaps_info+=f"{found_head} {len(overlaps)} {overlaps_head}\n"
|
| 589 |
-
else:
|
| 590 |
-
# print("没有重叠的方块。")
|
| 591 |
-
overlaps_info+="没有错误"
|
| 592 |
-
|
| 593 |
-
if vis:
|
| 594 |
-
# 可视化结果
|
| 595 |
-
pass
|
| 596 |
-
|
| 597 |
-
#print(overlaps_info)
|
| 598 |
-
return overlaps_info
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
def llm_feedback_3d(block_sizes, xml_block_details, block_details, autofit_gt=True, overlap_feedback=True, language="zh"):
|
| 602 |
-
with open(block_sizes, 'r', encoding='utf-8') as file:
|
| 603 |
-
block_sizes_content = json.load(file)
|
| 604 |
-
|
| 605 |
-
gp, gr = xml_block_details[0]["GlobalPosition"], xml_block_details[0]["GlobalRotation"]
|
| 606 |
-
corners_feedback_forquizzer = "块的3D信息:\n"
|
| 607 |
-
corners_feedback_forbuilder = "块的朝向信息:\n"
|
| 608 |
-
corners_parent_llm, corners_parent_llm_parent = [], []
|
| 609 |
-
|
| 610 |
-
for i, xml_block in enumerate(xml_block_details):
|
| 611 |
-
if "GlobalPosition" in xml_block: continue
|
| 612 |
-
|
| 613 |
-
block_id, order_id = xml_block["id"], xml_block["order_id"]
|
| 614 |
-
if str(block_id) in ("7", "9"):
|
| 615 |
-
corners_parent_llm_parent.append([block_id, order_id, -1])
|
| 616 |
-
corners_parent_llm.append(np.zeros((8,3)))
|
| 617 |
-
continue
|
| 618 |
-
|
| 619 |
-
x_transform = xml_block["Transform"]
|
| 620 |
-
pos, rot, scale = x_transform["Position"], x_transform["Rotation"], x_transform["Scale"]
|
| 621 |
-
# print(pos,rot,scale)
|
| 622 |
-
block_info = block_sizes_content[str(block_id)]
|
| 623 |
-
bbox_lp, bbox_gp = get_bbox(pos, rot, scale, block_info['bc_gc'], block_info['bbox_size'], gp, gr)
|
| 624 |
-
|
| 625 |
-
corners_parent_llm.append(bbox_gp)
|
| 626 |
-
corners_parent_llm_parent.append([block_id, order_id, block_details[i-1]["parent"]])
|
| 627 |
-
|
| 628 |
-
facing_dir = facing(rot)
|
| 629 |
-
corners_feedback_forquizzer += f"order_id:{order_id}\n朝向:{facing_dir}\n块近似长方体顶点位置:{bbox_gp.tolist()}\n"
|
| 630 |
-
corners_feedback_forbuilder += f"order_id:{order_id}\n朝向:{facing_dir}"
|
| 631 |
-
|
| 632 |
-
# Calculate machine dimensions
|
| 633 |
-
corners_arr = np.vstack([c for c in corners_parent_llm if c.size > 0])
|
| 634 |
-
min_vals, max_vals = corners_arr.min(axis=0), corners_arr.max(axis=0)
|
| 635 |
-
lowest_y, highest_y = min_vals[1], max_vals[1]
|
| 636 |
-
left_x, right_x = min_vals[0], max_vals[0]
|
| 637 |
-
back_z, forward_z = min_vals[2], max_vals[2]
|
| 638 |
-
|
| 639 |
-
geo_center = np.array([(right_x + left_x)/2, (highest_y + lowest_y)/2, (forward_z + back_z)/2])
|
| 640 |
-
|
| 641 |
-
if autofit_gt:
|
| 642 |
-
xml_block_details[0]["GlobalPosition"][1] -= (lowest_y - 0.5)
|
| 643 |
-
xml_block_details[0]["GlobalPosition"][0] -= geo_center[0]
|
| 644 |
-
xml_block_details[0]["GlobalPosition"][2] -= geo_center[2]
|
| 645 |
-
|
| 646 |
-
env_fail = (highest_y - lowest_y > 9.5) or (right_x - left_x > 17) or (forward_z - back_z > 17)
|
| 647 |
-
height, wide, long = round(highest_y - lowest_y, 2), round(right_x - left_x, 2), round(forward_z - back_z, 2)
|
| 648 |
-
|
| 649 |
-
# Validate machine structure
|
| 650 |
-
machine_structure_error = ""
|
| 651 |
-
if "corners" in block_details[1]:
|
| 652 |
-
for i, block in enumerate(block_details):
|
| 653 |
-
if "GlobalPosition" in block or str(block.get("id")) in ("7", "9"): continue
|
| 654 |
-
if not np.allclose(block["corners"], corners_parent_llm[i], atol=1e-2):
|
| 655 |
-
machine_structure_error += (f"order_id为{i}的方块的顶点信息不一致!\n"
|
| 656 |
-
f"顶点信息:{block['corners']}\n"
|
| 657 |
-
f"建造点相对信息反推的顶点信息:{corners_parent_llm[i]}\n")
|
| 658 |
-
|
| 659 |
-
overlap_infos = check_overlap(corners_parent_llm, vis=False, corners_parent_llm_parent=corners_parent_llm_parent, language=language) if overlap_feedback else "重叠检查被屏蔽"
|
| 660 |
-
|
| 661 |
-
return (corners_feedback_forquizzer, corners_feedback_forbuilder, env_fail,
|
| 662 |
-
long, wide, height, machine_structure_error, overlap_infos)
|
| 663 |
-
|
| 664 |
-
def create_xml(data):
|
| 665 |
-
"""要加很多功能,因为加入了大量的新块"""
|
| 666 |
-
|
| 667 |
-
machine = ET.Element("Machine", version="1", bsgVersion="1.3", name="
|
| 668 |
-
|
| 669 |
-
# 创建 Global 元素
|
| 670 |
-
global_elem = ET.SubElement(machine, "Global")
|
| 671 |
-
global_infos = data.pop(0)
|
| 672 |
-
gp = global_infos["GlobalPosition"]
|
| 673 |
-
gr = global_infos["GlobalRotation"]
|
| 674 |
-
# if gp[1]<1.5:
|
| 675 |
-
# print("警告,全局高度过低,小于1.5,调整到1.5")
|
| 676 |
-
# gp[1]=1.5
|
| 677 |
-
position = ET.SubElement(global_elem, "Position", x=str(gp[0]), y=str(gp[1]), z=str(gp[2]))
|
| 678 |
-
rotation = ET.SubElement(global_elem, "Rotation", x=str(gr[0]), y=str(gr[1]), z=str(gr[2]), w=str(gr[3]))
|
| 679 |
-
|
| 680 |
-
# 创建 Data 元素
|
| 681 |
-
data_elem = ET.SubElement(machine, "Data")
|
| 682 |
-
string_array = ET.SubElement(data_elem, "StringArray", key="requiredMods")
|
| 683 |
-
|
| 684 |
-
# 创建 Blocks 元素
|
| 685 |
-
blocks_elem = ET.SubElement(machine, "Blocks")
|
| 686 |
-
|
| 687 |
-
# 遍历 corners 数据并创建 Block 元素
|
| 688 |
-
for info in data:
|
| 689 |
-
|
| 690 |
-
block_id = info['id']
|
| 691 |
-
|
| 692 |
-
if info['id']=='18_1':
|
| 693 |
-
block_id ='18'
|
| 694 |
-
|
| 695 |
-
block = ET.SubElement(blocks_elem, "Block", id=str(block_id), guid=info['guid'])
|
| 696 |
-
transform = ET.SubElement(block, "Transform")
|
| 697 |
-
info_p = info['Transform']['Position']
|
| 698 |
-
position = ET.SubElement(transform, "Position", x=str(info_p[0]), y=str(info_p[1]), z=str(info_p[2]))
|
| 699 |
-
info_r = info['Transform']['Rotation']
|
| 700 |
-
rotation = ET.SubElement(transform, "Rotation", x=str(info_r[0]), y=str(info_r[1]), z=str(info_r[2]), w=str(info_r[3]))
|
| 701 |
-
info_s = info['Transform']['Scale']
|
| 702 |
-
scale = ET.SubElement(transform, "Scale", x=str(info_s[0]), y=str(info_s[1]), z=str(info_s[2]))
|
| 703 |
-
block_data = ET.SubElement(block, "Data")
|
| 704 |
-
if str(info['id'])=="0":
|
| 705 |
-
bmt = ET.SubElement(block_data, "Integer", key="bmt-version")
|
| 706 |
-
bmt.text = "1"
|
| 707 |
-
|
| 708 |
-
#线性块设置坐标
|
| 709 |
-
if str(info['id'])=="9":
|
| 710 |
-
bmt = ET.SubElement(block_data,"Single",key = "bmt-slider")
|
| 711 |
-
bmt.text = "10"
|
| 712 |
-
bmt = ET.SubElement(block_data,"StringArray",key = "bmt-contract")
|
| 713 |
-
bmt.text = "L"
|
| 714 |
-
bmt = ET.SubElement(block_data,"Boolean",key = "bmt-toggle")
|
| 715 |
-
bmt.text = "False"
|
| 716 |
-
|
| 717 |
-
if str(info['id'])=="7" or str(info['id'])=="9":
|
| 718 |
-
start_position = ET.SubElement(block_data,"Vector3",key = "start-position")
|
| 719 |
-
ET.SubElement(start_position, "X").text = str(0)
|
| 720 |
-
ET.SubElement(start_position, "Y").text = str(0)
|
| 721 |
-
ET.SubElement(start_position, "Z").text = str(0)
|
| 722 |
-
end_position = ET.SubElement(block_data,"Vector3",key = "end-position")
|
| 723 |
-
ET.SubElement(end_position, "X").text = str(info['end-position'][0])
|
| 724 |
-
ET.SubElement(end_position, "Y").text = str(info['end-position'][1])
|
| 725 |
-
ET.SubElement(end_position, "Z").text = str(info['end-position'][2])
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
if str(info['id'])=="22":
|
| 730 |
-
bmt = ET.SubElement(block_data, "Integer", key="bmt-version")
|
| 731 |
-
bmt.text = "1"
|
| 732 |
-
bmt = ET.SubElement(block_data,"Single",key = "bmt-speed")
|
| 733 |
-
bmt.text = "1"
|
| 734 |
-
bmt = ET.SubElement(block_data,"Single",key = "bmt-acceleration")
|
| 735 |
-
bmt.text = "Infinity"
|
| 736 |
-
bmt = ET.SubElement(block_data, "Boolean", key="bmt-auto-brake")
|
| 737 |
-
bmt.text = "True"
|
| 738 |
-
bmt = ET.SubElement(block_data, "Boolean", key="flipped")
|
| 739 |
-
bmt.text = "False"
|
| 740 |
-
|
| 741 |
-
if str(info['id'])=="35":
|
| 742 |
-
bmt = ET.SubElement(block_data,"Single",key = "bmt-mass")
|
| 743 |
-
bmt.text = "3"
|
| 744 |
-
|
| 745 |
-
|
| 746 |
-
#轮子镜像处理
|
| 747 |
-
if "auto" in info:
|
| 748 |
-
bmt = ET.SubElement(block_data, "Boolean", key="bmt-automatic")
|
| 749 |
-
bmt.text = "True"
|
| 750 |
-
bmt = ET.SubElement(block_data, "Boolean", key="bmt-auto-brake")
|
| 751 |
-
bmt.text = "False"
|
| 752 |
-
if "flip" in info and info["flip"]:
|
| 753 |
-
bmt = ET.SubElement(block_data, "Boolean", key="flipped")
|
| 754 |
-
bmt.text = "True"
|
| 755 |
-
if "WheelDoubleSpeed" in info and info["WheelDoubleSpeed"]:
|
| 756 |
-
bmt = ET.SubElement(block_data, "Single", key="bmt-speed")
|
| 757 |
-
bmt.text = "2"
|
| 758 |
-
|
| 759 |
-
# 将 ElementTree 转换为字符串
|
| 760 |
-
tree = ET.ElementTree(machine)
|
| 761 |
-
ET.indent(tree, space="\t", level=0)
|
| 762 |
-
xml_str = ET.tostring(machine, encoding="utf-8", method="xml", xml_declaration=True).decode("utf-8")
|
| 763 |
-
|
| 764 |
-
return xml_str
|
| 765 |
-
|
| 766 |
-
def json_to_xml(input_obj):
|
| 767 |
-
if isinstance(input_obj,str):
|
| 768 |
-
content = extract_json_from_string(input_obj)
|
| 769 |
-
elif isinstance(input_obj,list):
|
| 770 |
-
content = input_obj
|
| 771 |
-
else:
|
| 772 |
-
raise TypeError('Please make sure input type')
|
| 773 |
-
block_details = content
|
| 774 |
-
block_details = convert_to_numpy(block_details)
|
| 775 |
-
|
| 776 |
-
xml_block_details,block_details,_ = llm2xml_filetree(block_details,
|
| 777 |
-
BLOCKPROPERTYPATH,
|
| 778 |
-
selected_menu=None)
|
| 779 |
-
_,_,_,_,_,_,_,_ = llm_feedback_3d(block_sizes=BLOCKPROPERTYPATH,
|
| 780 |
-
xml_block_details=xml_block_details,
|
| 781 |
-
block_details = block_details)
|
| 782 |
-
xml_string = create_xml(xml_block_details)
|
| 783 |
return xml_string
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
from copy import deepcopy
|
| 4 |
+
import re
|
| 5 |
+
import ast
|
| 6 |
+
import numpy as np
|
| 7 |
+
from scipy.spatial.transform import Rotation as R
|
| 8 |
+
import uuid
|
| 9 |
+
import xml.etree.ElementTree as ET
|
| 10 |
+
|
| 11 |
+
BLOCKPROPERTYPATH=R"Besiege_blocks_markov.json"
|
| 12 |
+
|
| 13 |
+
FLIP_SENSITIVE_BLOCKS = ["2","46"]
|
| 14 |
+
def are_quaternions_similar(q1, angle_threshold=1e-3):
|
| 15 |
+
|
| 16 |
+
q2 = np.array([0, -0.7071068, 0, 0.7071068])
|
| 17 |
+
# 将四元数转换为旋转对象
|
| 18 |
+
r1 = R.from_quat(q1)
|
| 19 |
+
r2 = R.from_quat(q2)
|
| 20 |
+
|
| 21 |
+
# 计算两个旋转之间的夹角差异
|
| 22 |
+
relative_rotation = r1.inv() * r2
|
| 23 |
+
angle = relative_rotation.magnitude()
|
| 24 |
+
|
| 25 |
+
# 如果角度差异小于阈值,则认为两个四元数大致相同
|
| 26 |
+
return angle < angle_threshold
|
| 27 |
+
def generate_guid():
|
| 28 |
+
"""生成一个唯一的GUID"""
|
| 29 |
+
return str(uuid.uuid4())
|
| 30 |
+
|
| 31 |
+
def add_rotations(q1, q2):
|
| 32 |
+
"""叠加两个旋转四元数"""
|
| 33 |
+
r1 = R.from_quat(q1) # 从四元数创建旋转对象
|
| 34 |
+
r2 = R.from_quat(q2) # 从四元数创建旋转对象
|
| 35 |
+
r_combined = r1 * r2 # 叠加旋转
|
| 36 |
+
return r_combined.as_quat() # 返回四元数 (xyzw 格式)
|
| 37 |
+
def read_txt(path):
|
| 38 |
+
"""读取文本文件内容"""
|
| 39 |
+
with open(path, "r", encoding="utf-8") as file:
|
| 40 |
+
return file.read()
|
| 41 |
+
|
| 42 |
+
def write_file(path, content):
|
| 43 |
+
"""将内容写入文本文件"""
|
| 44 |
+
with open(path, 'w', encoding='utf-8') as file:
|
| 45 |
+
file.write(content)
|
| 46 |
+
def extract_json_from_string(input_string: str,return_raw_str=False):
|
| 47 |
+
if isinstance(input_string,list):
|
| 48 |
+
return input_string
|
| 49 |
+
if os.path.exists(input_string):
|
| 50 |
+
input_content = read_txt(input_string)
|
| 51 |
+
else:
|
| 52 |
+
input_content = deepcopy(input_string)
|
| 53 |
+
match = re.search(r"```json(.*?)```", input_content, re.DOTALL)
|
| 54 |
+
if match:
|
| 55 |
+
json_content = match.group(1).strip()
|
| 56 |
+
try:
|
| 57 |
+
if return_raw_str:
|
| 58 |
+
return json.loads(json_content),json_content
|
| 59 |
+
return json.loads(json_content)
|
| 60 |
+
except json.JSONDecodeError:
|
| 61 |
+
pass
|
| 62 |
+
|
| 63 |
+
try:
|
| 64 |
+
if return_raw_str:
|
| 65 |
+
return json.loads(input_content),input_content
|
| 66 |
+
return json.loads(input_content)
|
| 67 |
+
except json.JSONDecodeError:
|
| 68 |
+
try:
|
| 69 |
+
if return_raw_str:
|
| 70 |
+
return json.loads(input_content),input_content
|
| 71 |
+
return ast.literal_eval(input_content)
|
| 72 |
+
except (ValueError, SyntaxError):
|
| 73 |
+
if return_raw_str:
|
| 74 |
+
return None,""
|
| 75 |
+
return None
|
| 76 |
+
|
| 77 |
+
def get_relative_pos_list(bp_oldpos,ref_p,ref_r,scale=1,decimals=None):
|
| 78 |
+
bp_newpos = []
|
| 79 |
+
|
| 80 |
+
if ref_r.shape[0] != 3 or ref_r.shape[1] != 3:
|
| 81 |
+
ref_r = R.from_quat(ref_r).as_matrix() # 如果是四元数,转换为旋转矩阵
|
| 82 |
+
|
| 83 |
+
for point in bp_oldpos:
|
| 84 |
+
point_lp = ref_p+np.dot(ref_r, point*scale)
|
| 85 |
+
bp_newpos.append(tuple(point_lp))
|
| 86 |
+
bp_newpos = np.array(bp_newpos)#可建造点局部位置
|
| 87 |
+
|
| 88 |
+
if decimals!=None:
|
| 89 |
+
bp_newpos = np.round(bp_newpos,decimals=decimals)
|
| 90 |
+
|
| 91 |
+
return bp_newpos
|
| 92 |
+
|
| 93 |
+
def get_bbox(manu_lp,manu_lr,scale,bc_gc,bbox_size,gp,gr):
|
| 94 |
+
|
| 95 |
+
if manu_lr.shape[0] != 3 or manu_lr.shape[1] != 3:
|
| 96 |
+
manu_lr = R.from_quat(manu_lr).as_matrix()
|
| 97 |
+
if gr.shape[0] != 3 or gr.shape[1] != 3:
|
| 98 |
+
gr = R.from_quat(gr).as_matrix()
|
| 99 |
+
|
| 100 |
+
half_bbox_size = np.array(bbox_size) / 2.0
|
| 101 |
+
bbox_lp = []
|
| 102 |
+
for z in [-1, 1]:
|
| 103 |
+
for x in [-1, 1]:
|
| 104 |
+
for y in [-1, 1]:
|
| 105 |
+
point = (manu_lp+bc_gc) + (x * half_bbox_size[0], y * half_bbox_size[1], z * half_bbox_size[2])
|
| 106 |
+
bc_point = point-manu_lp
|
| 107 |
+
point_lp = manu_lp+np.dot(manu_lr, bc_point*scale)
|
| 108 |
+
bbox_lp.append(tuple(point_lp))
|
| 109 |
+
bbox_lp = np.array(bbox_lp)#碰撞盒顶点相对位置
|
| 110 |
+
|
| 111 |
+
bbox_gp = get_relative_pos_list(bbox_lp,gp,gr,decimals=2)
|
| 112 |
+
return bbox_lp,bbox_gp
|
| 113 |
+
|
| 114 |
+
def compute_normal_vector(vertices, bp):
|
| 115 |
+
bp = np.round(bp, decimals=3)
|
| 116 |
+
|
| 117 |
+
# 计算每个维度的最小和最大坐标值
|
| 118 |
+
min_coords = np.min(vertices, axis=0)
|
| 119 |
+
max_coords = np.max(vertices, axis=0)
|
| 120 |
+
|
| 121 |
+
# 初始化法向量
|
| 122 |
+
normal = np.zeros(3)
|
| 123 |
+
# epsilon = 5e-4 # 容差范围,还算严格
|
| 124 |
+
epsilon = 0.005 # 容差范围
|
| 125 |
+
|
| 126 |
+
# 检查点是否在x方向的面上
|
| 127 |
+
if abs(bp[0] - min_coords[0]) < epsilon:
|
| 128 |
+
normal = np.array([-1, 0, 0]) # 左面法向量
|
| 129 |
+
elif abs(bp[0] - max_coords[0]) < epsilon:
|
| 130 |
+
normal = np.array([1, 0, 0]) # 右面法向量
|
| 131 |
+
# 检查y方向
|
| 132 |
+
elif abs(bp[1] - min_coords[1]) < epsilon:
|
| 133 |
+
normal = np.array([0, -1, 0]) # 下面法向量
|
| 134 |
+
elif abs(bp[1] - max_coords[1]) < epsilon:
|
| 135 |
+
normal = np.array([0, 1, 0]) # 上面法向量
|
| 136 |
+
# 检查z方向
|
| 137 |
+
elif abs(bp[2] - min_coords[2]) < epsilon:
|
| 138 |
+
normal = np.array([0, 0, -1]) # 后面法向量
|
| 139 |
+
elif abs(bp[2] - max_coords[2]) < epsilon:
|
| 140 |
+
normal = np.array([0, 0, 1]) # 前面法向量
|
| 141 |
+
else:
|
| 142 |
+
raise ValueError("点不在长方体的任何一个面上")
|
| 143 |
+
|
| 144 |
+
return normal
|
| 145 |
+
|
| 146 |
+
def get_mybuildingpoints(bc_bp,manu_lp,manu_lr,gp,gr,bc_gc,bbox_size,scale=1):
|
| 147 |
+
|
| 148 |
+
bp_ori = np.array(bc_bp)
|
| 149 |
+
bp_lp = get_relative_pos_list(bp_ori,manu_lp,manu_lr,scale=scale)
|
| 150 |
+
bp_gp = get_relative_pos_list(bp_lp,gp,gr,decimals=2)
|
| 151 |
+
bbox_lp,bbox_gp = get_bbox(manu_lp,manu_lr,scale,bc_gc,bbox_size,gp,gr)
|
| 152 |
+
|
| 153 |
+
my_building_points = bp_gp.copy()
|
| 154 |
+
my_building_points_buildrotation=[]
|
| 155 |
+
# print(f"bp_gp:{bp_gp}")
|
| 156 |
+
|
| 157 |
+
for i in range(len(my_building_points)):
|
| 158 |
+
# print(f"bp_lp:{bp_lp[i]}")
|
| 159 |
+
# print(f"bbox_lp:{bbox_lp}")
|
| 160 |
+
normal_vector_l = compute_normal_vector(bbox_lp,bp_lp[i])
|
| 161 |
+
rotated_initvec = np.array([0,0,1])
|
| 162 |
+
building_points_rot_quat = rotation_quaternion(rotated_initvec,normal_vector_l)
|
| 163 |
+
my_building_points_buildrotation.append(building_points_rot_quat) #这个是对的
|
| 164 |
+
my_building_points_buildrotation = np.array(my_building_points_buildrotation)
|
| 165 |
+
|
| 166 |
+
return my_building_points,my_building_points_buildrotation
|
| 167 |
+
|
| 168 |
+
def rotation_quaternion(v_from, v_to):
|
| 169 |
+
"""计算从 v_from 到 v_to 的旋转四元数 (xyzw 格式)"""
|
| 170 |
+
v_from = v_from / np.linalg.norm(v_from) # 单位化
|
| 171 |
+
v_to = v_to / np.linalg.norm(v_to) # 单位化
|
| 172 |
+
|
| 173 |
+
# 计算旋转轴和旋转角
|
| 174 |
+
cross = np.cross(v_from, v_to)
|
| 175 |
+
dot = np.dot(v_from, v_to)
|
| 176 |
+
|
| 177 |
+
if np.allclose(cross, 0) and np.allclose(dot, 1):
|
| 178 |
+
return np.array([0, 0, 0, 1]) # 无需旋转
|
| 179 |
+
elif np.allclose(cross, 0) and np.allclose(dot, -1):
|
| 180 |
+
# 特殊情况:v_from 和 v_to 反方向
|
| 181 |
+
# 选择一个垂直于 v_from 的轴作为旋转轴
|
| 182 |
+
if np.isclose(v_from[0], 0) and np.isclose(v_from[1], 0):
|
| 183 |
+
axis = np.array([0, 1, 0]) # 如果 v_from 在 z 轴上,选择 y 轴作为旋转轴
|
| 184 |
+
else:
|
| 185 |
+
axis = np.cross(v_from, np.array([0, 1, 0])) # 选择垂直于 v_from 和 y 轴的向量
|
| 186 |
+
axis = axis / np.linalg.norm(axis)
|
| 187 |
+
angle = np.pi
|
| 188 |
+
else:
|
| 189 |
+
angle = np.arccos(dot)
|
| 190 |
+
axis = cross / np.linalg.norm(cross)
|
| 191 |
+
|
| 192 |
+
# 生成四元数
|
| 193 |
+
q = R.from_rotvec(axis * angle).as_quat() # xyzw格式
|
| 194 |
+
return q
|
| 195 |
+
|
| 196 |
+
def format_json(input_json):
|
| 197 |
+
try:
|
| 198 |
+
new_clean_json=[]
|
| 199 |
+
for json_info in input_json:
|
| 200 |
+
new_clean_dict={}
|
| 201 |
+
if int(json_info["id"]) not in [7,9]:
|
| 202 |
+
new_clean_dict["id"]=str(json_info["id"])
|
| 203 |
+
new_clean_dict["order_id"]=int(json_info["order_id"])
|
| 204 |
+
new_clean_dict["parent"]=int(json_info["parent"])
|
| 205 |
+
new_clean_dict["bp_id"]=int(json_info["bp_id"])
|
| 206 |
+
else:
|
| 207 |
+
new_clean_dict["id"]=str(json_info["id"])
|
| 208 |
+
new_clean_dict["order_id"]=int(json_info["order_id"])
|
| 209 |
+
new_clean_dict["parent_a"]=int(json_info["parent_a"])
|
| 210 |
+
new_clean_dict["bp_id_a"]=int(json_info["bp_id_a"])
|
| 211 |
+
new_clean_dict["parent_b"]=int(json_info["parent_b"])
|
| 212 |
+
new_clean_dict["bp_id_b"]=int(json_info["bp_id_b"])
|
| 213 |
+
new_clean_json.append(new_clean_dict)
|
| 214 |
+
return new_clean_json
|
| 215 |
+
except:
|
| 216 |
+
return input_json
|
| 217 |
+
|
| 218 |
+
def convert_to_numpy(data):
|
| 219 |
+
no_globalrt = True
|
| 220 |
+
for info in data:
|
| 221 |
+
if "GlobalPosition" in info:
|
| 222 |
+
info["GlobalPosition"] = np.array(info["GlobalPosition"])
|
| 223 |
+
info["GlobalRotation"] = np.array(info["GlobalRotation"])
|
| 224 |
+
no_globalrt = False
|
| 225 |
+
else:
|
| 226 |
+
|
| 227 |
+
keys_to_convert = ["corners", "building_center", "scale","manu_lr","manu_lp","bp_lr"]
|
| 228 |
+
for key in keys_to_convert:
|
| 229 |
+
if key in info:
|
| 230 |
+
info[key] = np.array(info[key])
|
| 231 |
+
|
| 232 |
+
new_data = [{"GlobalPosition":np.array([0,5.05,0]),"GlobalRotation":np.array([0,0,0,1])}]
|
| 233 |
+
if no_globalrt:
|
| 234 |
+
new_data.extend(data)
|
| 235 |
+
return new_data
|
| 236 |
+
|
| 237 |
+
return data # 返回原始数据
|
| 238 |
+
|
| 239 |
+
def get_3d_from_llm(block_sizes, input_info, gp, gr, log=False):
|
| 240 |
+
info = deepcopy(input_info)
|
| 241 |
+
for block in info:
|
| 242 |
+
order_id = int(block["order_id"])
|
| 243 |
+
block_id = str(block["id"])
|
| 244 |
+
|
| 245 |
+
# Handle scale
|
| 246 |
+
if "scale" not in block:
|
| 247 |
+
block["scale"] = np.array([1,1,1])
|
| 248 |
+
else:
|
| 249 |
+
print(f"警告!{order_id}改变了scale!使用初始值")
|
| 250 |
+
block["scale"] = np.array([1,1,1])
|
| 251 |
+
|
| 252 |
+
# Handle rotations
|
| 253 |
+
if "bp_lr" not in block:
|
| 254 |
+
if "manu_lr" not in block:
|
| 255 |
+
block["bp_lr"] = np.array([0,0,0,1])
|
| 256 |
+
elif "manu_lr" in block and str(block.get("parent", "")) not in ("-1", ""):
|
| 257 |
+
print(f"警告!{order_id}有manu_lr但不是根节点!旋转使用初始值")
|
| 258 |
+
block["bp_lr"] = np.array([0,0,0,1])
|
| 259 |
+
block.pop("manu_lr", None)
|
| 260 |
+
|
| 261 |
+
block_info = block_sizes[block_id]
|
| 262 |
+
parent = int(block.get("parent", -1))
|
| 263 |
+
|
| 264 |
+
# Handle parent cases
|
| 265 |
+
if parent == -1:
|
| 266 |
+
if block_id not in ("0","7", "9"):
|
| 267 |
+
print("警告!发现了非起始方块的无父节点块")
|
| 268 |
+
|
| 269 |
+
if block_id in ("7", "9"):
|
| 270 |
+
parent_a, parent_b = int(block["parent_a"]), int(block["parent_b"])
|
| 271 |
+
bp_id_a, bp_id_b = int(block["bp_id_a"]), int(block["bp_id_b"])
|
| 272 |
+
block["bp_lr"] = np.array([0,0,0,1])
|
| 273 |
+
block["manu_lr"] = add_rotations(
|
| 274 |
+
info[parent_a]["my_building_points_buildrotation"][bp_id_a],
|
| 275 |
+
block["bp_lr"]
|
| 276 |
+
)
|
| 277 |
+
block["manu_lp_a"] = info[parent_a]["my_building_points"][bp_id_a] - gp
|
| 278 |
+
block["manu_lp_b"] = info[parent_b]["my_building_points"][bp_id_b] - gp
|
| 279 |
+
else:
|
| 280 |
+
if "manu_lr" not in block:
|
| 281 |
+
block["manu_lr"] = np.array([0,0,0,1])
|
| 282 |
+
block["manu_lp"] = np.array([0,0,0])
|
| 283 |
+
else:
|
| 284 |
+
print("警告!发现了某个方块的manu_lr和manu_lp")
|
| 285 |
+
if block["manu_lr"].shape != (3, 3):
|
| 286 |
+
block["manu_lr"] = R.from_matrix(block["manu_lr"]).as_quat()
|
| 287 |
+
else:
|
| 288 |
+
try:
|
| 289 |
+
bp_id = int(block["bp_id"])
|
| 290 |
+
parent_rot = info[parent]["my_building_points_buildrotation"][bp_id]
|
| 291 |
+
block["manu_lr"] = add_rotations(parent_rot, block["bp_lr"])
|
| 292 |
+
block["manu_lp"] = info[parent]["my_building_points"][bp_id] - gp
|
| 293 |
+
except Exception:
|
| 294 |
+
print(f"警告!parent:{parent},order_id{order_id}的my_building_points或my_building_points_buildrotation不存在")
|
| 295 |
+
# print(info[parent])
|
| 296 |
+
pass
|
| 297 |
+
|
| 298 |
+
if block_id not in ("7", "9"):
|
| 299 |
+
if block_id in FLIP_SENSITIVE_BLOCKS:
|
| 300 |
+
block["flip"] = are_quaternions_similar(block["manu_lr"])
|
| 301 |
+
|
| 302 |
+
bc_bp = block_info['bc_bp']
|
| 303 |
+
bc_gc = block_info['bc_gc']
|
| 304 |
+
bbox_size = block_info['bbox_size']
|
| 305 |
+
|
| 306 |
+
if block_id == "30":
|
| 307 |
+
bc_gc = [0,0,0.5]
|
| 308 |
+
bbox_size = [1,1,1]
|
| 309 |
+
|
| 310 |
+
building_points, build_rotation = get_mybuildingpoints(
|
| 311 |
+
bc_bp, block["manu_lp"], block["manu_lr"], gp, gr,
|
| 312 |
+
bc_gc, bbox_size, scale=block["scale"]
|
| 313 |
+
)
|
| 314 |
+
block["my_building_points"] = building_points
|
| 315 |
+
block["my_building_points_buildrotation"] = build_rotation
|
| 316 |
+
|
| 317 |
+
if log:
|
| 318 |
+
print(f"block_id:{block_id}\nscale:{block['scale']}\nbc_gc:{bc_gc}\n"
|
| 319 |
+
f"bbox_size:{bbox_size}\nmanu_lp:{block['manu_lp']}\n"
|
| 320 |
+
f"manu_lr:{block['manu_lr']}\nmy_building_points:{building_points}\n"
|
| 321 |
+
f"my_building_points_buildrotation:{build_rotation}")
|
| 322 |
+
|
| 323 |
+
return info
|
| 324 |
+
|
| 325 |
+
def llm2xml_filetree(block_details, block_sizes_path, selected_menu=None):
|
| 326 |
+
with open(block_sizes_path, 'r', encoding='utf-8') as file:
|
| 327 |
+
block_sizes = json.load(file)
|
| 328 |
+
|
| 329 |
+
global_rt = block_details.pop(0)
|
| 330 |
+
gp, gr_quat = global_rt["GlobalPosition"], global_rt["GlobalRotation"]
|
| 331 |
+
gr_matrix = R.from_quat(gr_quat).as_matrix()
|
| 332 |
+
|
| 333 |
+
blocks_to_delete = set() # 使用集合以避免重复添加和快速查找
|
| 334 |
+
blocks_to_delete_feedback = []
|
| 335 |
+
|
| 336 |
+
#先对block_details做一个整体格式检查
|
| 337 |
+
linear = {"id","order_id","parent_a", "bp_id_a", "parent_b", "bp_id_b"}
|
| 338 |
+
non_linear = {"id","order_id", "parent", "bp_id"}
|
| 339 |
+
for i, block in enumerate(block_details):
|
| 340 |
+
if not (set(block.keys()) == linear or set(block.keys()) == non_linear):
|
| 341 |
+
blocks_to_delete.add(i)
|
| 342 |
+
blocks_to_delete_feedback.append(
|
| 343 |
+
f"警告:块(orderID {i})结构非法"
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
order_id_map = {int(b["order_id"]): b for b in block_details} # 方便快速查找父块
|
| 347 |
+
|
| 348 |
+
for i,block in enumerate(block_details):
|
| 349 |
+
is_linear = False
|
| 350 |
+
parent_order_a=-1
|
| 351 |
+
parent_order_b=-1
|
| 352 |
+
|
| 353 |
+
#检查一下value的格式
|
| 354 |
+
format_error = False
|
| 355 |
+
for k,v in block.items():
|
| 356 |
+
if k =="id":
|
| 357 |
+
if not isinstance(v,str):
|
| 358 |
+
if isinstance(v,int):
|
| 359 |
+
v = str(v)
|
| 360 |
+
else:
|
| 361 |
+
format_error = True
|
| 362 |
+
|
| 363 |
+
if k in["order_id","parent_a", "bp_id_a", "parent_b", "bp_id_b", "parent", "bp_id"]:
|
| 364 |
+
if not isinstance(v,int):
|
| 365 |
+
if isinstance(v,str):
|
| 366 |
+
try:
|
| 367 |
+
v = int(v)
|
| 368 |
+
except:
|
| 369 |
+
format_error = True
|
| 370 |
+
|
| 371 |
+
if format_error:
|
| 372 |
+
|
| 373 |
+
blocks_to_delete.add(i)
|
| 374 |
+
blocks_to_delete_feedback.append(f"警告:order{i}json格式非法")
|
| 375 |
+
continue
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
#先检查起始方块:
|
| 379 |
+
if i==0:
|
| 380 |
+
block_type = str(block["id"])
|
| 381 |
+
order_id = int(block["order_id"])
|
| 382 |
+
parent_order = int(block.get("parent", -2))
|
| 383 |
+
bp_id = int(block.get("bp_id", -2))
|
| 384 |
+
if any([block_type!="0",order_id!=0]):
|
| 385 |
+
blocks_to_delete.add(i)
|
| 386 |
+
blocks_to_delete_feedback.append(f"警告:起始方块非法")
|
| 387 |
+
continue
|
| 388 |
+
if any([parent_order!=-1,bp_id!=-1]):
|
| 389 |
+
#起始方块不规范,parent bpid改成-1 -1
|
| 390 |
+
block["parent"]=-1
|
| 391 |
+
block["bp_id"]=-1
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
order_id = int(block["order_id"])
|
| 395 |
+
parent_order = int(block.get("parent", -1))
|
| 396 |
+
if parent_order==-1 and order_id!=0:
|
| 397 |
+
is_linear = True
|
| 398 |
+
parent_order_a = int(block.get("parent_a", -1))
|
| 399 |
+
parent_order_b = int(block.get("parent_b", -1))
|
| 400 |
+
parents = [parent_order_a,parent_order_b]
|
| 401 |
+
else:
|
| 402 |
+
parents = [parent_order]
|
| 403 |
+
# 检查1: 父块是否已被标记为非法
|
| 404 |
+
if any(order in blocks_to_delete for order in parents):
|
| 405 |
+
blocks_to_delete.add(order_id)
|
| 406 |
+
blocks_to_delete_feedback.append(f"警告:块(orderID {order_id})的父块(orderID {parent_order})非法,因此也被标记为非法。")
|
| 407 |
+
continue
|
| 408 |
+
# 检查2: 父块的连接点(bp_id)是否有效
|
| 409 |
+
for i_th_parent,parent_order in enumerate(parents):
|
| 410 |
+
parent_block = order_id_map.get(parent_order)
|
| 411 |
+
if parent_block:
|
| 412 |
+
parent_block_id = str(parent_block["id"])
|
| 413 |
+
if i_th_parent==0:
|
| 414 |
+
bp_id = int(block.get("bp_id",block.get("bp_id_a",-1)))
|
| 415 |
+
elif i_th_parent==1:
|
| 416 |
+
bp_id = int(block.get("bp_id_b",-1))
|
| 417 |
+
else:
|
| 418 |
+
bp_id=-1
|
| 419 |
+
if parent_block_id in block_sizes and bp_id >= len(block_sizes[parent_block_id]["bc_bp"]):
|
| 420 |
+
blocks_to_delete.add(order_id)
|
| 421 |
+
blocks_to_delete_feedback.append(f"警告:块(orderID {order_id})的父块(ID {parent_block_id})不存在可建造点{bp_id}。")
|
| 422 |
+
continue
|
| 423 |
+
|
| 424 |
+
# 检查3: 双父块(线性块)的特殊处理
|
| 425 |
+
if (not is_linear) and str(block.get("id")) in ["7", "9"]:
|
| 426 |
+
blocks_to_delete.add(order_id)
|
| 427 |
+
blocks_to_delete_feedback.append(f"警告:块(orderID {order_id})是线性块但不存在双parent属性。")
|
| 428 |
+
continue
|
| 429 |
+
elif is_linear and (str(block.get("id")) not in ["7", "9"]):
|
| 430 |
+
blocks_to_delete.add(order_id)
|
| 431 |
+
blocks_to_delete_feedback.append(f"警告:块(orderID {order_id})存在双parent属性但不是线性块。")
|
| 432 |
+
continue
|
| 433 |
+
|
| 434 |
+
# print(blocks_to_delete_feedback)
|
| 435 |
+
|
| 436 |
+
if blocks_to_delete:
|
| 437 |
+
# 从 block_details 中过滤掉要删除的块
|
| 438 |
+
block_details = [b for b in block_details if int(b["order_id"]) not in blocks_to_delete]
|
| 439 |
+
|
| 440 |
+
# --- 计算 3D 位置并构建 XML 风格列表 ---
|
| 441 |
+
processed_details = get_3d_from_llm(block_sizes, block_details, gp, gr_matrix, log=False)
|
| 442 |
+
# print(block_details)
|
| 443 |
+
xml_block_details = [{"GlobalPosition": gp, "GlobalRotation": gr_quat}]
|
| 444 |
+
for block in processed_details:
|
| 445 |
+
xml_info = {
|
| 446 |
+
"id": block["id"],
|
| 447 |
+
"order_id": block["order_id"],
|
| 448 |
+
"guid": generate_guid()
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
if str(block["id"]) in ["7", "9"]: # 线性块
|
| 452 |
+
xml_info["Transform"] = {"Position": block["manu_lp_a"], "Rotation": np.array([0,0,0,1]), "Scale": block["scale"]}
|
| 453 |
+
xml_info["end-position"] = block["manu_lp_b"] - block["manu_lp_a"]
|
| 454 |
+
else: # 普通块
|
| 455 |
+
manu_lr = R.from_matrix(block["manu_lr"]).as_quat() if block["manu_lr"].shape == (3, 3) else block["manu_lr"]
|
| 456 |
+
xml_info["Transform"] = {"Position": block["manu_lp"], "Rotation": manu_lr, "Scale": block["scale"]}
|
| 457 |
+
if "flip" in block: # 轮子属性
|
| 458 |
+
xml_info.update({"flip": block["flip"], "auto": True, "autobrake": False})
|
| 459 |
+
if selected_menu and "special_props" in selected_menu:
|
| 460 |
+
xml_info["WheelDoubleSpeed"] = "WheelDoubleSpeed" in selected_menu["special_props"]
|
| 461 |
+
|
| 462 |
+
xml_block_details.append(xml_info)
|
| 463 |
+
|
| 464 |
+
# print("\n".join(blocks_to_delete_feedback))
|
| 465 |
+
|
| 466 |
+
return xml_block_details, processed_details, "\n".join(blocks_to_delete_feedback)
|
| 467 |
+
|
| 468 |
+
def facing(q_in):
|
| 469 |
+
q_z_pos = np.array([0, 0, 0, 1])
|
| 470 |
+
q_z_neg = np.array([0, 1, 0, 0])
|
| 471 |
+
q_x_neg = np.array([0, -0.7071068, 0, 0.7071068])
|
| 472 |
+
q_x_pos = np.array([0, 0.7071068, 0, 0.7071068])
|
| 473 |
+
q_y_pos = np.array([-0.7071068,0, 0,0.7071068])
|
| 474 |
+
q_y_neg = np.array([0.7071068,0, 0,0.7071068])
|
| 475 |
+
|
| 476 |
+
angle_threshold = 1e-3
|
| 477 |
+
rots = [q_z_pos,q_z_neg,q_x_neg,q_x_pos,q_y_pos,q_y_neg]
|
| 478 |
+
facing = ["z+","z-","x-","x+","y+","y-"]
|
| 479 |
+
# 将四元数转换为旋转对象
|
| 480 |
+
r1 = R.from_quat(q_in)
|
| 481 |
+
for q2 in range(len(rots)):
|
| 482 |
+
r2 = R.from_quat(rots[q2])
|
| 483 |
+
|
| 484 |
+
# 计算两个旋转之间的夹角差异
|
| 485 |
+
relative_rotation = r1.inv() * r2
|
| 486 |
+
angle = relative_rotation.magnitude()
|
| 487 |
+
|
| 488 |
+
# 如果角度差异小于阈值,则认为两个四元数大致相同
|
| 489 |
+
if(angle < angle_threshold):
|
| 490 |
+
return facing[q2]
|
| 491 |
+
|
| 492 |
+
return "Error!未找到正确方向"
|
| 493 |
+
|
| 494 |
+
def check_overlap_or_connection(cube1, cube2):
|
| 495 |
+
def get_bounds(vertices):
|
| 496 |
+
x_min = min(v[0] for v in vertices)
|
| 497 |
+
x_max = max(v[0] for v in vertices)
|
| 498 |
+
y_min = min(v[1] for v in vertices)
|
| 499 |
+
y_max = max(v[1] for v in vertices)
|
| 500 |
+
z_min = min(v[2] for v in vertices)
|
| 501 |
+
z_max = max(v[2] for v in vertices)
|
| 502 |
+
return x_min, x_max, y_min, y_max, z_min, z_max
|
| 503 |
+
|
| 504 |
+
x1_min, x1_max, y1_min, y1_max, z1_min, z1_max = get_bounds(cube1)
|
| 505 |
+
x2_min, x2_max, y2_min, y2_max, z2_min, z2_max = get_bounds(cube2)
|
| 506 |
+
|
| 507 |
+
if x1_max <= x2_min or x2_max <= x1_min:
|
| 508 |
+
return False
|
| 509 |
+
if y1_max <= y2_min or y2_max <= y1_min:
|
| 510 |
+
return False
|
| 511 |
+
if z1_max <= z2_min or z2_max <= z1_min:
|
| 512 |
+
return False
|
| 513 |
+
|
| 514 |
+
x_overlap = x1_min < x2_max and x2_min < x1_max
|
| 515 |
+
y_overlap = y1_min < y2_max and y2_min < y1_max
|
| 516 |
+
z_overlap = z1_min < z2_max and z2_min < z1_max
|
| 517 |
+
|
| 518 |
+
return x_overlap and y_overlap and z_overlap
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
def check_overlap(block_details,vis=True,corners_parent_llm_parent=None,
|
| 522 |
+
language="zh"):
|
| 523 |
+
|
| 524 |
+
def overlap_log(id1,id2):
|
| 525 |
+
head1 = "方块order_id"
|
| 526 |
+
head2 = "和方块order_id"
|
| 527 |
+
overlap_head = "重叠"
|
| 528 |
+
return f"{head1} {id1} {head2} {id2} {overlap_head}\n"
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
overlaps = []
|
| 532 |
+
connections = []
|
| 533 |
+
# 检查每对方块是否重叠
|
| 534 |
+
overlaps_info=""
|
| 535 |
+
# print(len(block_details))
|
| 536 |
+
# print(len(corners_parent_llm_parent))
|
| 537 |
+
for i in range(len(block_details)):
|
| 538 |
+
# print(block_details[i])
|
| 539 |
+
for j in range(i + 1, len(block_details)):
|
| 540 |
+
if "GlobalPosition" in block_details[i] or "GlobalPosition" in block_details[j]:continue
|
| 541 |
+
# if np.all(block_details[i] == 0) or np.all(block_details[j] == 0): continue
|
| 542 |
+
if "corners" in block_details[i] and "corners" in block_details[j]:
|
| 543 |
+
corners1, id1 = (block_details[i]["corners"],i)
|
| 544 |
+
corners2, id2 = (block_details[j]["corners"],j)
|
| 545 |
+
else:
|
| 546 |
+
corners1 = block_details[i]
|
| 547 |
+
id1 = i
|
| 548 |
+
corners2 = block_details[j]
|
| 549 |
+
id2 = j
|
| 550 |
+
|
| 551 |
+
#print(f"方块order_id {id1} 和方块order_id {id2}")
|
| 552 |
+
results = check_overlap_or_connection(corners1, corners2)
|
| 553 |
+
if results=="connected":
|
| 554 |
+
#print(f"方块order_id {id1} 和方块order_id {id2} 相交")
|
| 555 |
+
connections.append((id1, id2, corners1, corners2))
|
| 556 |
+
elif results:
|
| 557 |
+
if corners_parent_llm_parent !=None:
|
| 558 |
+
id1_type = str(corners_parent_llm_parent[id1][0])
|
| 559 |
+
id1_order = str(corners_parent_llm_parent[id1][1])
|
| 560 |
+
id1_parent_order = str(corners_parent_llm_parent[id1][2])
|
| 561 |
+
id2_type = str(corners_parent_llm_parent[id2][0])
|
| 562 |
+
id2_order = str(corners_parent_llm_parent[id2][1])
|
| 563 |
+
id2_parent_order = str(corners_parent_llm_parent[id2][2])
|
| 564 |
+
if id1_order==id2_parent_order:
|
| 565 |
+
if str(id1_type)=="30":#如果1是2的父节点,并且1是容器
|
| 566 |
+
pass
|
| 567 |
+
else:
|
| 568 |
+
|
| 569 |
+
overlaps_info+=overlap_log(id1,id2)
|
| 570 |
+
overlaps.append((id1, id2, corners1, corners2))
|
| 571 |
+
elif id2_order==id1_parent_order:
|
| 572 |
+
if str(id2_type)=="30":#如果2是1的父节点,并且2是容器
|
| 573 |
+
pass
|
| 574 |
+
else:
|
| 575 |
+
overlaps_info+=overlap_log(id1,id2)
|
| 576 |
+
overlaps.append((id1, id2, corners1, corners2))
|
| 577 |
+
else:
|
| 578 |
+
overlaps_info+=overlap_log(id1,id2)
|
| 579 |
+
overlaps.append((id1, id2, corners1, corners2))
|
| 580 |
+
else:
|
| 581 |
+
overlaps_info+=overlap_log(id1,id2)
|
| 582 |
+
overlaps.append((id1, id2, corners1, corners2))
|
| 583 |
+
|
| 584 |
+
if overlaps:
|
| 585 |
+
# print(f"共发现 {len(overlaps)} 处重叠。")
|
| 586 |
+
found_head = "共发现"
|
| 587 |
+
overlaps_head="处重叠"
|
| 588 |
+
overlaps_info+=f"{found_head} {len(overlaps)} {overlaps_head}\n"
|
| 589 |
+
else:
|
| 590 |
+
# print("没有重叠的方块。")
|
| 591 |
+
overlaps_info+="没有错误"
|
| 592 |
+
|
| 593 |
+
if vis:
|
| 594 |
+
# 可视化结果
|
| 595 |
+
pass
|
| 596 |
+
|
| 597 |
+
#print(overlaps_info)
|
| 598 |
+
return overlaps_info
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
def llm_feedback_3d(block_sizes, xml_block_details, block_details, autofit_gt=True, overlap_feedback=True, language="zh"):
|
| 602 |
+
with open(block_sizes, 'r', encoding='utf-8') as file:
|
| 603 |
+
block_sizes_content = json.load(file)
|
| 604 |
+
|
| 605 |
+
gp, gr = xml_block_details[0]["GlobalPosition"], xml_block_details[0]["GlobalRotation"]
|
| 606 |
+
corners_feedback_forquizzer = "块的3D信息:\n"
|
| 607 |
+
corners_feedback_forbuilder = "块的朝向信息:\n"
|
| 608 |
+
corners_parent_llm, corners_parent_llm_parent = [], []
|
| 609 |
+
|
| 610 |
+
for i, xml_block in enumerate(xml_block_details):
|
| 611 |
+
if "GlobalPosition" in xml_block: continue
|
| 612 |
+
|
| 613 |
+
block_id, order_id = xml_block["id"], xml_block["order_id"]
|
| 614 |
+
if str(block_id) in ("7", "9"):
|
| 615 |
+
corners_parent_llm_parent.append([block_id, order_id, -1])
|
| 616 |
+
corners_parent_llm.append(np.zeros((8,3)))
|
| 617 |
+
continue
|
| 618 |
+
|
| 619 |
+
x_transform = xml_block["Transform"]
|
| 620 |
+
pos, rot, scale = x_transform["Position"], x_transform["Rotation"], x_transform["Scale"]
|
| 621 |
+
# print(pos,rot,scale)
|
| 622 |
+
block_info = block_sizes_content[str(block_id)]
|
| 623 |
+
bbox_lp, bbox_gp = get_bbox(pos, rot, scale, block_info['bc_gc'], block_info['bbox_size'], gp, gr)
|
| 624 |
+
|
| 625 |
+
corners_parent_llm.append(bbox_gp)
|
| 626 |
+
corners_parent_llm_parent.append([block_id, order_id, block_details[i-1]["parent"]])
|
| 627 |
+
|
| 628 |
+
facing_dir = facing(rot)
|
| 629 |
+
corners_feedback_forquizzer += f"order_id:{order_id}\n朝向:{facing_dir}\n块近似长方体顶点位置:{bbox_gp.tolist()}\n"
|
| 630 |
+
corners_feedback_forbuilder += f"order_id:{order_id}\n朝向:{facing_dir}"
|
| 631 |
+
|
| 632 |
+
# Calculate machine dimensions
|
| 633 |
+
corners_arr = np.vstack([c for c in corners_parent_llm if c.size > 0])
|
| 634 |
+
min_vals, max_vals = corners_arr.min(axis=0), corners_arr.max(axis=0)
|
| 635 |
+
lowest_y, highest_y = min_vals[1], max_vals[1]
|
| 636 |
+
left_x, right_x = min_vals[0], max_vals[0]
|
| 637 |
+
back_z, forward_z = min_vals[2], max_vals[2]
|
| 638 |
+
|
| 639 |
+
geo_center = np.array([(right_x + left_x)/2, (highest_y + lowest_y)/2, (forward_z + back_z)/2])
|
| 640 |
+
|
| 641 |
+
if autofit_gt:
|
| 642 |
+
xml_block_details[0]["GlobalPosition"][1] -= (lowest_y - 0.5)
|
| 643 |
+
xml_block_details[0]["GlobalPosition"][0] -= geo_center[0]
|
| 644 |
+
xml_block_details[0]["GlobalPosition"][2] -= geo_center[2]
|
| 645 |
+
|
| 646 |
+
env_fail = (highest_y - lowest_y > 9.5) or (right_x - left_x > 17) or (forward_z - back_z > 17)
|
| 647 |
+
height, wide, long = round(highest_y - lowest_y, 2), round(right_x - left_x, 2), round(forward_z - back_z, 2)
|
| 648 |
+
|
| 649 |
+
# Validate machine structure
|
| 650 |
+
machine_structure_error = ""
|
| 651 |
+
if "corners" in block_details[1]:
|
| 652 |
+
for i, block in enumerate(block_details):
|
| 653 |
+
if "GlobalPosition" in block or str(block.get("id")) in ("7", "9"): continue
|
| 654 |
+
if not np.allclose(block["corners"], corners_parent_llm[i], atol=1e-2):
|
| 655 |
+
machine_structure_error += (f"order_id为{i}的方块的顶点信息不一致!\n"
|
| 656 |
+
f"顶点信息:{block['corners']}\n"
|
| 657 |
+
f"建造点相对信息反推的顶点信息:{corners_parent_llm[i]}\n")
|
| 658 |
+
|
| 659 |
+
overlap_infos = check_overlap(corners_parent_llm, vis=False, corners_parent_llm_parent=corners_parent_llm_parent, language=language) if overlap_feedback else "重叠检查被屏蔽"
|
| 660 |
+
|
| 661 |
+
return (corners_feedback_forquizzer, corners_feedback_forbuilder, env_fail,
|
| 662 |
+
long, wide, height, machine_structure_error, overlap_infos)
|
| 663 |
+
|
| 664 |
+
def create_xml(data):
|
| 665 |
+
"""要加很多功能,因为加入了大量的新块"""
|
| 666 |
+
|
| 667 |
+
machine = ET.Element("Machine", version="1", bsgVersion="1.3", name="ai")
|
| 668 |
+
|
| 669 |
+
# 创建 Global 元素
|
| 670 |
+
global_elem = ET.SubElement(machine, "Global")
|
| 671 |
+
global_infos = data.pop(0)
|
| 672 |
+
gp = global_infos["GlobalPosition"]
|
| 673 |
+
gr = global_infos["GlobalRotation"]
|
| 674 |
+
# if gp[1]<1.5:
|
| 675 |
+
# print("警告,全局高度过低,小于1.5,调整到1.5")
|
| 676 |
+
# gp[1]=1.5
|
| 677 |
+
position = ET.SubElement(global_elem, "Position", x=str(gp[0]), y=str(gp[1]), z=str(gp[2]))
|
| 678 |
+
rotation = ET.SubElement(global_elem, "Rotation", x=str(gr[0]), y=str(gr[1]), z=str(gr[2]), w=str(gr[3]))
|
| 679 |
+
|
| 680 |
+
# 创建 Data 元素
|
| 681 |
+
data_elem = ET.SubElement(machine, "Data")
|
| 682 |
+
string_array = ET.SubElement(data_elem, "StringArray", key="requiredMods")
|
| 683 |
+
|
| 684 |
+
# 创建 Blocks 元素
|
| 685 |
+
blocks_elem = ET.SubElement(machine, "Blocks")
|
| 686 |
+
|
| 687 |
+
# 遍历 corners 数据并创建 Block 元素
|
| 688 |
+
for info in data:
|
| 689 |
+
|
| 690 |
+
block_id = info['id']
|
| 691 |
+
|
| 692 |
+
if info['id']=='18_1':
|
| 693 |
+
block_id ='18'
|
| 694 |
+
|
| 695 |
+
block = ET.SubElement(blocks_elem, "Block", id=str(block_id), guid=info['guid'])
|
| 696 |
+
transform = ET.SubElement(block, "Transform")
|
| 697 |
+
info_p = info['Transform']['Position']
|
| 698 |
+
position = ET.SubElement(transform, "Position", x=str(info_p[0]), y=str(info_p[1]), z=str(info_p[2]))
|
| 699 |
+
info_r = info['Transform']['Rotation']
|
| 700 |
+
rotation = ET.SubElement(transform, "Rotation", x=str(info_r[0]), y=str(info_r[1]), z=str(info_r[2]), w=str(info_r[3]))
|
| 701 |
+
info_s = info['Transform']['Scale']
|
| 702 |
+
scale = ET.SubElement(transform, "Scale", x=str(info_s[0]), y=str(info_s[1]), z=str(info_s[2]))
|
| 703 |
+
block_data = ET.SubElement(block, "Data")
|
| 704 |
+
if str(info['id'])=="0":
|
| 705 |
+
bmt = ET.SubElement(block_data, "Integer", key="bmt-version")
|
| 706 |
+
bmt.text = "1"
|
| 707 |
+
|
| 708 |
+
#线性块设置坐标
|
| 709 |
+
if str(info['id'])=="9":
|
| 710 |
+
bmt = ET.SubElement(block_data,"Single",key = "bmt-slider")
|
| 711 |
+
bmt.text = "10"
|
| 712 |
+
bmt = ET.SubElement(block_data,"StringArray",key = "bmt-contract")
|
| 713 |
+
bmt.text = "L"
|
| 714 |
+
bmt = ET.SubElement(block_data,"Boolean",key = "bmt-toggle")
|
| 715 |
+
bmt.text = "False"
|
| 716 |
+
|
| 717 |
+
if str(info['id'])=="7" or str(info['id'])=="9":
|
| 718 |
+
start_position = ET.SubElement(block_data,"Vector3",key = "start-position")
|
| 719 |
+
ET.SubElement(start_position, "X").text = str(0)
|
| 720 |
+
ET.SubElement(start_position, "Y").text = str(0)
|
| 721 |
+
ET.SubElement(start_position, "Z").text = str(0)
|
| 722 |
+
end_position = ET.SubElement(block_data,"Vector3",key = "end-position")
|
| 723 |
+
ET.SubElement(end_position, "X").text = str(info['end-position'][0])
|
| 724 |
+
ET.SubElement(end_position, "Y").text = str(info['end-position'][1])
|
| 725 |
+
ET.SubElement(end_position, "Z").text = str(info['end-position'][2])
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
if str(info['id'])=="22":
|
| 730 |
+
bmt = ET.SubElement(block_data, "Integer", key="bmt-version")
|
| 731 |
+
bmt.text = "1"
|
| 732 |
+
bmt = ET.SubElement(block_data,"Single",key = "bmt-speed")
|
| 733 |
+
bmt.text = "1"
|
| 734 |
+
bmt = ET.SubElement(block_data,"Single",key = "bmt-acceleration")
|
| 735 |
+
bmt.text = "Infinity"
|
| 736 |
+
bmt = ET.SubElement(block_data, "Boolean", key="bmt-auto-brake")
|
| 737 |
+
bmt.text = "True"
|
| 738 |
+
bmt = ET.SubElement(block_data, "Boolean", key="flipped")
|
| 739 |
+
bmt.text = "False"
|
| 740 |
+
|
| 741 |
+
if str(info['id'])=="35":
|
| 742 |
+
bmt = ET.SubElement(block_data,"Single",key = "bmt-mass")
|
| 743 |
+
bmt.text = "3"
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
#轮子镜像处理
|
| 747 |
+
if "auto" in info:
|
| 748 |
+
bmt = ET.SubElement(block_data, "Boolean", key="bmt-automatic")
|
| 749 |
+
bmt.text = "True"
|
| 750 |
+
bmt = ET.SubElement(block_data, "Boolean", key="bmt-auto-brake")
|
| 751 |
+
bmt.text = "False"
|
| 752 |
+
if "flip" in info and info["flip"]:
|
| 753 |
+
bmt = ET.SubElement(block_data, "Boolean", key="flipped")
|
| 754 |
+
bmt.text = "True"
|
| 755 |
+
if "WheelDoubleSpeed" in info and info["WheelDoubleSpeed"]:
|
| 756 |
+
bmt = ET.SubElement(block_data, "Single", key="bmt-speed")
|
| 757 |
+
bmt.text = "2"
|
| 758 |
+
|
| 759 |
+
# 将 ElementTree 转换为字符串
|
| 760 |
+
tree = ET.ElementTree(machine)
|
| 761 |
+
ET.indent(tree, space="\t", level=0)
|
| 762 |
+
xml_str = ET.tostring(machine, encoding="utf-8", method="xml", xml_declaration=True).decode("utf-8")
|
| 763 |
+
|
| 764 |
+
return xml_str
|
| 765 |
+
|
| 766 |
+
def json_to_xml(input_obj):
|
| 767 |
+
if isinstance(input_obj,str):
|
| 768 |
+
content = extract_json_from_string(input_obj)
|
| 769 |
+
elif isinstance(input_obj,list):
|
| 770 |
+
content = input_obj
|
| 771 |
+
else:
|
| 772 |
+
raise TypeError('Please make sure input type')
|
| 773 |
+
block_details = content
|
| 774 |
+
block_details = convert_to_numpy(block_details)
|
| 775 |
+
|
| 776 |
+
xml_block_details,block_details,_ = llm2xml_filetree(block_details,
|
| 777 |
+
BLOCKPROPERTYPATH,
|
| 778 |
+
selected_menu=None)
|
| 779 |
+
_,_,_,_,_,_,_,_ = llm_feedback_3d(block_sizes=BLOCKPROPERTYPATH,
|
| 780 |
+
xml_block_details=xml_block_details,
|
| 781 |
+
block_details = block_details)
|
| 782 |
+
xml_string = create_xml(xml_block_details)
|
| 783 |
return xml_string
|