obj_to_rust.py 2.0 KB

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