Skip to content

Instantly share code, notes, and snippets.

@laura240406
Created October 4, 2025 11:12
Show Gist options
  • Select an option

  • Save laura240406/f9636b815aae2c5388d375344ed9df5e to your computer and use it in GitHub Desktop.

Select an option

Save laura240406/f9636b815aae2c5388d375344ed9df5e to your computer and use it in GitHub Desktop.
Center a binary STL file so that the average coordinate is (0, 0, 0)
# public domain
import struct, sys
if len(sys.argv) != 3:
print("[!] Usage:", sys.argv[0], "<in>", "<out>")
exit(1)
ax, ay, az = 0, 0, 0
with open(sys.argv[1], "rb") as fd:
fd.read(80)
count = int.from_bytes(fd.read(4), "little")
print(f"[*] {count} triangles")
for i in range(0, count):
fd.read(12)
for j in range(0, 3):
x, y, z = struct.unpack("fff", fd.read(12))
ax += x
ay += y
az += z
fd.read(2)
ax /= count * 3
ay /= count * 3
az /= count * 3
print(f"[*] Global offset is ({ax}, {ay}, {az})")
with open(sys.argv[1], "rb") as ifd:
with open(sys.argv[2], "wb") as ofd:
ofd.write(ifd.read(84))
for i in range(0, count):
ofd.write(ifd.read(12))
for j in range(0, 3):
x, y, z = struct.unpack("fff", ifd.read(12))
x -= ax
y -= ay
z -= az
ofd.write(struct.pack("fff", x, y, z))
ofd.write(ifd.read(2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment