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
|
"""Group the objects of a 3MF into one object with parts, for multi-colour printing.
python3 tools/threemf_group.py in.3mf out.3mf [name]
SolidCraft exports one 3MF object per body (its `objects: component` mode only groups bodies of
placed sub-components). A slicer loads those as separate objects, so a shell and its label inlays
could not get one colour each on one object. This writes a parent object (default name: the
first object's) whose components are all build items, and builds only the parent; the slicer
then loads one object with each body as a part. Build-item transforms are moved onto the
components.
"""
import sys
import zipfile
import xml.etree.ElementTree as ET
NS = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02"
MODEL = "3D/3dmodel.model"
def main():
src, dst = sys.argv[1], sys.argv[2]
ET.register_namespace("", NS)
with zipfile.ZipFile(src) as z:
files = {n: z.read(n) for n in z.namelist()}
root = ET.fromstring(files[MODEL])
q = lambda tag: "{%s}%s" % (NS, tag) # noqa: E731
resources, build = root.find(q("resources")), root.find(q("build"))
objects = resources.findall(q("object"))
name = sys.argv[3] if len(sys.argv) > 3 else objects[0].get("name")
parent = ET.SubElement(resources, q("object"), {
"id": str(max(int(o.get("id")) for o in objects) + 1), "type": "model", "name": name})
comps = ET.SubElement(parent, q("components"))
for item in build.findall(q("item")):
attrs = {"objectid": item.get("objectid")}
if item.get("transform"):
attrs["transform"] = item.get("transform")
ET.SubElement(comps, q("component"), attrs)
build.remove(item)
ET.SubElement(build, q("item"), {"objectid": parent.get("id")})
files[MODEL] = ET.tostring(root, encoding="UTF-8", xml_declaration=True)
with zipfile.ZipFile(dst, "w", zipfile.ZIP_DEFLATED) as z:
for n, data in files.items():
z.writestr(n, data)
print("%s: %d parts in object '%s'" % (dst, len(comps), name))
if __name__ == "__main__":
main()
|