obj_to_rust.py
1 #!/usr/bin/env python 2 3 import sys 4 5 class Obj: 6 7 def __init__(self, name): 8 self.name = name 9 self.v = [] 10 self.f = [] 11 12 def push_vert(self, args): 13 assert len(args) == 3 14 (x, y, z) = [float(v) for v in args] 15 assert y == 0 16 vert = (x, z) 17 self.v.append(vert) 18 19 def push_face(self, args): 20 idxs = [arg.split("/")[0] for arg in args] 21 assert len(idxs) == 3 22 idxs = [int(idx) - 1 for idx in idxs] 23 for idx in idxs: 24 assert idx < len(self.v) 25 self.f.extend(idxs) 26 27 def parse_obj(fname): 28 objs = [] 29 obj = None 30 31 for line in open(fname): 32 line = line.rstrip("\n") 33 if line[0] == '#': 34 continue 35 36 line = line.split(" ") 37 cmd = line[0] 38 args = line[1:] 39 40 match cmd: 41 case 'o': 42 if obj is not None: 43 objs.append(obj) 44 name = args[0] 45 #print(f"New object {name}") 46 obj = Obj(name) 47 continue 48 case 'v': 49 obj.push_vert(args) 50 case 'f': 51 obj.push_face(args) 52 53 case _: 54 #print(f"Skipping {cmd}: {args}") 55 pass 56 57 if obj is not None: 58 objs.append(obj) 59 return objs 60 61 def output(obj): 62 name = obj.name 63 print("use crate::{mesh::Color, ui::{VectorShape, ShapeVertex}};") 64 print(f"pub fn create_{name}(color: Color) -> VectorShape {{") 65 print(" VectorShape {") 66 print(" verts: vec![") 67 for (x, y) in obj.v: 68 print(f" ShapeVertex::from_xy({x}, {y}, color),") 69 print(" ],") 70 indices = ", ".join([str(f) for f in obj.f]) 71 print(f" indices: vec![{indices}]") 72 print(" }") 73 print("}") 74 75 def main(argv): 76 if len(argv) != 2: 77 print("obj_to_rust OBJFILE", file=sys.stderr) 78 return -1 79 80 objs = parse_obj(argv[1]) 81 82 for obj in objs: 83 output(obj) 84 85 return 0 86 87 if __name__ == "__main__": 88 sys.exit(main(sys.argv)) 89