aboutsummaryrefslogtreecommitdiff
path: root/tools/threemf_group.py
diff options
context:
space:
mode:
Diffstat (limited to 'tools/threemf_group.py')
-rw-r--r--tools/threemf_group.py48
1 files changed, 48 insertions, 0 deletions
diff --git a/tools/threemf_group.py b/tools/threemf_group.py
new file mode 100644
index 0000000..1f92df3
--- /dev/null
+++ b/tools/threemf_group.py
@@ -0,0 +1,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()