FrameConversion.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. # This script is used to convert ROS2FrameComponent to ROS2FrameEditorComponent in .prefab files.
  2. # To use this script, run the following command:
  3. # python script.py <directory_or_file>
  4. # where <directory_or_file> is the directory or file to be processed.
  5. # If <directory_or_file> is a directory, all .prefab files in the directory and its subdirectories will be processed.
  6. # If <directory_or_file> is a file, only that file will be processed.
  7. import sys
  8. import simplejson as json
  9. import os
  10. import decimal
  11. def find_and_replace(data):
  12. def search_for_components(item, foundComponents, insidePatches=False):
  13. if isinstance(item, dict):
  14. if "Components" in item:
  15. foundComponents = True
  16. if "ROS2FrameComponent" in item and foundComponents:
  17. modifiedElement = item["ROS2FrameComponent"]
  18. modifiedElement["$type"] = "ROS2FrameEditorComponent"
  19. del modifiedElement["m_template"]["$type"]
  20. modifiedElement["ROS2FrameConfiguration"] = modifiedElement["m_template"]
  21. del modifiedElement["m_template"]
  22. del item["ROS2FrameComponent"]
  23. item["ROS2FrameEditorComponent"] = modifiedElement
  24. if foundComponents and "m_template" in item:
  25. if "$type" in item["m_template"] and item["m_template"]["$type"] == "ROS2FrameComponent":
  26. modifiedElement = item
  27. modifiedElement["$type"] = "ROS2FrameEditorComponent"
  28. del modifiedElement["m_template"]["$type"]
  29. modifiedElement["ROS2FrameConfiguration"] = modifiedElement["m_template"]
  30. del modifiedElement["m_template"]
  31. item = modifiedElement
  32. # Check if inside "Patches" section
  33. if "Patches" in item:
  34. insidePatches = True
  35. # Only apply path changes inside "Patches"
  36. if insidePatches and "op" in item and "path" in item:
  37. # We directly look for the ROS2FrameComponent fields and replace "m_template" with "ROS2FrameConfiguration"
  38. if any(substring in item["path"] for substring in [
  39. "m_template/Namespace Configuration",
  40. "m_template/Frame Name",
  41. "m_template/Publish Transform",
  42. "m_template/Joint Name"
  43. ]):
  44. item["path"] = item["path"].replace("m_template", "ROS2FrameConfiguration")
  45. if item["op"] == "remove" and "ROS2FrameComponent" in item["path"]:
  46. item["path"] = item["path"].replace("ROS2FrameComponent", "ROS2FrameEditorComponent")
  47. for key, value in item.items():
  48. search_for_components(value, foundComponents, insidePatches)
  49. elif isinstance(item, list):
  50. for element in item:
  51. search_for_components(element, foundComponents, insidePatches)
  52. search_for_components(data, False)
  53. def write_json_to_file(data, filename):
  54. try:
  55. with open(filename, 'w') as file:
  56. json.dump(data, file, indent=4)
  57. print(f"Modified data written to '{filename}'.")
  58. except Exception as e:
  59. print(f"Error writing to '{filename}': {e}")
  60. def find_prefab_files(directory):
  61. prefab_files = []
  62. if os.path.isfile(directory) and directory.endswith(".prefab"):
  63. prefab_files.append(directory)
  64. elif os.path.isdir(directory):
  65. for root, dirs, files in os.walk(directory):
  66. for file in files:
  67. if file.endswith(".prefab"):
  68. prefab_files.append(os.path.join(root, file))
  69. return prefab_files
  70. def parse_float_decimal(s):
  71. return decimal.Decimal(s)
  72. class DecimalEncoder(json.JSONEncoder):
  73. def default(self, obj):
  74. if isinstance(obj, decimal.Decimal):
  75. return str(obj)
  76. return json.JSONEncoder.default(self, obj)
  77. def convert_scientific_notation(text):
  78. import re
  79. return re.sub(r'(\d+\.\d*|\.\d+)[Ee]([+-]?\d+)', r'\1e\2', text)
  80. def process_prefab_file(file_path):
  81. try:
  82. with open(file_path, 'r') as file:
  83. data = json.load(file, parse_float=parse_float_decimal)
  84. find_and_replace(data)
  85. with open(file_path, 'w') as file:
  86. json.dump(data, file, indent=4)
  87. print(f"Modified data written to '{file_path}'.")
  88. content = ""
  89. with open(file_path, 'r') as file:
  90. content = file.read()
  91. content = convert_scientific_notation(content)
  92. with open(file_path, 'w') as file:
  93. file.write(content)
  94. except Exception as e:
  95. print(f"Error processing '{file_path}': {e}")
  96. if __name__ == "__main__":
  97. if len(sys.argv) != 2:
  98. print("Usage: python script.py <directory_or_file>")
  99. else:
  100. input_path = sys.argv[1]
  101. prefab_files = find_prefab_files(input_path)
  102. if not prefab_files:
  103. print(f"No .prefab files found in '{input_path}'.")
  104. else:
  105. for file_path in prefab_files:
  106. print(f"Processing '{file_path}'...")
  107. process_prefab_file(file_path)