-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubmodel_render.py
More file actions
225 lines (172 loc) · 6.46 KB
/
submodel_render.py
File metadata and controls
225 lines (172 loc) · 6.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import xml.etree.ElementTree as ET
import sys
import os
from PIL import Image, ImageDraw
SCALE = 20 # increase for higher resolution (10–40 works well)
# ---------------------------------------------------------
# Parse CustomModel and Submodels
# ---------------------------------------------------------
def parse_xmodel(path):
print(f"Loading {path} ...")
tree = ET.parse(path)
root = tree.getroot()
custom = root.get("CustomModel")
if not custom:
raise ValueError("❌ No CustomModel attribute found in .xmodel file!")
# -------------------------
# Parse custom model grid
# -------------------------
rows = custom.split(";")
grid = [row.split(",") for row in rows]
pixel_coords = {}
for y, row in enumerate(grid):
for x, cell in enumerate(row):
cell = cell.strip()
if cell == "" or not cell.isdigit():
continue
pixel_index = int(cell) # 1-based index used by xLights
pixel_coords[pixel_index] = (x, y)
if not pixel_coords:
raise ValueError("❌ CustomModel grid contained no pixel numbers!")
max_index = max(pixel_coords.keys())
# Convert dictionary to sorted 0-based list
coords_list = [None] * max_index
for idx, pos in pixel_coords.items():
coords_list[idx - 1] = pos
# -------------------------
# Parse submodels
# -------------------------
submodels = {}
for sm in root.findall(".//subModel"):
name = sm.get("name")
groups = sm.get("group", None)
lines = [sm.get(f"line{i}") for i in range(10)]
lines = [ln for ln in lines if ln]
pix_indexes = []
for ln in lines:
parts = ln.split(",")
for part in parts:
part = part.strip()
if not part:
continue
if "-" in part:
a, b = part.split("-")
pix_indexes.extend(range(int(a), int(b) + 1))
else:
pix_indexes.append(int(part))
# convert to 0-based
submodels[name] = {
"pixels": [i - 1 for i in pix_indexes],
"groups": groups
}
return coords_list, submodels, len(grid[0]), len(grid)
# ---------------------------------------------------------
# Draw a submodel image
# ---------------------------------------------------------
def render_submodel(name, coords, active_pixels, width, height, outdir):
print(f"Rendering submodel: {name}")
img = Image.new("RGB", (width * SCALE, height * SCALE), "black")
draw = ImageDraw.Draw(img)
# Draw all pixels (dark gray)
for idx, pos in enumerate(coords):
if pos is None:
continue
x, y = pos
x0 = x * SCALE
y0 = y * SCALE
x1 = x0 + SCALE
y1 = y0 + SCALE
color = (75, 75, 75)
draw.rectangle([x0, y0, x1, y1], fill=color)
# Draw active submodel pixels (red)
for idx in active_pixels:
if idx < 0 or idx >= len(coords) or coords[idx] is None:
continue
x, y = coords[idx]
x0 = x * SCALE
y0 = y * SCALE
x1 = x0 + SCALE
y1 = y0 + SCALE
color = (255, 0, 0)
draw.rectangle([x0, y0, x1, y1], fill=color)
# Save
outpath = os.path.join(outdir, f"{name}.png")
img.save(outpath)
print(f"→ Saved {outpath}")
# ---------------------------------------------------------
# Parse model groups
# ---------------------------------------------------------
def parse_model_groups(path):
tree = ET.parse(path)
root = tree.getroot()
model_groups = {}
for mg in root.findall(".//modelGroup"):
name = mg.get("name")
models_raw = mg.get("models", "")
# Split models attribute: "EXPORTEDMODEL/Arm 1,EXPORTEDMODEL/Arm 2"
models = [
m.replace("EXPORTEDMODEL/", "").strip()
for m in models_raw.split(",")
if m.strip() != ""
]
model_groups[name] = models
return model_groups
# ---------------------------------------------------------
# Create README.md with embedded images
# ---------------------------------------------------------
def create_readme(outdir, model_name, submodels, model_groups):
readme_path = os.path.join(outdir, "README.md")
def enc(name):
"""URL-encode spaces for markdown images."""
return name.replace(" ", "%20")
with open(readme_path, "w", encoding="utf-8") as f:
f.write(f"# Submodel Renders for **{model_name}**\n\n")
f.write("Automatically generated by `submodel.py`.\n\n")
f.write("## Model Groups Overview\n\n")
for group_name, model_list in model_groups.items():
f.write(f"### {group_name}\n\n")
f.write("| " + " | ".join(model_list) + " |\n")
f.write("| " + " | ".join(["---"] * len(model_list)) + " |\n")
row = "| "
for sm in model_list:
filename = enc(f"images/{sm}.png") # points to images folder
row += f'<img src="{filename}" width="150"><br>{sm} | '
f.write(row + "\n\n")
f.write("\n---\n\n## Individual Submodels\n\n")
for name in submodels:
filename = enc(f"images/{name}.png") # points to images folder
f.write(f"### {name}\n")
f.write(f"\n\n")
f.write("---\n\n")
print(f"→ README created at {readme_path}")
# ---------------------------------------------------------
# MAIN
# ---------------------------------------------------------
def main():
if len(sys.argv) < 2:
print("Usage: python submodel.py <file.xmodel>")
return
path = sys.argv[1]
coords, submodels, width, height = parse_xmodel(path)
# Parse model groups
model_groups = parse_model_groups(path)
# Output directories
model_name = os.path.splitext(os.path.basename(path))[0]
outdir = os.path.join("renders", model_name)
images_dir = os.path.join(outdir, "images")
os.makedirs(images_dir, exist_ok=True)
# Render each submodel into images_dir
for name, info in submodels.items():
render_submodel(
name,
coords,
info["pixels"],
width,
height,
images_dir
)
# Create README.md pointing to images/
create_readme(outdir, model_name, submodels, model_groups)
print("\nAll submodels rendered!")
if __name__ == "__main__":
main()