text
stringlengths
15
267k
# Copyright Epic Games, Inc. All Rights Reserved. import os import unreal import subprocess from pathlib import Path #------------------------------------------------------------------------------- class Debugger(unreal.Debugger): name = "Visual Studio" def _debug(self, exec_context, cmd, *args): cmd = exec_context.create_runnable(cmd, *args) cmd.launch(suspended=True, new_term=True) pid = cmd.get_pid() try: if not self._attach(pid): cmd.kill() except: cmd.kill() raise def _attach(self, pid, transport=None, host_ip=None): engine = self.get_unreal_context().get_engine() engine_dir = engine.get_dir() import vs.dte for instance in vs.dte.running(): candidate = instance.get_sln_path() if candidate and engine_dir.is_relative_to(Path(candidate).parent): if instance.attach(pid, transport, host_ip): break else: # There's nothing to fallback if a fancy debugger is supposed to be used if transport: return False ret = subprocess.run(("vsjitdebugger.exe", "-p", str(pid))) if ret.returncode: return False if not transport: vs.dte.resume_process(pid) return True
""" Base class for all control rig functions """ # mca python imports # software specific imports import unreal # mca python imports from mca.common import log from mca.ue.rigging.controlrig import cr_base logger = log.MCA_LOGGER class PinsBase(cr_base.ControlRigBase): def __init__(self, control_rig, fnode): super().__init__(control_rig=control_rig, fnode=fnode) def get_pins(self): """ Returns all the pins on the sequence node. :return: Returns all the pins on the sequence node. :rtype: list[RigVMPin] """ return self.fnode.get_pins() def get_empty_source_pins(self): """ Returns a list of empty pins. :return: Returns a list of empty pins. :rtype: list[RigVMPin] """ empty_list = [] # Get all the pins in the sequence node. pins = self.get_pins() # Get all the links in the sequence node. This gets us all the connections as pins on the sequence node. links = [x.get_source_node() for x in self.fnode.get_links()] # We don't need the input link, so lets remove it. # Loop through and see if the pins match the links. If they don't match, we'll add it to the list. for x in range(len(pins)): if pins[x] not in links: empty_list.append(pins[x]) return empty_list def get_pin_by_name(self, pin_name): """ Returns a pin by name. :param str pin_name: Name of the pin. :return: Returns a pin by name. :rtype: RigVMPin """ pins = self.get_pins() found = [] if not pins: return for pin in pins: if str(pin_name) in str(pin.get_display_name()): found.append(pin) return found def list_target_connections(self): """ Returns a list of all the nodes connected from the right side. :return: Returns a list of all the nodes connected from the right side. :rtype: list[unreal.RigVMNode] """ return self.fnode.get_linked_target_nodes() def list_source_connections(self): """ Returns a list of all the nodes connected from the left side. :return: Returns a list of all the nodes connected from the left side. :rtype: list[unreal.RigVMNode] """ return self.fnode.get_linked_source_nodes() def list_connections(self, source=True, target=True, **kwargs): """ Returns a list of all connected nodes. :return: Returns a list of all connected nodes. :rtype: list[unreal.RigVMNode] """ t = kwargs.get('target', target) s = kwargs.get('source', source) connection_list = [] if t: connection_list.extend(self.list_target_connections()) if s: connection_list.extend(self.list_source_connections()) return connection_list def set_expand_pin(self, node_name, pin_name, expand=True): self.cr_controller.set_pin_expansion(pin_path=f'{node_name}.{pin_name}', is_expanded=expand) def set_rig_element_pin(self, node_name, pin_name, in_type, other_name): self.cr_controller.set_pin_default_value(f'{node_name}.{pin_name}.Type', in_type, False) self.cr_controller.set_pin_default_value(f'{node_name}.{pin_name}.Name', other_name, False) def link_flag(self, source_pin, target_pin): """ :param RigVMPin source_pin: The source pin. The pin from the node. :param unreal.RigVMPin target_pin: The target pin. The pin into the node. """ source_path = source_pin.get_pin_path() target_path = target_pin.get_pin_path() self.cr_controller.add_link(source_path, target_path) def add_link(self, pin_name, target, target_pin): if isinstance(target, PinsBase) and isinstance(target_pin, str): target = f'{target.get_fname()}.{target_pin}' elif isinstance(target, str) and '.' in target: target = target elif isinstance(target, str) and isinstance(target_pin, str): target = f'{target}.{target}' else: logger.warning('Unable to link nodes, It looks like the source or target link does not exist.') return source = f'{self.get_fname()}.{pin_name}' self.cr_controller.add_link(source, target)
# Copyright Epic Games, Inc. All Rights Reserved. import unreal def _log_error(error): import traceback unreal.log_error("{0}\n\t{1}".format(error, "\t".join(traceback.format_stack()))) @unreal.uclass() class PyTestPythonDefinedObject(unreal.PyTestObject): @unreal.ufunction(override=True) def func_blueprint_implementable(self, value): return value * 2 @unreal.ufunction(override=True) def func_blueprint_implementable_packed_getter(self): return None @unreal.ufunction(override=True) def func_blueprint_native(self, value): return value * 4 @unreal.ufunction(override=True) def func_blueprint_native_ref(self, struct): struct.int *= 4 struct.string = "wooble" return struct @unreal.uenum() class PyTestColor(unreal.EnumBase): RED = unreal.uvalue(1, meta={"DisplayName" : "Red (255, 0, 0)"}) GREEN = unreal.uvalue(2) BLUE = unreal.uvalue(3) unreal.flush_generated_type_reinstancing() # Used to verify if a callable method is properly added/project/ from a multicast delegate class PyTestDelegateCallableTest: def __init__(self): self.callback_count = 0 self.last_str_arg = "" self.last_int_arg = 0 self.last_struct_arg: unreal.PyTestStruct = None self.last_vector_arg: unreal.Vector2D = None def multicast_callback_method(self, str_param: str): self.callback_count += 1 self.last_str_arg = str_param def callback_method(self, int_value: int): self.callback_count += 1 self.last_int_arg = int_value return self.callback_count def on_struct_delegate(self, item: unreal.PyTestStruct) -> None: self.callback_count += 1 if type(item) != unreal.PyTestStruct: _log_error("Delegate callbable received the wrong type. Expected a PyTestStruct.") self.last_struct_arg = item def on_vector_delegate(self, item: unreal.Vector2D) -> None: self.callback_count += 1 if type(item) != unreal.Vector2D: _log_error("Delegate callbable received the wrong type. Expected a Vector2D.") self.last_vector_arg = item def _compare_value(val, other, inverse=False): if inverse: if val == other: _log_error("Value was '{0}' but it wasn't supposed to be!".format(other)) else: if val != other: _log_error("Value was '{0}' but '{1}' was expected!".format(val, other)) def _compare_property_value(obj, other, prop_name, inverse=False): obj_value = getattr(obj, prop_name) other_value = getattr(other, prop_name) if inverse: if obj_value == other_value: _log_error("Property '{0}' has the value '{1}' but it wasn't supposed to!".format(prop_name, other_value)) else: if obj_value != other_value: _log_error("Property '{0}' has the value '{1}' but '{2}' was expected!".format(prop_name, other_value, obj_value)) def _compare_common_properties(obj, other, inverse=False): _compare_property_value(obj, other, "bool", inverse) _compare_property_value(obj, other, "int", inverse) _compare_property_value(obj, other, "float", inverse) _compare_property_value(obj, other, "enum", inverse) _compare_property_value(obj, other, "string", inverse) _compare_property_value(obj, other, "name", inverse) _compare_property_value(obj, other, "text", inverse) _compare_property_value(obj, other, "field_path", inverse) _compare_property_value(obj, other, "struct_field_path", inverse) _compare_property_value(obj, other, "string_array", inverse) _compare_property_value(obj, other, "string_set", inverse) _compare_property_value(obj, other, "string_int_map", inverse) def _test_set_value(obj, prop_name, value): setattr(obj, prop_name, value) cur_value = getattr(obj, prop_name) if cur_value != value: _log_error("Property '{0}' on '{1}' has the value '{2}' but '{3}' was expected!".format(prop_name, type(obj).__name__, cur_value, value)) def _test_common_properties(obj): _test_set_value(obj, "bool", True) _test_set_value(obj, "int", 10) _test_set_value(obj, "float", 100) _test_set_value(obj, "enum", unreal.PyTestEnum.TWO) _test_set_value(obj, "string", "Hello World!") _test_set_value(obj, "name", "Hello World!") _test_set_value(obj, "text", "Hello World!") _test_set_value(obj, "field_path", unreal.FieldPath("/project/.PyTestStruct:StringArray")) _test_set_value(obj, "struct_field_path", unreal.FieldPath.cast("/project/.PyTestObject:Struct")) _test_set_value(obj, "string_array", ["One", "Two"]) _test_set_value(obj, "string_set", ["One", "Two"]) _test_set_value(obj, "string_int_map", {"One":1, "Two":2}) def _test_object_properties(obj): _test_common_properties(obj) _test_common_properties(obj.struct) _test_common_properties(obj.child_struct) if obj.delegate: _log_error("Property 'delegate' on '{0}' is bound when it should be unbound!".format(type(obj).__name__)) obj.delegate.bind_function(obj, "delegate_property_callback") if not obj.delegate: _log_error("Property 'delegate' on '{0}' is unbound when it should be bound!".format(type(obj).__name__)) if obj.delegate: _compare_value(obj.delegate(obj.int), 10) obj.delegate.unbind() if obj.delegate: _log_error("Property 'delegate' on '{0}' is bound when it should be unbound!".format(type(obj).__name__)) if obj.delegate: _log_error("Property 'delegate' on '{0}' is bound when it should be unbound!".format(type(obj).__name__)) obj.delegate.bind_callable(lambda value : value * 2) if not obj.delegate: _log_error("Property 'delegate' on '{0}' is unbound when it should be bound!".format(type(obj).__name__)) if obj.delegate: _compare_value(obj.delegate(obj.int), 20) obj.delegate.unbind() if obj.delegate: _log_error("Property 'delegate' on '{0}' is bound when it should be unbound!".format(type(obj).__name__)) if obj.multicast_delegate: _log_error("Property 'multicast_delegate' on '{0}' is bound when it should be unbound!".format(type(obj).__name__)) obj.multicast_delegate.add_function(obj, "multicast_delegate_property_callback") if not obj.multicast_delegate: _log_error("Property 'multicast_delegate' on '{0}' is unbound when it should be bound!".format(type(obj).__name__)) if obj.multicast_delegate: obj.multicast_delegate(obj.string) obj.multicast_delegate.clear() if obj.multicast_delegate: _log_error("Property 'multicast_delegate' on '{0}' is bound when it should be unbound!".format(type(obj).__name__)) # Bind/unbind the multicast delegate to a method callable. obj.multicast_delegate.clear() cb = PyTestDelegateCallableTest() obj.multicast_delegate.add_callable(cb.multicast_callback_method) if not obj.multicast_delegate: _log_error("Property 'multicast_delegate' on '{0}' is unbound when it should be bound!".format(type(obj).__name__)) if obj.multicast_delegate: obj.multicast_delegate(obj.string) _compare_value(cb.callback_count, 1) obj.multicast_delegate.remove_callable(cb.multicast_callback_method) if obj.multicast_delegate: _log_error("Property 'multicast_delegate' on '{0}' is bound when it should be unbound!".format(type(obj).__name__)) for s in obj.struct_array: _test_common_properties(s) _compare_common_properties(obj, obj.struct) for s in obj.struct_array: _compare_common_properties(obj, s, True) def _test_object_methods(obj): obj.func_taking_py_test_struct(unreal.PyTestStruct()) obj.func_taking_py_test_struct(unreal.PyTestChildStruct()) obj.func_taking_py_test_child_struct(unreal.PyTestChildStruct()) obj.func_taking_field_path(unreal.FieldPath()) def _test_object_method_overrides(obj, expected_bp_val, expected_native_val, expected_native_str): s = unreal.PyTestStruct() s.int = 10 s.string = "testing" _compare_value(obj.func_blueprint_implementable(10), expected_bp_val) _compare_value(obj.call_func_blueprint_implementable(10), expected_bp_val) _compare_value(obj.func_blueprint_implementable_packed_getter(), None) _compare_value(obj.call_func_blueprint_implementable_packed_getter(), None) _compare_value(obj.func_blueprint_native(10), expected_native_val) _compare_value(obj.call_func_blueprint_native(10), expected_native_val) rs = obj.func_blueprint_native_ref(s) _compare_value(rs.int, expected_native_val) _compare_value(rs.string, expected_native_str) rs = obj.call_func_blueprint_native_ref(s) _compare_value(rs.int, expected_native_val) _compare_value(rs.string, expected_native_str) def _test_object_method_interfaces(obj): _compare_value(obj.func_interface(100), 100) _compare_value(obj.func_interface_child(100), 100) _compare_value(obj.func_interface_other(100), 100) def _test_struct_extension_methods(s): _test_set_value(s, "int", 0) s.add_int(10) _compare_value(s.int, 10) s += 10 _compare_value(s.int, 20) _test_set_value(s, "float", 0.0) s.add_float(10.0) _compare_value(s.float, 10.0) s += 10.0 _compare_value(s.float, 20.0) _test_set_value(s, "string", "") s.add_str("Foo") _compare_value(s.string, "Foo") s += "Bar" _compare_value(s.string, "FooBar") s.set_bool_mutable() _compare_value(s.bool_mutable, True) s.clear_bool_mutable() _compare_value(s.bool_mutable, False) s.set_bool_mutable_via_ref() _compare_value(s.bool_mutable, True) s.clear_bool_mutable_via_ref() _compare_value(s.bool_mutable, False) def _test_list_api(l): _compare_value(len(l), 2) _compare_value(l[0], "one") _compare_value(l[1], "two") l.append("three") _compare_value(l[2], "three") l[2] = "three?" _compare_value(l[2], "three?") _compare_value(l.count("three?"), 1) _compare_value("three?" in l, True) l.remove("three?") _compare_value(l.count("three?"), 0) _compare_value("three?" in l, False) l.pop() _compare_value("two" in l, False) l.insert(1, "two") _compare_value(l.index("two"), 1) l.extend(["three", "four"]) _compare_value(l[2], "three") _compare_value(l[3], "four") l.reverse() _compare_value(l[0], "four") l.sort() _compare_value(l[1], "one") def _test_enum_type(): _compare_value(unreal.PyTestEnum.ONE.name, "ONE") _compare_value(unreal.PyTestEnum.ONE.value, 0) # Not an error, the value of the ONE is zero... _compare_value(unreal.PyTestEnum.ONE.get_display_name(), "Says One but my value is Zero") _compare_value(unreal.PyTestEnum.TWO.name, "TWO") _compare_value(unreal.PyTestEnum.TWO.value, 1) # Not an error, the value of the TWO is 1... _compare_value(unreal.PyTestEnum.TWO.get_display_name(), "Two") # No meta data set, default to the name in C++ file. _compare_value(PyTestColor.RED.name, "RED") _compare_value(PyTestColor.RED.value, 1) _compare_value(PyTestColor.RED.get_display_name(), "Red (255, 0, 0)") _compare_value(PyTestColor.BLUE.name, "BLUE") _compare_value(PyTestColor.BLUE.value, 3) _compare_value(PyTestColor.BLUE.get_display_name(), "BLUE") # No meta data set, default to name. def _test_array_type(): p = ["one", "two"] u = unreal.Array.cast(str, p) _test_list_api(p) _test_list_api(u) def _test_set_api(s): _compare_value(len(s), 2) _compare_value("one" in s, True) _compare_value("two" in s, True) _compare_value("three" in s, False) s.add("three") _compare_value("three" in s, True) s.remove("three") _compare_value("three" in s, False) s.pop() _compare_value(len(s), 1) s.clear() _compare_value(len(s), 0) s.add("one") s.add("two") s.add("three") _compare_value(s.difference(set(["one", "four"])), set(["two", "three"])) _compare_value(s.intersection(set(["one", "four"])), set(["one"])) _compare_value(s.symmetric_difference(set(["one", "four"])), set(["two", "three", "four"])) _compare_value(s.union(set(["one", "four"])), set(["one", "two", "three", "four"])) _compare_value(s.isdisjoint(set(["four"])), True) _compare_value(s.isdisjoint(set(["one", "four"])), False) _compare_value(s.issubset(set(["one", "two", "three", "four"])), True) _compare_value(s.issubset(set(["one", "four"])), False) _compare_value(s.issuperset(set(["one", "two"])), True) _compare_value(s.issuperset(set(["one", "four"])), False) def _test_set_type(): p = set(["one", "two"]) u = unreal.Set.cast(str, p) _test_set_api(p) _test_set_api(u) def _test_dict_api(d): _compare_value(len(d), 2) _compare_value("one" in d, True) _compare_value("two" in d, True) _compare_value("three" in d, False) d["three"] = 3 _compare_value("three" in d, True) del d["three"] _compare_value("three" in d, False) _compare_value(d.get("two", 20), 2) _compare_value(d.get("three", 30), 30) d.setdefault("two", 20) d.setdefault("three", 30) _compare_value(d["two"], 2) _compare_value(d["three"], 30) _compare_value(d.pop("two", 20), 2) _compare_value(d.get("three", 3), 30) _compare_value(d.get("four", 40), 40) d.clear() _compare_value(len(d), 0) d.update({"one":1, "two":2}) _compare_value(len(d), 2) def _test_map_type(): p = {"one":1, "two":2} u = unreal.Map.cast(str, int, p) _test_dict_api(p) _test_dict_api(u) def _test_field_path_type(): # This is a valid path to a field. valid_fp = "/project/.PyTestStruct:StringArray" # This is an invalid path. invalid_fp = "This is junk" # The function was designed to return a path to an existing field. if not unreal.PyTestObject().return_field_path().is_valid(): _log_error("PyTestObject should return a valid FieldPath") # The PyTestObject.field_path is initialized to an existing field in C++. if not unreal.PyTestObject().field_path.is_valid(): _log_error("PyTestObject field path property should be valid") fp = unreal.FieldPath() if fp.is_valid(): _log_error("Uninitialize field path should not be valid") fp = unreal.FieldPath(valid_fp) if not fp.is_valid(): _log_error("Failed to initialize from a valid path.") fp = unreal.FieldPath(invalid_fp) if fp.is_valid(): _log_error("Invalid field path should not be valid") o = unreal.PyTestObject() # PyTestObject is created with a valid field_path, tested above. o.field_path = unreal.FieldPath(invalid_fp) # Set an invalid path if o.field_path.is_valid(): _log_error("Invalid field path should not be valid") fpA = unreal.FieldPath.cast(valid_fp) fpB = fpA.copy() _compare_value(fpA, fpB) def _test_delegate_name_clash(): """ Verify that delegates with the same type/name are not mismatched by the implementation and call the right callback is invoked with the right parameter(s). """ struct_inst_cb = PyTestDelegateCallableTest() vector_inst_cb = PyTestDelegateCallableTest() cb_struct = unreal.PyTestStructDelegate() cb_vector = unreal.PyTestVectorDelegate() cb_struct.on_name_collision_test_delegate.add_callable(struct_inst_cb.on_struct_delegate) cb_vector.on_name_collision_test_delegate.add_callable(vector_inst_cb.on_vector_delegate) cb_struct.on_name_collision_test_delegate.broadcast(unreal.PyTestStruct(True, 44)) cb_vector.on_name_collision_test_delegate.broadcast(unreal.Vector2D(88, 99)) _compare_value(struct_inst_cb.last_struct_arg.int, 44) # struct callback was called with the struct parameters. _compare_value(vector_inst_cb.last_vector_arg.x, 88) # vector callback was called with a vector parameter. if __name__ == "__main__": s = unreal.PyTestStruct() _test_common_properties(s) _test_struct_extension_methods(s) o = unreal.PyTestObject() _test_object_properties(o) _test_object_methods(o) _test_object_method_overrides(o, 0, 10, "testing") _test_object_method_interfaces(o) co = unreal.PyTestChildObject() _test_object_properties(co) _test_object_methods(co) _test_object_method_overrides(co, 0, 10, "testing") _test_object_method_interfaces(co) pdo = PyTestPythonDefinedObject() _test_object_properties(pdo) _test_object_methods(pdo) _test_object_method_overrides(pdo, 20, 40, "wooble") _test_object_method_interfaces(pdo) _test_enum_type() _test_array_type() _test_set_type() _test_map_type() _test_field_path_type() oa = unreal.PyTestObject.return_array() _compare_value(len(oa), 1) _compare_value(oa[0], 10) os = unreal.PyTestObject.return_set() _compare_value(len(os), 1) _compare_value(10 in os, True) om = unreal.PyTestObject.return_map() _compare_value(len(om), 1) _compare_value(10 in om, True) _compare_value(om.get(10, False), True) # Test accessing class sparse data via a CDO cdo = unreal.PyTestObject.get_default_object() _compare_value(cdo.get_editor_property('IntFromSparseData'), 0) cdo.set_editor_property('IntFromSparseData', 10) _compare_value(cdo.get_editor_property('IntFromSparseData'), 10) cdo.set_editor_property('IntFromSparseData', 0) # Regression tests: Ensure that MakeTransform() correctly apply its default parameters. t = unreal.Transform() _compare_value(t.translation, [0, 0, 0]) _compare_value(t.scale3d, [1, 1, 1]) t = unreal.Transform([11, 12, 13]) _compare_value(t.translation, [11, 12, 13]) _compare_value(t.scale3d, [1, 1, 1]) t = unreal.Transform([11, 12, 13], [0, 0, 0], [100, 101, 102]) _compare_value(t.translation, [11, 12, 13]) _compare_value(t.scale3d, [100, 101, 102]) # Ensure that delegate of the same name and same type name don't clash. _test_delegate_name_clash() unreal.log("Tests Completed!")
# coding: utf-8 import unreal import argparse parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") parser.add_argument("-debugeachsave") args = parser.parse_args() #print(args.vrm) ###### rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r h_mod = rig.get_hierarchy_modifier() elements = h_mod.get_selection() print(unreal.SystemLibrary.get_engine_version()) if (unreal.SystemLibrary.get_engine_version()[0] == '5'): c = rig.get_controller() else: c = rig.controller g = c.get_graph() n = g.get_nodes() mesh = rig.get_preview_mesh() morphList = mesh.get_all_morph_target_names() morphListWithNo = morphList[:] morphListRenamed = [] morphListRenamed.clear() for i in range(len(morphList)): morphListWithNo[i] = '{}'.format(morphList[i]) print(morphListWithNo) ###### root key = unreal.RigElementKey(unreal.RigElementType.SPACE, 'MorphControlRoot_s') space = h_mod.get_space(key) if (space.get_editor_property('index') < 0): space = h_mod.add_space('MorphControlRoot_s', space_type=unreal.RigSpaceType.SPACE) else: space = key a:unreal.RigUnit_CollectionItems = unreal.RigUnit_CollectionItems() print(a) # 配列ノード追加 values_forCurve:unreal.RigVMStructNode = [] items_forControl:unreal.RigVMStructNode = [] items_forCurve:unreal.RigVMStructNode = [] for node in n: print(node) print(node.get_node_title()) # set curve num if (node.get_node_title() == 'For Loop'): print(node) pin = node.find_pin('Count') print(pin) c.set_pin_default_value(pin.get_pin_path(), str(len(morphList))) # curve name array pin if (node.get_node_title() == 'Select'): print(node) pin = node.find_pin('Values') #print(pin) #print(pin.get_array_size()) #print(pin.get_default_value()) values_forCurve.append(pin) # items if (node.get_node_title() == 'Items'): if ("Type=Curve," in c.get_pin_default_value(node.find_pin('Items').get_pin_path())): items_forCurve.append(node.find_pin('Items')) else: items_forControl.append(node.find_pin('Items')) print(values_forCurve) # reset controller for e in reversed(h_mod.get_elements()): if (e.type!= unreal.RigElementType.CONTROL): continue tmp = h_mod.get_control(e) if (tmp.space_name == 'MorphControlRoot_s'): #if (str(e.name).rstrip('_c') in morphList): # continue print('delete') #print(str(e.name)) h_mod.remove_element(e) # curve array for v in values_forCurve: c.clear_array_pin(v.get_pin_path()) for morph in morphList: tmp = "{}".format(morph) c.add_array_pin(v.get_pin_path(), default_value=tmp) # curve controller for morph in morphListWithNo: name_c = "{}_c".format(morph) key = unreal.RigElementKey(unreal.RigElementType.CONTROL, name_c) try: control = h_mod.get_control(key) if (control.get_editor_property('index') < 0): k = h_mod.add_control(name_c, control_type=unreal.RigControlType.FLOAT, space_name=space.name, gizmo_color=[1.0, 0.0, 0.0, 1.0], ) control = h_mod.get_control(k) except: k = h_mod.add_control(name_c, control_type=unreal.RigControlType.FLOAT, space_name=space.name, gizmo_color=[1.0, 0.0, 0.0, 1.0], ) control = h_mod.get_control(k) control.set_editor_property('gizmo_visible', False) control.set_editor_property('gizmo_enabled', False) h_mod.set_control(control) morphListRenamed.append(control.get_editor_property('name')) if (args.debugeachsave == '1'): try: unreal.EditorAssetLibrary.save_loaded_asset(rig) except: print('save error') #unreal.SystemLibrary.collect_garbage() # curve Control array for v in items_forControl: c.clear_array_pin(v.get_pin_path()) for morph in morphListRenamed: tmp = '(Type=Control,Name=' tmp += "{}".format(morph) tmp += ')' c.add_array_pin(v.get_pin_path(), default_value=tmp) # curve Float array for v in items_forCurve: c.clear_array_pin(v.get_pin_path()) for morph in morphList: tmp = '(Type=Curve,Name=' tmp += "{}".format(morph) tmp += ')' c.add_array_pin(v.get_pin_path(), default_value=tmp)
import unreal import pathlib import os import logging import logging.handlers import abc from enum import Enum import traceback from typing import Union import tempfile @unreal.uclass() class CGTeamWorkFbxImportOptions(unreal.Object): skeleton = unreal.uproperty(unreal.Skeleton, meta={"DisplayName": "骨 骼", "Category": "参 数"}) out_directory = unreal.uproperty(unreal.DirectoryPath, meta={"DisplayName": "目标路径", "ContentDir": "", "Category": "参 数"}) in_directory = unreal.uproperty(unreal.DirectoryPath, meta={"DisplayName": "Fbx文件夹路径", "RelativePath": "", "BlueprintReadOnly": "", "Category": "参 数"}) class ToolShelfLogger: logger_list = [] default_output = None class LoggerState(Enum): START = 0 END = 1 @staticmethod def create_logger(logger_name, logger_output=None): if not logger_output and ToolShelfLogger.default_output: logger_output = ToolShelfLogger.default_output result = ToolShelfLogger(logger_name, logger_output) ToolShelfLogger.logger_list.append(result) return result @staticmethod def set_default_output(logger_output): ToolShelfLogger.default_output = logger_output def __init__(self, name, out_object): self._logger = logging.getLogger(name) if self._logger.hasHandlers(): for i in self._logger.handlers: i.close() self._logger.handlers.clear() logger_handle = logging.StreamHandler() formatter = logging.Formatter('%(filename)s-[line:%(lineno)d]' '-%(levelname)s-[日志信息]: %(message)s', datefmt='%Y-%m-%d') self.log_str = "" self.warning_str= "" logger_handle.setFormatter(formatter) logger_handle.setStream(self) temp_dir = os.path.join(os.path.dirname(__file__), "logs") log_path = temp_dir if not os.path.exists(log_path): os.mkdir(log_path) log_name = os.path.join(log_path, f"{self._logger.name}.log") fh = logging.handlers.TimedRotatingFileHandler(log_name, when="midnight", interval=1, encoding="utf-8", backupCount=30) fh.suffix = "%Y-%m-%d_%H-%M-%S.log" formatter = logging.Formatter('%(asctime)s-%(name)s-%(filename)s-[line:%(lineno)d]' '-%(levelname)s-[日志信息]: %(message)s', datefmt='%a, %d %b %Y %H:%M:%S') fh.setLevel(logging.INFO) fh.setFormatter(formatter) self._logger.addHandler(fh) self._logger.addHandler(logger_handle) self.out_object = out_object self.__tmp_str = "" self.__tmp_error_str = "" self.__tmp_warning_str = "" self.__logger_state = ToolShelfLogger.LoggerState.END def get_log_path(self): temp_dir = tempfile.gettempdir() log_path = os.path.join(temp_dir, "ToolShelf") return os.path.join(log_path, f"{self._logger.name}.log") def begin(self): if self.__logger_state == ToolShelfLogger.LoggerState.START: raise SystemError("尚未使用log end") self.__tmp_error_str = "" self.__tmp_warning_str = "" self.__logger_state = ToolShelfLogger.LoggerState.START ... def end(self): self.__tmp_str = "" self.__logger_state = ToolShelfLogger.LoggerState.END ... @property def logger(self): return self._logger def write(self, text, *args, **kwargs): log_type = None if "-WARNING-" in text: self.warning_str += text + "\n" log_type = logging.WARNING if self.__logger_state == ToolShelfLogger.LoggerState.START: self.__tmp_warning_str += text + "\n" elif "-ERROR-" in text: self.log_str += text + "\n" log_type = logging.ERROR if self.__logger_state == ToolShelfLogger.LoggerState.START: self.__tmp_error_str += text + "\n" if self.out_object: for i in text.split("\n"): self.out_object.write(log_type, i) def get_section_log(self, log_type): result = None if log_type == logging.WARNING: result = self.__tmp_warning_str elif log_type == logging.ERROR: result = self.__tmp_error_str return result class BaseHandle: support_tool = [] padding = [0,0,0,0] order = 0 valid = True def __init__(self, handle_id=""): self._root_widget = None self._handle_id = handle_id if handle_id else type(self).__name__ self.__logger: ToolShelfLogger = None self.__create_logger() self.setup() def __create_logger(self): self.__logger = ToolShelfLogger.create_logger(type(self).__name__) @property def logger(self): return self.__logger @property def bind_tool(self): return self._support_tool def get_bind_tool(self): return self._support_tool def set_bind_tool(self, result: list): self._support_tool = result def export_widget(self) -> unreal.Widget: return self._root_widget @abc.abstractmethod def setup(self): ... class SideEntity: def __init__(self, display_name="", icon_path="", tool_tip="", entity_id=None, bottom=True): self.display_name = display_name self.icon_path = icon_path self.tool_tip = tool_tip if tool_tip else display_name self.entity_id = entity_id if entity_id else display_name class StackWidgetHandle(BaseHandle): instance = False fill = False def __init__(self, entity: SideEntity, handle_id=""): self.entity = entity super().__init__(handle_id) def get_handle_id(self): return self._handle_id ... def on_active_changed(self, in_entity: SideEntity, **kwargs): ... def get_logger(self): ... class Utl: @staticmethod def get_full_icon_path(image_name): res_path = pathlib.Path(__file__).parent.joinpath("resources") return res_path.joinpath(image_name).as_posix() def create_size_wrapper(widget): size_box = unreal.SizeBox() size_box.add_child(widget) return size_box def create_button(text="", icon_path="", size=None): layout = unreal.HorizontalBox() image = None if icon_path and pathlib.Path(icon_path).exists(): image = unreal.Image() texture = unreal.PythonWidgetExtendLib.create_texture2d_from_file(icon_path) image.set_brush_from_texture(texture) button = unreal.Button() if image: size_box = create_size_wrapper(image) size_box.set_width_override(25) size_box.set_height_override(25) slot = layout.add_child_to_horizontal_box(size_box) slot.set_horizontal_alignment(unreal.HorizontalAlignment.H_ALIGN_CENTER) slot.set_vertical_alignment(unreal.VerticalAlignment.V_ALIGN_CENTER) slot.set_padding(unreal.Margin(3, 0, 0, 0)) button_text = unreal.TextBlock() button_text.font.size = 10 button_text.set_text(text) slot = layout.add_child_to_horizontal_box(button_text) slot.set_horizontal_alignment(unreal.HorizontalAlignment.H_ALIGN_RIGHT) slot.set_vertical_alignment(unreal.VerticalAlignment.V_ALIGN_CENTER) slot.set_padding(unreal.Margin(10, 0, 0, 0)) button.set_content(layout) button.set_tool_tip_text(text) return button def create_side_button_with_text(text="", tool_tip="", icon_path="", button_type=unreal.Button.static_class(), display=True) -> unreal.Button: layout = unreal.HorizontalBox() image = None if icon_path and pathlib.Path(icon_path).exists(): image = unreal.Image() texture = unreal.PythonWidgetExtendLib.create_texture2d_from_file(icon_path) image.set_brush_from_texture(texture) ... if button_type == unreal.CheckBox.static_class(): checked_hover_color = unreal.SlateColor(unreal.LinearColor(0, 0.2, 0.7, 1 if display else int(display))) hover_color = unreal.SlateColor(unreal.LinearColor(0, 0.2, 1, 0.8 if display else int(display))) press_color = unreal.SlateColor(unreal.LinearColor(0.43, 0.43, 0.43, 1)) unchecked_color = unreal.SlateColor(unreal.LinearColor(1, 1, 1, 0)) button = unreal.CheckBox() widget_style: unreal.CheckBoxStyle = button.get_editor_property("widget_style") widget_style.check_box_type = unreal.SlateCheckBoxType.TOGGLE_BUTTON brush = unreal.SlateBrush() widget_style.checked_hovered_image = brush widget_style.checked_image = brush widget_style.checked_pressed_image = brush # widget_style.checked_hovered_image.set_editor_property("resource_name", "") # widget_style.checked_image.set_editor_property("resource_name", "") # widget_style.checked_pressed_image.set_editor_property("resource_name", "") widget_style.checked_hovered_image.tint_color = press_color if not display else checked_hover_color widget_style.checked_image.tint_color = hover_color widget_style.checked_pressed_image.tint_color = hover_color widget_style.unchecked_pressed_image.tint_color = press_color widget_style.unchecked_image.tint_color = unchecked_color widget_style.unchecked_hovered_image.tint_color = press_color widget_style.unchecked_hovered_image.draw_as = unreal.SlateBrushDrawType.IMAGE else: button = unreal.Button() if image: size_box = create_size_wrapper(image) size_box.set_width_override(25) size_box.set_height_override(25) slot = layout.add_child_to_horizontal_box(size_box) slot.set_horizontal_alignment(unreal.HorizontalAlignment.H_ALIGN_CENTER) slot.set_vertical_alignment(unreal.VerticalAlignment.V_ALIGN_CENTER) slot.set_padding(unreal.Margin(3, 0, 0, 0)) button_text = unreal.TextBlock() button_text.font.size = 10 button_text.set_text(text) #size_box = create_size_wrapper(button_text) slot = layout.add_child_to_horizontal_box(button_text) slot.set_horizontal_alignment(unreal.HorizontalAlignment.H_ALIGN_RIGHT) slot.set_vertical_alignment(unreal.VerticalAlignment.V_ALIGN_CENTER) slot.set_padding(unreal.Margin(10, 0, 0, 0)) button.set_content(layout) button.set_tool_tip_text(tool_tip) return button def check_status(message="发生错误,请查看日志"): def wrapper(func): def wrapper2(instance: Union[StackWidgetHandle, unreal.Object], *args, **kwargs): t_logger = None if isinstance(instance, StackWidgetHandle): t_logger = instance.logger elif isinstance(instance, unreal.Object): if not hasattr(instance, "logger"): raise AttributeError("实例没有logger属性") t_logger = unreal.resolve_python_object_handle(instance.logger) elif hasattr(instance, "logger") and isinstance(instance.logger, ToolShelfLogger): t_logger = instance.logger else: raise TypeError("实例类型不正确") t_logger.begin() try: func(instance, *args, **kwargs) except Exception as e: t_logger.error(traceback.format_exc()) t_logger.end() error_message = t_logger.get_section_log(logging.ERROR) warning_message = t_logger.get_section_log(logging.WARNING) if error_message: unreal.EditorDialog.show_message("错误", f"{message}\n{error_message}", unreal.AppMsgType.OK) elif warning_message: unreal.EditorDialog.show_message("成功", f"操作成功,但存在一些警告\n{warning_message}", unreal.AppMsgType.OK) else: unreal.EditorDialog.show_message("成功", "操作成功", unreal.AppMsgType.OK) return wrapper2 return wrapper class BaseInterface: def __init__(self, logger: ToolShelfLogger): self.logger = logger
import unreal import os # content directory where assets will be stored content_folder = "/project/" input_directory = "C:/project/" def count_jt_files_in_directory(directory): count = 0 item_list = os.listdir(directory) for item in item_list: item_full_path = os.path.join(directory, item) if os.path.isdir(item_full_path): count = count + count_jt_files_in_directory(item_full_path) else: ext = os.path.splitext(item)[1] if ext == '.jt': count = count + 1 return count def process_directory(directory, parent_actor, slow_task): global file_index global assetSubsystem global levelSubsystem actorSubsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) jt_files = [] item_list = os.listdir(directory) for item in item_list: if slow_task.should_cancel(): return item_full_path = os.path.join(directory, item) if os.path.isdir(item_full_path): # create a dummy actor for sub directories # no python access to the Empty Actor Factory, so we use Static Mesh Actor with no mesh new_actor = actorSubsystem.spawn_actor_from_class(unreal.StaticMeshActor, unreal.Vector(0, 0, 0), unreal.Rotator(0, 0, 0)) new_actor.root_component.set_editor_property("mobility", unreal.ComponentMobility.MOVABLE) new_actor.set_actor_label(item) new_actor.attach_to_actor(parent_actor, unreal.Name(), unreal.AttachmentRule.KEEP_WORLD, unreal.AttachmentRule.KEEP_WORLD, unreal.AttachmentRule.KEEP_WORLD, False) process_directory(item_full_path, new_actor, slow_task) else: ext = os.path.splitext(item)[1] if ext == '.jt': slow_task.enter_progress_frame(1) print("loading file " + item_full_path) asset_content_path = content_folder + '/' + str(file_index).zfill(3) file_index = file_index + 1 # if the directory already exists, it means we already processed it in a previous execution so we skip this file if assetSubsystem.does_directory_exist(asset_content_path): continue # init datasmith CAD scene import from a CAD file and a target content directory datasmith_scene = unreal.DatasmithSceneElement.construct_datasmith_scene_from_file(item_full_path) # check scene initialization if datasmith_scene is None: print("Error: Failed creating Datasmith CAD scene") continue # set CAD import options base_options = datasmith_scene.get_options().base_options base_options.scene_handling = unreal.DatasmithImportScene.CURRENT_LEVEL base_options.static_mesh_options.generate_lightmap_u_vs = False tessellation_options = datasmith_scene.get_options(unreal.DatasmithCommonTessellationOptions) if tessellation_options: tessellation_options.options.chord_tolerance = 0.3 tessellation_options.options.max_edge_length = 200.0 tessellation_options.options.normal_tolerance = 25.0 tessellation_options.options.stitching_technique = unreal.DatasmithCADStitchingTechnique.STITCHING_NONE # import the scene into the current level result = datasmith_scene.import_scene(asset_content_path) if not result.import_succeed: print("Error: Datasmith scene import failed") continue # no geometry imported, nothing to do if len(result.imported_actors) == 0: print("Warning: Non actor imported") continue # set mobility and parent on actors for imported_actor in result.imported_actors: imported_actor.root_component.set_editor_property("mobility", unreal.ComponentMobility.MOVABLE) if imported_actor.get_attach_parent_actor() is None: imported_actor.attach_to_actor(parent_actor, unreal.Name(), unreal.AttachmentRule.KEEP_WORLD, unreal.AttachmentRule.KEEP_WORLD, unreal.AttachmentRule.KEEP_WORLD, False) # save static meshes and materials assets for static_mesh in result.imported_meshes: assetSubsystem.save_loaded_asset(static_mesh) for i in range(static_mesh.get_num_sections(0)): material_interface = static_mesh.get_material(i) assetSubsystem.save_loaded_asset(material_interface) # save level saved_level = levelSubsystem.save_all_dirty_levels() if not saved_level: print("Error: Cannot save level") return # get the number of JT files in the directory nb_jt_files = count_jt_files_in_directory(input_directory) # global variable file_index = 0 assetSubsystem = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem) levelSubsystem = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem) # progress bar with unreal.ScopedSlowTask(nb_jt_files, "Data Preparation") as slow_task: slow_task.make_dialog(True) level_path = content_folder + "/ImportedLevel" if assetSubsystem.does_asset_exist(level_path): # if the level already exists, we just load it levelSubsystem.load_level(level_path) else: # create a new level to hold the imported scene created_new_level = levelSubsystem.new_level_from_template(level_path, "/project/") if not created_new_level: print("Error: Cannot create new level") quit() process_directory(input_directory, None, slow_task)
# unreal._ObjectBase # https://api.unrealengine.com/project/.html import unreal # object_to_cast: obj unreal.Object : The object you want to cast # object_class: obj unreal.Class : The class you want to cast the object into def cast(object_to_cast=None, object_class=None): try: return object_class.cast(object_to_cast) except: return None # Cpp ######################################################################################################################################################################################## # Note: Also work using the command : help(unreal.StaticMesh) # unreal_class: obj : The class you want to know the properties # return: str List : The available properties (formatted the way you can directly use them to get their values) def getAllProperties(unreal_class=None): return unreal.CppLib.get_all_properties(unreal_class)
# coding: utf-8 from asyncio.windows_events import NULL import unreal import argparse parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") parser.add_argument("-meta") args = parser.parse_args() print(args.vrm) reg = unreal.AssetRegistryHelpers.get_asset_registry(); ## rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r #rig = rigs[10] hierarchy = unreal.ControlRigBlueprintLibrary.get_hierarchy(rig) h_con = hierarchy.get_controller() r_con = rig.get_controller() graph = r_con.get_graph() node = graph.get_nodes() def checkAndSwapPin(pin): subpins = pin.get_sub_pins() #print(subpins) if (len(subpins) != 2): return; typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') #if (typePin==None or namePin==None): if (typePin==None): return; #if (typePin.get_default_value() == '' or namePin.get_default_value() == ''): if (typePin.get_default_value() == ''): return; if (typePin.get_default_value() != 'Bone'): return; print(typePin.get_default_value() + ' : ' + namePin.get_default_value()) r_con.set_pin_default_value(typePin.get_pin_path(), 'Control') print('swap end') #end check pin bonePin = None controlPin = None while(len(hierarchy.get_bones()) > 0): e = hierarchy.get_bones()[-1] h_con.remove_all_parents(e) h_con.remove_element(e) h_con.import_bones(unreal.ControlRigBlueprintLibrary.get_preview_mesh(rig).skeleton) ## for n in node: pins = n.get_pins() for pin in pins: if (pin.is_array()): if (pin.get_array_size() > 40): # long bone list typePin = pin.get_sub_pins()[0].find_sub_pin('Type') if (typePin.get_default_value() == 'Bone'): bonePin = pin if (typePin.get_default_value() == 'Control'): controlPin = pin continue for item in pin.get_sub_pins(): checkAndSwapPin(item) else: checkAndSwapPin(pin) for e in hierarchy.get_controls(): tmp = "{}".format(e.name) if (tmp.endswith('_ctrl') == False): continue if (tmp.startswith('thumb_0') or tmp.startswith('index_0') or tmp.startswith('middle_0') or tmp.startswith('ring_0') or tmp.startswith('pinky_0')): print('') else: continue c = hierarchy.find_control(e) print(e.name) #ttt = unreal.RigComputedTransform(transform=[[0.0, 0.0, 2.0], [90.0, 0.0, 0.0], [0.03, 0.03, 0.25]]) #ttt = unreal.RigComputedTransform(transform=[[0.0, 0.0, 2.0], [90.0, 0.0, 0.0], [0.03, 0.03, 0.25]]) ttt = unreal.Transform(location=[0.0, 0.0, 2.0], rotation=[0.0, 0.0, 90.0], scale=[0.03, 0.03, 0.25]) hierarchy.set_control_shape_transform(e, ttt, True) ''' shape = c.get_editor_property('shape') init = shape.get_editor_property('initial') #init = shape.get_editor_property('current') local = init.get_editor_property('local') local = ttt init.set_editor_property('local', local) gl = init.get_editor_property('global_') gl = ttt init.set_editor_property('global_', gl) shape.set_editor_property('initial', init) shape.set_editor_property('current', init) c.set_editor_property('shape', shape) ''' ### swapBoneTable = [ ["Root",""], ["Pelvis","hips"], ["spine_01","spine"], ["spine_02","chest"], ["spine_03","upperChest"], ["clavicle_l","leftShoulder"], ["UpperArm_L","leftUpperArm"], ["lowerarm_l","leftLowerArm"], ["Hand_L","leftHand"], ["index_01_l","leftIndexProximal"], ["index_02_l","leftIndexIntermediate"], ["index_03_l","leftIndexDistal"], ["middle_01_l","leftMiddleProximal"], ["middle_02_l","leftMiddleIntermediate"], ["middle_03_l","leftMiddleDistal"], ["pinky_01_l","leftLittleProximal"], ["pinky_02_l","leftLittleIntermediate"], ["pinky_03_l","leftLittleDistal"], ["ring_01_l","leftRingProximal"], ["ring_02_l","leftRingIntermediate"], ["ring_03_l","leftRingDistal"], ["thumb_01_l","leftThumbProximal"], ["thumb_02_l","leftThumbIntermediate"], ["thumb_03_l","leftThumbDistal"], ["lowerarm_twist_01_l",""], ["upperarm_twist_01_l",""], ["clavicle_r","rightShoulder"], ["UpperArm_R","rightUpperArm"], ["lowerarm_r","rightLowerArm"], ["Hand_R","rightHand"], ["index_01_r","rightIndexProximal"], ["index_02_r","rightIndexIntermediate"], ["index_03_r","rightIndexDistal"], ["middle_01_r","rightMiddleProximal"], ["middle_02_r","rightMiddleIntermediate"], ["middle_03_r","rightMiddleDistal"], ["pinky_01_r","rightLittleProximal"], ["pinky_02_r","rightLittleIntermediate"], ["pinky_03_r","rightLittleDistal"], ["ring_01_r","rightRingProximal"], ["ring_02_r","rightRingIntermediate"], ["ring_03_r","rightRingDistal"], ["thumb_01_r","rightThumbProximal"], ["thumb_02_r","rightThumbIntermediate"], ["thumb_03_r","rightThumbDistal"], ["lowerarm_twist_01_r",""], ["upperarm_twist_01_r",""], ["neck_01","neck"], ["head","head"], ["Thigh_L","leftUpperLeg"], ["calf_l","leftLowerLeg"], ["calf_twist_01_l",""], ["Foot_L","leftFoot"], ["ball_l","leftToes"], ["thigh_twist_01_l",""], ["Thigh_R","rightUpperLeg"], ["calf_r","rightLowerLeg"], ["calf_twist_01_r",""], ["Foot_R","rightFoot"], ["ball_r","rightToes"], ["thigh_twist_01_r",""], ["index_metacarpal_l",""], ["index_metacarpal_r",""], ["middle_metacarpal_l",""], ["middle_metacarpal_r",""], ["ring_metacarpal_l",""], ["ring_metacarpal_r",""], ["pinky_metacarpal_l",""], ["pinky_metacarpal_r",""], #custom ["eye_l", "leftEye"], ["eye_r", "rightEye"], ] humanoidBoneList = [ "hips", "leftUpperLeg", "rightUpperLeg", "leftLowerLeg", "rightLowerLeg", "leftFoot", "rightFoot", "spine", "chest", "upperChest", # 9 optional "neck", "head", "leftShoulder", "rightShoulder", "leftUpperArm", "rightUpperArm", "leftLowerArm", "rightLowerArm", "leftHand", "rightHand", "leftToes", "rightToes", "leftEye", "rightEye", "jaw", "leftThumbProximal", # 24 "leftThumbIntermediate", "leftThumbDistal", "leftIndexProximal", "leftIndexIntermediate", "leftIndexDistal", "leftMiddleProximal", "leftMiddleIntermediate", "leftMiddleDistal", "leftRingProximal", "leftRingIntermediate", "leftRingDistal", "leftLittleProximal", "leftLittleIntermediate", "leftLittleDistal", "rightThumbProximal", "rightThumbIntermediate", "rightThumbDistal", "rightIndexProximal", "rightIndexIntermediate", "rightIndexDistal", "rightMiddleProximal", "rightMiddleIntermediate", "rightMiddleDistal", "rightRingProximal", "rightRingIntermediate", "rightRingDistal", "rightLittleProximal", "rightLittleIntermediate", "rightLittleDistal", #54 ] for i in range(len(humanoidBoneList)): humanoidBoneList[i] = humanoidBoneList[i].lower() for i in range(len(swapBoneTable)): swapBoneTable[i][0] = swapBoneTable[i][0].lower() swapBoneTable[i][1] = swapBoneTable[i][1].lower() ### 全ての骨 modelBoneElementList = [] modelBoneNameList = [] for e in hierarchy.get_bones(): if (e.type == unreal.RigElementType.BONE): modelBoneElementList.append(e) modelBoneNameList.append("{}".format(e.name)) ## meta 取得 reg = unreal.AssetRegistryHelpers.get_asset_registry(); a = reg.get_all_assets(); if (args.meta): for aa in a: if (aa.get_editor_property("object_path") == args.meta): v:unreal.VrmMetaObject = aa vv = aa.get_asset() if (vv == None): for aa in a: if (aa.get_editor_property("object_path") == args.vrm): v:unreal.VrmAssetListObject = aa vv = v.get_asset().vrm_meta_object meta = vv # Backwards Bone Names allBackwardsNode = [] def r_nodes(node): b = False try: allBackwardsNode.index(node) except: b = True if (b == True): allBackwardsNode.append(node) linknode = node.get_linked_source_nodes() for n in linknode: r_nodes(n) linknode = node.get_linked_target_nodes() for n in linknode: r_nodes(n) for n in node: if (n.get_node_title() == 'Backwards Solve'): r_nodes(n) print(len(allBackwardsNode)) print(len(node)) def boneOverride(pin): subpins = pin.get_sub_pins() if (len(subpins) != 2): return typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') if (typePin==None): return controlName = namePin.get_default_value() if (controlName.endswith('_ctrl')): return if (controlName.endswith('_space')): return r_con.set_pin_default_value(typePin.get_pin_path(), 'Bone') table = [i for i in swapBoneTable if i[0]==controlName] if (len(table) == 0): return if (table[0][0] == 'root'): metaTable = "{}".format(hierarchy.get_bones()[0].name) else: metaTable = meta.humanoid_bone_table.get(table[0][1]) if (metaTable == None): metaTable = 'None' #print(table[0][1]) #print('<<') #print(controlName) #print('<<<') #print(metaTable) r_con.set_pin_default_value(namePin.get_pin_path(), metaTable) #for e in meta.humanoid_bone_table: for n in allBackwardsNode: pins = n.get_pins() for pin in pins: if (pin.is_array()): # finger 無変換チェック linknode = n.get_linked_target_nodes() if (len(linknode) == 1): if (linknode[0].get_node_title()=='At'): continue for p in pin.get_sub_pins(): boneOverride(p) else: boneOverride(pin) #sfsdjfkasjk ### 骨名対応表。Humanoid名 -> Model名 humanoidBoneToModel = {"" : ""} humanoidBoneToModel.clear() humanoidBoneToMannequin = {"" : ""} humanoidBoneToMannequin.clear() # humanoidBone -> modelBone のテーブル作る for searchHumanoidBone in humanoidBoneList: bone_h = None for e in meta.humanoid_bone_table: if ("{}".format(e).lower() == searchHumanoidBone): bone_h = e; break; if (bone_h==None): # not found continue bone_m = meta.humanoid_bone_table[bone_h] try: i = modelBoneNameList.index(bone_m) except: i = -1 if (i < 0): # no bone continue humanoidBoneToModel["{}".format(bone_h).lower()] = "{}".format(bone_m) #humanoidBoneToMannequin["{}".format(bone_h).lower()] = "{}".format(bone_m).lower(bone_h) #print(humanoidBoneToModel) #print(bonePin) #print(controlPin) if (bonePin != None and controlPin !=None): r_con.clear_array_pin(bonePin.get_pin_path()) r_con.clear_array_pin(controlPin.get_pin_path()) #c.clear_array_pin(v.get_pin_path()) #tmp = '(Type=Control,Name=' #tmp += "{}".format('aaaaa') #tmp += ')' #r_con.add_array_pin(bonePin.get_pin_path(), default_value=tmp) for e in swapBoneTable: try: i = 0 humanoidBoneToModel[e[1]] except: i = -1 if (i < 0): # no bone continue #e[0] -> grayman #e[1] -> humanoid #humanoidBoneToModel[e[1]] -> modelBone bone = unreal.RigElementKey(unreal.RigElementType.BONE, humanoidBoneToModel[e[1]]) space = unreal.RigElementKey(unreal.RigElementType.NULL, "{}_s".format(e[0])) #print('aaa') #print(bone) #print(space) #p = hierarchy.get_first_parent(humanoidBoneToModel[result[0][1]]) t = hierarchy.get_global_transform(bone) #print(t) hierarchy.set_global_transform(space, t, True) if (bonePin != None and controlPin !=None): tmp = '(Type=Control,Name=' tmp += "{}".format(e[0]) tmp += ')' r_con.add_array_pin(controlPin.get_pin_path(), default_value=tmp) tmp = '(Type=Bone,Name=' tmp += "\"{}\"".format(humanoidBoneToModel[e[1]]) tmp += ')' r_con.add_array_pin(bonePin.get_pin_path(), default_value=tmp) # for bone name space namePin = bonePin.get_sub_pins()[-1].find_sub_pin('Name') r_con.set_pin_default_value(namePin.get_pin_path(), "{}".format(humanoidBoneToModel[e[1]]))
import unreal tempSkeleton = '/project/' tempSkeleton = unreal.EditorAssetLibrary.load_asset(tempSkeleton) unreal.AssetTools.create_asset('BS','/project/') BP = '/project/' BP1 = unreal.EditorAssetLibrary.load_asset(BP) unreal.EditorAssetLibrary.get_editor_property(BP1)
"""Module to export sequencer data using OTIO""" import os import opentimelineio as otio import path_utils import unreal def get_master_sequencer(): """Get the master sequencer in the content browser.""" #/Game/ represents the root of the Content folder path = "/project/.MasterSequencer" master_sequencer = unreal.EditorAssetLibrary.load_asset(path) if master_sequencer: return master_sequencer else: unreal.log_error("Could not find 'MasterSequencer' LevelSequencer in the Content folder") return None def export_sequencer_data_as_otio(): """Export out of unreal folder""" # Get the output folder for the out usd data out_dir = path_utils.get_otio_export_folder() master_sequencer = get_master_sequencer() print(os.path.exists(out_dir)) if not os.path.exists(out_dir): os.makedirs(out_dir) # Find shot track master_shot_track = master_sequencer.find_tracks_by_exact_type( unreal.MovieSceneCinematicShotTrack )[0] if out_dir and master_sequencer: # Creat OTIO timeline timeline = otio.schema.Timeline(name="MyTimeline") track = otio.schema.Track() timeline.tracks.append(track) # Get shots inside the master sequence adn add them to the timeline for shot in master_shot_track.get_sections(): shot_name = shot.get_shot_display_name() start_frame = shot.get_start_frame() end_frame = shot.get_end_frame() clip = otio.schema.Clip(name=shot_name) duration = end_frame - start_frame + 1 clip.source_range = otio.opentime.TimeRange( start_time=otio.opentime.RationalTime(start_frame, 24), # Assuming 24 fps duration=otio.opentime.RationalTime(duration, 24) ) track.append(clip) out_path = out_dir + "my_timeline.otio" if os.path.exists(out_dir): otio.adapters.write_to_file(timeline, out_path) else: unreal.log_error("Can't write OTIO files, {} dir does not exists".format(out_dir)) else: unreal.log_error("Interrupting sequencer data export.")
# This file is based on templates provided and copyrighted by Autodesk, Inc. # This file has been modified by Epic Games, Inc. and is subject to the license # file included in this repository. import sgtk import unreal from tank_vendor import six import copy import datetime import os import pprint import subprocess import sys import tempfile # Local storage path field for known Oses. _OS_LOCAL_STORAGE_PATH_FIELD = { "darwin": "mac_path", "win32": "windows_path", "linux": "linux_path", "linux2": "linux_path", }[sys.platform] HookBaseClass = sgtk.get_hook_baseclass() class UnrealMoviePublishPlugin(HookBaseClass): """ Plugin for publishing an Unreal sequence as a rendered movie file. This hook relies on functionality found in the base file publisher hook in the publish2 app and should inherit from it in the configuration. The hook setting for this plugin should look something like this:: hook: "{self}/publish_file.py:{engine}/tk-multi-publish2/project/.py" To learn more about writing a publisher plugin, visit http://developer.shotgunsoftware.com/tk-multi-publish2/plugin.html """ # NOTE: The plugin icon and name are defined by the base file plugin. @property def description(self): """ Verbose, multi-line description of what the plugin does. This can contain simple html for formatting. """ return """Publishes the sequence as a rendered movie to Shotgun. A <b>Publish</b> entry will be created in Shotgun which will include a reference to the movie's current path on disk. A <b>Version</b> entry will also be created in Shotgun with the movie file being uploaded there. Other users will be able to review the movie in the browser or in RV. <br> If available, the Movie Render Queue will be used for rendering, the Level Sequencer will be used otherwise. """ @property def settings(self): """ Dictionary defining the settings that this plugin expects to receive through the settings parameter in the accept, validate, publish and finalize methods. A dictionary on the following form:: { "Settings Name": { "type": "settings_type", "default": "default_value", "description": "One line description of the setting" } The type string should be one of the data types that toolkit accepts as part of its environment configuration. """ # inherit the settings from the base publish plugin base_settings = super(UnrealMoviePublishPlugin, self).settings or {} # Here you can add any additional settings specific to this plugin publish_template_setting = { "Publish Template": { "type": "template", "default": None, "description": "Template path for published work files. Should" "correspond to a template defined in " "templates.yml.", }, "Movie Render Queue Presets Path": { "type": "string", "default": None, "description": "Optional Unreal Path to saved presets " "for rendering with the Movie Render Queue" }, "Publish Folder": { "type": "string", "default": None, "description": "Optional folder to use as a root for publishes" } } # update the base settings base_settings.update(publish_template_setting) return base_settings @property def item_filters(self): """ List of item types that this plugin is interested in. Only items matching entries in this list will be presented to the accept() method. Strings can contain glob patters such as *, for example ["maya.*", "file.maya"] """ return ["unreal.asset.LevelSequence"] def create_settings_widget(self, parent): """ Creates a Qt widget, for the supplied parent widget (a container widget on the right side of the publish UI). :param parent: The parent to use for the widget being created :return: A :class:`QtGui.QFrame` that displays editable widgets for modifying the plugin's settings. """ # defer Qt-related imports from sgtk.platform.qt import QtGui, QtCore # Create a QFrame with all our widgets settings_frame = QtGui.QFrame(parent) # Create our widgets, we add them as properties on the QFrame so we can # retrieve them easily. Qt uses camelCase so our xxxx_xxxx names can't # clash with existing Qt properties. # Show this plugin description settings_frame.description_label = QtGui.QLabel(self.description) settings_frame.description_label.setWordWrap(True) settings_frame.description_label.setOpenExternalLinks(True) settings_frame.description_label.setTextFormat(QtCore.Qt.RichText) # Unreal setttings settings_frame.unreal_render_presets_label = QtGui.QLabel("Render with Movie Pipeline Presets:") settings_frame.unreal_render_presets_widget = QtGui.QComboBox() settings_frame.unreal_render_presets_widget.addItem("No presets") presets_folder = unreal.MovieRenderPipelineProjectSettings().preset_save_dir for preset in unreal.EditorAssetLibrary.list_assets(presets_folder.path): settings_frame.unreal_render_presets_widget.addItem(preset.split(".")[0]) settings_frame.unreal_publish_folder_label = QtGui.QLabel("Publish folder:") storage_roots = self.parent.shotgun.find( "LocalStorage", [], ["code", _OS_LOCAL_STORAGE_PATH_FIELD] ) settings_frame.storage_roots_widget = QtGui.QComboBox() settings_frame.storage_roots_widget.addItem("Current Unreal Project") for storage_root in storage_roots: if storage_root[_OS_LOCAL_STORAGE_PATH_FIELD]: settings_frame.storage_roots_widget.addItem( "%s (%s)" % ( storage_root["code"], storage_root[_OS_LOCAL_STORAGE_PATH_FIELD] ), userData=storage_root, ) # Create the layout to use within the QFrame settings_layout = QtGui.QVBoxLayout() settings_layout.addWidget(settings_frame.description_label) settings_layout.addWidget(settings_frame.unreal_render_presets_label) settings_layout.addWidget(settings_frame.unreal_render_presets_widget) settings_layout.addWidget(settings_frame.unreal_publish_folder_label) settings_layout.addWidget(settings_frame.storage_roots_widget) settings_layout.addStretch() settings_frame.setLayout(settings_layout) return settings_frame def get_ui_settings(self, widget): """ Method called by the publisher to retrieve setting values from the UI. :returns: A dictionary with setting values. """ # defer Qt-related imports from sgtk.platform.qt import QtCore self.logger.info("Getting settings from UI") # Please note that we don't have to return all settings here, just the # settings which are editable in the UI. render_presets_path = None if widget.unreal_render_presets_widget.currentIndex() > 0: # First entry is "No Presets" render_presets_path = six.ensure_str(widget.unreal_render_presets_widget.currentText()) storage_index = widget.storage_roots_widget.currentIndex() publish_folder = None if storage_index > 0: # Something selected and not the first entry storage = widget.storage_roots_widget.itemData(storage_index, role=QtCore.Qt.UserRole) publish_folder = storage[_OS_LOCAL_STORAGE_PATH_FIELD] settings = { "Movie Render Queue Presets Path": render_presets_path, "Publish Folder": publish_folder, } return settings def set_ui_settings(self, widget, settings): """ Method called by the publisher to populate the UI with the setting values. :param widget: A QFrame we created in `create_settings_widget`. :param settings: A list of dictionaries. :raises NotImplementedError: if editing multiple items. """ # defer Qt-related imports from sgtk.platform.qt import QtCore self.logger.info("Setting UI settings") if len(settings) > 1: # We do not allow editing multiple items raise NotImplementedError cur_settings = settings[0] render_presets_path = cur_settings["Movie Render Queue Presets Path"] preset_index = 0 if render_presets_path: preset_index = widget.unreal_render_presets_widget.findText(render_presets_path) self.logger.info("Index for %s is %s" % (render_presets_path, preset_index)) widget.unreal_render_presets_widget.setCurrentIndex(preset_index) # Note: the template is validated in the accept method, no need to check it here. publish_template_setting = cur_settings.get("Publish Template") publisher = self.parent publish_template = publisher.get_template_by_name(publish_template_setting) if isinstance(publish_template, sgtk.TemplatePath): widget.unreal_publish_folder_label.setEnabled(False) widget.storage_roots_widget.setEnabled(False) folder_index = 0 publish_folder = cur_settings["Publish Folder"] if publish_folder: for i in range(widget.storage_roots_widget.count()): data = widget.storage_roots_widget.itemData(i, role=QtCore.Qt.UserRole) if data and data[_OS_LOCAL_STORAGE_PATH_FIELD] == publish_folder: folder_index = i break self.logger.debug("Index for %s is %s" % (publish_folder, folder_index)) widget.storage_roots_widget.setCurrentIndex(folder_index) def load_saved_ui_settings(self, settings): """ Load saved settings and update the given settings dictionary with them. :param settings: A dictionary where keys are settings names and values Settings instances. """ # Retrieve SG utils framework settings module and instantiate a manager fw = self.load_framework("tk-framework-shotgunutils_v5.x.x") module = fw.import_module("settings") settings_manager = module.UserSettings(self.parent) # Retrieve saved settings settings["Movie Render Queue Presets Path"].value = settings_manager.retrieve( "publish2.movie_render_queue_presets_path", settings["Movie Render Queue Presets Path"].value, settings_manager.SCOPE_PROJECT, ) settings["Publish Folder"].value = settings_manager.retrieve( "publish2.publish_folder", settings["Publish Folder"].value, settings_manager.SCOPE_PROJECT ) self.logger.debug("Loaded settings %s" % settings["Publish Folder"]) self.logger.debug("Loaded settings %s" % settings["Movie Render Queue Presets Path"]) def save_ui_settings(self, settings): """ Save UI settings. :param settings: A dictionary of Settings instances. """ # Retrieve SG utils framework settings module and instantiate a manager fw = self.load_framework("tk-framework-shotgunutils_v5.x.x") module = fw.import_module("settings") settings_manager = module.UserSettings(self.parent) # Save settings render_presets_path = settings["Movie Render Queue Presets Path"].value settings_manager.store("publish2.movie_render_queue_presets_path", render_presets_path, settings_manager.SCOPE_PROJECT) publish_folder = settings["Publish Folder"].value settings_manager.store("publish2.publish_folder", publish_folder, settings_manager.SCOPE_PROJECT) def accept(self, settings, item): """ Method called by the publisher to determine if an item is of any interest to this plugin. Only items matching the filters defined via the item_filters property will be presented to this method. A publish task will be generated for each item accepted here. Returns a dictionary with the following booleans: - accepted: Indicates if the plugin is interested in this value at all. Required. - enabled: If True, the plugin will be enabled in the UI, otherwise it will be disabled. Optional, True by default. - visible: If True, the plugin will be visible in the UI, otherwise it will be hidden. Optional, True by default. - checked: If True, the plugin will be checked in the UI, otherwise it will be unchecked. Optional, True by default. :param settings: Dictionary of Settings. The keys are strings, matching the keys returned in the settings property. The values are `Setting` instances. :param item: Item to process :returns: dictionary with boolean keys accepted, required and enabled """ accepted = True checked = True if sys.platform != "win32": self.logger.warning( "Movie publishing is not supported on other platforms than Windows..." ) return { "accepted": False, } publisher = self.parent # ensure the publish template is defined publish_template_setting = settings.get("Publish Template") publish_template = publisher.get_template_by_name(publish_template_setting.value) if not publish_template: self.logger.debug( "A publish template could not be determined for the " "item. Not accepting the item." ) accepted = False # we've validated the work and publish templates. add them to the item properties # for use in subsequent methods item.properties["publish_template"] = publish_template self.load_saved_ui_settings(settings) return { "accepted": accepted, "checked": checked } def validate(self, settings, item): """ Validates the given item to check that it is ok to publish. Returns a boolean to indicate validity. :param settings: Dictionary of Settings. The keys are strings, matching the keys returned in the settings property. The values are `Setting` instances. :param item: Item to process :returns: True if item is valid, False otherwise. """ # raise an exception here if something is not valid. # If you use the logger, warnings will appear in the validation tree. # You can attach callbacks that allow users to fix these warnings # at the press of a button. # # For example: # # self.logger.info( # "Your session is not part of a maya project.", # extra={ # "action_button": { # "label": "Set Project", # "tooltip": "Set the maya project", # "callback": lambda: mel.eval('setProject ""') # } # } # ) asset_path = item.properties.get("asset_path") asset_name = item.properties.get("asset_name") if not asset_path or not asset_name: self.logger.debug("Sequence path or name not configured.") return False # Retrieve the Level Sequences sections tree for this Level Sequence. # This is needed to get frame ranges in the "edit" context. edits_path = item.properties.get("edits_path") if not edits_path: self.logger.debug("Edits path not configured.") return False self.logger.info("Edits path %s" % edits_path) item.properties["unreal_master_sequence"] = edits_path[0] item.properties["unreal_shot"] = ".".join([lseq.get_name() for lseq in edits_path[1:]]) self.logger.info("Master sequence %s, shot %s" % ( item.properties["unreal_master_sequence"].get_name(), item.properties["unreal_shot"] or "all shots", )) # Get the configured publish template publish_template = item.properties["publish_template"] # Get the context from the Publisher UI context = item.context unreal.log("context: {}".format(context)) # Query the fields needed for the publish template from the context try: fields = context.as_template_fields(publish_template) except Exception: # We likely failed because of folder creation, trigger that self.parent.sgtk.create_filesystem_structure( context.entity["type"], context.entity["id"], self.parent.engine.instance_name ) # In theory, this should now work because we've created folders and # updated the path cache fields = item.context.as_template_fields(publish_template) unreal.log("context fields: {}".format(fields)) # Ensure that the current map is saved on disk unreal_map = unreal.EditorLevelLibrary.get_editor_world() unreal_map_path = unreal_map.get_path_name() # Transient maps are not supported, must be saved on disk if unreal_map_path.startswith("/Temp/"): self.logger.debug("Current map must be saved first.") return False # Add the map name to fields world_name = unreal_map.get_name() # Add the Level Sequence to fields, with the shot if any fields["ue_world"] = world_name if len(edits_path) > 1: fields["ue_level_sequence"] = "%s_%s" % (edits_path[0].get_name(), edits_path[-1].get_name()) else: fields["ue_level_sequence"] = edits_path[0].get_name() # Stash the level sequence and map paths in properties for the render item.properties["unreal_asset_path"] = asset_path item.properties["unreal_map_path"] = unreal_map_path # Add a version number to the fields, incremented from the current asset version version_number = self._unreal_asset_get_version(asset_path) version_number = version_number + 1 fields["version"] = version_number # Add today's date to the fields date = datetime.date.today() fields["YYYY"] = date.year fields["MM"] = date.month fields["DD"] = date.day # Check if we can use the Movie Render queue available from 4.26 use_movie_render_queue = False render_presets = None if hasattr(unreal, "MoviePipelineQueueEngineSubsystem"): if hasattr(unreal, "MoviePipelineAppleProResOutput"): use_movie_render_queue = True self.logger.info("Movie Render Queue will be used for rendering.") render_presets_path = settings["Movie Render Queue Presets Path"].value if render_presets_path: self.logger.info("Validating render presets path %s" % render_presets_path) render_presets = unreal.EditorAssetLibrary.load_asset(render_presets_path) for _, reason in self._check_render_settings(render_presets): self.logger.warning(reason) else: self.logger.info( "Apple ProRes Media plugin must be loaded to be able to render with the Movie Render Queue, " "Level Sequencer will be used for rendering." ) if not use_movie_render_queue: if item.properties["unreal_shot"]: raise ValueError("Rendering invidual shots for a sequence is only supported with the Movie Render Queue.") self.logger.info("Movie Render Queue not available, Level Sequencer will be used for rendering.") item.properties["use_movie_render_queue"] = use_movie_render_queue item.properties["movie_render_queue_presets"] = render_presets # Set the UE movie extension based on the current platform and rendering engine if use_movie_render_queue: fields["ue_mov_ext"] = "mov" # mov on all platforms else: if sys.platform == "win32": fields["ue_mov_ext"] = "avi" else: fields["ue_mov_ext"] = "mov" # Ensure the fields work for the publish template missing_keys = publish_template.missing_keys(fields) if missing_keys: error_msg = "Missing keys required for the publish template " \ "%s" % (missing_keys) self.logger.error(error_msg) raise ValueError(error_msg) publish_path = publish_template.apply_fields(fields) if not os.path.isabs(publish_path): # If the path is not absolute, prepend the publish folder setting. publish_folder = settings["Publish Folder"].value if not publish_folder: publish_folder = unreal.Paths.project_saved_dir() publish_path = os.path.abspath( os.path.join( publish_folder, publish_path ) ) item.properties["path"] = publish_path item.properties["publish_path"] = publish_path item.properties["publish_type"] = "Unreal Render" item.properties["version_number"] = version_number self.save_ui_settings(settings) return True def _check_render_settings(self, render_config): """ Check settings from the given render preset and report which ones are problematic and why. :param render_config: An Unreal Movie Pipeline render config. :returns: A potentially empty list of tuples, where each tuple is a setting and a string explaining the problem. """ invalid_settings = [] # To avoid having multiple outputs, only keep the main render pass and the expected output format. for setting in render_config.get_all_settings(): # Check for render passes. Since some classes derive from MoviePipelineDeferredPassBase, which is what we want to only keep # we can't use isinstance and use type instead. if isinstance(setting, unreal.MoviePipelineImagePassBase) and type(setting) != unreal.MoviePipelineDeferredPassBase: invalid_settings.append((setting, "Render pass %s would cause multiple outputs" % setting.get_name())) # Check rendering outputs elif isinstance(setting, unreal.MoviePipelineOutputBase) and not isinstance(setting, unreal.MoviePipelineAppleProResOutput): invalid_settings.append((setting, "Render output %s would cause multiple outputs" % setting.get_name())) return invalid_settings def publish(self, settings, item): """ Executes the publish logic for the given item and settings. :param settings: Dictionary of Settings. The keys are strings, matching the keys returned in the settings property. The values are `Setting` instances. :param item: Item to process """ # This is where you insert custom information into `item`, like the # path of the file being published or any dependency this publish # has on other publishes. # get the path in a normalized state. no trailing separator, separators # are appropriate for current os, no double separators, etc. # let the base class register the publish publish_path = os.path.normpath(item.properties["publish_path"]) # Split the destination path into folder and filename destination_folder, movie_name = os.path.split(publish_path) movie_name = os.path.splitext(movie_name)[0] # Ensure that the destination path exists before rendering the sequence self.parent.ensure_folder_exists(destination_folder) # Get the level sequence and map paths again unreal_asset_path = item.properties["unreal_asset_path"] unreal_map_path = item.properties["unreal_map_path"] unreal.log("movie name: {}".format(movie_name)) # Render the movie if item.properties.get("use_movie_render_queue"): presets = item.properties["movie_render_queue_presets"] if presets: self.logger.info("Rendering %s with the Movie Render Queue with %s presets." % (publish_path, presets.get_name())) else: self.logger.info("Rendering %s with the Movie Render Queue." % publish_path) res, _ = self._unreal_render_sequence_with_movie_queue( publish_path, unreal_map_path, unreal_asset_path, presets, item.properties.get("unreal_shot") or None, ) else: self.logger.info("Rendering %s with the Level Sequencer." % publish_path) res, _ = self._unreal_render_sequence_with_sequencer( publish_path, unreal_map_path, unreal_asset_path ) if not res: raise RuntimeError( "Unable to render %s" % publish_path ) # Increment the version number self._unreal_asset_set_version(unreal_asset_path, item.properties["version_number"]) # Publish the movie file to Shotgun super(UnrealMoviePublishPlugin, self).publish(settings, item) # Create a Version entry linked with the new publish # Populate the version data to send to SG self.logger.info("Creating Version...") version_data = { "project": item.context.project, "code": movie_name, "description": item.description, "entity": self._get_version_entity(item), "sg_path_to_movie": publish_path, "sg_task": item.context.task } publish_data = item.properties.get("sg_publish_data") # If the file was published, add the publish data to the version if publish_data: version_data["published_files"] = [publish_data] # Log the version data for debugging self.logger.debug( "Populated Version data...", extra={ "action_show_more_info": { "label": "Version Data", "tooltip": "Show the complete Version data dictionary", "text": "<pre>%s</pre>" % ( pprint.pformat(version_data), ) } } ) # Create the version self.logger.info("Creating version for review...") version = self.parent.shotgun.create("Version", version_data) # Stash the version info in the item just in case item.properties["sg_version_data"] = version # On windows, ensure the path is utf-8 encoded to avoid issues with # the shotgun api upload_path = str(item.properties.get("publish_path")) unreal.log("upload_path: {}".format(upload_path)) # Upload the file to SG self.logger.info("Uploading content...") self.parent.shotgun.upload( "Version", version["id"], upload_path, "sg_uploaded_movie" ) self.logger.info("Upload complete!") def finalize(self, settings, item): """ Execute the finalization pass. This pass executes once all the publish tasks have completed, and can for example be used to version up files. :param settings: Dictionary of Settings. The keys are strings, matching the keys returned in the settings property. The values are `Setting` instances. :param item: Item to process """ # do the base class finalization super(UnrealMoviePublishPlugin, self).finalize(settings, item) def _get_version_entity(self, item): """ Returns the best entity to link the version to. """ if item.context.entity: return item.context.entity elif item.context.project: return item.context.project else: return None def _unreal_asset_get_version(self, asset_path): asset = unreal.EditorAssetLibrary.load_asset(asset_path) version_number = 0 if not asset: return version_number engine = sgtk.platform.current_engine() tag = engine.get_metadata_tag("version_number") metadata = unreal.EditorAssetLibrary.get_metadata_tag(asset, tag) if not metadata: return version_number try: version_number = int(metadata) except ValueError: pass return version_number def _unreal_asset_set_version(self, asset_path, version_number): asset = unreal.EditorAssetLibrary.load_asset(asset_path) if not asset: return engine = sgtk.platform.current_engine() tag = engine.get_metadata_tag("version_number") unreal.EditorAssetLibrary.set_metadata_tag(asset, tag, str(version_number)) unreal.EditorAssetLibrary.save_loaded_asset(asset) # The save will pop up a progress bar that will bring the editor to the front thus hiding the publish app dialog # Workaround: Force all Shotgun dialogs to be brought to front engine = sgtk.platform.current_engine() for dialog in engine.created_qt_dialogs: dialog.raise_() def _unreal_render_sequence_with_sequencer(self, output_path, unreal_map_path, sequence_path): """ Renders a given sequence in a given level to a movie file with the Level Sequencer. :param str output_path: Full path to the movie to render. :param str unreal_map_path: Path of the Unreal map in which to run the sequence. :param str sequence_path: Content Browser path of sequence to render. :returns: True if a movie file was generated, False otherwise string representing the path of the generated movie file """ output_folder, output_file = os.path.split(output_path) movie_name = os.path.splitext(output_file)[0] # First, check if there's a file that will interfere with the output of the Sequencer # Sequencer can only render to avi or mov file format if os.path.isfile(output_path): # Must delete it first, otherwise the Sequencer will add a number in the filename try: os.remove(output_path) except OSError: self.logger.error( "Couldn't delete {}. The Sequencer won't be able to output the movie to that file.".format(output_path) ) return False, None # Render the sequence to a movie file using the following command-line arguments cmdline_args = [ sys.executable, # Unreal executable path "%s" % os.path.join( unreal.SystemLibrary.get_project_directory(), "%s.uproject" % unreal.SystemLibrary.get_game_name(), ), # Unreal project unreal_map_path, # Level to load for rendering the sequence # Command-line arguments for Sequencer Render to Movie # See: https://docs.unrealengine.com/en-us/project/ # "-LevelSequence=%s" % sequence_path, # The sequence to render "-MovieFolder=%s" % output_folder, # Output folder, must match the work template "-MovieName=%s" % movie_name, # Output filename "-game", "-MovieSceneCaptureType=/project/.AutomatedLevelSequenceCapture", "-ResX=1280", "-ResY=720", "-ForceRes", "-Windowed", "-MovieCinematicMode=yes", "-MovieFormat=Video", "-MovieFrameRate=24", "-MovieQuality=75", "-NoTextureStreaming", "-NoLoadingScreen", "-NoScreenMessages", ] unreal.log( "Sequencer command-line arguments: {}".format( " ".join(cmdline_args) ) ) # Make a shallow copy of the current environment and clear some variables run_env = copy.copy(os.environ) # Prevent SG TK to try to bootstrap in the new process if "UE_SHOTGUN_BOOTSTRAP" in run_env: del run_env["UE_SHOTGUN_BOOTSTRAP"] if "UE_SHOTGRID_BOOTSTRAP" in run_env: del run_env["UE_SHOTGRID_BOOTSTRAP"] subprocess.call(cmdline_args, env=run_env) return os.path.isfile(output_path), output_path def _unreal_render_sequence_with_movie_queue(self, output_path, unreal_map_path, sequence_path, presets=None, shot_name=None): """ Renders a given sequence in a given level with the Movie Render queue. :param str output_path: Full path to the movie to render. :param str unreal_map_path: Path of the Unreal map in which to run the sequence. :param str sequence_path: Content Browser path of sequence to render. :param presets: Optional :class:`unreal.MoviePipelineMasterConfig` instance to use for renderig. :param str shot_name: Optional shot name to render a single shot from this sequence. :returns: True if a movie file was generated, False otherwise string representing the path of the generated movie file :raises ValueError: If a shot name is specified but can't be found in the sequence. """ output_folder, output_file = os.path.split(output_path) movie_name = os.path.splitext(output_file)[0] qsub = unreal.MoviePipelineQueueEngineSubsystem() queue = qsub.get_queue() job = queue.allocate_new_job(unreal.MoviePipelineExecutorJob) job.sequence = unreal.SoftObjectPath(sequence_path) job.map = unreal.SoftObjectPath(unreal_map_path) # If a specific shot was given, disable all the others. if shot_name: shot_found = False for shot in job.shot_info: if shot.outer_name != shot_name: self.logger.info("Disabling shot %s" % shot.outer_name) shot.enabled = False else: shot_found = True if not shot_found: raise ValueError( "Unable to find shot %s in sequence %s, aborting..." % (shot_name, sequence_path) ) # Set settings from presets, if any if presets: job.set_preset_origin(presets) # Ensure the settings we need are set. config = job.get_configuration() # https://docs.unrealengine.com/4.26/en-US/project/.html?highlight=setting#unreal.MoviePipelineOutputSetting output_setting = config.find_or_add_setting_by_class(unreal.MoviePipelineOutputSetting) output_setting.output_directory = unreal.DirectoryPath(output_folder) output_setting.output_resolution = unreal.IntPoint(1280, 720) output_setting.file_name_format = movie_name output_setting.override_existing_output = True # Overwrite existing files # If needed we could enforce a frame rate, like for the Sequencer code. # output_setting.output_frame_rate = unreal.FrameRate(24) # output_setting.use_custom_frame_rate = True # Remove problematic settings for setting, reason in self._check_render_settings(config): self.logger.warning("Disabling %s: %s." % (setting.get_name(), reason)) config.remove_setting(setting) # Default rendering config.find_or_add_setting_by_class(unreal.MoviePipelineDeferredPassBase) # Render to a movie config.find_or_add_setting_by_class(unreal.MoviePipelineAppleProResOutput) # TODO: check which codec we should use. # We render in a forked process that we can control. # It would be possible to render in from the running process using an # Executor, however it seems to sometimes deadlock if we don't let Unreal # process its internal events, rendering is asynchronous and being notified # when the render completed does not seem to be reliable. # Sample code: # exc = unreal.MoviePipelinePIEExecutor() # # If needed, we can store data in exc.user_data # # In theory we can set a callback to be notified about completion # def _on_movie_render_finished_cb(executor, result): # print("Executor %s finished with %s" % (executor, result)) # # exc.on_executor_finished_delegate.add_callable(_on_movie_render_finished_cb) # r = qsub.render_queue_with_executor_instance(exc) # We can't control the name of the manifest file, so we save and then rename the file. _, manifest_path = unreal.MoviePipelineEditorLibrary.save_queue_to_manifest_file(queue) manifest_path = os.path.abspath(manifest_path) manifest_dir, manifest_file = os.path.split(manifest_path) f, new_path = tempfile.mkstemp( suffix=os.path.splitext(manifest_file)[1], dir=manifest_dir ) os.close(f) os.replace(manifest_path, new_path) self.logger.debug("Queue manifest saved in %s" % new_path) # We now need a path local to the unreal project "Saved" folder. manifest_path = new_path.replace( "%s%s" % ( os.path.abspath( os.path.join(unreal.SystemLibrary.get_project_directory(), "Saved") ), os.path.sep, ), "", ) self.logger.debug("Manifest short path: %s" % manifest_path) # Command line parameters were retrieved by submitting a queue in Unreal Editor with # a MoviePipelineNewProcessExecutor executor. # https://docs.unrealengine.com/4.27/en-US/project/.html?highlight=executor cmd_args = [ sys.executable, "%s" % os.path.join( unreal.SystemLibrary.get_project_directory(), "%s.uproject" % unreal.SystemLibrary.get_game_name(), ), "MoviePipelineEntryMap?game=/project/.MoviePipelineGameMode", "-game", "-Multiprocess", "-NoLoadingScreen", "-FixedSeed", "-log", "-Unattended", "-messaging", "-SessionName=\"Publish2 Movie Render\"", "-nohmd", "-windowed", "-ResX=1280", "-ResY=720", # TODO: check what these settings are "-dpcvars=%s" % ",".join([ "sg.ViewDistanceQuality=4", "sg.AntiAliasingQuality=4", "sg.ShadowQuality=4", "sg.PostProcessQuality=4", "sg.TextureQuality=4", "sg.EffectsQuality=4", "sg.FoliageQuality=4", "sg.ShadingQuality=4", "r.TextureStreaming=0", "r.ForceLOD=0", "r.SkeletalMeshLODBias=-10", "r.ParticleLODBias=-10", "foliage.DitheredLOD=0", "foliage.ForceLOD=0", "r.Shadow.DistanceScale=10", "r.ShadowQuality=5", "r.Shadow.RadiusThreshold=0.001000", "r.ViewDistanceScale=50", "r.D3D12.GPUTimeout=0", "a.URO.Enable=0", ]), "-execcmds=r.HLOD 0", # This need to be a path relative the to the Unreal project "Saved" folder. "-MoviePipelineConfig=\"%s\"" % manifest_path, ] unreal.log( "Movie Queue command-line arguments: {}".format( " ".join(cmd_args) ) ) # Make a shallow copy of the current environment and clear some variables run_env = copy.copy(os.environ) # Prevent SG TK to try to bootstrap in the new process if "UE_SHOTGUN_BOOTSTRAP" in run_env: del run_env["UE_SHOTGUN_BOOTSTRAP"] if "UE_SHOTGRID_BOOTSTRAP" in run_env: del run_env["UE_SHOTGRID_BOOTSTRAP"] self.logger.info("Running %s" % cmd_args) subprocess.call(cmd_args, env=run_env) return os.path.isfile(output_path), output_path
import threading from http.server import BaseHTTPRequestHandler, HTTPServer import unreal import sys import socket import json import queue import importlib import os import time script_dir = os.path.dirname(__file__) tools_dir = os.path.dirname(script_dir) sys.path.append(tools_dir) # Shared queue between HTTP server and tick handler request_queue = queue.Queue() def import_function(func_path): """ Dynamically import a function from a module path string. used in a payload for the HTTP Handler POST :param func_path: Example func "unreal_tools.get_skeletons.get_all_assets_of_type" :return: """ module_path, func_name = func_path.rsplit(".", 1) module = importlib.import_module(module_path) return getattr(module, func_name) def tick(delta_time): while not request_queue.empty(): task = request_queue.get() try: func_path = task["function"] args = task.get("args", []) kwargs = task.get("kwargs", {}) module_path, func_name = func_path.rsplit(".", 1) module = __import__(module_path, fromlist=[func_name]) func = getattr(module, func_name) unreal.log(f"[Tick] Calling function: {func_path} with args={args}, kwargs={kwargs}") result = func(*args, **kwargs) # Store result to send back task["__result__"] = result except Exception as e: unreal.log_error(f"Function call failed: {e}") task["__result__"] = {"error": str(e)} finally: task["__handled__"] = True unreal.register_slate_post_tick_callback(tick) class RequestHandler(BaseHTTPRequestHandler): def log_message(self, format, *args): unreal.log(f"HTTP: {self.address_string()} - {format % args}") def do_POST(self): content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length) try: data = json.loads(post_data.decode('utf-8')) if "function" not in data: raise ValueError("Missing 'function' in request body") # Build task with placeholders for result task = { "function": data["function"], "args": data.get("args", []), "kwargs": data.get("kwargs", {}), "__result__": None, "__handled__": False } # Queue it request_queue.put(task) # Wait for Unreal tick to process it while not task["__handled__"]: time.sleep(0.05) # Send back result result = task["__result__"] self.send_response(200) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(json.dumps(result, indent=2, default=str).encode('utf-8')) except Exception as e: unreal.log_error(f"Error handling request: {e}") self.send_response(500) self.end_headers() self.wfile.write(json.dumps({"error": str(e)}).encode('utf-8')) def is_port_in_use(port): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: return s.connect_ex(('127.0.0.1', port)) == 0 def run_server(): port = 12347 if is_port_in_use(port): unreal.log_error(f"Port {port} already in use — HTTP server won't start.") return server_address = ('127.0.0.1', port) httpd = HTTPServer(server_address, RequestHandler) unreal.log(f"HTTP Server started on port {port}") httpd.serve_forever() def start_http_server_in_thread(): server_thread = threading.Thread(target=run_server, daemon=True) server_thread.start() if __name__ == "__main__": start_http_server_in_thread()
import unreal level_actors = unreal.EditorLevelLibrary.get_all_level_actors() actors = level_actors for actor in actors : label = actor.get_actor_label() tags = actor.get_editor_property('tags') if label == 'Ultra_Dynamic_Weather' : tags = []
#!/project/ python3 """ Python Execution Test for MCP Server This script tests executing Python code through the MCP Server. It connects to the server, sends a Python code snippet, and verifies the execution. """ import socket import json import sys def main(): """Connect to the MCP Server and execute Python code.""" try: # Create socket print("Connecting to MCP Server on localhost:13377...") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(5) # 5 second timeout # Connect to server s.connect(("localhost", 13377)) print("✓ Connected successfully") # Python code to execute code = """ import unreal # Get the current level level = unreal.EditorLevelLibrary.get_editor_world() level_name = level.get_name() # Get all actors in the level actors = unreal.EditorLevelLibrary.get_all_level_actors() actor_count = len(actors) # Log some information unreal.log(f"Current level: {level_name}") unreal.log(f"Actor count: {actor_count}") # Return a result return { "level_name": level_name, "actor_count": actor_count } """ # Create command command = { "type": "execute_python", "code": code } # Send command print("Sending execute_python command...") command_str = json.dumps(command) + "\n" # Add newline s.sendall(command_str.encode('utf-8')) # Receive response print("Waiting for response...") response = b"" while True: data = s.recv(4096) if not data: break response += data if b"\n" in data: # Check for newline which indicates end of response break # Close connection s.close() print("✓ Connection closed properly") # Process response if response: response_str = response.decode('utf-8').strip() try: response_json = json.loads(response_str) print("\n=== RESPONSE ===") print(f"Status: {response_json.get('status', 'unknown')}") if response_json.get('status') == 'success': print("✓ Python execution successful") result = response_json.get('result', {}) if isinstance(result, dict) and 'output' in result: print(f"Output: {result['output']}") return True else: print("✗ Python execution failed") print(f"Error: {response_json.get('message', 'Unknown error')}") return False except json.JSONDecodeError as e: print(f"✗ Error parsing JSON response: {e}") print(f"Raw response: {response_str}") return False else: print("✗ No response received from server") return False except ConnectionRefusedError: print("✗ Connection refused. Is the MCP Server running?") return False except socket.timeout: print("✗ Connection timed out. Is the MCP Server running?") return False except Exception as e: print(f"✗ Error: {e}") return False if __name__ == "__main__": print("=== MCP Server Python Execution Test ===") success = main() print("\n=== TEST RESULT ===") if success: print("✓ Python execution test PASSED") sys.exit(0) else: print("✗ Python execution test FAILED") sys.exit(1)
import unreal def create_material_instance(parent_material:unreal.Material, path:str, material_type:str)->unreal.MaterialInstanceConstant: asset_library:unreal.EditorAssetLibrary = unreal.EditorAssetLibrary() if asset_library.do_assets_exist([path]): return asset_library.load_asset(path) else: material_factory = unreal.MaterialInstanceConstantFactoryNew() material_instance = unreal.AssetToolsHelpers.get_asset_tools().create_asset(asset_name=path[path.rfind("/") + 1:],package_path=path[0:path.rfind("/")],asset_class=unreal.MaterialInstanceConstant,factory=material_factory) if material_instance: material_instance.set_editor_property("parent", parent_material) if material_type == "masked" or material_type == "translucency": overrides:unreal.MaterialInstanceBasePropertyOverrides = unreal.MaterialInstanceBasePropertyOverrides() overrides.set_editor_property("override_blend_mode", True) if material_type == "masked": overrides.set_editor_property("blend_mode", unreal.BlendMode.BLEND_MASKED) if material_type == "translucency": overrides.set_editor_property("blend_mode", unreal.BlendMode.BLEND_TRANSLUCENT) material_instance.set_editor_property("base_property_overrides", overrides) unreal.EditorAssetLibrary.save_asset(path) return material_instance def get_material_instance(path:str, bco_path:str, es_path:str, mra_path:str, n_path:str, udmi:bool, material_type:str)->unreal.MaterialInstanceConstant: material = create_material(path[0:path.rfind("/")] + "/M_Base", bco_path, es_path, mra_path, n_path, udmi, "", False) return create_material_instance(material, path, material_type)
# -*- coding: utf-8 -*- import time import unreal from Utilities.Utils import Singleton import random import os class ChameleonSketch(metaclass=Singleton): def __init__(self, jsonPath): self.jsonPath = jsonPath self.data = unreal.PythonBPLib.get_chameleon_data(self.jsonPath) self.ui_names = ["SMultiLineEditableTextBox", "SMultiLineEditableTextBox_2"] self.debug_index = 1 self.ui_python_not_ready = "IsPythonReadyImg" self.ui_python_is_ready = "IsPythonReadyImgB" self.ui_is_python_ready_text = "IsPythonReadyText" print ("ChameleonSketch.Init") def mark_python_ready(self): print("set_python_ready call") self.data.set_visibility(self.ui_python_not_ready, "Collapsed") self.data.set_visibility(self.ui_python_is_ready, "Visible") self.data.set_text(self.ui_is_python_ready_text, "Python Path Ready.") def get_texts(self): for name in self.ui_names: n = self.data.get_text(name) print(f"name: {n}") def set_texts(self): for name in self.ui_names: self.data.set_text(name, ["AAA", "BBB", "CCC", "DDD", "EEE", "FFF"][random.randint(0, 5)]) def set_text_one(self): self.data.set_text(self.ui_names[self.debug_index], ["AAA", "BBB", "CCC", "DDD", "EEE", "FFF"][random.randint(0, 5)] ) def get_text_one(self): print(f"name: {self.data.get_text(self.ui_names[self.debug_index])}") def tree(self): print(time.time()) names = [] parent_indices = [] name_to_index = dict() for root, folders, files in os.walk(r"/project/"): root_name = os.path.basename(root) if root not in name_to_index: name_to_index[root] = len(names) parent_indices.append(-1 if not names else name_to_index[os.path.dirname(root)]) names.append(root_name) parent_id = name_to_index[root] for items in [folders, files]: for item in items: names.append(item) parent_indices.append(parent_id) print(len(names)) self.data.set_tree_view_items("TreeViewA", names, parent_indices) print(time.time())
import unreal class SceneCapture2DActor: def __init__(self,): pass def add_sceneCapture2DActor(self,name, location, rotation): capture_actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.SceneCapture2D, location, rotation) capture_actor.set_actor_label(name + "_Capture") capture_component = capture_actor.get_component_by_class(unreal.SceneCaptureComponent2D) render_target = unreal.AssetToolsHelpers.get_asset_tools().create_asset( asset_name=name + "_RenderTarget", package_path="/Game", asset_class=unreal.TextureRenderTarget2D, factory=unreal.TextureRenderTargetFactoryNew() ) render_target.render_target_format = unreal.TextureRenderTargetFormat.RTF_RGBA8 render_target.set_editor_property("render_target_format", unreal.TextureRenderTargetFormat.RTF_RGBA8) render_target.set_editor_property("size_x", 1024) render_target.set_editor_property("size_y", 1024) render_target.post_edit_change() unreal.log("Created RenderTarget: {}".format(render_target.get_name())) # Assign the Render Target to the capture component capture_component.texture_target = render_target capture_component.capture_source = unreal.SceneCaptureSource.SCS_FINAL_COLOR_LDR capture_component.set_editor_property("bCaptureEveryFrame", False) return capture_actor def find_sceneCapture2DActor(self,name): actors = unreal.EditorLevelLibrary.get_all_level_actors() for actor in actors: if actor.get_actor_label() == name + "_Capture": return actor return None def find_all_sceneCapture2DActor(self): actors = unreal.EditorLevelLibrary.get_all_level_actors() result=[] for actor in actors: if 'Capture' in actor.get_actor_label(): result.append(actor) return result def clear_all_render_targets(self): folder_path='/Game' assets=unreal.EditorAssetLibrary.list_assets(folder_path) for asset in assets: if 'RenderTarget' in asset: unreal.EditorAssetLibrary.delete_asset(asset) unreal.log(f"Deleted {asset}") # test=SceneCapture2DActor() # test.add_sceneCapture2DActor("test",(0,0,300),(-90,0,0)) # print(test.find_sceneCapture2DActor("test")) # test.clear_all_render_targets()
import unreal factory = unreal.BlendSpaceFactory1D() # target_skeleton = unreal.EditorAssetLibrary.load_asset('/project/') # factory.set_editor_property('target_skeleton', target_skeleton) # factory.set_editor_property asset_tools = unreal.AssetToolsHelpers.get_asset_tools() asset_tools.create_asset( 'tt', '/project/', unreal.BlendSpace1D(), unreal.BlendSpaceFactory1D(), 'None' )
import unreal selected_assets = unreal.EditorUtilityLibrary.get_selected_assets() asset_tools = unreal.AssetToolsHelpers.get_asset_tools() loaded_subsystem = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem) counter = 0 deleted_assets = "" for asset in selected_assets: path_name = asset.get_path_name().split('.')[0] list = loaded_subsystem.find_package_referencers_for_asset(path_name) hasNoReference = len(list) == 0 if hasNoReference: if(unreal.EditorAssetLibrary.delete_loaded_asset(asset)): deleted_assets += path_name + '\n' counter += 1 else: print('failed to delete: ', path_name) print('Deleted asset list: \n', deleted_assets) print('Deleted ', counter, ' unused assets')
import unreal _seek_comp_name : str = 'CapsuleComponent' selected = unreal.EditorUtilityLibrary.get_selected_assets()[0] name_selected = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(selected) name_bp_c = name_selected + '_C' loaded_bp = unreal.EditorAssetLibrary.load_blueprint_class(name_bp_c)
# Copyright (c) <2021> Side Effects Software Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. The name of Side Effects Software may not be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN # NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unreal """ Example for getting the API instance and starting/creating the Houdini Engine Session. """ def run(): # Get the API singleton api = unreal.HoudiniPublicAPIBlueprintLib.get_api() # Check if there is an existing valid session if not api.is_session_valid(): # Create a new session api.create_session() if __name__ == '__main__': run()
#레벨에 있는 머트리얼 인스턴스 긁어서 source_path에 있는 같은 이름의 MI로 대체해주기 import unreal selected_assets = unreal.EditorLevelLibrary.get_selected_level_actors() source_path = '/project/' #리플레이스 머트리얼 def replace_material_instance(actor, material_instance, source_path): material_instance_name = material_instance.get_name() new_material_instance_path = source_path + material_instance_name + '.' + material_instance_name new_material_instance = unreal.EditorAssetLibrary.load_asset(new_material_instance_path) if not new_material_instance: unreal.log_error(f"Failed to load material instance: {new_material_instance_path}") return if isinstance(actor, unreal.StaticMeshActor): get_smComp = actor.static_mesh_component for index, mat in enumerate(get_smComp.get_materials()): if mat == material_instance: get_smComp.set_material(index, new_material_instance) unreal.log(f"Replaced material instance {material_instance_name} in StaticMeshActor {actor.get_name()}") elif isinstance(actor.get_class(), unreal.BlueprintGeneratedClass): actor_components = actor.get_components_by_class(unreal.ActorComponent) for comp in actor_components: if isinstance(comp, unreal.StaticMeshComponent): for index, mat in enumerate(comp.get_materials()): if mat == material_instance: comp.set_material(index, new_material_instance) unreal.log(f"Replaced material instance {material_instance_name} in Blueprint {actor.get_name()}") for actor in selected_assets: #SM Actor 대응 if isinstance(actor, unreal.StaticMeshActor): get_smComp = actor.static_mesh_component for get_mi in get_smComp.get_materials(): if get_mi is not None: replace_material_instance(actor, get_mi, source_path) #BP 대응 elif isinstance(actor.get_class(), unreal.BlueprintGeneratedClass): actor_components = actor.get_components_by_class(unreal.ActorComponent) for comp in actor_components: if isinstance(comp, unreal.StaticMeshComponent): for get_mi in comp.get_materials(): if get_mi is not None: replace_material_instance(actor, get_mi, source_path)
# coding: utf-8 from asyncio.windows_events import NULL import unreal import argparse parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") parser.add_argument("-meta") args = parser.parse_args() print(args.vrm) reg = unreal.AssetRegistryHelpers.get_asset_registry(); ## rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r #rig = rigs[10] hierarchy = unreal.ControlRigBlueprintLibrary.get_hierarchy(rig) h_con = hierarchy.get_controller() r_con = rig.get_controller() graph = r_con.get_graph() node = graph.get_nodes() for e in hierarchy.get_controls(True): h_con.remove_element(e) for e in hierarchy.get_nulls(True): h_con.remove_element(e) boneCount = 0 for e in hierarchy.get_bones(): p = hierarchy.get_first_parent(e) print('===') print(e) print(p) t = unreal.Transform() s = unreal.RigControlSettings() s.shape_visible = False v = unreal.RigControlValue() shape_t = unreal.Transform(location=[0.0, 0.0, 0.0], rotation=[0.0, 0.0, 0.0], scale=[0.001, 0.001, 0.001]) if (boneCount == 0): n = h_con.add_null("{}_s".format(e.name), unreal.RigElementKey(), t) c = h_con.add_control(e.name, n, s, v) t = hierarchy.get_global_transform(n) hierarchy.set_global_transform(c, t, True) hierarchy.set_control_shape_transform(c, shape_t, True) else: p.type = unreal.RigElementType.CONTROL n = h_con.add_null("{}_s".format(e.name), p, t) c = h_con.add_control(e.name, n, s, v) t = hierarchy.get_global_transform(n) hierarchy.set_global_transform(c, t, True) hierarchy.set_control_shape_transform(c, shape_t, True) if ("{}".format(e.name) == "head"): parent = c n = h_con.add_null("eye_l_s", parent, t) c = h_con.add_control("eye_l", n, s, v) t = hierarchy.get_global_transform(n) hierarchy.set_global_transform(c, t, True) hierarchy.set_control_shape_transform(c, shape_t, True) n = h_con.add_null("eye_r_s", parent, t) c = h_con.add_control("eye_r", n, s, v) t = hierarchy.get_global_transform(n) hierarchy.set_global_transform(c, t, True) hierarchy.set_control_shape_transform(c, shape_t, True) boneCount += 1
# -*- coding: utf-8 -*- import unreal def bake_binding_transform_to_duplicate(level_sequence, source_binding_id_struct, clear_keys_on_duplicate=True): """ 지정된 레벨 시퀀스에서 source_binding_id_struct에 해당하는 바인딩의 평가된(evaluated) 트랜스폼을 복제된 스포너블 바인딩에 베이크합니다. 원본 바인딩은 동적으로 움직이는 스포너블 액터라고 가정합니다. Args: level_sequence (unreal.LevelSequence): 베이크할 대상 레벨 시퀀스 에셋. source_binding_id_struct (unreal.MovieSceneObjectBindingID): 원본 스포너블 바인딩의 ID 구조체. clear_keys_on_duplicate (bool): True이면 베이크 전 복제된 액터의 기존 트랜스폼 키를 삭제합니다. """ unreal.log("복제된 스포너블 바인딩으로 트랜스폼 베이크 시작...") # --- 입력 유효성 검사 --- if not level_sequence: unreal.log_error("베이크 실패: 레벨 시퀀스가 유효하지 않습니다.") return False # source_binding_id_struct 자체는 None이 아닐 것으로 가정 (호출부에서 확인) # GUID 유효성 검사 (선택적이지만 추가 가능) source_guid = source_binding_id_struct.guid if source_guid == unreal.Guid(): unreal.log_error("베이크 실패: 소스 바인딩 ID의 GUID가 유효하지 않습니다.") return False # --- 원본 바인딩 찾기 --- (GUID 사용) try: source_binding = level_sequence.find_binding_by_id(source_guid) if not source_binding: # 로그 출력 시 GUID를 문자열로 변환하는 것이 안전할 수 있음 unreal.log_error(f"베이크 실패: ID '{str(source_guid)}'에 해당하는 바인딩을 찾을 수 없습니다.") return False unreal.log(f"소스 바인딩 찾음: {source_binding.get_name()}") # 원본이 스포너블인지 확인 (선택적이지만 권장) if not source_binding.get_spawnable(): unreal.log_warning(f"소스 바인딩 '{source_binding.get_name()}'은(는) 스포너블이 아닐 수 있습니다. 계속 진행합니다.") except Exception as e: unreal.log_error(f"베이크 실패 (소스 바인딩 검색 중): {e}") return False # --- 스포너블 복제 (새로운 스포너블 추가 방식) --- duplicate_binding = None # 나중에 정리하기 위해 변수 선언 try: unreal.log(f"다음을 기반으로 새 스포너블 생성 중: {source_binding.get_name()}") object_template = source_binding.get_object_template() # 원본 스포너블의 템플릿 가져오기 if not object_template: unreal.log_error("베이크 실패: 소스 스포너블 바인딩에서 오브젝트 템플릿을 가져올 수 없습니다.") return False # 템플릿을 사용하여 새로운 스포너블 바인딩 추가 duplicate_binding = level_sequence.add_spawnable_from_instance(object_template) if not duplicate_binding: unreal.log_error("베이크 실패: 시퀀스에 새 스포너블 바인딩을 추가할 수 없습니다.") return False # 복제된 스포너블 이름 설정 (옵션) # 기본 이름은 클래스 이름으로 생성됨. 필요시 수정. # duplicate_binding.set_name(f"{source_binding.get_name()}_Baked") # 이름 직접 설정 API 가 없을 수 있음 # 스포너블 자체의 이름 변경은 다른 방식 필요할 수 있음 (예: 내부 오브젝트 접근) unreal.log(f"새 스포너블 바인딩 추가됨: {duplicate_binding.get_name()}") except Exception as e: unreal.log_error(f"베이크 실패 (스포너블 복제 중): {e}") return False # --- 시간 및 프레임 정보 가져오기 --- frame_rate = level_sequence.get_display_rate() start_frame = level_sequence.get_playback_start_frame() end_frame = level_sequence.get_playback_end_frame() unreal.log(f"시퀀스 정보: {start_frame}-{end_frame} 프레임 @ {frame_rate.numerator}/{frame_rate.denominator} fps") # --- 복제된 스포너블의 트랜스폼 트랙 찾기 또는 추가 --- transform_track = None channels = [] try: transform_track = duplicate_binding.find_track_by_type(unreal.MovieSceneTransformTrack) if not transform_track: unreal.log("복제된 스포너블에서 트랜스폼 트랙을 찾을 수 없어 새로 추가합니다.") transform_track = duplicate_binding.add_track(unreal.MovieSceneTransformTrack) if not transform_track: unreal.log_error("베이크 실패: 복제된 스포너블 바인딩에서 트랜스폼 트랙을 찾거나 추가할 수 없습니다.") # 실패 시 복제된 스포너블 정리 필요 level_sequence.remove_spawnable(duplicate_binding) return False channels = transform_track.get_channels() if len(channels) != 9: unreal.log_warning(f"복제된 스포너블에 대해 9개의 트랜스폼 채널이 예상되었으나 {len(channels)}개를 찾았습니다. 키프레임이 잘못될 수 있습니다.") except Exception as e: unreal.log_error(f"베이크 실패 (복제된 스포너블 트랙/채널 설정 중): {e}") if duplicate_binding: level_sequence.remove_spawnable(duplicate_binding) return False # --- 기존 키 삭제 (옵션 - 복제된 스포너블 대상) --- if clear_keys_on_duplicate: unreal.log("복제된 스포너블 트랙의 기존 트랜스폼 키 삭제 중...") try: for channel in channels: channel.reset_to_default() unreal.log("복제된 스포너블의 기존 키 삭제 완료.") except Exception as e: unreal.log_error(f"복제된 스포너블의 키 삭제 중 오류 발생: {e}") # --- 프레임별 베이크 루프 --- bake_success_count = 0 bake_fail_count = 0 unreal.log(f"{end_frame - start_frame + 1} 프레임에 대한 베이크 루프 시작...") with unreal.ScopedEditorTransaction("복제된 스포너블로 트랜스폼 베이크 스크립트") as trans: for frame_num in range(start_frame, end_frame + 1): try: current_frame_time = unreal.FrameTime(frame_number=frame_num) # 1. *원본* 바인딩의 트랜스폼 평가 (source_binding_id_struct 사용) source_transform = unreal.MovieSceneSequenceExtensions.evaluate_binding_transform( level_sequence, source_binding_id_struct, current_frame_time ) # 2. 평가된 트랜스폼을 복제된 스포너블의 트랙에 키프레임으로 추가 loc = source_transform.location rot = source_transform.rotation.rotator() scale = source_transform.scale3d key_values_corrected = [ loc.x, loc.y, loc.z, rot.x, rot.y, rot.z, # Roll, Pitch, Yaw scale.x, scale.y, scale.z ] if len(channels) == 9: for i in range(9): channels[i].add_key(time=current_frame_time, new_value=key_values_corrected[i]) else: if frame_num == start_frame: unreal.log_warning("예상치 못한 채널 수로 인해 복제된 스포너블에 키를 추가할 수 없습니다.") if frame_num % 10 == 0 or frame_num == end_frame: unreal.log(f" 프레임 처리됨: {frame_num}") bake_success_count += 1 except Exception as e: unreal.log_error(f"프레임 {frame_num} 베이크 실패: {e}") bake_fail_count += 1 # --- 최종 결과 로그 및 저장 --- unreal.log(f"베이크 처리 완료. 성공: {bake_success_count}, 실패: {bake_fail_count}") if bake_success_count > 0: try: unreal.EditorAssetLibrary.save_loaded_asset(level_sequence) unreal.log(f"레벨 시퀀스 '{level_sequence.get_path_name()}' 저장 완료.") return True except Exception as e: unreal.log_error(f"레벨 시퀀스 저장 실패: {e}") return False else: unreal.log("성공적으로 베이크된 프레임이 없습니다.") # 실패 시 복제된 스포너블 삭제 if duplicate_binding: unreal.log("베이크 실패로 인해 스포너블 복제 롤백 중.") # 트랜잭션 밖에서 실행해야 할 수 있음. Scoped Transaction 끝나고 실행. # level_sequence.remove_spawnable(duplicate_binding) # 여기서하면 트랜잭션 문제 발생 가능 # 임시 해결책: 그냥 두거나, 별도 함수로 빼서 처리 unreal.log_warning("베이크 실패: 복제된 스포너블이 자동으로 제거되지 않았습니다. 필요시 수동으로 제거해주세요.") return False # --- 스크립트 직접 실행 테스트용 (옵션) --- if __name__ == "__main__": unreal.log("포커스된 시퀀스와 선택된 바인딩을 사용하여 bake_binding_transform_to_duplicate 함수 테스트 중...") # 현재 포커스된 레벨 시퀀스 가져오기 test_sequence = unreal.LevelSequenceEditorBlueprintLibrary.get_focused_level_sequence() if not test_sequence: unreal.log_warning("현재 에디터에 포커스된 레벨 시퀀스가 없습니다. 시퀀스 또는 서브시퀀스를 열고 포커스해주세요.") else: unreal.log(f"포커스된 시퀀스 사용: {test_sequence.get_path_name()}") # 시퀀서에서 현재 선택된 바인딩 가져오기 selected_binding_proxies = unreal.LevelSequenceEditorBlueprintLibrary.get_selected_bindings() if not selected_binding_proxies: unreal.log_warning("시퀀서에서 선택된 바인딩이 없습니다. 포커스된 시퀀스에서 소스 스포너블 바인딩을 선택해주세요.") else: selected_binding_proxy = selected_binding_proxies[0] # Guid 가져오기 selected_guid = selected_binding_proxy.binding_id # 선택된 바인딩 ID 유효성 검사 (Guid 비교) if selected_guid == unreal.Guid(): unreal.log_warning("선택된 바인딩의 GUID가 유효하지 않습니다.") else: # MovieSceneObjectBindingID 구조체 생성 # Guid만으로는 부족하고, Sequence 정보도 필요할 수 있음. resolve_binding_id 사용 시도. # Alternatively, construct directly if possible. try: # Method 1: Resolve Binding ID (Potentially better if it exists and works) # resolved_binding_id = unreal.LevelSequenceEditorBlueprintLibrary.resolve_binding_id(test_sequence, selected_guid) # if not resolved_binding_id or not resolved_binding_id.is_valid(): ... # Method 2: Construct MovieSceneObjectBindingID directly (Requires knowing the structure) # This might require sequence information for context. Let's assume it's implicit for now or try simple construction. # A simple Guid might not be enough context for some operations like evaluate_binding_transform. # Let's try finding the binding first, then getting its struct ID. source_binding = test_sequence.find_binding_by_id(selected_guid) if not source_binding: unreal.log_error(f"선택된 GUID '{str(selected_guid)}'에 해당하는 바인딩을 포커스된 시퀀스에서 찾을 수 없습니다.") else: # 바인딩을 찾았으면, 그 바인딩으로부터 완전한 MovieSceneObjectBindingID 구조체를 가져옴 # This mirrors the pattern in change_constraint_id_multi.py source_binding_id_struct = unreal.MovieSceneSequenceExtensions.get_binding_id(level_sequence=test_sequence, binding=source_binding) if not source_binding_id_struct: unreal.log_error(f"바인딩 '{source_binding.get_name()}'에서 MovieSceneObjectBindingID 구조체를 가져올 수 없습니다.") else: unreal.log(f"선택된 바인딩 사용: {source_binding.get_name()} (GUID: {str(selected_guid)})") # 베이크 함수 호출 (구조체 전달) test_clear_keys = True bake_binding_transform_to_duplicate(test_sequence, source_binding_id_struct, test_clear_keys) except Exception as e: unreal.log_error(f"MovieSceneObjectBindingID 처리 중 오류 발생: {e}")
# _ # (_) # _ __ ___ __ _ _ __ ___ ___ _ __ _ ___ _ __ ___ # | '_ ` _ \ / _` | '_ ` _ \ / _ \| '_ \| |/ _ \ '_ ` _ \ # | | | | | | (_| | | | | | | (_) | | | | | __/ | | | | | # |_| |_| |_|\__,_|_| |_| |_|\___/|_| |_|_|\___|_| |_| |_| # www.mamoniem.com # www.ue4u.xyz #Copyright 2022 Muhammad A.Moniem (@_mamoniem). All Rights Reserved. # import unreal @unreal.uclass() class MyEditorLevelUtility(unreal.EditorLevelUtils): pass streamingLvl = MyEditorLevelUtility().create_new_streaming_level(unreal.LevelStreamingDynamic, "/project/", False)
import sys import csv import os def ImportUnreal(): try: import unreal except ImportError: print('NB. The file must be run in Unreal Engine using "Python Editor Script Plugin".') sys.exit() def GetAbsolutePath(): filePath = os.path.realpath(__file__) fileDirectory = "\\".join(filePath.split("\\")[:-1]) + "\\" fileName = filePath.split("\\")[-1] for file in os.listdir(fileDirectory): if file != fileName: collisionFileName = file if file.split(".")[-1] != "csv": print('NB. Put the CSV collision file in the same directory as this script.') sys.exit() try: absolutePath = fileDirectory + collisionFileName except: print('NB. Put the CSV collision file in the same directory as this script.') sys.exit() return absolutePath def GetCSV(csvPath): file = open(csvPath, "r") csvReader = csv.reader(file) csvList = list(csvReader) file.close() return csvList def LoadAssets(assetPath): # Based on: # https://docs.unrealengine.com/en-us/project/-and-Automating-the-Editor/Editor-Scripting-How-Tos/Setting-up-Collision-Properties-in-Blueprints-and-Python try: # Get a list of all Assets in the path listOfAssets = unreal.EditorAssetLibrary.list_assets(assetPath) # Load them into memory assets = [unreal.EditorAssetLibrary.load_asset(eachAsset) for eachAsset in listOfAssets] except: print('Loading assets failed.\nMake sure the assets are located in the folder "Revit".') return assets def FilterAssets(csvList,assets): filteredAssets = [] for idName in csvList: # Compare Revit assets with imported Unreal Assets # Maybe add funcitons for the last letters in the Swedish language idName = idName[0] idName = idName.replace(" ","_") idName = idName.replace(".","_") temporaryFinding = unreal.EditorFilterLibrary.by_id_name(assets, idName) if len(temporaryFinding) != 0: filteredAssets.append(temporaryFinding) return filteredAssets def AddBoxCollision(staticMesh): # N.B. You could instead use: # .SPHERE, .CAPSULE, N.DOP10_X, .NDOP10_Y, .NDOP10_Z, .NDOP18, .NDOP26 shapeType = unreal.ScriptingCollisionShapeType.BOX unreal.EditorStaticMeshLibrary.add_simple_collisions(staticMesh, shapeType) unreal.EditorAssetLibrary.save_loaded_asset(staticMesh) def main(): ImportUnreal() ### SET PATHS ### ### Unreal Assets Path # N.B. The "Content" folder should be replaced with "Game". # Look at the info box when importing Datasmith Model. # Defualt: asset_path = "/project/" assetPath = "/project/" ### CSV Path # Absolute Path csvAbsPath = "" # Depricated # Relative Path csvRelPath = "" # Depricated csvAbsPath = GetAbsolutePath() ### GET DATA ### # Get refrence items. Choose absolute or relative path as parameter csvList = GetCSV(csvAbsPath) # Get all items assets = LoadAssets(assetPath) ### FILTER DATA ### filteredAssets = FilterAssets(csvList,assets) ### ADD COLLISION ### for eachAsset in filteredAssets: map(AddBoxCollision, eachAsset) if __name__ == '__main__': main()
import unreal import os def get_dependencies_hard(asset_data): """ get the dependencies hard from the asset data, deep is one """ dependencies_hard = None if isinstance(asset_data, unreal.AssetData): asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() include_hard_management_references = True include_hard_package_references = True include_searchable_names = False include_soft_management_references = False include_soft_package_references = False asset_registry_option = unreal.AssetRegistryDependencyOptions(include_hard_management_references, include_hard_package_references, include_searchable_names, include_soft_management_references, include_soft_package_references) dependencies_hard = asset_registry.get_dependencies(asset_data.package_name, asset_registry_option) # # unreal.log("================dependencies_hard===============") # for item in dependencies_hard: # unreal.log(item) return dependencies_hard def fbx_import_options(): """ import fbx default options """ _options = unreal.FbxImportUI() _options.import_mesh = True _options.import_textures = False _options.import_materials = False _options.import_as_skeletal = False _options.static_mesh_import_data.combine_meshes = True _options.static_mesh_import_data.generate_lightmap_uvs = True _options.static_mesh_import_data.auto_generate_collision = True return _options def fbx_export_option(): """ export fbx default options """ _options = unreal.FbxExportOption() _options.ascii = False _options.collision = False _options.export_local_time = True _options.export_morph_targets = True _options.export_preview_mesh = True _options.fbx_export_compatibility = unreal.FbxExportCompatibility.FBX_2018 _options.force_front_x_axis = False _options.level_of_detail = False _options.map_skeletal_motion_to_root = False _options.vertex_color = True return _options def create_export_task(exporter, obj, options, name): """ create export task and set property """ _task = unreal.AssetExportTask() _task.exporter = exporter _task.object = obj _task.options = options _task.automated = True _task.replace_identical = True _task.write_empty_files = False _task.filename = name return _task def generate_task_from_asset(asset, name): """ auto generate task by the asset type. only support static mesh and 2d texture """ filename = unreal.Paths.project_saved_dir() + 'export/' + name + '/' + asset.get_name() + '.fbx' ex = None _task = None if isinstance(asset, unreal.StaticMesh): ex = unreal.StaticMeshExporterFBX() _task = create_export_task(ex, asset, fbx_export_option(), filename) elif isinstance(asset, unreal.SkeletalMesh): ex = unreal.SkeletalMeshExporterFBX() _task = create_export_task(ex, asset, fbx_export_option(), filename) elif isinstance(asset, unreal.Texture2D): ex = unreal.TextureExporterTGA() filename = unreal.Paths.project_saved_dir() + 'export/' + name + '/' + asset.get_name() + '.tga' _task = create_export_task(ex, asset, None, filename) return _task # AssetToolsHelpers High Level Method ( The dialog windows can not avoid appeared) # export = unreal.AssetToolsHelpers.get_asset_tools().export_assets_with_dialog([asset_sld[0].get_path_name()], False) # export = unreal.AssetToolsHelpers.get_asset_tools().export_assets([asset_sld[0].get_path_name()], filename) unreal.log("==============Export Begin===============") # ======================================================================== # assets = unreal.EditorUtilityLibrary.get_selected_asset_data() # get the textures refer to the static mesh export_asset = [] file_name = "default_object" for asset_data in assets: # only export mesh ? if isinstance(asset_data.get_asset(), unreal.StaticMesh) or isinstance(asset_data.get_asset(), unreal.SkeletalMesh): file_name = asset_data.get_asset().get_name() unreal.log("export asset : %s" % file_name) export_asset.append(asset_data.get_asset()) dependencies = get_dependencies_hard(asset_data) for depend in dependencies: # get the materials if not str(depend).startswith("/Game"): continue depend_asset = unreal.load_asset(depend) depend_asset_data = unreal.EditorAssetLibrary.find_asset_data(depend) # get the Textures if isinstance(depend_asset, unreal.MaterialInstanceConstant): textures = get_dependencies_hard(depend_asset_data) for tex in textures: if not str(tex).startswith("/Game"): continue tex_asset = unreal.load_asset(tex) if isinstance(tex_asset, unreal.Texture2D): unreal.log("export asset : %s" % tex_asset.get_name()) export_asset.append(tex_asset) unreal.log("Export Asset Number: %d"%(len(export_asset))) file_name = 'default_name' export_tasks_sm = [] export_tasks_tx = [] # generate the export tasks for t in export_asset: if isinstance(t, unreal.StaticMesh) or isinstance(t, unreal.SkeletalMesh): file_name = t.get_name() export_tasks_sm.append(generate_task_from_asset(t, file_name)) else: export_tasks_tx.append(generate_task_from_asset(t, file_name)) # export texture first, because it will fail if export fbx when the folder do not exist export_tasks = export_tasks_tx + export_tasks_sm for task in export_tasks: unreal.log(task.object.get_name()) # begin export tasks, and make a progress dialog progress = len(export_tasks) current_progress = 1.0 with unreal.ScopedSlowTask(progress, 'Export Meshes and Textures') as export_task_progress: export_task_progress.make_dialog(True) for task in export_tasks: if export_task_progress.should_cancel(): # cancel manual break if task: # run export task ! if unreal.Exporter.run_asset_export_task(task): export_task_progress.enter_progress_frame(1.0, "export : %s success" % (task.object.get_name())) else: export_task_progress.enter_progress_frame(1.0, "export : %s failure" % (task.object.get_name())) current_progress += 1.0 # auto open the folder when finished path = unreal.Paths.convert_relative_path_to_full(unreal.Paths.project_saved_dir()) + 'export/' os.startfile(path) unreal.log("export task finished : %s" % path) unreal.log(unreal.Paths.project_saved_dir()) unreal.log("==============Export End===============")
from pathlib import Path import unreal import pyblish.api from ayon_core.pipeline import get_current_project_name from ayon_core.pipeline import Anatomy from ayon_core.hosts.unreal.api import pipeline class CollectRenderInstances(pyblish.api.InstancePlugin): """ This collector will try to find all the rendered frames. """ order = pyblish.api.CollectorOrder hosts = ["unreal"] families = ["render"] label = "Collect Render Instances" def process(self, instance): self.log.debug("Preparing Rendering Instances") context = instance.context data = instance.data data['remove'] = True ar = unreal.AssetRegistryHelpers.get_asset_registry() sequence = ar.get_asset_by_object_path( data.get('sequence')).get_asset() sequences = [{ "sequence": sequence, "output": data.get('output'), "frame_range": ( data.get('frameStart'), data.get('frameEnd')) }] for s in sequences: self.log.debug(f"Processing: {s.get('sequence').get_name()}") subscenes = pipeline.get_subsequences(s.get('sequence')) if subscenes: for ss in subscenes: sequences.append({ "sequence": ss.get_sequence(), "output": (f"{s.get('output')}/" f"{ss.get_sequence().get_name()}"), "frame_range": ( ss.get_start_frame(), ss.get_end_frame() - 1) }) else: # Avoid creating instances for camera sequences if "_camera" not in s.get('sequence').get_name(): seq = s.get('sequence') seq_name = seq.get_name() product_type = "render" new_product_name = f"{data.get('productName')}_{seq_name}" new_instance = context.create_instance( new_product_name ) new_instance[:] = seq_name new_data = new_instance.data new_data["folderPath"] = f"/{s.get('output')}" new_data["setMembers"] = seq_name new_data["productName"] = new_product_name new_data["productType"] = product_type new_data["family"] = product_type new_data["families"] = [product_type, "review"] new_data["parent"] = data.get("parent") new_data["level"] = data.get("level") new_data["output"] = s.get('output') new_data["fps"] = seq.get_display_rate().numerator new_data["frameStart"] = int(s.get('frame_range')[0]) new_data["frameEnd"] = int(s.get('frame_range')[1]) new_data["sequence"] = seq.get_path_name() new_data["master_sequence"] = data["master_sequence"] new_data["master_level"] = data["master_level"] self.log.debug(f"new instance data: {new_data}") try: project = get_current_project_name() anatomy = Anatomy(project) root = anatomy.roots['renders'] except Exception as e: raise Exception(( "Could not find render root " "in anatomy settings.")) from e render_dir = f"{root}/{project}/{s.get('output')}" render_path = Path(render_dir) frames = [] for x in render_path.iterdir(): if x.is_file() and x.suffix == '.png': frames.append(str(x.name)) if "representations" not in new_instance.data: new_instance.data["representations"] = [] repr = { 'frameStart': instance.data["frameStart"], 'frameEnd': instance.data["frameEnd"], 'name': 'png', 'ext': 'png', 'files': frames, 'stagingDir': render_dir, 'tags': ['review'] } new_instance.data["representations"].append(repr)
import unreal import sys import tempfile def export_asset(asset_path: str) -> bytes: asset = unreal.EditorAssetLibrary.load_asset(asset_path) if not asset: raise ValueError(f"Asset not found at {asset_path}") export_task = unreal.AssetExportTask() export_task.automated = True export_task.prompt = False export_task.replace_identical = True export_task.exporter = None export_task.object = asset temp_file = tempfile.NamedTemporaryFile(delete=True, suffix=".uasset.copy") export_file_path = temp_file.name export_task.filename = export_file_path result = unreal.Exporter.run_asset_export_task(export_task) if not result: raise RuntimeError( f"Failed to export asset {asset.get_name()} to {export_file_path}" ) file = open(export_file_path, "rb") data = file.read() file.close() temp_file.close() return data def main(): data = export_asset("${asset_path}") sys.stdout.buffer.write(data) if __name__ == "__main__": main()
import unreal selected_assets: list[unreal.Object] = unreal.EditorUtilityLibrary.get_selected_assets() loaded_subsystem = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem) ## set sm materials sm_materials = [] selected_sm:unreal.SkeletalMesh = selected_assets[0] sm_mats_length = len(selected_sm.materials) for material in selected_sm.materials: mic:unreal.MaterialInstanceConstant = material.material_interface sm_materials.append(mic) # set data asset destination_path_array = selected_sm.get_path_name().split('/') new_da_path = '/'.join(destination_path_array[:-1]) + '/DA_' + selected_sm.get_name() does_da_exist = loaded_subsystem.does_asset_exist(new_da_path) if(does_da_exist == False): ## set data asset target_da_path = "/project/" ## duplicate and save loaded_subsystem.duplicate_asset(target_da_path, new_da_path) loaded_subsystem.save_asset(new_da_path) blueprint_asset = unreal.EditorAssetLibrary.load_asset(new_da_path) ### set materials to data asset property_info = {'Materials': sm_materials} blueprint_asset.set_editor_properties(property_info) loaded_subsystem.save_asset(new_da_path)
import unreal import importlib #Functions level_subsys = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem) actor_subsys = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) editor_subsys = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem) layers_subsys = unreal.get_editor_subsystem(unreal.LayersSubsystem) sys_lib = unreal.SystemLibrary SM_COMPONENT_CLASS = unreal.StaticMeshComponent.static_class() CURRENT_LEVEL = editor_subsys.get_editor_world() selected_actors = actor_subsys.get_selected_level_actors() all_level_actors = actor_subsys.get_all_level_actors() def get_materials(actor): """ Get the materials of a static mesh component. """ materials = [] if isinstance(actor, unreal.StaticMeshActor): static_mesh_component = actor.get_component_by_class(SM_COMPONENT_CLASS) if static_mesh_component: materials = static_mesh_component.get_materials() return materials def get_materials_data(actor): """获取StaticMesh完整的材质信息,matIndex,matSlotName,material,输出Dict Example: materials_data = get_materials_data(actor) for index in range(len(materials_data["index"])): slot_name = materials_data["slot_name"][index] material = materials_data["material"][index] """ materials_data = {"index": [], "slot_name": [], "material": []} if isinstance(actor, unreal.StaticMeshActor): static_mesh_component = actor.get_component_by_class(SM_COMPONENT_CLASS) mat_slot_names = unreal.StaticMeshComponent.get_material_slot_names(static_mesh_component) for slot_name in mat_slot_names: mat_index = unreal.StaticMeshComponent.get_material_index( static_mesh_component, slot_name ) material = unreal.StaticMeshComponent.get_material(static_mesh_component, mat_index) materials_data["index"].append(mat_index) materials_data["slot_name"].append(slot_name) materials_data["material"].append(material) return materials_data def set_sm_materials(static_mesh, materials_data): """ Set the materials of a static mesh asset. """ if isinstance(static_mesh, unreal.StaticMesh): print(f"replacing materials for {static_mesh.get_name()}") for index in range(len(materials_data["index"])): # slot_name = materials_data["slot_name"][index] material = materials_data["material"][index] unreal.StaticMesh.set_material(static_mesh, index, material) def apply_material_changes(actors): """ Replace the materials of static mesh components in the selected actors. """ print(f"selected actors: {actors}") for actor in actors: if isinstance(actor, unreal.StaticMeshActor): static_mesh_component = actor.get_component_by_class(SM_COMPONENT_CLASS) if static_mesh_component: # get materials materials_data=get_materials_data(actor) #find static mesh asset static_mesh_asset = static_mesh_component.get_editor_property("static_mesh") if static_mesh_asset: set_sm_materials(static_mesh_asset, materials_data) # apply_material_changes(selected_actors)
# This script shows how to setup dependencies between variants when using the Variant Manager Python API import unreal lvs = unreal.VariantManagerLibrary.create_level_variant_sets_asset("LVS", "/Game/") if lvs is None: print ("Failed to spawn either the LevelVariantSets asset or the LevelVariantSetsActor!") quit() var_set_colors = unreal.VariantSet() var_set_colors.set_display_text("Colors") var_set_letters = unreal.VariantSet() var_set_letters.set_display_text("Letters") var_set_fruits = unreal.VariantSet() var_set_fruits.set_display_text("Fruits") var_red = unreal.Variant() var_red.set_display_text("Red") var_green = unreal.Variant() var_green.set_display_text("Green") var_blue = unreal.Variant() var_blue.set_display_text("Blue") var_a = unreal.Variant() var_a.set_display_text("A") var_b = unreal.Variant() var_b.set_display_text("B") var_apple = unreal.Variant() var_apple.set_display_text("Apple") var_orange = unreal.Variant() var_orange.set_display_text("Orange") # Adds the objects to the correct parents lvs.add_variant_set(var_set_colors) lvs.add_variant_set(var_set_letters) lvs.add_variant_set(var_set_fruits) var_set_colors.add_variant(var_red) var_set_colors.add_variant(var_green) var_set_colors.add_variant(var_blue) var_set_letters.add_variant(var_a) var_set_letters.add_variant(var_b) var_set_fruits.add_variant(var_apple) var_set_fruits.add_variant(var_orange) # Let's make variant 'Red' also switch on variant 'A' before it is switched on dep1 = unreal.VariantDependency() dep1.set_editor_property('VariantSet', var_set_letters) dep1.set_editor_property('Variant', var_a) dep1_index = var_red.add_dependency(dep1) # Let's also make variant 'A' also switch on variant 'Orange' before it is switched on dep2 = unreal.VariantDependency() dep2.set_editor_property('VariantSet', var_set_fruits) dep2.set_editor_property('Variant', var_orange) var_a.add_dependency(dep2) # Because dependencies trigger first, this will switch on 'Orange', then 'A' and finally 'Red' var_red.switch_on() # Let's disable the first dependency # Note we need to set the struct back into the variant, as it's returned by value dep1.set_editor_property('bEnabled', False) var_red.set_dependency(dep1_index[0], dep1) # Now this will only trigger 'Red', because dep1 is disabled and doesn't propagate to variant 'A' var_red.switch_on ( )
# This script shows how to setup dependencies between variants when using the Variant Manager Python API import unreal lvs = unreal.VariantManagerLibrary.create_level_variant_sets_asset("LVS", "/Game/") if lvs is None: print ("Failed to spawn either the LevelVariantSets asset or the LevelVariantSetsActor!") quit() var_set_colors = unreal.VariantSet() var_set_colors.set_display_text("Colors") var_set_letters = unreal.VariantSet() var_set_letters.set_display_text("Letters") var_set_fruits = unreal.VariantSet() var_set_fruits.set_display_text("Fruits") var_red = unreal.Variant() var_red.set_display_text("Red") var_green = unreal.Variant() var_green.set_display_text("Green") var_blue = unreal.Variant() var_blue.set_display_text("Blue") var_a = unreal.Variant() var_a.set_display_text("A") var_b = unreal.Variant() var_b.set_display_text("B") var_apple = unreal.Variant() var_apple.set_display_text("Apple") var_orange = unreal.Variant() var_orange.set_display_text("Orange") # Adds the objects to the correct parents lvs.add_variant_set(var_set_colors) lvs.add_variant_set(var_set_letters) lvs.add_variant_set(var_set_fruits) var_set_colors.add_variant(var_red) var_set_colors.add_variant(var_green) var_set_colors.add_variant(var_blue) var_set_letters.add_variant(var_a) var_set_letters.add_variant(var_b) var_set_fruits.add_variant(var_apple) var_set_fruits.add_variant(var_orange) # Let's make variant 'Red' also switch on variant 'A' before it is switched on dep1 = unreal.VariantDependency() dep1.set_editor_property('VariantSet', var_set_letters) dep1.set_editor_property('Variant', var_a) dep1_index = var_red.add_dependency(dep1) # Let's also make variant 'A' also switch on variant 'Orange' before it is switched on dep2 = unreal.VariantDependency() dep2.set_editor_property('VariantSet', var_set_fruits) dep2.set_editor_property('Variant', var_orange) var_a.add_dependency(dep2) # Because dependencies trigger first, this will switch on 'Orange', then 'A' and finally 'Red' var_red.switch_on() # Let's disable the first dependency # Note we need to set the struct back into the variant, as it's returned by value dep1.set_editor_property('bEnabled', False) var_red.set_dependency(dep1_index[0], dep1) # Now this will only trigger 'Red', because dep1 is disabled and doesn't propagate to variant 'A' var_red.switch_on ( )
# Copyright (c) <2021> Side Effects Software Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. The name of Side Effects Software may not be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN # NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ An example script that uses the API and HoudiniEngineV2.asyncprocessor.ProcessHDA. ProcessHDA is configured with the asset to instantiate, as well as 2 inputs: a geometry input (a cube) and a curve input (a helix). ProcessHDA is then activiated upon which the asset will be instantiated, inputs set, and cooked. The ProcessHDA class's on_post_processing() function is overridden to fetch the input structure and logged. The other state/phase functions (on_pre_instantiate(), on_post_instantiate() etc) are overridden to simply log the function name, in order to observe progress in the log. """ import math import unreal from HoudiniEngineV2.asyncprocessor import ProcessHDA _g_processor = None class ProcessHDAExample(ProcessHDA): @staticmethod def _print_api_input(in_input): print('\t\tInput type: {0}'.format(in_input.__class__)) print('\t\tbKeepWorldTransform: {0}'.format(in_input.keep_world_transform)) print('\t\tbImportAsReference: {0}'.format(in_input.import_as_reference)) if isinstance(in_input, unreal.HoudiniPublicAPIGeoInput): print('\t\tbPackBeforeMerge: {0}'.format(in_input.pack_before_merge)) print('\t\tbExportLODs: {0}'.format(in_input.export_lo_ds)) print('\t\tbExportSockets: {0}'.format(in_input.export_sockets)) print('\t\tbExportColliders: {0}'.format(in_input.export_colliders)) elif isinstance(in_input, unreal.HoudiniPublicAPICurveInput): print('\t\tbCookOnCurveChanged: {0}'.format(in_input.cook_on_curve_changed)) print('\t\tbAddRotAndScaleAttributesOnCurves: {0}'.format(in_input.add_rot_and_scale_attributes_on_curves)) input_objects = in_input.get_input_objects() if not input_objects: print('\t\tEmpty input!') else: print('\t\tNumber of objects in input: {0}'.format(len(input_objects))) for idx, input_object in enumerate(input_objects): print('\t\t\tInput object #{0}: {1}'.format(idx, input_object)) if hasattr(in_input, 'supports_transform_offset') and in_input.supports_transform_offset(): print('\t\t\tObject Transform Offset: {0}'.format(in_input.get_input_object_transform_offset(idx))) if isinstance(input_object, unreal.HoudiniPublicAPICurveInputObject): print('\t\t\tbClosed: {0}'.format(input_object.is_closed())) print('\t\t\tCurveMethod: {0}'.format(input_object.get_curve_method())) print('\t\t\tCurveType: {0}'.format(input_object.get_curve_type())) print('\t\t\tReversed: {0}'.format(input_object.is_reversed())) print('\t\t\tCurvePoints: {0}'.format(input_object.get_curve_points())) def on_failure(self): print('on_failure') global _g_processor _g_processor = None def on_complete(self): print('on_complete') global _g_processor _g_processor = None def on_pre_instantiation(self): print('on_pre_instantiation') def on_post_instantiation(self): print('on_post_instantiation') def on_post_auto_cook(self, cook_success): print('on_post_auto_cook, success = {0}'.format(cook_success)) def on_pre_process(self): print('on_pre_process') def on_post_processing(self): print('on_post_processing') # Fetch inputs, iterate over it and log node_inputs = self.asset_wrapper.get_inputs_at_indices() parm_inputs = self.asset_wrapper.get_input_parameters() if not node_inputs: print('No node inputs found!') else: print('Number of node inputs: {0}'.format(len(node_inputs))) for input_index, input_wrapper in node_inputs.items(): print('\tInput index: {0}'.format(input_index)) self._print_api_input(input_wrapper) if not parm_inputs: print('No parameter inputs found!') else: print('Number of parameter inputs: {0}'.format(len(parm_inputs))) for parm_name, input_wrapper in parm_inputs.items(): print('\tInput parameter name: {0}'.format(parm_name)) self._print_api_input(input_wrapper) def on_post_auto_bake(self, bake_success): print('on_post_auto_bake, succes = {0}'.format(bake_success)) def get_test_hda_path(): return '/project/.copy_to_curve_1_0' def get_test_hda(): return unreal.load_object(None, get_test_hda_path()) def get_geo_asset_path(): return '/project/.Cube' def get_geo_asset(): return unreal.load_object(None, get_geo_asset_path()) def build_inputs(): print('configure_inputs') # get the API singleton houdini_api = unreal.HoudiniPublicAPIBlueprintLib.get_api() node_inputs = {} # Create a geo input geo_input = houdini_api.create_empty_input(unreal.HoudiniPublicAPIGeoInput) # Set the input objects/assets for this input geo_object = get_geo_asset() geo_input.set_input_objects((geo_object, )) # store the input data to the HDA as node input 0 node_inputs[0] = geo_input # Create a curve input curve_input = houdini_api.create_empty_input(unreal.HoudiniPublicAPICurveInput) # Create a curve wrapper/helper curve_object = unreal.HoudiniPublicAPICurveInputObject(curve_input) # Make it a Nurbs curve curve_object.set_curve_type(unreal.HoudiniPublicAPICurveType.NURBS) # Set the points of the curve, for this example we create a helix # consisting of 100 points curve_points = [] for i in range(100): t = i / 20.0 * math.pi * 2.0 x = 100.0 * math.cos(t) y = 100.0 * math.sin(t) z = i curve_points.append(unreal.Transform([x, y, z], [0, 0, 0], [1, 1, 1])) curve_object.set_curve_points(curve_points) # Set the curve wrapper as an input object curve_input.set_input_objects((curve_object, )) # Store the input data to the HDA as node input 1 node_inputs[1] = curve_input return node_inputs def run(): # Create the processor with preconfigured inputs global _g_processor _g_processor = ProcessHDAExample( get_test_hda(), node_inputs=build_inputs()) # Activate the processor, this will starts instantiation, and then cook if not _g_processor.activate(): unreal.log_warning('Activation failed.') else: unreal.log('Activated!') if __name__ == '__main__': run()
import unreal import os def import_obj_to_unreal(obj_file_path, destination_path, asset_name): asset_tools = unreal.AssetToolsHelpers.get_asset_tools() # Create an import task obj_import_task = unreal.AssetImportTask() obj_import_task.set_editor_property('filename', obj_file_path) obj_import_task.set_editor_property('destination_path', destination_path) obj_import_task.set_editor_property('destination_name', asset_name) obj_import_task.set_editor_property('save', True) obj_import_task.set_editor_property('replace_existing', True) obj_import_task.set_editor_property('automated', True) # Avoid the confirmation prompt # Execute the import task asset_tools.import_asset_tasks([obj_import_task]) # Verify and return the imported asset path imported_paths = obj_import_task.get_editor_property('imported_object_paths') for path in imported_paths: obj_asset = unreal.EditorAssetLibrary.load_asset(path) if isinstance(obj_asset, unreal.StaticMesh): unreal.log(f"File OBJ imported into Unreal Engine: {obj_asset.get_path_name()}") return obj_asset.get_path_name() unreal.log_error("OBJ file import failed or did not result in a StaticMesh.") return None def place_obj_in_scene(obj_asset_path, location, scale): unreal.log(f"Placing object in the scene: {obj_asset_path}") obj_asset = unreal.EditorAssetLibrary.load_asset(obj_asset_path) if not obj_asset: unreal.log(f"Error: Unable to load asset {obj_asset_path}") return # Ensure the asset is a static mesh if isinstance(obj_asset, unreal.StaticMesh): # Place the object in the scene actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.StaticMeshActor, location) if actor: actor.set_actor_label("Mappa") static_mesh_component = actor.get_component_by_class(unreal.StaticMeshComponent) if static_mesh_component: static_mesh_component.set_static_mesh(obj_asset) actor.set_actor_scale3d(unreal.Vector(scale, scale, scale)) # Set Collision Presets to NoCollision static_mesh_component.set_collision_profile_name('NoCollision') unreal.EditorLevelLibrary.save_current_level() unreal.log(f"Object placed in the scene: {actor} with scale {scale}.") else: unreal.log(f"Error: Unable to find StaticMeshComponent for actor {actor}.") else: unreal.log(f"Error: Unable to place asset {obj_asset_path} in the scene.") else: unreal.log(f"Error: The imported asset is not a StaticMesh. Asset type: {type(obj_asset)}") def main(): # Path to the OBJ file obj_file_relative_path = 'Mappa.obj' script_dir = os.path.dirname(os.path.abspath(__file__)) obj_file_path = os.path.join(script_dir, obj_file_relative_path) # Debug: verifica il percorso del file OBJ unreal.log(f"Percorso del file OBJ: {obj_file_path}") # Import the OBJ file destination_path = '/project/' asset_name = 'Mappa' obj_asset_path = import_obj_to_unreal(obj_file_path, destination_path, asset_name) # If the import was successful, place the object in the scene if obj_asset_path: location = unreal.Vector(0.0, 0.0, 0.0) # Adjust this position as needed scale = 100.0 # Desired scale place_obj_in_scene(obj_asset_path, location, scale) # Execute the main function if this file is run as a script if __name__ == "__main__": main()
# coding: utf-8 import os import unreal # import AssetFunction_2 as af # reload(af) # af.importMyAssets() asset_folder = 'D:/project/' static_mesh_fbx = os.path.join(asset_folder, 'static_fbx.fbx').replace('\\','/') skeletal_mesh_fbx = os.path.join(asset_folder, 'skeletal_fbx.fbx').replace('\\','/') def importMyAssets(): # ! 静态网格 static_mesh_task = bulidImportTask(static_mesh_fbx, '/project/', buildStaticMeshImportOptions()) # ! 带骨骼的网格 skeletal_mesh_task = bulidImportTask(skeletal_mesh_fbx, '/project/', buildSkeletalMeshImportOptions()) executeImportTasks([static_mesh_task, skeletal_mesh_task]) def bulidImportTask(filename, destination_path, options=None): task = unreal.AssetImportTask() task.set_editor_property('automated', True) task.set_editor_property('destination_name', '') task.set_editor_property('destination_path', destination_path) task.set_editor_property('filename', filename) task.set_editor_property('replace_existing', True) task.set_editor_property('save', True) task.set_editor_property('options', options) return task def executeImportTasks(tasks): unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks(tasks) for task in tasks: for path in task.get_editor_property('imported_object_paths'): print 'Imported {}'.format(path) def buildStaticMeshImportOptions(): options = unreal.FbxImportUI() # unreal.FbxImportUI options.set_editor_property('import_mesh', True) options.set_editor_property('import_textures', False) options.set_editor_property('import_materials', True) options.set_editor_property('import_as_skeletal', False) # Static Mesh # unreal.FbxMeshImportData options.static_mesh_import_data.set_editor_property('import_translation', unreal.Vector(50.0, 0.0, 0.0)) options.static_mesh_import_data.set_editor_property('import_rotation', unreal.Rotator(0.0, 110.0, 0.0)) options.static_mesh_import_data.set_editor_property('import_uniform_scale', 1.0) # unreal.FbxStaticMeshImportData options.static_mesh_import_data.set_editor_property('combine_meshes', True) options.static_mesh_import_data.set_editor_property('generate_lightmap_u_vs', True) options.static_mesh_import_data.set_editor_property('auto_generate_collision', True) return options def buildSkeletalMeshImportOptions(): options = unreal.FbxImportUI() # unreal.FbxImportUI options.set_editor_property('import_mesh', True) options.set_editor_property('import_textures', True) options.set_editor_property('import_materials', True) options.set_editor_property('import_as_skeletal', True) # Skeletal Mesh # unreal.FbxMeshImportData options.skeletal_mesh_import_data.set_editor_property('import_translation', unreal.Vector(0.0, 0.0, 0.0)) options.skeletal_mesh_import_data.set_editor_property('import_rotation', unreal.Rotator(0.0, 0.0, 0.0)) options.skeletal_mesh_import_data.set_editor_property('import_uniform_scale', 1.0) # unreal.FbxSkeletalMeshImportData options.skeletal_mesh_import_data.set_editor_property('import_morph_targets', True) options.skeletal_mesh_import_data.set_editor_property('update_skeleton_reference_pose', False) return options
# -*- coding: utf-8 -*- """ Created on Thu Feb 22 12:12:57 2024 @author: WillQuantique """ import unreal world = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem).get_editor_world() level_path = "/project/" lp = "/project/" lp2 = "/project/" @unreal.uclass() class MyEditorLevelUtility(unreal.EditorLevelUtils): pass #streamingLvl = MyEditorLevelUtility().create_new_streaming_level(unreal.LevelStreaming, lp, False) #level = unreal.EditorLevelUtils.add_level_to_world(world,lp2, unreal.LevelStreamingPersistent) #MyEditorLevelUtility().make_level_current(streamingLvl) # Chargez le niveau #unreal.EditorLoadingAndSavingUtils.load_map(lp2) unreal.get_editor_subsystem(unreal.LevelEditorSubsystem).load_level(lp2)
# Copyright (c) <2021> Side Effects Software Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. The name of Side Effects Software may not be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN # NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ An example script that uses the API and HoudiniEngineV2.asyncprocessor.ProcessHDA. ProcessHDA is configured with the asset to instantiate, as well as 2 inputs: a geometry input (a cube) and a curve input (a helix). ProcessHDA is then activiated upon which the asset will be instantiated, inputs set, and cooked. The ProcessHDA class's on_post_processing() function is overridden to fetch the input structure and logged. The other state/phase functions (on_pre_instantiate(), on_post_instantiate() etc) are overridden to simply log the function name, in order to observe progress in the log. """ import math import unreal from HoudiniEngineV2.asyncprocessor import ProcessHDA _g_processor = None class ProcessHDAExample(ProcessHDA): @staticmethod def _print_api_input(in_input): print('\t\tInput type: {0}'.format(in_input.__class__)) print('\t\tbKeepWorldTransform: {0}'.format(in_input.keep_world_transform)) print('\t\tbImportAsReference: {0}'.format(in_input.import_as_reference)) if isinstance(in_input, unreal.HoudiniPublicAPIGeoInput): print('\t\tbPackBeforeMerge: {0}'.format(in_input.pack_before_merge)) print('\t\tbExportLODs: {0}'.format(in_input.export_lo_ds)) print('\t\tbExportSockets: {0}'.format(in_input.export_sockets)) print('\t\tbExportColliders: {0}'.format(in_input.export_colliders)) elif isinstance(in_input, unreal.HoudiniPublicAPICurveInput): print('\t\tbCookOnCurveChanged: {0}'.format(in_input.cook_on_curve_changed)) print('\t\tbAddRotAndScaleAttributesOnCurves: {0}'.format(in_input.add_rot_and_scale_attributes_on_curves)) input_objects = in_input.get_input_objects() if not input_objects: print('\t\tEmpty input!') else: print('\t\tNumber of objects in input: {0}'.format(len(input_objects))) for idx, input_object in enumerate(input_objects): print('\t\t\tInput object #{0}: {1}'.format(idx, input_object)) if hasattr(in_input, 'supports_transform_offset') and in_input.supports_transform_offset(): print('\t\t\tObject Transform Offset: {0}'.format(in_input.get_input_object_transform_offset(idx))) if isinstance(input_object, unreal.HoudiniPublicAPICurveInputObject): print('\t\t\tbClosed: {0}'.format(input_object.is_closed())) print('\t\t\tCurveMethod: {0}'.format(input_object.get_curve_method())) print('\t\t\tCurveType: {0}'.format(input_object.get_curve_type())) print('\t\t\tReversed: {0}'.format(input_object.is_reversed())) print('\t\t\tCurvePoints: {0}'.format(input_object.get_curve_points())) def on_failure(self): print('on_failure') global _g_processor _g_processor = None def on_complete(self): print('on_complete') global _g_processor _g_processor = None def on_pre_instantiation(self): print('on_pre_instantiation') def on_post_instantiation(self): print('on_post_instantiation') def on_post_auto_cook(self, cook_success): print('on_post_auto_cook, success = {0}'.format(cook_success)) def on_pre_process(self): print('on_pre_process') def on_post_processing(self): print('on_post_processing') # Fetch inputs, iterate over it and log node_inputs = self.asset_wrapper.get_inputs_at_indices() parm_inputs = self.asset_wrapper.get_input_parameters() if not node_inputs: print('No node inputs found!') else: print('Number of node inputs: {0}'.format(len(node_inputs))) for input_index, input_wrapper in node_inputs.items(): print('\tInput index: {0}'.format(input_index)) self._print_api_input(input_wrapper) if not parm_inputs: print('No parameter inputs found!') else: print('Number of parameter inputs: {0}'.format(len(parm_inputs))) for parm_name, input_wrapper in parm_inputs.items(): print('\tInput parameter name: {0}'.format(parm_name)) self._print_api_input(input_wrapper) def on_post_auto_bake(self, bake_success): print('on_post_auto_bake, succes = {0}'.format(bake_success)) def get_test_hda_path(): return '/project/.copy_to_curve_1_0' def get_test_hda(): return unreal.load_object(None, get_test_hda_path()) def get_geo_asset_path(): return '/project/.Cube' def get_geo_asset(): return unreal.load_object(None, get_geo_asset_path()) def build_inputs(): print('configure_inputs') # get the API singleton houdini_api = unreal.HoudiniPublicAPIBlueprintLib.get_api() node_inputs = {} # Create a geo input geo_input = houdini_api.create_empty_input(unreal.HoudiniPublicAPIGeoInput) # Set the input objects/assets for this input geo_object = get_geo_asset() geo_input.set_input_objects((geo_object, )) # store the input data to the HDA as node input 0 node_inputs[0] = geo_input # Create a curve input curve_input = houdini_api.create_empty_input(unreal.HoudiniPublicAPICurveInput) # Create a curve wrapper/helper curve_object = unreal.HoudiniPublicAPICurveInputObject(curve_input) # Make it a Nurbs curve curve_object.set_curve_type(unreal.HoudiniPublicAPICurveType.NURBS) # Set the points of the curve, for this example we create a helix # consisting of 100 points curve_points = [] for i in range(100): t = i / 20.0 * math.pi * 2.0 x = 100.0 * math.cos(t) y = 100.0 * math.sin(t) z = i curve_points.append(unreal.Transform([x, y, z], [0, 0, 0], [1, 1, 1])) curve_object.set_curve_points(curve_points) # Set the curve wrapper as an input object curve_input.set_input_objects((curve_object, )) # Store the input data to the HDA as node input 1 node_inputs[1] = curve_input return node_inputs def run(): # Create the processor with preconfigured inputs global _g_processor _g_processor = ProcessHDAExample( get_test_hda(), node_inputs=build_inputs()) # Activate the processor, this will starts instantiation, and then cook if not _g_processor.activate(): unreal.log_warning('Activation failed.') else: unreal.log('Activated!') if __name__ == '__main__': run()
# ----------------------------------------------------------- # ueUtils.py # v.1.0 # Updated: 20211108 # ----------------------------------------------------------- import unreal # ----------------------------------------------------------- # HOT RELOADING IN UE ))))))))))))))))))))))))))))))))) START # ----------------------------------------------------------- # Include the following to allow for hot reload in UE Python console. # In console simply type the following to load the module: # Syntax Example # import <module> import ueUtils # Then to reload any edits made to the module: # Syntax Example # reload(<module>) reload(ueUtils) import importlib __builtins__['reload'] = importlib.reload # ----------------------------------------------------------- # HOT RELOADING IN UE ))))))))))))))))))))))))))))))))))) END # ----------------------------------------------------------- def testprint(string): print(string + "00100") def logSelectedActors(): # ----------------------------------------------------------- # LOG SELECTED ACTORS ))))))))))))))))))))))))))))))))) START # ----------------------------------------------------------- """Log names of selected scene actors to console.""" @unreal.uclass() class ueUtility(unreal.GlobalEditorUtilityBase): pass selectedActors = ueUtility().get_selection_set() for actor in selectedActors: unreal.log("Selected Actors:") unreal.log(actor.get_name()) # ----------------------------------------------------------- # LOG SELECTED ACTORS ))))))))))))))))))))))))))))))))))) END # ----------------------------------------------------------- def rename_assets(search_pattern, replaced_pattern, case_sensitivity=True): # ----------------------------------------------------------- # REPLACE SELECTED ACTORS ))))))))))))))))))))))))))))) START # ----------------------------------------------------------- r""" Replace search pattern in selected assets with new string. Args: search_pattern: string replaced_pattern: string case_sensitivity: bool Returns: None """ # Instantiate classes # Accessing UE's System Library. system_lib = unreal.SystemLibrary() # Access UE's Editor Utility Library to perform operations # within UE's Editor. editor_util = unreal.EditorUtilityLibrary() # Access UE's own String Library, to be used in lieu of # default Python's string functions. string_lib = unreal.StringLibrary() # Collect the assets selected by user and log their count. selected_assets = editor_util.get_selected_assets() num_of_assets = len(selected_assets) # Counter to track replaced assets. replaced_assets = 0 # Debug log unreal.log("Selected {} assets.".format(num_of_assets)) # Iterate thru each selected asset and rename. for asset in selected_assets: # Get asset name as clear text. This is the display # name for the asset as seen in the Content Browser. asset_name = system_lib.get_object_name(asset) # Debug log retrieved name. unreal.log(asset_name) # Check if asset name contains the string spec'd to # be searched and replaced using UE's String Lib's # contains() function. 3rd arg spec's if case-sensitive. if string_lib.contains(asset_name, search_pattern, use_case=case_sensitivity): # Specify new asset name by replacing matched search # pattern with new replaced pattern. Note that replace() # function includes arg to specify case sensitivity # with UE's SearchCase enum. Case enum toggles between # user spec'd use_case arg. # Ref: https://docs.unrealengine.com/4.27/en-US/project/.html case_enum = unreal.SearchCase.CASE_SENSITIVE if case_sensitivity else unreal.SearchCase.IGNORE_CASE new_asset_name = string_lib.replace(asset_name, search_pattern, replaced_pattern, search_case=case_enum) # Aggregate replaced asset counter. replaced_assets += 1 # Execute renaming operation using UE's Editor Utility # rename_asset() function. editor_util.rename_asset(asset, new_asset_name) # Debug log for found search pattern and rename. unreal.log("Search pattern found in {}, renamed to {}".format(asset_name, new_asset_name)) # Debug log for instances where search pattern was not # found in selected assets' name. else: unreal.log("Search pattern not found in {}, therefore, skipped.".format(asset_name)) # Log number of selected assets that were successfully renamed. unreal.log("Renamed {}/{} assets".format(replaced_assets, num_of_assets)) # ----------------------------------------------------------- # REPLACE SELECTED ACTORS ))))))))))))))))))))))))))))))) END # ----------------------------------------------------------- def org_world_outliner(): # ----------------------------------------------------------- # ORGANIZE WORLD OUTLINER ))))))))))))))))))))))))))))) START # ----------------------------------------------------------- r""" Organize world outliner based on actor type and categorize into corresponding folders. Args: None Returns: None """ # Access UE's Editor Level & Filter Libraries to access level # content. editor_level_lib = unreal.EditorLevelLibrary() editor_filter_lib = unreal.EditorFilterLibrary() # Retrieve all actors in current level; store in array. actors = editor_level_lib.get_all_level_actors() # Filter thru array and isolate by class. Each filter focuses # on each type of actor being isolated, such as by class, string # or other method. static_mesh = editor_filter_lib.by_class(actors, unreal.StaticMeshActor) lighting = editor_filter_lib.by_class(actors, unreal.Light) # Rather than by class, filter BP's by string in name. blueprint = editor_filter_lib.by_id_name(actors, "BP") # For tagged actors, specify the tag as a Name object and spec # Filter Type. If set to 'INCLUDE', then it will only include # actors with the spec'd tag. With 'EXCLUDE', all non-tagged # actors will be assigned to array variable. tag_name = unreal.Name("tagged") tagged = editor_filter_lib.by_actor_tag(actors, tag_name, filter_type=unreal.EditorScriptingFilterType.INCLUDE) untagged = editor_filter_lib.by_actor_tag(actors, tag_name, filter_type=unreal.EditorScriptingFilterType.EXCLUDE) # Counter to track number of moved actors. moved_actors = 0 # Create map that matches spec'd folder names to each of the # filters created above. folders = { "StaticMesh": static_mesh, "Lighting": lighting, "BP": blueprint, "Tagged": tagged, "Untagged": untagged } # Iterate thru each folder within the map. for folder_name in folders: # Iterate thru each actor based on folder name. for actor in folders[folder_name]: # Get name of spec'd actor instance. actor_name = actor.get_fname() # Redefine the path to the actor so that it is now # within its respective folder, as spec'd in the arg. #actor.set_folder_path(folder_name) unreal.log("{} moved into {} folder.".format(actor_name, folder_name)) # Aggregate actors moved into folder. moved_actors += 1 # Debug log total number of actors moved into folders. unreal.log("Moved {} actors into folders.".format(moved_actors)) # ----------------------------------------------------------- # ORGANIZE WORLD OUTLINER ))))))))))))))))))))))))))))))) END # ----------------------------------------------------------- def log_bp_components(): # ----------------------------------------------------------- # LOG BP COMPONENTS ))))))))))))))))))))))))))))))))))) START # ----------------------------------------------------------- r""" Access components within selected blueprint actors. Args: None Returns: None """ # Access UE's Editor Level Library to access level content. editor_level_lib = unreal.EditorLevelLibrary() editor_filter_lib = unreal.EditorFilterLibrary() # Retrieve selected bp actors in current level; store in array. bp_actors = editor_level_lib.get_selected_level_actors() # Counter to track identified actors and children. num_of_actors = 0 # Iterate thru each static mesh actor. for actor in bp_actors: # --------------------------------------- 0 # Get root component property for current actor. scene_component = actor.root_component # Get all children within current bp. children = scene_component.get_children_components(True) # Get num of children for current root scene component. # Note that this number includes itself as array item 0. num_of_children = len(children) # Alt built-in method in scene component class to log # num of children. alt_num_of_children = scene_component.get_num_children_components() current_child = 0 sm_children = editor_filter_lib.by_class(children, unreal.StaticMeshComponent) # The above returns all sm components, including hism. # Identify array of only hism children, to be used to filter # out hism from sm array. hism_children = editor_filter_lib.by_class(children, unreal.HierarchicalInstancedStaticMeshComponent) unreal.log("HISM: {}".format(hism_children)) num_of_sm_children = len(sm_children) # Iterate through each child component. for child in sm_children: # --------------------------------------- 1 child_name = child.get_fname() child_class = child.get_class() # Check if current sm child is not an hism. Process # only if not an hism. if child not in hism_children: current_child += 1 unreal.log("{}: {}".format(current_child, child_name)) # --------------------------------------- 1 num_of_actors += 1 unreal.log("Documented {} static mesh components from {} ({}) total children.".format(current_child, num_of_children, alt_num_of_children)) # --------------------------------------- 0 # ----------------------------------------------------------- # LOG BP COMPONENTS ))))))))))))))))))))))))))))))))))))) END # ----------------------------------------------------------- def add_component(): # ----------------------------------------------------------- # ADD COMPONENTS )))))))))))))))))))))))))))))))))))))) START # ----------------------------------------------------------- r""" Add component within selected blueprint actors. Args: None Returns: None """ # !!!!!!!!!!!! NOTE !!!!!!!!!!!!!!! # This function superseded by new actor class and function via C++. # Access UE's Editor Level Library to access level content. editor_level_lib = unreal.EditorLevelLibrary() editor_util_lib = unreal.EditorUtilityLibrary() actor = editor_level_lib.get_selected_level_actors()[0] asset = editor_util_lib.get_selected_assets()[0] hism_component = unreal.HierarchicalInstancedStaticMeshComponent() unreal.log("{} \n {}".format(actor, hism_component)) # Init transform object to 0 location, 0 rotation, 1 scale xform = unreal.Transform() unreal.uproperty(unreal.InstancedStaticMeshComponent()) hism_component.attach_to_component(actor.root_component, unreal.Name(), unreal.AttachmentRule.KEEP_WORLD, unreal.AttachmentRule.KEEP_WORLD, unreal.AttachmentRule.KEEP_WORLD, False) actor.set_editor_property('root_component', hism_component) # ----------------------------------------------------------- # ADD COMPONENTS )))))))))))))))))))))))))))))))))))))))) END # -----------------------------------------------------------
# coding: utf-8 import unreal import argparse parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") parser.add_argument("-meta") args = parser.parse_args() print(args.vrm) #print(dummy[3]) humanoidBoneList = [ "hips", "leftUpperLeg", "rightUpperLeg", "leftLowerLeg", "rightLowerLeg", "leftFoot", "rightFoot", "spine", "chest", "upperChest", # 9 optional "neck", "head", "leftShoulder", "rightShoulder", "leftUpperArm", "rightUpperArm", "leftLowerArm", "rightLowerArm", "leftHand", "rightHand", "leftToes", "rightToes", "leftEye", "rightEye", "jaw", "leftThumbProximal", # 24 "leftThumbIntermediate", "leftThumbDistal", "leftIndexProximal", "leftIndexIntermediate", "leftIndexDistal", "leftMiddleProximal", "leftMiddleIntermediate", "leftMiddleDistal", "leftRingProximal", "leftRingIntermediate", "leftRingDistal", "leftLittleProximal", "leftLittleIntermediate", "leftLittleDistal", "rightThumbProximal", "rightThumbIntermediate", "rightThumbDistal", "rightIndexProximal", "rightIndexIntermediate", "rightIndexDistal", "rightMiddleProximal", "rightMiddleIntermediate", "rightMiddleDistal", "rightRingProximal", "rightRingIntermediate", "rightRingDistal", "rightLittleProximal", "rightLittleIntermediate", "rightLittleDistal", #54 ] humanoidBoneParentList = [ "", #"hips", "hips",#"leftUpperLeg", "hips",#"rightUpperLeg", "leftUpperLeg",#"leftLowerLeg", "rightUpperLeg",#"rightLowerLeg", "leftLowerLeg",#"leftFoot", "rightLowerLeg",#"rightFoot", "hips",#"spine", "spine",#"chest", "chest",#"upperChest" 9 optional "chest",#"neck", "neck",#"head", "chest",#"leftShoulder", # <-- upper.. "chest",#"rightShoulder", "leftShoulder",#"leftUpperArm", "rightShoulder",#"rightUpperArm", "leftUpperArm",#"leftLowerArm", "rightUpperArm",#"rightLowerArm", "leftLowerArm",#"leftHand", "rightLowerArm",#"rightHand", "leftFoot",#"leftToes", "rightFoot",#"rightToes", "head",#"leftEye", "head",#"rightEye", "head",#"jaw", "leftHand",#"leftThumbProximal", "leftThumbProximal",#"leftThumbIntermediate", "leftThumbIntermediate",#"leftThumbDistal", "leftHand",#"leftIndexProximal", "leftIndexProximal",#"leftIndexIntermediate", "leftIndexIntermediate",#"leftIndexDistal", "leftHand",#"leftMiddleProximal", "leftMiddleProximal",#"leftMiddleIntermediate", "leftMiddleIntermediate",#"leftMiddleDistal", "leftHand",#"leftRingProximal", "leftRingProximal",#"leftRingIntermediate", "leftRingIntermediate",#"leftRingDistal", "leftHand",#"leftLittleProximal", "leftLittleProximal",#"leftLittleIntermediate", "leftLittleIntermediate",#"leftLittleDistal", "rightHand",#"rightThumbProximal", "rightThumbProximal",#"rightThumbIntermediate", "rightThumbIntermediate",#"rightThumbDistal", "rightHand",#"rightIndexProximal", "rightIndexProximal",#"rightIndexIntermediate", "rightIndexIntermediate",#"rightIndexDistal", "rightHand",#"rightMiddleProximal", "rightMiddleProximal",#"rightMiddleIntermediate", "rightMiddleIntermediate",#"rightMiddleDistal", "rightHand",#"rightRingProximal", "rightRingProximal",#"rightRingIntermediate", "rightRingIntermediate",#"rightRingDistal", "rightHand",#"rightLittleProximal", "rightLittleProximal",#"rightLittleIntermediate", "rightLittleIntermediate",#"rightLittleDistal", ] for i in range(len(humanoidBoneList)): humanoidBoneList[i] = humanoidBoneList[i].lower() for i in range(len(humanoidBoneParentList)): humanoidBoneParentList[i] = humanoidBoneParentList[i].lower() ###### reg = unreal.AssetRegistryHelpers.get_asset_registry(); ## rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r #rig = rigs[10] h_mod = rig.get_hierarchy_modifier() #elements = h_mod.get_selection() #sk = rig.get_preview_mesh() #k = sk.skeleton #print(k) #print(sk.bone_tree) # #kk = unreal.RigElementKey(unreal.RigElementType.BONE, "hipssss"); #kk.name = "" #kk.type = 1; #print(h_mod.get_bone(kk)) #print(h_mod.get_elements()) ### 全ての骨 modelBoneListAll = [] modelBoneNameList = [] #for e in reversed(h_mod.get_elements()): # if (e.type != unreal.RigElementType.BONE): # h_mod.remove_element(e) for e in h_mod.get_elements(): if (e.type == unreal.RigElementType.BONE): modelBoneListAll.append(e) modelBoneNameList.append("{}".format(e.name).lower()) # else: # h_mod.remove_element(e) print(modelBoneListAll[0]) #exit #print(k.get_editor_property("bone_tree")[0].get_editor_property("translation_retargeting_mode")) #print(k.get_editor_property("bone_tree")[0].get_editor_property("parent_index")) #unreal.select #vrmlist = unreal.VrmAssetListObject #vrmmeta = vrmlist.vrm_meta_object #print(vrmmeta.humanoid_bone_table) #selected_actors = unreal.EditorLevelLibrary.get_selected_level_actors() #selected_static_mesh_actors = unreal.EditorFilterLibrary.by_class(selected_actors,unreal.StaticMeshActor.static_class()) #static_meshes = np.array([]) ## meta 取得 reg = unreal.AssetRegistryHelpers.get_asset_registry(); a = reg.get_all_assets(); if (args.meta): for aa in a: if (aa.get_editor_property("object_path") == args.meta): v:unreal.VrmMetaObject = aa vv = aa.get_asset() if (vv == None): for aa in a: if (aa.get_editor_property("object_path") == args.vrm): v:unreal.VrmAssetListObject = aa vv = v.get_asset().vrm_meta_object print(vv) meta = vv #v:unreal.VrmAssetListObject = None #if (True): # a = reg.get_assets_by_path(args.vrm) # a = reg.get_all_assets(); # for aa in a: # if (aa.get_editor_property("object_path") == args.vrm): # v:unreal.VrmAssetListObject = aa #v = unreal.VrmAssetListObject.cast(v) #print(v) #unreal.VrmAssetListObject.vrm_meta_object #meta = v.vrm_meta_object() #meta = unreal.EditorFilterLibrary.by_class(asset,unreal.VrmMetaObject.static_class()) print (meta) #print(meta[0].humanoid_bone_table) ### モデル骨のうち、ヒューマノイドと同じもの ### 上の変換テーブル humanoidBoneToModel = {"" : ""} humanoidBoneToModel.clear() ### modelBoneでループ #for bone_h in meta.humanoid_bone_table: for bone_h_base in humanoidBoneList: bone_h = None for e in meta.humanoid_bone_table: if ("{}".format(e).lower() == bone_h_base): bone_h = e; break; print("{}".format(bone_h)) if (bone_h==None): continue bone_m = meta.humanoid_bone_table[bone_h] try: i = modelBoneNameList.index(bone_m.lower()) except: i = -1 if (i < 0): continue if ("{}".format(bone_h).lower() == "upperchest"): continue; humanoidBoneToModel["{}".format(bone_h).lower()] = "{}".format(bone_m).lower() if ("{}".format(bone_h).lower() == "chest"): #upperchestがあれば、これの次に追加 bh = 'upperchest' print("upperchest: check begin") for e in meta.humanoid_bone_table: if ("{}".format(e).lower() != 'upperchest'): continue bm = "{}".format(meta.humanoid_bone_table[e]).lower() if (bm == ''): continue humanoidBoneToModel[bh] = bm humanoidBoneParentList[10] = "upperchest" humanoidBoneParentList[12] = "upperchest" humanoidBoneParentList[13] = "upperchest" print("upperchest: find and insert parent") break print("upperchest: check end") parent=None control_to_mat={None:None} count = 0 ### 骨名からControlへのテーブル name_to_control = {"dummy_for_table" : None} print("loop begin") ###### root key = unreal.RigElementKey(unreal.RigElementType.SPACE, 'root_s') space = h_mod.get_space(key) if (space.get_editor_property('index') < 0): space = h_mod.add_space('root_s', space_type=unreal.RigSpaceType.SPACE) else: space = key key = unreal.RigElementKey(unreal.RigElementType.CONTROL, 'root_c') control = h_mod.get_control(key) if (control.get_editor_property('index') < 0): control = h_mod.add_control('root_c', space_name=space.name, gizmo_color=[1.0, 0.0, 0.0, 1.0], ) else: control = key h_mod.reparent_element(control, space) parent = control cc = h_mod.get_control(control) cc.set_editor_property('gizmo_visible', False) h_mod.set_control(cc) for ee in humanoidBoneToModel: element = humanoidBoneToModel[ee] humanoidBone = ee modelBoneNameSmall = element # 対象の骨 #modelBoneNameSmall = "{}".format(element.name).lower() #humanoidBone = modelBoneToHumanoid[modelBoneNameSmall]; boneNo = humanoidBoneList.index(humanoidBone) print("{}_{}_{}__parent={}".format(modelBoneNameSmall, humanoidBone, boneNo,humanoidBoneParentList[boneNo])) # 親 if count != 0: parent = name_to_control[humanoidBoneParentList[boneNo]] # 階層作成 bIsNew = False name_s = "{}_s".format(humanoidBone) key = unreal.RigElementKey(unreal.RigElementType.SPACE, name_s) space = h_mod.get_space(key) if (space.get_editor_property('index') < 0): space = h_mod.add_space(name_s, space_type=unreal.RigSpaceType.SPACE) bIsNew = True else: space = key name_c = "{}_c".format(humanoidBone) key = unreal.RigElementKey(unreal.RigElementType.CONTROL, name_c) control = h_mod.get_control(key) if (control.get_editor_property('index') < 0): control = h_mod.add_control(name_c, space_name=space.name, gizmo_color=[1.0, 0.0, 0.0, 1.0], ) #h_mod.get_control(control).gizmo_transform = gizmo_trans if (24<=boneNo & boneNo<=53): gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.1, 0.1, 0.1]) else: gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1, 1, 1]) if (17<=boneNo & boneNo<=18): gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1, 1, 1]) cc = h_mod.get_control(control) cc.set_editor_property('gizmo_transform', gizmo_trans) cc.set_editor_property('control_type', unreal.RigControlType.ROTATOR) h_mod.set_control(cc) #h_mod.set_control_value_transform(control,gizmo_trans) bIsNew = True else: control = key if (bIsNew == True): h_mod.reparent_element(control, space) # テーブル登録 name_to_control[humanoidBone] = control print(humanoidBone) # ロケータ 座標更新 # 不要な上層階層を考慮 gTransform = h_mod.get_global_transform(modelBoneListAll[modelBoneNameList.index(modelBoneNameSmall)]) if count == 0: bone_initial_transform = gTransform else: #bone_initial_transform = h_mod.get_initial_transform(element) bone_initial_transform = gTransform.multiply(control_to_mat[parent].inverse()) h_mod.set_initial_transform(space, bone_initial_transform) control_to_mat[control] = gTransform # 階層修正 h_mod.reparent_element(space, parent) count += 1 if (count >= 500): break
# Copyright Epic Games, Inc. All Rights Reserved. import os import json import time import sys import inspect from xmlrpc.client import ProtocolError from http.client import RemoteDisconnected sys.path.append(os.path.dirname(__file__)) import rpc.factory import remote_execution try: import unreal except ModuleNotFoundError: pass REMAP_PAIRS = [] UNREAL_PORT = int(os.environ.get('UNREAL_PORT', 9998)) # use a different remap pairs when inside a container if os.environ.get('TEST_ENVIRONMENT'): UNREAL_PORT = int(os.environ.get('UNREAL_PORT', 8998)) REMAP_PAIRS = [(os.environ.get('HOST_REPO_FOLDER'), os.environ.get('CONTAINER_REPO_FOLDER'))] # this defines a the decorator that makes function run as remote call in unreal remote_unreal_decorator = rpc.factory.remote_call( port=UNREAL_PORT, default_imports=['import unreal'], remap_pairs=REMAP_PAIRS, ) rpc_client = rpc.client.RPCClient(port=UNREAL_PORT) unreal_response = '' def get_response(): """ Gets the stdout produced by the remote python call. :return str: The stdout produced by the remote python command. """ if unreal_response: full_output = [] output = unreal_response.get('output') if output: full_output.append('\n'.join([line['output'] for line in output if line['type'] != 'Warning'])) result = unreal_response.get('result') if result != 'None': full_output.append(result) return '\n'.join(full_output) return '' def add_indent(commands, indent): """ Adds an indent to the list of python commands. :param list commands: A list of python commands that will be run by unreal engine. :param str indent: A str of tab characters. :return str: A list of python commands that will be run by unreal engine. """ indented_line = [] for command in commands: for line in command.split('\n'): indented_line.append(f'{indent}{line}') return indented_line def print_python(commands): """ Prints the list of commands as formatted output for debugging and development. :param list commands: A list of python commands that will be run by unreal engine. """ if os.environ.get('REMOTE_EXECUTION_SHOW_PYTHON'): dashes = '-' * 50 label = 'Remote Execution' sys.stdout.write(f'{dashes}{label}{dashes}\n') # get the function name current_frame = inspect.currentframe() caller_frame = inspect.getouterframes(current_frame, 2) function_name = caller_frame[3][3] kwargs = caller_frame[3][0].f_locals kwargs.pop('commands', None) kwargs.pop('result', None) # write out the function name and its arguments sys.stdout.write( f'{function_name}(kwargs={json.dumps(kwargs, indent=2, default=lambda element: type(element).__name__)})\n') # write out the code with the lines numbers for index, line in enumerate(commands, 1): sys.stdout.write(f'{index} {line}\n') sys.stdout.write(f'{dashes}{"-" * len(label)}{dashes}\n') def run_unreal_python_commands(remote_exec, commands, failed_connection_attempts=0): """ Finds the open unreal editor with remote connection enabled, and sends it python commands. :param object remote_exec: A RemoteExecution instance. :param list commands: A list of python commands that will be run by unreal engine. :param int failed_connection_attempts: A counter that keeps track of how many times an editor connection attempt was made. """ if failed_connection_attempts == 0: print_python(commands) # wait a tenth of a second before attempting to connect time.sleep(0.1) try: # try to connect to an editor for node in remote_exec.remote_nodes: remote_exec.open_command_connection(node.get("node_id")) # if a connection is made if remote_exec.has_command_connection(): # run the import commands and save the response in the global unreal_response variable global unreal_response unreal_response = remote_exec.run_command('\n'.join(commands), unattended=False) # otherwise make an other attempt to connect to the engine else: if failed_connection_attempts < 50: run_unreal_python_commands(remote_exec, commands, failed_connection_attempts + 1) else: remote_exec.stop() raise ConnectionError("Could not find an open Unreal Editor instance!") # catch all errors except: raise ConnectionError("Could not find an open Unreal Editor instance!") # shutdown the connection finally: remote_exec.stop() return get_response() def run_commands(commands): """ Runs a list of python commands and returns the result of the output. :param list commands: A formatted string of python commands that will be run by unreal engine. :return str: The stdout produced by the remote python command. """ # wrap the commands in a try except so that all exceptions can be logged in the output commands = ['try:'] + add_indent(commands, '\t') + ['except Exception as error:', '\tprint(error)'] # start a connection to the engine that lets you send python-commands.md strings remote_exec = remote_execution.RemoteExecution() remote_exec.start() # send over the python code as a string and run it return run_unreal_python_commands(remote_exec, commands) def is_connected(): """ Checks the rpc server connection """ try: return rpc_client.proxy.is_running() except (RemoteDisconnected, ConnectionRefusedError, ProtocolError): return False def set_rpc_env(key, value): """ Sets an env value on the unreal RPC server. """ rpc_client.proxy.set_env(key, value) def bootstrap_unreal_with_rpc_server(): """ Bootstraps the running unreal editor with the unreal rpc server if it doesn't already exist. """ if not os.environ.get('TEST_ENVIRONMENT'): if not is_connected(): import bpy rpc_response_timeout = bpy.context.preferences.addons["send2ue"].preferences.rpc_response_timeout dependencies_path = os.path.dirname(__file__) result = run_commands( [ 'import sys', 'import os', 'import threading', 'for thread in threading.enumerate():', '\tif thread.name =="UnrealRPCServer":', '\t\tthread.kill()', f'os.environ["RPC_TIME_OUT"] = "{rpc_response_timeout}"', f'sys.path.append(r"{dependencies_path}")', 'from rpc import unreal_server', 'rpc_server = unreal_server.RPCServer()', 'rpc_server.start(threaded=True)', ] ) if result: raise ConnectionError(result) class Unreal: @staticmethod def get_value(value, unreal_type=None): """ Gets the value as an unreal type. :param Any value: A value that can be any generic python type. :param str unreal_type: The name of an unreal type. :return Any: The converted unreal value. """ if unreal_type == 'Array': if isinstance(value, str): value = value.split(',') if value: array = unreal.Array(type(value[0])) for element in value: array.append(element) return array elif unreal_type == 'Int32Interval': int_32_interval = unreal.Int32Interval() int_32_interval.set_editor_property("min", value[0]) int_32_interval.set_editor_property("max", value[1]) return int_32_interval elif unreal_type == 'Vector': return unreal.Vector(x=value[0], y=value[1], z=value[2]) elif unreal_type == 'Rotator': return unreal.Rotator(roll=value[0], pitch=value[1], yaw=value[2]) elif unreal_type == 'Color': return unreal.Color(r=value[0], g=value[1], b=value[2], a=value[3]) elif unreal_type == 'Name': return unreal.Name(value) elif unreal_type == 'SoftObjectPath': return unreal.SoftObjectPath(path_string=value) elif unreal_type == 'Enum': enum_value = unreal for attribute in value.split('.')[1:]: enum_value = getattr(enum_value, attribute) return enum_value elif unreal_type == 'Asset': if value: return Unreal.get_asset(value) else: return None else: return value @staticmethod def get_asset(asset_path): """ Adds the commands that load an unreal asset. :param str asset_path: The unreal project path of an asset. :return str: A list of python commands that will be run by unreal engine. """ asset = unreal.load_asset(asset_path) if not asset: raise RuntimeError(f"The {asset_path} does not exist in the project!") return asset @staticmethod def get_component_handles(blueprint_asset_path): """ Gets all subobject data handles of a blueprint asset. :param str blueprint_asset_path: The unreal path to the blueprint asset. :return list(subobjectDataHandle) data_handle: A list of subobject data handles within the blueprint asset. """ subsystem = unreal.get_engine_subsystem(unreal.SubobjectDataSubsystem) blueprint_asset = unreal.load_asset(blueprint_asset_path) subobject_data_handles = subsystem.k2_gather_subobject_data_for_blueprint(blueprint_asset) return subobject_data_handles @staticmethod def get_groom_handle(component_handles, binding_asset_path, groom_asset_path): """ Gets the subobject data handle of a groom component from a list of component handles that contains assets drawn from binding_asset_path and groom_asset_path. :param str component_handles: A list of component handles. :param str binding_asset_path: The path to the unreal binding asset. :param str groom_asset_path: The path to the unreal groom asset. :return subobjectDataHandle data_handle: The subobject data handle of the groom component. """ bp_subobject_library = unreal.SubobjectDataBlueprintFunctionLibrary for data_handle in component_handles: subobject = bp_subobject_library.get_object(bp_subobject_library.get_data(data_handle)) if type(subobject) == unreal.GroomComponent: has_groom = subobject.get_editor_property('groom_asset') == unreal.load_asset(groom_asset_path) has_binding = subobject.get_editor_property('binding_asset') == unreal.load_asset(binding_asset_path) if has_groom and has_binding: return data_handle return None @staticmethod def get_skeletal_mesh_handle(component_handles, mesh_asset_path): """ Gets the subobject data handle of a skeletal mesh component from a list of component handles that contains asset drawn from mesh_asset_path. :param str component_handles: A list of component handles. :param str mesh_asset_path: The path to the unreal mesh asset. :return subobjectDataHandle data_handle: The subobject data handle of the skeletal mesh component. """ bp_subobject_library = unreal.SubobjectDataBlueprintFunctionLibrary for data_handle in component_handles: subobject = bp_subobject_library.get_object(bp_subobject_library.get_data(data_handle)) if type(subobject) == unreal.SkeletalMeshComponent: if subobject.get_skeletal_mesh_asset() == unreal.load_asset(mesh_asset_path): return data_handle return None @staticmethod def set_settings(property_group, data_object): """ Sets a group of properties onto an unreal object. :param dict property_group: A dictionary of properties and their data. :param object data_object: A object. """ for attribute, data in property_group.items(): value = Unreal.get_value( value=data.get('value'), unreal_type=data.get('unreal_type'), ) data_object.set_editor_property(attribute, value) return data_object @staticmethod def is_parent_component_of_child(parent_data_handle, child_data_handle): """ Checks to see if the component associated with child_data_handle is parented under a component associated with parent_data_handle. :param subobjectDataHandle parent_data_handle: The unreal handle of the parent component. :param subobjectDataHandle child_data_handle: The unreal handle of the child component. :return bool: Whether or not the child_data_handle is a child of parent_data_handle. """ bp_subobject_library = unreal.SubobjectDataBlueprintFunctionLibrary child_data = bp_subobject_library.get_data(child_data_handle) return bp_subobject_library.is_attached_to(child_data, parent_data_handle) @staticmethod def object_attributes_to_dict(object_instance): """ Converts the attributes of the given python object to a dictionary. :param object object_instance: A object instance. :return dict: A dictionary of attributes and values. """ data = {} if object_instance: for attribute in dir(object_instance): value = getattr(object_instance, attribute) if isinstance(value, (bool, str, float, int, list)) and not attribute.startswith("_"): data[attribute] = getattr(object_instance, attribute) return data @staticmethod def create_asset(asset_path, asset_class=None, asset_factory=None, unique_name=True): """ Creates a new unreal asset. :param str asset_path: The project path to the asset. :param type(Class) asset_class: The unreal asset class. :param Factory asset_factory: The unreal factory. :param bool unique_name: Whether or not the check if the name is unique before creating the asset. """ asset_tools = unreal.AssetToolsHelpers.get_asset_tools() if unique_name: asset_path, _ = asset_tools.create_unique_asset_name( base_package_name=asset_path, suffix='' ) path, name = asset_path.rsplit("/", 1) return asset_tools.create_asset( asset_name=name, package_path=path, asset_class=asset_class, factory=asset_factory ) @staticmethod def create_binding_asset(groom_asset_path, mesh_asset_path): """ Creates a groom binding asset. :param str groom_asset_path: The unreal asset path to the imported groom asset. :param str mesh_asset_path: The unreal asset path to the associated mesh asset. :return str binding_asset_path: The unreal asset path to the created binding asset. """ mesh_asset = Unreal.get_asset(mesh_asset_path) # only create binding asset if the particle system's mesh asset is a skeletal mesh if mesh_asset.__class__.__name__ == 'SkeletalMesh': groom_asset = Unreal.get_asset(groom_asset_path) binding_asset_path = f'{groom_asset_path}_{mesh_asset.get_name()}_Binding' temp_asset_path = f'{binding_asset_path}_Temp' # renames the existing binding asset (one that had the same name) that will be consolidated existing_binding_asset = unreal.load_asset(binding_asset_path) if existing_binding_asset: unreal.EditorAssetLibrary.rename_asset( binding_asset_path, temp_asset_path ) # create the binding asset groom_binding_asset = Unreal.create_asset( binding_asset_path, unreal.GroomBindingAsset, unreal.GroomBindingFactory(), False ) # source groom asset and target skeletal mesh for the binding asset groom_binding_asset.set_editor_property('groom', groom_asset) groom_binding_asset.set_editor_property('target_skeletal_mesh', mesh_asset) # if a previous version of the binding asset exists, consolidate all references with new asset if existing_binding_asset: unreal.EditorAssetLibrary.consolidate_assets(groom_binding_asset, [existing_binding_asset]) unreal.EditorAssetLibrary.delete_asset(temp_asset_path) return binding_asset_path @staticmethod def create_blueprint_asset(blueprint_asset_path): """ Creates a blueprint asset at the specified path. :param str blueprint_asset_path: The unreal path where the blueprint asset will be created. :return object(Blueprint): The blueprint asset created. """ bp_factory = unreal.BlueprintFactory() bp_factory.set_editor_property("parent_class", unreal.Actor) return Unreal.create_asset(blueprint_asset_path, None, bp_factory, False) @staticmethod def create_blueprint_component(blueprint_asset, parent_handle, component_class, component_name='untitled_component'): """ Creates a blueprint component for a blueprint asset. :param object(Blueprint) blueprint_asset: The blueprint context for the component to be created. :param SubobjectDataHandle parent_handle: The parent handle of the new component. :param type(Class) component_class: The class of the new subobject (component) that will be created. :param str component_name: The unreal path where the blueprint asset will be created. :return object(component), sub_handle: The component and its data handle. """ subsystem = unreal.get_engine_subsystem(unreal.SubobjectDataSubsystem) # add sub object sub_handle, fail_reason = subsystem.add_new_subobject( unreal.AddNewSubobjectParams( parent_handle=parent_handle, new_class=component_class, blueprint_context=blueprint_asset) ) if not fail_reason.is_empty(): raise Exception("ERROR from sub_object_subsystem.add_new_subobject: {fail_reason}") # Need futher investigation to whether attach_subobject call is actually necessary subsystem.attach_subobject(parent_handle, sub_handle) subsystem.rename_subobject(handle=sub_handle, new_name=unreal.Text(component_name)) bp_subobject_library = unreal.SubobjectDataBlueprintFunctionLibrary component = bp_subobject_library.get_object(bp_subobject_library.get_data(sub_handle)) return component, sub_handle @staticmethod def create_blueprint_for_groom(groom_asset_path, mesh_asset_path, binding_asset_path): """ Creates a blueprint asset with a skeletal mesh component that has a child groom component populated by a groom asset and binding asset. :param dict groom_asset_path: The unreal asset path to the imported groom asset. :param str mesh_asset_path: The unreal asset path to the associated mesh asset. :param str binding_asset_path: The unreal asset path to the created binding asset. :return str blueprint_asset_path: The unreal path to the blueprint asset. """ groom_asset_name = groom_asset_path.split('/')[-1] mesh_asset_name = mesh_asset_path.split('/')[-1] blueprint_asset_path = f'{mesh_asset_path}_BP' # Todo figure out why create blueprint in None sometimes on linux blueprint_asset = Unreal.create_blueprint_asset(blueprint_asset_path) subsystem = unreal.get_engine_subsystem(unreal.SubobjectDataSubsystem) root_handles = subsystem.k2_gather_subobject_data_for_blueprint(context=blueprint_asset) or [] if root_handles: skeletal_comp, skeletal_comp_handle = Unreal.create_blueprint_component( blueprint_asset, root_handles[0], unreal.SkeletalMeshComponent, mesh_asset_name ) if skeletal_comp and skeletal_comp_handle: # add imported skeletal mesh asset to skeletal mesh component skeletal_comp.set_skeletal_mesh_asset(unreal.load_asset(mesh_asset_path)) groom_comp, groom_comp_handle = Unreal.create_blueprint_component( blueprint_asset, skeletal_comp_handle, unreal.GroomComponent, groom_asset_name ) # add binding asset and groom asset to groom component groom_comp.set_groom_asset(unreal.load_asset(groom_asset_path)) groom_comp.set_binding_asset(unreal.load_asset(binding_asset_path)) return blueprint_asset_path @staticmethod def add_groom_component_to_blueprint(groom_asset_path, mesh_asset_path, binding_asset_path): """ Adds a groom component to a blueprint asset with specific skeletal mesh. If queried blueprint asset does not exist, creates a blueprint asset with a skeletal mesh component that has a child groom component populated by a groom asset and binding asset. :param dict groom_asset_path: The unreal asset path to the imported groom asset. :param str mesh_asset_path: The unreal asset path to the associated mesh asset. :param str binding_asset_path: The unreal asset path to the created binding asset. :return str blueprint_asset_path: The unreal path to the blueprint asset. """ asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() registry_options = unreal.AssetRegistryDependencyOptions() registry_options.set_editor_property('include_hard_package_references', True) groom_asset_name = groom_asset_path.split('/')[-1] references = list(asset_registry.get_referencers(mesh_asset_path, registry_options) or []) subsystem = unreal.get_engine_subsystem(unreal.SubobjectDataSubsystem) bp_subobject_library = unreal.SubobjectDataBlueprintFunctionLibrary if references: for reference_path in references: if unreal.EditorAssetLibrary.find_asset_data(reference_path).asset_class_path.asset_name == 'Blueprint': blueprint_asset = Unreal.get_asset(reference_path) subobject_data_handles = subsystem.k2_gather_subobject_data_for_blueprint(blueprint_asset) skeletal_mesh_component_handle = None groom_component = None groom_asset = Unreal.get_asset(groom_asset_path) mesh_asset = Unreal.get_asset(mesh_asset_path) binding_asset = Unreal.get_asset(binding_asset_path) for data_handle in subobject_data_handles: subobject = bp_subobject_library.get_object(bp_subobject_library.get_data(data_handle)) if type(subobject) == unreal.SkeletalMeshComponent: if subobject.get_skeletal_mesh_asset() == mesh_asset: skeletal_mesh_component_handle = data_handle if type(subobject) == unreal.GroomComponent: if subobject.get_editor_property('groom_asset') == groom_asset: groom_component = subobject if not groom_component: groom_component, groom_component_handle = Unreal.create_blueprint_component( blueprint_asset, skeletal_mesh_component_handle, unreal.GroomComponent, groom_asset_name ) # add binding asset and groom asset to groom component groom_component.set_groom_asset(groom_asset) groom_component.set_binding_asset(binding_asset) unreal.EditorAssetLibrary.save_loaded_asset(blueprint_asset) return str(reference_path) # if there is no references to the surface mesh asset, create new blueprint else: blueprint_asset_path = Unreal.create_blueprint_for_groom( groom_asset_path, mesh_asset_path, binding_asset_path ) unreal.EditorAssetLibrary.save_loaded_asset(unreal.load_asset(blueprint_asset_path)) return blueprint_asset_path @staticmethod def get_assets_on_actor(actor, only_type=None): """ Gets only actors that are created by directly instancing assets. """ assets = [] # only get the asset type specified in only_type if it is provided if not only_type or only_type == 'StaticMesh': for component in actor.get_components_by_class(unreal.StaticMeshComponent): if component.static_mesh and actor.get_class().get_name() == 'StaticMeshActor': # make sure we only get one unique instance of the asset if component.static_mesh not in assets: assets.append(component.static_mesh) for component in actor.get_components_by_class(unreal.SkeletalMeshComponent): if component.skeletal_mesh: # only get the asset type specified in only_type if it is provided if not only_type or only_type == 'SkeletalMesh': # make sure we only get one unique instance of the asset if component.skeletal_mesh not in assets: assets.append(component.skeletal_mesh) # only get the asset type specified in only_type if it is provided if not only_type or only_type == 'AnimSequence': if component.animation_mode == unreal.AnimationMode.ANIMATION_SINGLE_NODE: if component.animation_data and component.animation_data.anim_to_play not in assets: assets.append(component.animation_data.anim_to_play) return assets @staticmethod def get_asset_actors_in_level(): """ Gets actors from the active level that have assets assigned to them. """ actors = [] actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) for actor in actor_subsystem.get_all_level_actors(): if Unreal.get_assets_on_actor(actor): actors.append(actor) return actors @staticmethod def get_asset_actor_by_label(label): """ Gets the asset actor by the given label. """ for actor in Unreal.get_asset_actors_in_level(): if label == actor.get_actor_label(): return actor @staticmethod def has_asset_actor_with_label(label): """ Checks if the level has actors with the given label. """ for actor in Unreal.get_asset_actors_in_level(): if label == actor.get_actor_label(): return True return False @staticmethod def delete_all_asset_actors(): """ Deletes all actors from the active level that have assets assigned to them. """ actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) for actor in Unreal.get_asset_actors_in_level(): actor_subsystem.destroy_actor(actor) break @staticmethod def delete_asset_actor_with_label(label): """ Deletes the actor with the given label. """ actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) for actor in Unreal.get_asset_actors_in_level(): if label == actor.get_actor_label(): actor_subsystem.destroy_actor(actor) break class UnrealImportAsset(Unreal): def __init__(self, file_path, asset_data, property_data): """ Initializes the import with asset data and property data. :param str file_path: The full path to the file to import. :param dict asset_data: A dictionary that contains various data about the asset. :param PropertyData property_data: A property data instance that contains all property values of the tool. """ self._file_path = file_path self._asset_data = asset_data self._property_data = property_data self._import_task = unreal.AssetImportTask() self._options = None def set_skeleton(self): """ Sets a skeleton to the import options. """ skeleton_path = self._asset_data.get('skeleton_asset_path') if skeleton_path: self._options.skeleton = self.get_asset(skeleton_path) def set_physics_asset(self): """ Sets a physics asset to the import options. """ asset_path = self._asset_data.get('asset_path') physics_asset_path = self._property_data.get('unreal_physics_asset_path', {}).get('value', '') default_physics_asset = f'{asset_path}_PhysicsAsset' # try to load the provided physics asset if physics_asset_path: physics_asset = unreal.load_asset(physics_asset_path) else: physics_asset = unreal.load_asset(default_physics_asset) if physics_asset: self._options.create_physics_asset = False self._options.physics_asset = physics_asset else: self._options.create_physics_asset = True def set_static_mesh_import_options(self): """ Sets the static mesh import options. """ if self._asset_data.get('_asset_type') == 'StaticMesh': self._options.mesh_type_to_import = unreal.FBXImportType.FBXIT_STATIC_MESH self._options.static_mesh_import_data.import_mesh_lo_ds = False import_data = unreal.FbxStaticMeshImportData() self.set_settings( self._property_data['unreal']['import_method']['fbx']['static_mesh_import_data'], import_data ) self._options.static_mesh_import_data = import_data def set_skeletal_mesh_import_options(self): """ Sets the skeletal mesh import options. """ if self._asset_data.get('_asset_type') == 'SkeletalMesh': self.set_skeleton() self.set_physics_asset() self._options.mesh_type_to_import = unreal.FBXImportType.FBXIT_SKELETAL_MESH self._options.skeletal_mesh_import_data.import_mesh_lo_ds = False import_data = unreal.FbxSkeletalMeshImportData() self.set_settings( self._property_data['unreal']['import_method']['fbx']['skeletal_mesh_import_data'], import_data ) self._options.skeletal_mesh_import_data = import_data def set_animation_import_options(self): """ Sets the animation import options. """ if self._asset_data.get('_asset_type') == 'AnimSequence': self.set_skeleton() self.set_physics_asset() self._options.mesh_type_to_import = unreal.FBXImportType.FBXIT_ANIMATION import_data = unreal.FbxAnimSequenceImportData() self.set_settings( self._property_data['unreal']['import_method']['fbx']['anim_sequence_import_data'], import_data, ) self._options.anim_sequence_import_data = import_data def set_texture_import_options(self): """ Sets the texture import options. """ if self._property_data.get('import_materials_and_textures', {}).get('value', False): import_data = unreal.FbxTextureImportData() self.set_settings( self._property_data['unreal']['import_method']['fbx']['texture_import_data'], import_data ) self._options.texture_import_data = import_data def set_groom_import_options(self): """ Sets the groom import options. """ self._options = unreal.GroomImportOptions() if self._asset_data.get('_asset_type') == 'Groom': import_data = unreal.GroomConversionSettings() self.set_settings( self._property_data['unreal']['import_method']['abc']['conversion_settings'], import_data ) self._options.set_editor_property('conversion_settings', import_data) def set_fbx_import_task_options(self): """ Sets the FBX import options. """ self.set_import_task_options() import_materials_and_textures = self._property_data.get('import_materials_and_textures', {}).get('value', True) import_mesh = self._asset_data.get('_asset_type') in ['SkeletalMesh', 'StaticMesh'] import_animations = self._asset_data.get('_asset_type') == 'AnimSequence' import_as_skeletal = self._asset_data.get('_asset_type') == 'SkeletalMesh' # set the options self._options = unreal.FbxImportUI() self._options.set_editor_property('automated_import_should_detect_type', False) self._options.set_editor_property('import_mesh', import_mesh) self._options.set_editor_property('import_as_skeletal', import_as_skeletal) self._options.set_editor_property('import_animations', import_animations) self._options.set_editor_property('import_materials', import_materials_and_textures) self._options.set_editor_property('import_textures', import_materials_and_textures) # set the static mesh import options self.set_static_mesh_import_options() # add the skeletal mesh import options self.set_skeletal_mesh_import_options() # add the animation import options self.set_animation_import_options() # add the texture import options self.set_texture_import_options() def set_abc_import_task_options(self): """ Sets the ABC import options. """ # set the options self.set_import_task_options() # set the groom import options self.set_groom_import_options() def set_import_task_options(self): """ Sets common import options. """ self._import_task.set_editor_property('filename', self._file_path) self._import_task.set_editor_property('destination_path', self._asset_data.get('asset_folder')) self._import_task.set_editor_property('replace_existing', True) self._import_task.set_editor_property('replace_existing_settings', True) self._import_task.set_editor_property( 'automated', not self._property_data.get('advanced_ui_import', {}).get('value', False) ) def run_import(self): # assign the options object to the import task and import the asset self._import_task.options = self._options unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks([self._import_task]) return list(self._import_task.get_editor_property('imported_object_paths')) class UnrealImportSequence(Unreal): def __init__(self, asset_path, file_path, track_name, start=None, end=None): """ Initializes the import with asset data and property data. :param str asset_path: The project path to the asset. :param str file_path: The full file path to the import file. :param str track_name: The name of the track. :param int start: The start frame. :param int end: The end frame. """ self._asset_path = asset_path self._file_path = file_path self._track_name = track_name self._control_channel_mappings = [] self._sequence = self.get_asset(asset_path) self._control_rig_settings = unreal.MovieSceneUserImportFBXControlRigSettings() if start and end: self._control_rig_settings.start_time_range = int(start) self._control_rig_settings.end_time_range = int(end) @staticmethod def get_control_rig_mappings(): """ Set the control rig mappings. :return list[tuple]: A list channels, transforms and negations that define the control rig mappings. """ return [ (unreal.FControlRigChannelEnum.BOOL, unreal.FTransformChannelEnum.TRANSLATE_X, False), (unreal.FControlRigChannelEnum.FLOAT, unreal.FTransformChannelEnum.TRANSLATE_Y, False), (unreal.FControlRigChannelEnum.VECTOR2DX, unreal.FTransformChannelEnum.TRANSLATE_X, False), (unreal.FControlRigChannelEnum.VECTOR2DY, unreal.FTransformChannelEnum.TRANSLATE_Y, False), (unreal.FControlRigChannelEnum.POSITION_X, unreal.FTransformChannelEnum.TRANSLATE_X, False), (unreal.FControlRigChannelEnum.POSITION_Y, unreal.FTransformChannelEnum.TRANSLATE_Y, False), (unreal.FControlRigChannelEnum.POSITION_Z, unreal.FTransformChannelEnum.TRANSLATE_Z, False), (unreal.FControlRigChannelEnum.ROTATOR_X, unreal.FTransformChannelEnum.ROTATE_X, False), (unreal.FControlRigChannelEnum.ROTATOR_Y, unreal.FTransformChannelEnum.ROTATE_Y, False), (unreal.FControlRigChannelEnum.ROTATOR_Z, unreal.FTransformChannelEnum.ROTATE_Z, False), (unreal.FControlRigChannelEnum.SCALE_X, unreal.FTransformChannelEnum.SCALE_X, False), (unreal.FControlRigChannelEnum.SCALE_Y, unreal.FTransformChannelEnum.SCALE_Y, False), (unreal.FControlRigChannelEnum.SCALE_Z, unreal.FTransformChannelEnum.SCALE_Z, False) ] def set_control_mapping(self, control_channel, fbx_channel, negate): """ Sets the control mapping. :param str control_channel: The unreal enum of the control channel. :param str fbx_channel: The unreal enum of the transform channel. :param bool negate: Whether or not the mapping is negated. :return str: A list of python commands that will be run by unreal engine. """ control_map = unreal.ControlToTransformMappings() control_map.set_editor_property('control_channel', control_channel) control_map.set_editor_property('fbx_channel', fbx_channel) control_map.set_editor_property('negate', negate) self._control_maps.append(control_map) def remove_level_sequence_keyframes(self): """ Removes all key frames from the given sequence and track name. """ bindings = {binding.get_name(): binding for binding in self._sequence.get_bindings()} binding = bindings.get(self._track_name) track = binding.get_tracks()[0] section = track.get_sections()[0] for channel in section.get_channels(): for key in channel.get_keys(): channel.remove_key(key) def run_import(self, import_type='control_rig'): """ Imports key frames onto the given sequence track name from a file. :param str import_type: What type of sequence import to run. """ sequencer_tools = unreal.SequencerTools() self.remove_level_sequence_keyframes() if import_type == 'control_rig': for control_channel, fbx_channel, negate in self.get_control_rig_mappings(): self.set_control_mapping(control_channel, fbx_channel, negate) self._control_rig_settings.control_channel_mappings = self._control_channel_mappings self._control_rig_settings.insert_animation = False self._control_rig_settings.import_onto_selected_controls = False sequencer_tools.import_fbx_to_control_rig( world=unreal.EditorLevelLibrary.get_editor_world(), sequence=self._sequence, actor_with_control_rig_track=self._track_name, selected_control_rig_names=[], import_fbx_control_rig_settings=self._control_rig_settings, import_filename=self._file_path ) @rpc.factory.remote_class(remote_unreal_decorator) class UnrealRemoteCalls: @staticmethod def get_lod_count(asset_path): """ Gets the number of lods on the given asset. :param str asset_path: The path to the unreal asset. :return int: The number of lods on the asset. """ lod_count = 0 asset = Unreal.get_asset(asset_path) if asset.__class__.__name__ == 'SkeletalMesh': lod_count = unreal.get_editor_subsystem(unreal.SkeletalMeshEditorSubsystem).get_lod_count(asset) if asset.__class__.__name__ == 'StaticMesh': lod_count = unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem).get_lod_count(asset) return lod_count @staticmethod def asset_exists(asset_path): """ Checks to see if an asset exist in unreal. :param str asset_path: The path to the unreal asset. :return bool: Whether or not the asset exists. """ return bool(unreal.load_asset(asset_path)) @staticmethod def directory_exists(asset_path): """ Checks to see if a directory exist in unreal. :param str asset_path: The path to the unreal asset. :return bool: Whether or not the asset exists. """ # TODO fix this when the unreal API is fixed where it queries the registry correctly # https://jira.it.epicgames.com/project/-142234 # return unreal.EditorAssetLibrary.does_directory_exist(asset_path) return True @staticmethod def get_static_mesh_collision_info(asset_path): """ Gets the number of convex and simple collisions on a static mesh. :param str asset_path: The path to the unreal asset. :return str: The name of the complex collision. """ mesh = Unreal.get_asset(asset_path) return { 'simple': unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem).get_simple_collision_count(mesh), 'convex': unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem).get_convex_collision_count(mesh), 'customized': mesh.get_editor_property('customized_collision') } @staticmethod def get_material_index_by_name(asset_path, material_name): """ Checks to see if an asset has a complex collision. :param str asset_path: The path to the unreal asset. :param str material_name: The name of the material. :return str: The name of the complex collision. """ mesh = Unreal.get_asset(asset_path) if mesh.__class__.__name__ == 'SkeletalMesh': for index, material in enumerate(mesh.materials): if material.material_slot_name == material_name: return index if mesh.__class__.__name__ == 'StaticMesh': for index, material in enumerate(mesh.static_materials): if material.material_slot_name == material_name: return index @staticmethod def get_enabled_plugins(): """ Checks to see if the current project has certain plugins enabled. :returns: Returns a list of missing plugins if any. :rtype: list[str] """ uproject_path = unreal.Paths.get_project_file_path() with open(uproject_path, 'r') as uproject: project_data = json.load(uproject) return [plugin.get('Name') for plugin in project_data.get('Plugins', {}) if plugin.get('Enabled')] @staticmethod def get_project_settings_value(config_name, section_name, setting_name): """ Gets a specified setting value from a project settings file. Note: method only works correctly with config sections with unique setting names. :param str config_name: The config file to use in the unreal project config directory. :param str section_name: The section to query in the config file. :param str setting_name: The setting to query in the supplied section. :return: Value of the queried setting. """ engine_config_dir = unreal.Paths.project_config_dir() config_path = f'{engine_config_dir}{config_name}.ini' from configparser import ConfigParser # setting strict to False to bypass duplicate keys in the config file parser = ConfigParser(strict=False) parser.read(config_path) return parser.get(section_name, setting_name, fallback=None) @staticmethod def has_socket(asset_path, socket_name): """ Checks to see if an asset has a socket. :param str asset_path: The path to the unreal asset. :param str socket_name: The name of the socket to look for. :return bool: Whether or not the asset has the given socket or not. """ mesh = Unreal.get_asset(asset_path) return bool(mesh.find_socket(socket_name)) @staticmethod def has_binding_groom_asset(binding_asset_path, groom_asset_path): """ Checks to see if the binding asset at binding_asset_path has the groom asset set at groom_asset_path. :param str binding_asset_path: The path to the unreal binding asset. :param str groom_asset_path: The path to the unreal groom asset. :return bool: Whether or not the binding asset has the given groom. """ binding_asset = unreal.load_asset(binding_asset_path) groom_asset = unreal.load_asset(groom_asset_path) if binding_asset and groom_asset: return bool(binding_asset.get_editor_property('groom') == groom_asset) return False @staticmethod def has_binding_target(binding_asset_path, target_mesh_path): """ Checks to see if the binding asset at binding_asset_path has the target skeletal mesh asset set at target_mesh_path. :param str binding_asset_path: The path to the unreal binding asset. :param str target_mesh_path: The path to the unreal skeletal mesh asset. :return bool: Whether or not the binding asset has the given skeletal mesh target. """ binding_asset = unreal.load_asset(binding_asset_path) mesh_asset = unreal.load_asset(target_mesh_path) if binding_asset and mesh_asset: return bool(binding_asset.get_editor_property('target_skeletal_mesh') == mesh_asset) return False @staticmethod def has_groom_and_mesh_components(blueprint_asset_path, binding_asset_path, groom_asset_path, mesh_asset_path): """ Checks if a blueprint asset has mesh and groom components with the correct assets. :param str blueprint_asset_path: The path to the unreal blueprint asset. :param str binding_asset_path: The path to the unreal binding asset. :param str groom_asset_path: The path to the unreal groom asset. :param str mesh_asset_path: The path to the unreal mesh asset. :return bool: Whether the blueprint asset has the right mesh and groom components configured. """ component_handles = Unreal.get_component_handles(blueprint_asset_path) groom_handle = Unreal.get_groom_handle(component_handles, binding_asset_path, groom_asset_path) mesh_handle = Unreal.get_skeletal_mesh_handle(component_handles, mesh_asset_path) return groom_handle and mesh_handle and Unreal.is_parent_component_of_child(mesh_handle, groom_handle) @staticmethod def has_groom_component(blueprint_asset_path, binding_asset_path, groom_asset_path): """ Checks if a blueprint asset has groom component with the correct assets. :param str blueprint_asset_path: The path to the unreal blueprint asset. :param str binding_asset_path: The path to the unreal binding asset. :param str groom_asset_path: The path to the unreal groom asset. :return bool: Whether the blueprint asset has the right groom component configured. """ component_handles = Unreal.get_component_handles(blueprint_asset_path) groom_handle = Unreal.get_groom_handle(component_handles, binding_asset_path, groom_asset_path) if groom_handle: return True return False @staticmethod def has_mesh_component(blueprint_asset_path, mesh_asset_path): """ Checks if a blueprint asset has mesh component with the correct assets. :param str blueprint_asset_path: The path to the unreal blueprint asset. :param str mesh_asset_path: The path to the unreal mesh asset. :return bool: Whether the blueprint asset has the right mesh and groom components configured. """ component_handles = Unreal.get_component_handles(blueprint_asset_path) mesh_handle = Unreal.get_skeletal_mesh_handle(component_handles, mesh_asset_path) if mesh_handle: return True return False @staticmethod def has_socket_outer(asset_path, socket_name): """ Checks to see if an asset has a socket and the owner (outer) is assigned to the mesh. :param str asset_path: The path to the unreal asset. :param str socket_name: The name of the socket to look for. :return bool: Whether or not the asset has the given socket and the owner (outer) is properly assigned or not. """ mesh = Unreal.get_asset(asset_path) socket = mesh.find_socket(socket_name) if socket: return socket.get_outer() == mesh else: return False @staticmethod def delete_asset(asset_path): """ Deletes an asset in unreal. :param str asset_path: The path to the unreal asset. :return bool: Whether or not the asset was deleted. """ if unreal.EditorAssetLibrary.does_asset_exist(asset_path): unreal.EditorAssetLibrary.delete_asset(asset_path) @staticmethod def delete_directory(directory_path): """ Deletes an folder and its contents in unreal. :param str directory_path: The game path to the unreal project folder. :return bool: Whether or not the directory was deleted. """ # API BUG:cant check if exists https://jira.it.epicgames.com/project/-142234 # if unreal.EditorAssetLibrary.does_directory_exist(directory_path): unreal.EditorAssetLibrary.delete_directory(directory_path) @staticmethod def import_asset(file_path, asset_data, property_data): """ Imports an asset to unreal based on the asset data in the provided dictionary. :param str file_path: The full path to the file to import. :param dict asset_data: A dictionary of import parameters. :param dict property_data: A dictionary representation of the properties. """ # import if valid file_path was provided if file_path: unreal_import_asset = UnrealImportAsset( file_path=file_path, asset_data=asset_data, property_data=property_data ) file_path, file_type = os.path.splitext(file_path) if file_type.lower() == '.fbx': unreal_import_asset.set_fbx_import_task_options() elif file_type.lower() == '.abc': unreal_import_asset.set_abc_import_task_options() # run the import task return unreal_import_asset.run_import() @staticmethod def create_asset(asset_path, asset_class=None, asset_factory=None, unique_name=True): """ Creates a new unreal asset. :param str asset_path: The project path to the asset. :param str asset_class: The name of the unreal asset class. :param str asset_factory: The name of the unreal factory. :param bool unique_name: Whether or not the check if the name is unique before creating the asset. """ asset_class = getattr(unreal, asset_class) factory = getattr(unreal, asset_factory)() unreal_asset = Unreal.create_asset(asset_path, asset_class, factory, unique_name) return unreal_asset @staticmethod def create_binding_asset(groom_asset_path, mesh_asset_path): """ Creates a groom binding asset. :param str groom_asset_path: The unreal asset path to the imported groom asset. :param str mesh_asset_path: The unreal asset path to the associated mesh asset. :return str binding_asset_path: The unreal asset path to the created binding asset. """ return Unreal.create_binding_asset(groom_asset_path, mesh_asset_path) @staticmethod def create_blueprint_with_groom(groom_asset_path, mesh_asset_path, binding_asset_path): """ Adds a groom component to a blueprint asset with specific skeletal mesh. If queried blueprint asset does not exist, create a blueprint asset with a skeletal mesh component that has a child groom component with the imported groom asset and binding asset. :param dict groom_asset_path: The unreal asset path to the imported groom asset. :param str mesh_asset_path: The unreal asset path to the associated mesh asset. :param str binding_asset_path: The unreal asset path to the created binding asset. :return str blueprint_asset_path: The unreal path to the blueprint asset. """ return Unreal.add_groom_component_to_blueprint(groom_asset_path, mesh_asset_path, binding_asset_path) @staticmethod def import_sequence_track(asset_path, file_path, track_name, start=None, end=None): """ Initializes the import with asset data and property data. :param str asset_path: The project path to the asset. :param str file_path: The full file path to the import file. :param str track_name: The name of the track. :param int start: The start frame. :param int end: The end frame. """ unreal_import_sequence = UnrealImportSequence( asset_path=asset_path, file_path=file_path, track_name=track_name, start=start, end=start ) # run the import task unreal_import_sequence.run_import() @staticmethod def import_skeletal_mesh_lod(asset_path, file_path, index): """ Imports a lod onto a skeletal mesh. :param str asset_path: The project path to the skeletal mesh in unreal. :param str file_path: The path to the file that contains the lods on disk. :param int index: Which lod index to import the lod on. """ skeletal_mesh = Unreal.get_asset(asset_path) skeletal_mesh_subsystem = unreal.get_editor_subsystem(unreal.SkeletalMeshEditorSubsystem) result = skeletal_mesh_subsystem.import_lod(skeletal_mesh, index, file_path) if result == -1: raise RuntimeError(f"{file_path} import failed!") @staticmethod def import_static_mesh_lod(asset_path, file_path, index): """ Imports a lod onto a static mesh. :param str asset_path: The project path to the skeletal mesh in unreal. :param str file_path: The path to the file that contains the lods on disk. :param int index: Which lod index to import the lod on. """ static_mesh = Unreal.get_asset(asset_path) static_mesh_subsystem = unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem) result = static_mesh_subsystem.import_lod(static_mesh, index, file_path) if result == -1: raise RuntimeError(f"{file_path} import failed!") @staticmethod def set_skeletal_mesh_lod_build_settings(asset_path, index, property_data): """ Sets the lod build settings for skeletal mesh. :param str asset_path: The project path to the skeletal mesh in unreal. :param int index: Which lod index to import the lod on. :param dict property_data: A dictionary representation of the properties. """ skeletal_mesh = Unreal.get_asset(asset_path) skeletal_mesh_subsystem = unreal.get_editor_subsystem(unreal.SkeletalMeshEditorSubsystem) options = unreal.SkeletalMeshBuildSettings() options = Unreal.set_settings( property_data['unreal']['editor_skeletal_mesh_library']['lod_build_settings'], options ) skeletal_mesh_subsystem.set_lod_build_settings(skeletal_mesh, index, options) @staticmethod def set_static_mesh_lod_build_settings(asset_path, index, property_data): """ Sets the lod build settings for static mesh. :param str asset_path: The project path to the static mesh in unreal. :param int index: Which lod index to import the lod on. :param dict property_data: A dictionary representation of the properties. """ static_mesh = Unreal.get_asset(asset_path) static_mesh_subsystem = unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem) options = unreal.MeshBuildSettings() options = Unreal.set_settings( property_data['unreal']['editor_static_mesh_library']['lod_build_settings'], options ) static_mesh_subsystem.set_lod_build_settings(static_mesh, index, options) @staticmethod def reset_skeletal_mesh_lods(asset_path, property_data): """ Removes all lods on the given skeletal mesh. :param str asset_path: The project path to the skeletal mesh in unreal. :param dict property_data: A dictionary representation of the properties. """ skeletal_mesh = Unreal.get_asset(asset_path) skeletal_mesh_subsystem = unreal.get_editor_subsystem(unreal.SkeletalMeshEditorSubsystem) lod_count = skeletal_mesh_subsystem.get_lod_count(skeletal_mesh) if lod_count > 1: skeletal_mesh.remove_lo_ds(list(range(1, lod_count))) lod_settings_path = property_data.get('unreal_skeletal_mesh_lod_settings_path', {}).get('value', '') if lod_settings_path: data_asset = Unreal.get_asset(asset_path) skeletal_mesh.lod_settings = data_asset skeletal_mesh_subsystem.regenerate_lod(skeletal_mesh, new_lod_count=lod_count) @staticmethod def reset_static_mesh_lods(asset_path): """ Removes all lods on the given static mesh. :param str asset_path: The project path to the static mesh in unreal. """ static_mesh = Unreal.get_asset(asset_path) static_mesh_subsystem = unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem) lod_count = static_mesh_subsystem.get_lod_count(static_mesh) if lod_count > 1: static_mesh_subsystem.remove_lods(static_mesh) @staticmethod def set_static_mesh_sockets(asset_path, asset_data): """ Sets sockets on a static mesh. :param str asset_path: The project path to the skeletal mesh in unreal. :param dict asset_data: A dictionary of import parameters. """ static_mesh = Unreal.get_asset(asset_path) for socket_name, socket_data in asset_data.get('sockets').items(): socket = unreal.StaticMeshSocket(static_mesh) # apply the socket settings socket.set_editor_property('relative_location', socket_data.get('relative_location')) socket.set_editor_property('relative_rotation', socket_data.get('relative_rotation')) socket.set_editor_property('relative_scale', socket_data.get('relative_scale')) socket.set_editor_property('socket_name', socket_name) # if that socket already exists remove it existing_socket = static_mesh.find_socket(socket_name) if existing_socket: static_mesh.remove_socket(existing_socket) # create a new socket static_mesh.add_socket(socket) @staticmethod def get_lod_build_settings(asset_path, index): """ Gets the lod build settings from the given asset. :param str asset_path: The project path to the asset. :param int index: The lod index to check. :return dict: A dictionary of lod build settings. """ build_settings = None mesh = Unreal.get_asset(asset_path) if not mesh: raise RuntimeError(f'"{asset_path}" was not found in the unreal project!') if mesh.__class__.__name__ == 'SkeletalMesh': skeletal_mesh_subsystem = unreal.get_editor_subsystem(unreal.SkeletalMeshEditorSubsystem) build_settings = skeletal_mesh_subsystem.get_lod_build_settings(mesh, index) if mesh.__class__.__name__ == 'StaticMesh': static_mesh_subsystem = unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem) build_settings = static_mesh_subsystem.get_lod_build_settings(mesh, index) return Unreal.object_attributes_to_dict(build_settings) @staticmethod def get_bone_path_to_root(asset_path, bone_name): """ Gets the path to the root bone from the given skeleton. :param str asset_path: The project path to the asset. :param str bone_name: The name of the bone to start from. :return list: A list of bone name all the way to the root bone. """ animation = Unreal.get_asset(asset_path) path = unreal.AnimationLibrary.find_bone_path_to_root(animation, bone_name) return [str(i) for i in path] @staticmethod def get_bone_transform_for_frame(asset_path, bone_name, frame): """ Gets the transformations of the given bone on the given frame. :param str asset_path: The project path to the asset. :param str bone_name: The name of the bone to get the transforms of. :param float frame: The frame number. :return dict: A dictionary of transformation values. """ animation = Unreal.get_asset(asset_path) path = unreal.AnimationLibrary.find_bone_path_to_root(animation, bone_name) transform = unreal.AnimationLibrary.get_bone_pose_for_frame(animation, bone_name, frame, True) world_rotation = unreal.Rotator() world_location = unreal.Transform() for bone in path: bone_transform = unreal.AnimationLibrary.get_bone_pose_for_frame(animation, str(bone), frame, True) world_rotation = world_rotation.combine(bone_transform.rotation.rotator()) world_location = world_location.multiply(bone_transform) return { 'scale': transform.scale3d.to_tuple(), 'world_rotation': world_rotation.transform().rotation.euler().to_tuple(), 'local_rotation': transform.rotation.euler().to_tuple(), 'world_location': world_location.translation.to_tuple(), 'local_location': transform.translation.to_tuple() } @staticmethod def get_bone_count(skeleton_path): """ Gets the bone count from the given skeleton. :param str skeleton_path: The project path to the skeleton. :return int: The number of bones. """ skeleton = unreal.load_asset(skeleton_path) return len(skeleton.get_editor_property('bone_tree')) @staticmethod def get_origin(asset_path): """ Gets the location of the assets origin. :param str asset_path: The project path to the asset. :return list: A list of bone name all the way to the root bone. """ mesh = Unreal.get_asset(asset_path) return mesh.get_bounds().origin.to_tuple() @staticmethod def get_morph_target_names(asset_path): """ Gets the name of the morph targets on the given asset. :param str asset_path: The project path to the asset. :return list[str]: A list of morph target names. """ skeletal_mesh = Unreal.get_asset(asset_path) return list(skeletal_mesh.get_all_morph_target_names()) @staticmethod def get_sequence_track_keyframe(asset_path, track_name, curve_name, frame): """ Gets the transformations of the given bone on the given frame. :param str asset_path: The project path to the asset. :param str track_name: The name of the track. :param str curve_name: The curve name. :param float frame: The frame number. :return dict: A dictionary of transformation values. """ sequence = unreal.load_asset(asset_path) bindings = {binding.get_name(): binding for binding in sequence.get_bindings()} binding = bindings.get(track_name) track = binding.get_tracks()[0] section = track.get_sections()[0] data = {} for channel in section.get_channels(): if channel.get_name().startswith(curve_name): for key in channel.get_keys(): if key.get_time().frame_number.value == frame: data[channel.get_name()] = key.get_value() return data @staticmethod def import_animation_fcurves(asset_path, fcurve_file_path): """ Imports fcurves from a file onto an animation sequence. :param str asset_path: The project path to the skeletal mesh in unreal. :param str fcurve_file_path: The file path to the fcurve file. """ animation_sequence = Unreal.get_asset(asset_path) with open(fcurve_file_path, 'r') as fcurve_file: fcurve_data = json.load(fcurve_file) for fcurve_name, keys in fcurve_data.items(): unreal.AnimationLibrary.add_curve(animation_sequence, fcurve_name) for key in keys: unreal.AnimationLibrary.add_float_curve_key(animation_sequence, fcurve_name, key[0], key[1]) @staticmethod def does_curve_exist(asset_path, curve_name): """ Checks if the fcurve exists on the animation sequence. :param str asset_path: The project path to the skeletal mesh in unreal. :param str curve_name: The fcurve name. """ animation_sequence = Unreal.get_asset(asset_path) return unreal.AnimationLibrary.does_curve_exist( animation_sequence, curve_name, unreal.RawCurveTrackTypes.RCT_FLOAT ) @staticmethod def instance_asset(asset_path, location, rotation, scale, label): """ Instances the given asset into the active level. :param str asset_path: The project path to the asset in unreal. :param list location: The unreal actor world location. :param list rotation: The unreal actor world rotation. :param list scale: The unreal actor world scale. :param str label: The unreal actor label. """ asset = Unreal.get_asset(asset_path) actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) # if the unique name is found delete it if Unreal.has_asset_actor_with_label(label): Unreal.delete_asset_actor_with_label(label) # spawn the actor actor = actor_subsystem.spawn_actor_from_object( asset, location, rotation=rotation, transient=False ) actor.set_actor_label(label) # set the transforms of the actor with the tag that matches the unique name actor = Unreal.get_asset_actor_by_label(label) if actor: actor.set_actor_transform( new_transform=unreal.Transform( location=location, rotation=rotation, scale=scale ), sweep=False, teleport=True ) @staticmethod def delete_all_asset_actors(): """ Deletes all asset actors from the current level. """ Unreal.delete_all_asset_actors() @staticmethod def get_asset_actor_transforms(label): """ Get the transforms for the provided actor. :param str label: The unreal actor label. :returns: A dictionary of transforms. :rtype: dict """ actor = Unreal.get_asset_actor_by_label(label) if actor: root_component = actor.get_editor_property('root_component') return { 'location': root_component.get_world_location().to_tuple(), 'rotation': root_component.get_world_rotation().to_tuple(), 'scale': root_component.get_world_scale().to_tuple(), }
# -*- coding: utf-8 -*- import unreal def do_some_things(*args, **kwargs): unreal.log("do_some_things start:") for arg in args: unreal.log(arg) unreal.log("do_some_things end.")
# coding: utf-8 import unreal import argparse print("VRM4U python begin") print (__file__) parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") parser.add_argument("-meta") args = parser.parse_args() print(args.vrm) #print(dummy[3]) humanoidBoneList = [ "hips", "leftUpperLeg", "rightUpperLeg", "leftLowerLeg", "rightLowerLeg", "leftFoot", "rightFoot", "spine", "chest", "upperChest", # 9 optional "neck", "head", "leftShoulder", "rightShoulder", "leftUpperArm", "rightUpperArm", "leftLowerArm", "rightLowerArm", "leftHand", "rightHand", "leftToes", "rightToes", "leftEye", "rightEye", "jaw", "leftThumbProximal", # 24 "leftThumbIntermediate", "leftThumbDistal", "leftIndexProximal", "leftIndexIntermediate", "leftIndexDistal", "leftMiddleProximal", "leftMiddleIntermediate", "leftMiddleDistal", "leftRingProximal", "leftRingIntermediate", "leftRingDistal", "leftLittleProximal", "leftLittleIntermediate", "leftLittleDistal", "rightThumbProximal", "rightThumbIntermediate", "rightThumbDistal", "rightIndexProximal", "rightIndexIntermediate", "rightIndexDistal", "rightMiddleProximal", "rightMiddleIntermediate", "rightMiddleDistal", "rightRingProximal", "rightRingIntermediate", "rightRingDistal", "rightLittleProximal", "rightLittleIntermediate", "rightLittleDistal", #54 ] humanoidBoneParentList = [ "", #"hips", "hips",#"leftUpperLeg", "hips",#"rightUpperLeg", "leftUpperLeg",#"leftLowerLeg", "rightUpperLeg",#"rightLowerLeg", "leftLowerLeg",#"leftFoot", "rightLowerLeg",#"rightFoot", "hips",#"spine", "spine",#"chest", "chest",#"upperChest" 9 optional "chest",#"neck", "neck",#"head", "chest",#"leftShoulder", # <-- upper.. "chest",#"rightShoulder", "leftShoulder",#"leftUpperArm", "rightShoulder",#"rightUpperArm", "leftUpperArm",#"leftLowerArm", "rightUpperArm",#"rightLowerArm", "leftLowerArm",#"leftHand", "rightLowerArm",#"rightHand", "leftFoot",#"leftToes", "rightFoot",#"rightToes", "head",#"leftEye", "head",#"rightEye", "head",#"jaw", "leftHand",#"leftThumbProximal", "leftThumbProximal",#"leftThumbIntermediate", "leftThumbIntermediate",#"leftThumbDistal", "leftHand",#"leftIndexProximal", "leftIndexProximal",#"leftIndexIntermediate", "leftIndexIntermediate",#"leftIndexDistal", "leftHand",#"leftMiddleProximal", "leftMiddleProximal",#"leftMiddleIntermediate", "leftMiddleIntermediate",#"leftMiddleDistal", "leftHand",#"leftRingProximal", "leftRingProximal",#"leftRingIntermediate", "leftRingIntermediate",#"leftRingDistal", "leftHand",#"leftLittleProximal", "leftLittleProximal",#"leftLittleIntermediate", "leftLittleIntermediate",#"leftLittleDistal", "rightHand",#"rightThumbProximal", "rightThumbProximal",#"rightThumbIntermediate", "rightThumbIntermediate",#"rightThumbDistal", "rightHand",#"rightIndexProximal", "rightIndexProximal",#"rightIndexIntermediate", "rightIndexIntermediate",#"rightIndexDistal", "rightHand",#"rightMiddleProximal", "rightMiddleProximal",#"rightMiddleIntermediate", "rightMiddleIntermediate",#"rightMiddleDistal", "rightHand",#"rightRingProximal", "rightRingProximal",#"rightRingIntermediate", "rightRingIntermediate",#"rightRingDistal", "rightHand",#"rightLittleProximal", "rightLittleProximal",#"rightLittleIntermediate", "rightLittleIntermediate",#"rightLittleDistal", ] for i in range(len(humanoidBoneList)): humanoidBoneList[i] = humanoidBoneList[i].lower() for i in range(len(humanoidBoneParentList)): humanoidBoneParentList[i] = humanoidBoneParentList[i].lower() ###### reg = unreal.AssetRegistryHelpers.get_asset_registry(); ## rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r #rig = rigs[10] hierarchy = unreal.ControlRigBlueprintLibrary.get_hierarchy(rig) h_con = hierarchy.get_controller() #elements = h_con.get_selection() #sk = rig.get_preview_mesh() #k = sk.skeleton #print(k) #print(sk.bone_tree) # #kk = unreal.RigElementKey(unreal.RigElementType.BONE, "hipssss"); #kk.name = "" #kk.type = 1; #print(h_con.get_bone(kk)) #print(h_con.get_elements()) ### 全ての骨 modelBoneListAll = [] modelBoneNameList = [] #for e in reversed(h_con.get_elements()): # if (e.type != unreal.RigElementType.BONE): # h_con.remove_element(e) for e in hierarchy.get_bones(): if (e.type == unreal.RigElementType.BONE): modelBoneListAll.append(e) modelBoneNameList.append("{}".format(e.name).lower()) # else: # h_con.remove_element(e) print(modelBoneListAll[0]) #exit #print(k.get_editor_property("bone_tree")[0].get_editor_property("translation_retargeting_mode")) #print(k.get_editor_property("bone_tree")[0].get_editor_property("parent_index")) #unreal.select #vrmlist = unreal.VrmAssetListObject #vrmmeta = vrmlist.vrm_meta_object #print(vrmmeta.humanoid_bone_table) #selected_actors = unreal.EditorLevelLibrary.get_selected_level_actors() #selected_static_mesh_actors = unreal.EditorFilterLibrary.by_class(selected_actors,unreal.StaticMeshActor.static_class()) #static_meshes = np.array([]) ## meta 取得 reg = unreal.AssetRegistryHelpers.get_asset_registry(); a = reg.get_all_assets(); if (args.meta): for aa in a: if (aa.get_editor_property("object_path") == args.meta): v:unreal.VrmMetaObject = aa vv = aa.get_asset() if (vv == None): for aa in a: if (aa.get_editor_property("object_path") == args.vrm): v:unreal.VrmAssetListObject = aa vv = v.get_asset().vrm_meta_object print(vv) meta = vv #v:unreal.VrmAssetListObject = None #if (True): # a = reg.get_assets_by_path(args.vrm) # a = reg.get_all_assets(); # for aa in a: # if (aa.get_editor_property("object_path") == args.vrm): # v:unreal.VrmAssetListObject = aa #v = unreal.VrmAssetListObject.cast(v) #print(v) #unreal.VrmAssetListObject.vrm_meta_object #meta = v.vrm_meta_object() #meta = unreal.EditorFilterLibrary.by_class(asset,unreal.VrmMetaObject.static_class()) print (meta) #print(meta[0].humanoid_bone_table) ### モデル骨のうち、ヒューマノイドと同じもの ### 上の変換テーブル humanoidBoneToModel = {"" : ""} humanoidBoneToModel.clear() ### modelBoneでループ #for bone_h in meta.humanoid_bone_table: for bone_h_base in humanoidBoneList: bone_h = None for e in meta.humanoid_bone_table: if ("{}".format(e).lower() == bone_h_base): bone_h = e; break; print("{}".format(bone_h)) if (bone_h==None): continue bone_m = meta.humanoid_bone_table[bone_h] try: i = modelBoneNameList.index(bone_m.lower()) except: i = -1 if (i < 0): continue if ("{}".format(bone_h).lower() == "upperchest"): continue; humanoidBoneToModel["{}".format(bone_h).lower()] = "{}".format(bone_m).lower() if ("{}".format(bone_h).lower() == "chest"): #upperchestがあれば、これの次に追加 bh = 'upperchest' print("upperchest: check begin") for e in meta.humanoid_bone_table: if ("{}".format(e).lower() != 'upperchest'): continue bm = "{}".format(meta.humanoid_bone_table[e]).lower() if (bm == ''): continue humanoidBoneToModel[bh] = bm humanoidBoneParentList[10] = "upperchest" humanoidBoneParentList[12] = "upperchest" humanoidBoneParentList[13] = "upperchest" print("upperchest: find and insert parent") break print("upperchest: check end") parent=None control_to_mat={None:None} count = 0 ### 骨名からControlへのテーブル name_to_control = {"dummy_for_table" : None} print("loop begin") ###### root key = unreal.RigElementKey(unreal.RigElementType.NULL, 'root_s') space = hierarchy.find_null(key) if (space.get_editor_property('index') < 0): space = h_con.add_null('root_s', space_type=unreal.RigSpaceType.SPACE) else: space = key key = unreal.RigElementKey(unreal.RigElementType.CONTROL, 'root_c') control = hierarchy.find_control(key) if (control.get_editor_property('index') < 0): control = h_con.add_control('root_c', space_name=space.name, gizmo_color=[1.0, 0.0, 0.0, 1.0], ) else: control = key h_con.set_parent(control, space) parent = control setting = h_con.get_control_settings(control) setting.shape_visible = False h_con.set_control_settings(control, setting) for ee in humanoidBoneToModel: element = humanoidBoneToModel[ee] humanoidBone = ee modelBoneNameSmall = element # 対象の骨 #modelBoneNameSmall = "{}".format(element.name).lower() #humanoidBone = modelBoneToHumanoid[modelBoneNameSmall]; boneNo = humanoidBoneList.index(humanoidBone) print("{}_{}_{}__parent={}".format(modelBoneNameSmall, humanoidBone, boneNo,humanoidBoneParentList[boneNo])) # 親 if count != 0: parent = name_to_control[humanoidBoneParentList[boneNo]] # 階層作成 bIsNew = False name_s = "{}_s".format(humanoidBone) key = unreal.RigElementKey(unreal.RigElementType.NULL, name_s) space = hierarchy.find_null(key) if (space.get_editor_property('index') < 0): space = h_con.add_space(name_s, space_type=unreal.RigSpaceType.SPACE) bIsNew = True else: space = key name_c = "{}_c".format(humanoidBone) key = unreal.RigElementKey(unreal.RigElementType.CONTROL, name_c) control = hierarchy.find_control(key) if (control.get_editor_property('index') < 0): control = h_con.add_control(name_c, space_name=space.name, gizmo_color=[1.0, 0.0, 0.0, 1.0], ) #h_con.get_control(control).gizmo_transform = gizmo_trans if (24<=boneNo & boneNo<=53): gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.1, 0.1, 0.1]) else: gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1, 1, 1]) if (17<=boneNo & boneNo<=18): gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1, 1, 1]) cc = h_con.get_control(control) cc.set_editor_property('gizmo_transform', gizmo_trans) cc.set_editor_property('control_type', unreal.RigControlType.ROTATOR) h_con.set_control(cc) #h_con.set_control_value_transform(control,gizmo_trans) bIsNew = True else: control = key if (bIsNew == True): h_con.set_parent(control, space) # テーブル登録 name_to_control[humanoidBone] = control print(humanoidBone) # ロケータ 座標更新 # 不要な上層階層を考慮 gTransform = hierarchy.get_global_transform(modelBoneListAll[modelBoneNameList.index(modelBoneNameSmall)]) if count == 0: bone_initial_transform = gTransform else: #bone_initial_transform = h_con.get_initial_transform(element) bone_initial_transform = gTransform.multiply(control_to_mat[parent].inverse()) hierarchy.set_global_transform(space, gTransform, True) control_to_mat[control] = gTransform # 階層修正 h_con.set_parent(space, parent) count += 1 if (count >= 500): break
# _ # (_) # _ __ ___ __ _ _ __ ___ ___ _ __ _ ___ _ __ ___ # | '_ ` _ \ / _` | '_ ` _ \ / _ \| '_ \| |/ _ \ '_ ` _ \ # | | | | | | (_| | | | | | | (_) | | | | | __/ | | | | | # |_| |_| |_|\__,_|_| |_| |_|\___/|_| |_|_|\___|_| |_| |_| # www.mamoniem.com # www.ue4u.xyz #Copyright 2022 Muhammad A.Moniem (@_mamoniem). All Rights Reserved. # import unreal workingPath = "/Game/" @unreal.uclass() class GetEditorAssetLibrary(unreal.EditorAssetLibrary): pass editorAssetLib = GetEditorAssetLibrary(); allAssets = editorAssetLib.list_assets(workingPath, True, False) processingAssetPath = "" allAssetsCount = len(allAssets) if ( allAssetsCount > 0): with unreal.ScopedSlowTask(allAssetsCount, processingAssetPath) as slowTask: slowTask.make_dialog(True) for asset in allAssets: processingAssetPath = asset deps = editorAssetLib.find_package_referencers_for_asset(asset, False) if (len(deps) <= 0): print (">>> Deleting >>> %s" % asset) editorAssetLib.delete_asset(asset) if slowTask.should_cancel(): break slowTask.enter_progress_frame(1, processingAssetPath)
import unreal import json import os # === Use tkinter to open Windows file dialog === import tkinter as tk from tkinter import filedialog def choose_json_file(): root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename( title="Choose JSON File", filetypes=[("JSON Files", "*.json")], initialdir="H:/project/" ) return file_path if file_path else None # === Select JSON File === json_path = choose_json_file() if not json_path: unreal.log_error("No JSON file selected. Aborting.") raise SystemExit() # === Paths === content_root = "/Game/" content_dir = "H:/project/" # === Load JSON Data === with open(json_path, 'r') as f: data = json.load(f) # === Global Configuration === GLOBAL_SCALE = unreal.Vector(1.0, 1.0, 1.0) spawned_count = 0 def safe_scale(vec): return unreal.Vector( max(min(vec.x, 100.0), 0.01), max(min(vec.y, 100.0), 0.01), max(min(vec.z, 100.0), 0.01) ) def create_convex_brush(convex_elem, location, rotation, scale, name): verts = convex_elem.get("VertexData", []) if not verts: return None brush = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.Brush, location, rotation) if not brush: return None converted = [unreal.Vector(v["X"] * scale.x, v["Y"] * scale.y, v["Z"] * scale.z) for v in verts] builder = unreal.BrushBuilder() builder.poly_flag = 0 builder.vertices = converted brush.set_actor_label(name + "_Brush") print(f"🧱 Created convex brush for {name} with {len(converted)} verts") return brush def spawn_light_actor(obj_type, props, name, rot, scl): loc_data = props.get("RelativeLocation", {"X": 0, "Y": 0, "Z": 0}) loc = unreal.Vector(loc_data["X"], loc_data["Y"], loc_data["Z"]) light_class_map = { "PointLightComponent": unreal.PointLight, "SpotLightComponent": unreal.SpotLight, "RectLightComponent": unreal.RectLight } actor_class = light_class_map.get(obj_type) if not actor_class: return actor = unreal.EditorLevelLibrary.spawn_actor_from_class(actor_class, loc, rot) if not actor: return actor.set_actor_scale3d(scl) actor.set_actor_label(name) # Manually grab the first matching light component components = actor.get_components_by_class(unreal.LightComponentBase) light_component = components[0] if components else None if not light_component: return if props.get("Intensity") is not None: light_component.set_editor_property("intensity", props["Intensity"]) if props.get("CastShadows") is not None: light_component.set_editor_property("cast_shadows", props["CastShadows"]) color_data = props.get("LightColor") if color_data: color = unreal.Color( r=int(color_data["R"]), g=int(color_data["G"]), b=int(color_data["B"]), a=int(color_data.get("A", 255)) ) light_component.set_editor_property("light_color", color) for prop_name in ["SourceRadius", "SoftSourceRadius", "SourceWidth", "SourceHeight"]: if props.get(prop_name) is not None: uprop = prop_name[0].lower() + prop_name[1:] try: light_component.set_editor_property(uprop, props[prop_name]) except Exception as e: print(f"⚠️ Could not set property '{uprop}': {e}") print(f"💡 Spawned {obj_type}: {name} at {loc} with rotation {rot} and scale {scl}") for obj in data: props = obj.get("Properties") or {} obj_type = obj.get("Type", "") name = obj.get("Name", "Unnamed") location = obj.get("RelativeLocation") or props.get("RelativeLocation", {"X": 0, "Y": 0, "Z": 0}) rotation = obj.get("RelativeRotation") or props.get("RelativeRotation", {"Pitch": 0, "Yaw": 0, "Roll": 0}) scale = props.get("RelativeScale3D", {"X": 1, "Y": 1, "Z": 1}) loc = unreal.Vector(location["X"], location["Y"], location["Z"]) rot = unreal.Rotator(rotation["Roll"], rotation["Pitch"], rotation["Yaw"]) scl = unreal.Vector(scale["X"], scale["Y"], scale["Z"]) * GLOBAL_SCALE # === Lighting === if obj_type in ["PointLightComponent", "SpotLightComponent", "RectLightComponent"]: spawn_light_actor(obj_type, props, name, rot, scl) spawned_count += 1 continue if obj_type == "BlockingVolume" and "BodySetup" in props: convex_elems = props["BodySetup"].get("AggGeom", {}).get("ConvexElems", []) for i, convex in enumerate(convex_elems): create_convex_brush(convex, loc, rot, scl, f"{name}_Part{i}") spawned_count += 1 continue elif "StaticMesh" in props and isinstance(props["StaticMesh"], dict): mesh_path_raw = props["StaticMesh"].get("ObjectPath", "") if mesh_path_raw: mesh_file = os.path.basename(mesh_path_raw).split(".")[0] print(f"🕵️‍♂️ Searching for mesh: {mesh_file}") found_path = None for root, _, files in os.walk(content_dir): for file in files: if file.lower() == mesh_file.lower() + ".uasset": relative = os.path.relpath(root, content_dir).replace("\\", "/") found_path = content_root + relative + "/" + mesh_file print(f"✅ Found asset: {found_path}") break if found_path: break if found_path: static_mesh = unreal.EditorAssetLibrary.load_asset(found_path) if static_mesh and isinstance(static_mesh, unreal.StaticMesh): actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.StaticMeshActor, loc, rot) if actor: actor.set_actor_scale3d(scl) actor.set_actor_label(name) smc = actor.static_mesh_component smc.set_static_mesh(static_mesh) smc.set_editor_property("mobility", unreal.ComponentMobility.MOVABLE) print(f"🧱 Placed StaticMeshActor: {name} using mesh {found_path}") spawned_count += 1 else: print(f"❌ Failed to spawn actor for {name}") else: print(f"⚠️ Asset found but not a valid StaticMesh: {found_path} for {name}") else: print(f"❌ Could not locate asset for mesh: {mesh_file} (original path: {mesh_path_raw})") continue actor_class = unreal.BlockingVolume if obj_type == "BlockingVolume" else unreal.Actor actor = unreal.EditorLevelLibrary.spawn_actor_from_class(actor_class, loc, rot) if actor: actor.set_actor_scale3d(scl) actor.set_actor_label(name) spawned_count += 1 print(f"✅ Spawned {obj_type}: {name} at {loc} with rotation {rot} and scale {scl}") print(f"🎉 Total objects placed: {spawned_count}")
# Copyright (c) <2021> Side Effects Software Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. The name of Side Effects Software may not be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN # NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unreal """ Example script for instantiating an asset, setting parameters, cooking it and iterating over and logging all of its output objects. """ _g_wrapper = None def get_test_hda_path(): return '/project/.pig_head_subdivider_v01' def get_test_hda(): return unreal.load_object(None, get_test_hda_path()) def on_post_instantiation(in_wrapper): print('on_post_instantiation') # in_wrapper.on_post_instantiation_state_exited_delegate_delegate.remove_callable(on_post_instantiation) # Set parameter values for the next cook # in_wrapper.set_bool_parameter_value('add_instances', True) # in_wrapper.set_int_parameter_value('num_instances', 8) in_wrapper.set_parameter_tuples({ 'add_instances': unreal.HoudiniParameterTuple(bool_values=(True, )), 'num_instances': unreal.HoudiniParameterTuple(int32_values=(8, )), }) # Print all parameter values param_tuples = in_wrapper.get_parameter_tuples() print('parameter tuples: {}'.format(len(param_tuples) if param_tuples else 0)) if param_tuples: for param_tuple_name, param_tuple in param_tuples.items(): print('parameter tuple name: {}'.format(param_tuple_name)) print('\tbool_values: {}'.format(param_tuple.bool_values)) print('\tfloat_values: {}'.format(param_tuple.float_values)) print('\tint32_values: {}'.format(param_tuple.int32_values)) print('\tstring_values: {}'.format(param_tuple.string_values)) # Force a cook/recook in_wrapper.recook() def on_post_process(in_wrapper): print('on_post_process') # in_wrapper.on_post_processing_delegate.remove_callable(on_post_process) # Print out all outputs generated by the HDA num_outputs = in_wrapper.get_num_outputs() print('num_outputs: {}'.format(num_outputs)) if num_outputs > 0: for output_idx in range(num_outputs): identifiers = in_wrapper.get_output_identifiers_at(output_idx) print('\toutput index: {}'.format(output_idx)) print('\toutput type: {}'.format(in_wrapper.get_output_type_at(output_idx))) print('\tnum_output_objects: {}'.format(len(identifiers))) if identifiers: for identifier in identifiers: output_object = in_wrapper.get_output_object_at(output_idx, identifier) output_component = in_wrapper.get_output_component_at(output_idx, identifier) is_proxy = in_wrapper.is_output_current_proxy_at(output_idx, identifier) print('\t\tidentifier: {}'.format(identifier)) print('\t\toutput_object: {}'.format(output_object.get_name() if output_object else 'None')) print('\t\toutput_component: {}'.format(output_component.get_name() if output_component else 'None')) print('\t\tis_proxy: {}'.format(is_proxy)) print('') def run(): # get the API singleton api = unreal.HoudiniPublicAPIBlueprintLib.get_api() global _g_wrapper # instantiate an asset, disabling auto-cook of the asset (so we have to # call wrapper.reCook() to cook it) _g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform(), enable_auto_cook=False) # Bind to the on post instantiation delegate (before the first cook) _g_wrapper.on_post_instantiation_delegate.add_callable(on_post_instantiation) # Bind to the on post processing delegate (after a cook and after all # outputs have been generated in Unreal) _g_wrapper.on_post_processing_delegate.add_callable(on_post_process) if __name__ == '__main__': run()
import unreal workingPath = "/Game/" @unreal.uclass() class GetEditorAssetLibrary(unreal.EditorAssetLibrary): pass editorAssetLib = GetEditorAssetLibrary(); allAssets = editorAssetLib.list_assets(workingPath, True, False) if (len(allAssets) > 0): for asset in allAssets: deps = editorAssetLib.find_package_referencers_for_asset(asset, False) if (len(deps) == 0): print (">>>%s" % asset)
# Copyright Epic Games, Inc. All Rights Reserved """ This script handles processing jobs for a specific queue asset """ import unreal from .render_queue_jobs import render_jobs from .utils import ( get_asset_data, movie_pipeline_queue, update_queue ) def setup_queue_parser(subparser): """ This method adds a custom execution function and args to a queue subparser :param subparser: Subparser for processing custom sequences """ # Set the name of the job subparser.add_argument( "queue", type=str, help="The name or path to a movie pipeline queue." ) # Add option to only load the contents of the queue. By default, # this will only load the queue and render its contents subparser.add_argument( "--load", action="store_true", help="Load the contents of the queue asset. By default the queue asset will loaded and render its contents.", ) # We will use the level sequence and the map as our context for # other subsequence arguments. subparser.add_argument( "--jobs", type=str, nargs="+", help="A list of jobs to execute in the queue. " "If no jobs are provided, all jobs in the queue will be rendered.", ) # Function to process arguments subparser.set_defaults(func=_process_args) def render_queue_asset( queue_name, only_load=False, shots=None, jobs=None, all_shots=False, is_cmdline=False, is_remote=False, user=None, remote_batch_name=None, remote_job_preset=None, executor_instance=None, output_dir_override=None, output_filename_override=None ): """ Render using a Movie Render Queue asset :param str queue_name: The name of the Queue asset :param bool only_load: Only load the queue asset. This is usually used when you need to process intermediary steps before rendering :param list shots: Shots to render from the queue. :param list jobs: The list job to render in the Queue asset. :param bool all_shots: Flag to render all shots in a job in the queue. :param bool is_cmdline: Flag to determine if the job is a commandline job :param bool is_remote: Flag to determine if the jobs should be rendered remote :param str user: Render user :param str remote_batch_name: Batch name for remote renders :param str remote_job_preset: Remote render job preset :param executor_instance: Movie Pipeline executor instance :param str output_dir_override: Movie Pipeline output directory override :param str output_filename_override: Movie Pipeline filename format override :return: MRQ Executor """ # The queue subsystem behaves like a singleton so # clear all the jobs in the current queue. movie_pipeline_queue.delete_all_jobs() # Get the queue data asset package path by name or by path # Create a new queue from the queue asset movie_pipeline_queue.copy_from( get_asset_data(queue_name, "MoviePipelineQueue").get_asset() ) # If we only want to load the queue asset, then exit after loading. # If we want to shut down the editor as well, then do so if only_load: if is_cmdline: unreal.SystemLibrary.quit_editor() return None if not movie_pipeline_queue.get_jobs(): # Make sure we have jobs in the queue to work with raise RuntimeError("There are no jobs in the queue!!") # Allow executing the render queue in its current loaded state if all_shots or (any([shots, jobs])): update_queue( jobs=jobs, shots=shots, all_shots=all_shots, user=user ) try: # Execute the render. This will execute the render based on whether # its remote or local executor = render_jobs( is_remote, remote_batch_name=remote_batch_name, remote_job_preset=remote_job_preset, is_cmdline=is_cmdline, executor_instance=executor_instance, output_dir_override=output_dir_override, output_filename_override=output_filename_override ) except Exception: raise return executor def _process_args(args): """ Function to process the arguments for the sequence subcommand :param args: Parsed Arguments from parser """ return render_queue_asset( args.queue, only_load=args.load, shots=args.shots, jobs=args.jobs, all_shots=args.all_shots, is_remote=args.remote, is_cmdline=args.cmdline, user=args.user, remote_batch_name=args.batch_name, remote_job_preset=args.deadline_job_preset, output_dir_override=args.output_override, output_filename_override=args.filename_override )
from os import listdir import os from os.path import isfile, join import unreal import csv import string import unicodedata import argparse ##Command line to run without editor open ## /project/-Cmd.exe /project/.uproject -run=pythonscript -script="/project/.py" class USendToUnreal: #csv filepaths ''' standardMaterials (instances) material name, customMaterials (master materials) mesh locations ''' ##material parameters variables. baseColorParamName = "BaseColor" metallicParamName = "Metallic" roughnessParamName = "Roughness" aoParamName = "AmbientOcclusion" ormParamName = "ORM" useOrm = False normalParamName = "Normal" subSurfaceColorParamName = "Subsurface Color Map" subSurfaceTransParamName = "Subsurface Intensity Mask" alphaTextureParamName = "Opacity Mask" baseColorTintParamName = "BaseColor Tint" alphaConstParamValName = "Opacity" parentMaterialPath = '/project/' ###directories #import from rootImportFolder = "C:/project/ Projects/UE4-VirtualProductionTools/project/" materialInstanceCSVPath = rootImportFolder + "MaterialInstanceImport.csv" textureCSVPath = rootImportFolder + "TextureImport.csv" fbxName = "scene.fbx" fbxPath = rootImportFolder + fbxName UEsceneName = "fish" #Import directory folder structure ''' Root Master latest.fbx latest.blend latest.csv/py for importing thumbnail.img turntable.mov? Textures latest.img Versions V001 name_V001.fbx name_V001.blend ... V002 ... WIP latest.blend add a dropdown to switch between versions with notes and such ''' #import to UEMeshDirectory = '/project/' UEMaterialDirectory = '/project/' UETextureDirectory = '/project/' UEMakeNewFolderPerMesh = False UEMaterialDirectoryToSearch = '/project/' #where to look for a library of materials before creating a new one UEMeshDirectoryToSearch = '/project/' #where to look for standard meshes for referenced objects #MetadataTagsToAddToObject - make as a txt file that appends per version. Version, date, comment #current version = "001" #add function to increment this number #rootImportFolder #artist notes #Import setup AssetTools = unreal.AssetToolsHelpers.get_asset_tools() EditorLibrary = unreal.EditorAssetLibrary automateImports = True def queryMaterials(self): print("query materials") asset_reg = unreal.AssetRegistryHelpers.get_asset_registry() filter = unreal.ARFilter(class_names=["MaterialInstanceConstant"], recursive_paths=False, include_only_on_disk_assets=True,package_paths=[self.UEMaterialDirectory]) assets = asset_reg.get_assets(filter) ret = "query materials: "+ str(assets) print(ret) return ret def queryEnvironments(self): print("query environment") path = unreal.Paths.project_content_dir() ret = unreal.Paths.convert_relative_path_to_full(path) print(ret) return ret def runBlutility(self, path = ""):#TODO: Cast test to make sure it can execute & see if autorun = true if self.EditorLibrary.does_asset_exist(path): blutility = self.EditorLibrary.load_asset(path)#.get_default_object() utilitySubsytem = unreal.EditorUtilitySubsystem() utilitySubsytem.try_run(blutility) def openEditorWidget(self, path = ""): #TODO: Cast test to make sure it can execute if self.EditorLibrary.does_asset_exist(path): editorWidget = self.EditorLibrary.load_asset(path) utilitySubsytem = unreal.EditorUtilitySubsystem() utilitySubsytem.spawn_and_register_tab(editorWidget) def getparameters(self): #TODO set configuration from a file - use argument pass def buildFbxImportOptions(self): '''TODO set the below values in saved - config - editorperprojectusersettings.ini and figure out how to hotload. Or set them using C++ [/project/.FbxSceneImportOptions] bCreateContentFolderHierarchy=False bImportAsDynamic=False HierarchyType=FBXSOCHT_CreateActorComponents bForceFrontXAxis=False bBakePivotInVertex=False bImportStaticMeshLODs=False bImportSkeletalMeshLODs=False bInvertNormalMaps=False ''' options = unreal.FbxImportUI() options.set_editor_property('import_mesh',True) options.set_editor_property('import_materials',False) #TODO: Set to false and assign materials per mesh. Does not work with FBX scenes. maybe wipe mats after import? options.set_editor_property('import_textures',False) #in this process, materials go into the same folder, and then we restructure them after the fact options.set_editor_property('import_as_skeletal',False) options.set_editor_property('override_full_name',False) options.static_mesh_import_data.set_editor_property('combine_meshes',False) options.static_mesh_import_data.set_editor_property('generate_lightmap_u_vs',True) #TODO: use lightmaps from blender if available options.static_mesh_import_data.set_editor_property('auto_generate_collision',True) options.static_mesh_import_data.set_editor_property('normal_import_method',unreal.FBXNormalImportMethod.FBXNIM_IMPORT_NORMALS_AND_TANGENTS) #FBXNIM_COMPUTE_NORMALS FBXNIM_IMPORT_NORMALS FBXNIM_IMPORT_NORMALS_AND_TANGENTS TODO decide if this is the best option options.static_mesh_import_data.set_editor_property('reorder_material_to_fbx_order',True) options.static_mesh_import_data.set_editor_property('convert_scene',False) options.static_mesh_import_data.set_editor_property('convert_scene_unit',True) options.static_mesh_import_data.set_editor_property('transform_vertex_to_absolute',True) options.static_mesh_import_data.set_editor_property('bake_pivot_in_vertex',True) #options.static_mesh_import_data.set_editor_property('convert_scene',True) #options.static_mesh_import_data.set_editor_property('force_front_x_axis ',False) ''' auto_generate_collision (bool): [Read-Write] If checked, collision will automatically be generated (ignored if custom collision is imported or used). bake_pivot_in_vertex (bool): [Read-Write] - Experimental - If this option is true the inverse node rotation pivot will be apply to the mesh vertices. The pivot from the DCC will then be the origin of the mesh. Note: “TransformVertexToAbsolute” must be false. build_adjacency_buffer (bool): [Read-Write] Required for PNT tessellation but can be slow. Recommend disabling for larger meshes. build_reversed_index_buffer (bool): [Read-Write] Build Reversed Index Buffer /combine_meshes (bool): [Read-Write] If enabled, combines all meshes into a single mesh compute_weighted_normals (bool): [Read-Write] Enabling this option will use weighted normals algorithm (area and angle) when computing normals or tangents /convert_scene (bool): [Read-Write] Convert the scene from FBX coordinate system to UE4 coordinate system /convert_scene_unit (bool): [Read-Write] Convert the scene from FBX unit to UE4 unit (centimeter). /force_front_x_axis (bool): [Read-Write] Convert the scene from FBX coordinate system to UE4 coordinate system with front X axis instead of -Y generate_lightmap_u_vs (bool): [Read-Write] Generate Lightmap UVs import_mesh_lo_ds (bool): [Read-Write] If enabled, creates LOD models for Unreal meshes from LODs in the import file; If not enabled, only the base mesh from the LOD group is imported import_rotation (Rotator): [Read-Write] Import Rotation import_translation (Vector): [Read-Write] Import Translation import_uniform_scale (float): [Read-Write] Import Uniform Scale normal_generation_method (FBXNormalGenerationMethod): [Read-Write] Use the MikkTSpace tangent space generator for generating normals and tangents on the mesh normal_import_method (FBXNormalImportMethod): [Read-Write] Enabling this option will read the tangents(tangent,binormal,normal) from FBX file instead of generating them automatically. one_convex_hull_per_ucx (bool): [Read-Write] If checked, one convex hull per UCX_ prefixed collision mesh will be generated instead of decomposing into multiple hulls remove_degenerates (bool): [Read-Write] Disabling this option will keep degenerate triangles found. In general you should leave this option on. reorder_material_to_fbx_order (bool): [Read-Write] If checked, The material list will be reorder to the same order has the FBX file. source_data (AssetImportInfo): [Read-Only] Source file data describing the files that were used to import this asset. static_mesh_lod_group (Name): [Read-Write] The LODGroup to associate with this mesh when it is imported transform_vertex_to_absolute (bool): [Read-Write] If this option is true the node absolute transform (transform, offset and pivot) will be apply to the mesh vertices. vertex_color_import_option (VertexColorImportOption): [Read-Write] Specify how vertex colors should be imported vertex_override_color (Color): [Read-Write] Specify override color in the case that VertexColorImportOption is set to Override ''' return options def legalizeName(self,text): #valid_chars = "-_ %s%s" % (string.ascii_letters, string.digits) #text = unicodedata.normalize('NFKD', text).encode('ASCII', 'ignore') #return ''.join(c for c in text if c in valid_chars) return text def createMaterialInstance(self , NewMatName = "MI_test",parameterNames = [], parameters = []): EditorLibrary=self.EditorLibrary if parameters[3] == "y" or parameters[3] == "True" or parameters[3] == "yes": writeParameters = True else: writeParameters = False if unreal.EditorAssetLibrary.does_asset_exist(self.UEMaterialDirectory + '/' + self.legalizeName(NewMatName)): #unreal.log_warning("material already exists, skipping") #TODO if the overwrite command is set, set parameters for that material anyway. NewMaterial = unreal.EditorAssetLibrary.load_asset(self.UEMaterialDirectory + '/' + self.legalizeName(NewMatName)) else: writeParameters = True NewMaterial = self.AssetTools.create_asset(asset_name=self.legalizeName(NewMatName),package_path=self.UEMaterialDirectory,asset_class = unreal.MaterialInstanceConstant, factory=unreal.MaterialInstanceConstantFactoryNew()) #EditorLibrary.save_asset(NewMaterial.get_path_name(),True) #TODO Fix error? if writeParameters ==True: index = 0 for parameterName in parameterNames: try: if index == 2: unreal.log("foundParent") parentPath = parameters[index] if not parentPath.startswith("/"): parentPath = "/"+parentPath if EditorLibrary.does_asset_exist(parentPath): unreal.log("parent confirmed") parentMaterial = EditorLibrary.load_asset(parentPath) unreal.MaterialEditingLibrary.set_material_instance_parent(NewMaterial,parentMaterial) else: unreal.log_error("No parent material found for:" + NewMaterial.get_path_name()) break elif parameterName.startswith('T_') and parameters[index]: if parameters[index].startswith('/Game/'): texPath = parameters[index] else: texPath = UEImporter.UEMaterialDirectory + "/"+parameters[index] if EditorLibrary.does_asset_exist(texPath): unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value(NewMaterial,parameterName[2:],EditorLibrary.load_asset(texPath)) else: unreal.log_warning("Texture not found for ")# + NewMaterial.get_path_name() + ": " + parameters[index]) #TODO FIX ERROR ? elif parameterName.startswith('S_') and parameters[index]: #unreal.log("foundScalar") unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(NewMaterial,parameterName[2:],float(parameters[index])) elif parameterName.startswith('V_') and parameters[index]: unreal.log("foundVector3") colorfour = parameters[index] if colorfour.startswith("["): colorfour = colorfour [1:-1] colorfour = colorfour.split(",") color = unreal.LinearColor(r=float(colorfour[0]), g=float(colorfour[1]), b=float(colorfour[2]), a=1) unreal.MaterialEditingLibrary.set_material_instance_vector_parameter_value(NewMaterial,parameterName[2:],color) ''' doesn't work elif parameterName.startswith('B_') and parameters[index]: unreal.log("foundBool") unreal.MaterialEditingLibrary.set_material_instance_boolean_parameter_value(NewMaterial,parameterName[2:],False) #if parameters[index] == "True" or parameters[index] == "TRUE" or parameters[index] == "yes" or parameters[index] == "yes" or parameters[index] == "true" or parameters[index] == "y": # unreal.MaterialEditingLibrary.set_material_instance_boolean_parameter_value(NewMaterial,parameterName[2:],True) #elif parameters[index] == "False" or parameters[index] == "FALSE" or parameters[index] == "false" or parameters[index] == "FALSE" or parameters[index] == "no" or parameters[index] == "n": # unreal.MaterialEditingLibrary.set_material_instance_boolean_parameter_value(NewMaterial,parameterName[2:],False) ''' except Exception: unreal.log("no index") unreal.log_warning(index) index += 1 return def createTexture(self , filepath = '', importLocation = '' , overwrite = "" , textureName = "test"): import_tasks = [] if overwrite == "y" or overwrite == "True" or overwrite == "yes" or overwrite == "Y" or overwrite == "TRUE" or overwrite == "true": replace = True else: replace = False if "." in textureName: textureName = textureName.split(".")[0] textureName = self.legalizeName(textureName) if unreal.EditorAssetLibrary.does_asset_exist(importLocation + '/' + textureName):# or not replace: unreal.log_warning("texture " + textureName + " already exists, skipping") else: if not os.path.exists(filepath): if os.path.exists(os.path.join(UEImporter.rootImportFolder,filepath)): filepath = os.path.join(UEImporter.rootImportFolder,filepath) else: filepath = os.path.join(UEImporter.rootImportFolder,"textures",filepath) #unreal.log_error(filepath) if os.path.exists(filepath): AssetImportTask = unreal.AssetImportTask() AssetImportTask.set_editor_property('filename', filepath) AssetImportTask.set_editor_property('destination_path', importLocation) AssetImportTask.set_editor_property('replace_existing',True) AssetImportTask.set_editor_property('save', True) import_tasks.append(AssetImportTask) self.AssetTools.import_asset_tasks(import_tasks) #import all textures def readTextureCSV(self): #TODO: search for texture in directory and link to that if it exists (swap in materials csv?) #TODO: figure out how to mark a texture as used in the surfaces directory in blender. Can do in UE4 try: with open(self.textureCSVPath, mode='r') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 parameterNames = [] for row in csv_reader: if line_count == 0: unreal.log("Parameters To Import: " + " | ".join(row)) parameterNames = row line_count += 1 else: #Add texture to import list self.createTexture(filepath = row[1], importLocation = self.UETextureDirectory, overwrite = row[4], textureName = row[0]) line_count += 1 unreal.log('Processed ' + str(line_count-1) + ' textures') unreal.EditorAssetLibrary.save_directory(self.UETextureDirectory) except Exception: unreal.log_warning("Issue reading texture csv file") def readMaterialInstanceCSV(self): try: with open(self.materialInstanceCSVPath, mode='r') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 parameterNames = [] for row in csv_reader: if line_count == 0: unreal.log("Parameters To Import: " + " | ".join(row)) parameterNames = row line_count += 1 else: self.createMaterialInstance(NewMatName = row[1],parameterNames = parameterNames, parameters = row) #unreal.log("row:" + str(line_count) + " :".join(row)) line_count += 1 unreal.log('Processed ' + str(line_count-1) + ' materials') #TODO: search for textures before import unreal.EditorAssetLibrary.save_directory(self.UEMaterialDirectory) except Exception: unreal.log_warning("Issue reading material csv file") def importfbxstack(self): #FBX scene ''' data = unreal.AutomatedAssetImportData() data.set_editor_property('destination_path', self.UEMeshDirectory) data.set_editor_property('filenames', [self.fbxPath]) #data.set_editor_property('level_to_load', '/project/') data.set_editor_property('replace_existing', True) factory = unreal.FbxSceneImportFactory() data.set_editor_property('factory', factory) unreal.AssetToolsHelpers.get_asset_tools().import_assets_automated(data) ''' ###delete all static meshes in directory unreal.EditorAssetLibrary.save_directory(self.UEMeshDirectory) #save directory we imported into unreal.EditorAssetLibrary.does_directory_have_assets(self.UEMeshDirectory, recursive=True) registry = unreal.AssetRegistryHelpers.get_asset_registry() assetsinfolder = registry.get_assets_by_path(self.UEMeshDirectory,False,False) #assetsinfolder = unreal.EditorAssetLibrary.list_assets(self.UEMeshDirectory, recursive=False, include_folder=False) #staticMeshes = unreal.EditorFilterLibrary.by_class( assetsinfolder , unreal.StaticMeshActor) for deletedmesh in assetsinfolder: #unreal.log_warning(deletedmesh.asset_class) if str(deletedmesh.asset_class) == 'StaticMesh' or str(deletedmesh.asset_class) == 'DataTable': #unreal.log_warning("delete") unreal.EditorAssetLibrary.delete_asset(deletedmesh.package_name) #FBX normal #set up the import import_tasks = [] #factory = unreal.FbxSceneImportFactory() factory = unreal.FbxFactory() fbxPath = self.rootImportFolder + self.fbxName factory.script_factory_can_import(fbxPath) ##########use this to test if the file is an FBX AssetImportTask = unreal.AssetImportTask() AssetImportTask.set_editor_property('filename', fbxPath) AssetImportTask.set_editor_property('factory', factory) AssetImportTask.set_editor_property('destination_path', self.UEMeshDirectory) AssetImportTask.set_editor_property('automated', True)#self.automateImports) AssetImportTask.set_editor_property('options', self.buildFbxImportOptions()) AssetImportTask.set_editor_property('save', False) import_tasks.append(AssetImportTask) #do the import self.AssetTools.import_asset_tasks(import_tasks) unreal.log_warning("starting Rename") #rename the fbxs to the correct format #unreal.EditorAssetLibrary.does_directory_have_assets("/Game/", recursive=True) meshesInFolder = unreal.AssetRegistryHelpers.get_asset_registry().get_assets_by_path(self.UEMeshDirectory, recursive=True, include_only_on_disk_assets=False) #static_mesh_objects = [data.get_asset() for data in static_mesh_data] #unreal.log_warning(len(meshesInFolder)) for renamedmesh in meshesInFolder: #unreal.log_warning("testingasset") #unreal.log_warning(str(renamedmesh.asset_name)) if str(renamedmesh.asset_class) == 'StaticMesh': unreal.log_warning(renamedmesh) oldMeshName = renamedmesh.object_path #.package_name unreal.log_warning(oldMeshName) newMeshName = str(renamedmesh.object_path).rpartition(".")[2] if newMeshName == self.fbxName[0:-3]: True else: unreal.log_warning(newMeshName) newMeshName = newMeshName[len(self.fbxName)-3:] unreal.log_warning(newMeshName) if newMeshName[0:4] == "prep": #remove prep from the start of the name if it exists newMeshName = newMeshName[4:] newMeshName = str(renamedmesh.package_path) + "/" + newMeshName unreal.log_warning("4:"+newMeshName) #newMeshName = self.UEMeshDirectory + str(oldMeshName).rpartition("/") if True: #start of code to reassign static mesh materials per object in content browser assetObject = renamedmesh.get_asset() unreal.log_warning(assetObject) mesh = unreal.StaticMesh.cast(assetObject) for material_index in range(0,mesh.get_num_sections(0)): material_name = mesh.get_material(material_index).get_name() unreal.log_error(material_name) #mesh.set_material(material_index, new_material) #unreal.log_warning("rename: "+ str(renamedmesh.object_path) + " to " + str(renamedmesh.package_name) + " to " + str(renamedmesh.package_path))#+ str(newMeshName)) #TODO unreal.log_warning("rename: "+ str(oldMeshName) + " to " + newMeshName) unreal.EditorAssetLibrary.rename_asset(oldMeshName , newMeshName) #unreal.EditorAssetLibrary.save_directory(self.UEMeshDirectory) #save directory we imported into #does_directory_have_assets(directory_path, recursive=True) TODO does the tool delete any copies of the meshes already out in the world? ''' actors = unreal.EditorLevelLibrary.get_all_level_actors() for actor in actors: #delete the imported actor if actor.get_actor_location() == unreal.Vector(x=0.0, y=0.0, z=0.0) and self.fbxName[0:-4] in actor.get_actor_label(): if actor.get_component_by_class(unreal.StaticMeshComponent) != None: mesh = actor.get_component_by_class(unreal.StaticMeshComponent).static_mesh path = self.UEMeshDirectory in unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(mesh) if path: unreal.EditorLevelLibrary.destroy_actor(actor) ''' #Fbx automated sample code ''' #Fbx automated task factory = unreal.FbxFactory() factory.set_editor_property('options',self.buildFbxImportOptions()) assetImportData = unreal.AutomatedAssetImportData() #factory.script_factory_can_import(filename) ##########use this to test if the file is an FBX assetImportData.set_editor_property('filenames', [self.fbxPath]) assetImportData.set_editor_property('destination_path', self.UEMeshDirectory) assetImportData.set_editor_property('factory',factory ) #Pointer to the factory currently being used #assetImportData.set_editor_property('factory_name', ) #Name of the factory to use when importing these assets. If not specified the factory type will be auto detected assetImportData.set_editor_property('group_name',"BlenderFiles") #Display name of the group. This is for logging purposes only. assetImportData.set_editor_property('replace_existing',True) assetImportData.set_editor_property('skip_read_only',False) #Whether or not to skip importing over read only assets that could not be checked out importedFiles = self.AssetTools.import_assets_automated(assetImportData) ''' unreal.EditorAssetLibrary.save_directory(self.UEMeshDirectory) #save directories we imported into def createBlueprintScene(self): # New Asset Name try: newname = self.fbxName.partition('.')[0] if newname[0:3] == "SM_": #todo if there are any other prefixes in the future, test for them asset_name = "ASB_"+ newname[3:] h_name = "ASH_"+ newname[3:] elif newname[0:4] == "CAM_": #todo if there are any other prefixes in the future, test for them asset_name = "ASB_"+ newname[4:] h_name = "ASH_"+ newname[4:] elif newname[0:4] == "LGT_": #todo if there are any other prefixes in the future, test for them asset_name = "ASB_"+ newname[4:] h_name = "ASH_"+ newname[4:] else: asset_name = "ASB_"+ newname h_name = "ASH_"+ newname # Save Path package_path = self.UEMeshDirectory unreal.log_warning(package_path) # Derive a Class from a string path root_class = '/project/.B2UAdgBridge_ImportedSceneObject' root_class_generated = root_class + "_C" root_class_loaded = unreal.EditorAssetLibrary.load_asset(root_class) # Derive a BlueprintGeneratedClass from a UBlueprint # If you have a C++ class, you can replace all this with just ue.CPPCLASSNAMEHERE parent_class = unreal.get_default_object(unreal.load_object(None, root_class_generated)).get_class() # Factory Setup factory = unreal.BlueprintFactory() factory.set_editor_property("ParentClass", parent_class) # Get Asset Tools asset_tools = unreal.AssetToolsHelpers.get_asset_tools() #todo test if asset already exists. If so, do not try to create a new one? # Create Asset childBP = asset_tools.create_asset(asset_name, package_path, root_class_loaded.static_class(), factory) #bp_gc = unreal.EditorAssetLibrary.load_blueprint_class(childBP.get_path_name()) #bp_cdo = unreal.get_default_object(bp_gc) bploc = package_path + "/" + asset_name + "." + asset_name + "_C" bp_cdo = unreal.get_default_object(unreal.load_object(None, bploc)) unreal.log_warning(h_name) bp_cdo.set_editor_property('Hierarchy', unreal.load_object(None, package_path + "/" + h_name + "." + h_name)) sceneactor = unreal.EditorLevelLibrary.spawn_actor_from_class(bp_cdo.get_class(),unreal.Vector(x=0.0, y=0.0, z=0.0)) #spawn the imported geo out into the world. TODO decide if I want to test to see if there is already a scene out in the world unreal.EditorAssetLibrary.save_directory(self.UEMeshDirectory) #save directory we imported into unreal.EditorAssetLibrary.sync_browser_to_objects([bploc]) except Exception: unreal.log_warning("Issue creating ASM blueprint") def importHierarchyCSV(self): try: newname = self.fbxName.partition('.')[0] if newname[0:3] == "SM_": #todo if there are any other prefixes in the future, test for them newname = "ASH_"+ newname[3:] elif newname[0:4] == "CAM_": #todo if there are any other prefixes in the future, test for them newname = "ASH_"+ newname[4:] elif newname[0:4] == "LGT_": #todo if there are any other prefixes in the future, test for them newname = "ASH_"+ newname[4:] else: newname = "ASH_"+ newname asset_name = newname import_tasks = [] factory = unreal.CSVImportFactory() csvPath = self.rootImportFolder + asset_name + '.csv' #todo at some point fix the hierarchy name so it is unique per import factory.script_factory_can_import(csvPath) # AssetImportTask = unreal.AssetImportTask() AssetImportTask.set_editor_property('filename', csvPath) AssetImportTask.set_editor_property('factory', factory) AssetImportTask.set_editor_property('destination_path', self.UEMeshDirectory) AssetImportTask.set_editor_property('automated', True)#self.automateImports) importSettings = unreal.CSVImportSettings() #importSettings.set_editor_property('import_row_struct',True) path_to_asset = '/project/'#.B2UADGBrige_MeshHierarcyCSV' asset_reg = unreal.AssetRegistryHelpers.get_asset_registry() #CSVstruct = asset_reg.get_asset_by_object_path(path_to_asset) CSVstruct = unreal.load_asset(path_to_asset) #unreal.log_warning(str(CSVstruct)) factory.automated_import_settings.import_row_struct = CSVstruct #AssetImportTask.set_editor_property('save', False) import_tasks.append(AssetImportTask) #do the import self.AssetTools.import_asset_tasks(import_tasks) unreal.EditorAssetLibrary.save_directory(self.UEMeshDirectory) #save directory we imported into except Exception: unreal.log("Issue with hierarcy file") # Initialize parser parser = argparse.ArgumentParser() # Adding optional argument parser.add_argument("-i", "--hardDiskPath", help = "Root of path to files for import") #"C:/project/ Projects/UE4-VirtualProductionTools/project/" parser.add_argument("-mp", "--UnrealMeshPath", help = "Unreal folder to import mesh into") #'/project/' parser.add_argument("-fn", "--FBXName", help = "Name of fbx to import name.fbx") #"scene.fbx" parser.add_argument("-tp", "--UnrealTexturePath",help = "Unreal Folder to import textures into") parser.add_argument("-mt", "--UnrealMatPath",help = "Unreal Folder to import materials into") parser.add_argument("-q", "--query", help = "query unreal for info on the current project") parser.add_argument("-s", "--simple", help = "if this argument is set, the import will not include an ash or asb file in the folder") # Read arguments from command line args = parser.parse_args() UEImporter = USendToUnreal() if args.UnrealMatPath: if args.UnrealMatPath.endswith("/"): args.UnrealMatPath = args.UnrealMatPath[0:len(args.UnrealMatPath)-1] if args.UnrealMeshPath and args.hardDiskPath and args.FBXName: #test with #BlenderToUnrealADGBridge_Import.py -i "C:/project/ Projects/UE4-VirtualProductionTools/project/" -mp "/project/" -fn "scene.fbx" unreal.log_warning("Importing FBX from: % s" % args.hardDiskPath) unreal.log_warning("to: % s" % args.UnrealMeshPath) UEImporter.rootImportFolder = args.hardDiskPath UEImporter.UEMeshDirectory = args.UnrealMeshPath UEImporter.fbxName = args.FBXName UEImporter.UEMaterialDirectory = args.UnrealMatPath UEImporter.UETextureDirectory = args.UnrealTexturePath newname = UEImporter.fbxName.partition('.')[0] if newname[0:3] == "SM_": #todo if there are any other prefixes in the future, test for them UEImporter.materialInstanceCSVPath = UEImporter.rootImportFolder + "ASM_"+ newname[3:] + ".csv" UEImporter.textureCSVPath = UEImporter.rootImportFolder +"AST_"+ newname[3:] + ".csv" elif newname[0:4] == "CAM_": #todo if there are any other prefixes in the future, test for them UEImporter.materialInstanceCSVPath = UEImporter.rootImportFolder + "ASM_"+ newname[4:] + ".csv" UEImporter.textureCSVPath = UEImporter.rootImportFolder +"AST_"+ newname[4:] + ".csv" elif newname[0:4] == "LGT_": #todo if there are any other prefixes in the future, test for them UEImporter.materialInstanceCSVPath = UEImporter.rootImportFolder + "ASM_"+ newname[4:] + ".csv" UEImporter.textureCSVPath = UEImporter.rootImportFolder +"AST_"+ newname[4:] + ".csv" else: UEImporter.materialInstanceCSVPath = UEImporter.rootImportFolder + "ASM_" + newname +".csv" UEImporter.textureCSVPath = UEImporter.rootImportFolder +"AST_"+ newname +".csv" UEImporter.readTextureCSV() UEImporter.readMaterialInstanceCSV() UEImporter.importfbxstack() if not args.simple: UEImporter.importHierarchyCSV() UEImporter.createBlueprintScene() elif args.query: if args.query == "m" and args.UnrealMatPath: UEImporter.UEMaterialDirectory = args.UnrealMatPath UEImporter.queryMaterials() if args.query == "env": UEImporter.queryEnvironments() else: unreal.log_warning("not enough or incorrect arguments") #fish.runBlutility('/project/') #fish.openEditorWidget('/project/') #fish.runBlutility('/project/') #import csv file ''' from unreal_engine.classes import AssetImportTask from unreal_engine.classes import CSVImportFactory fpath = fpath = '/project/.csv' dpath = '/project/' # Create the AssetImportTask object ait = AssetImportTask() ait.Filename = fpath ait.DestinationPath = dpath ait.bAutomated = True ait.bSave = True # Create the factory csv_factory = CSVImportFactory() csv_factory.AutomatedImportSettings.ImportRowStruct = MyCustomDataTableStruct csv_factory.AssetImportTask = ait # Actually import the table # You probably don't need to specify the paths twice as I'm doing here. csv_factory.factory_import_object(fpath, dpath) ''' #tests to do before this mess all happens: ''' is the folder empty? ''' #write Csv ''' import csv with open('employee_file.csv', mode='w') as employee_file: employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) employee_writer.writerow(['John Smith', 'Accounting', 'November']) employee_writer.writerow(['Erica Meyers', 'IT', 'March']) ''' #make a material sample code ''' NewMatName = "MI_test" NewMaterial = AssetTools.create_asset(asset_name=NewMatName,package_path='/project/',asset_class = unreal.MaterialInstanceConstant, factory=unreal.MaterialInstanceConstantFactoryNew()) EditorLibrary.save_asset(NewMaterial.get_path_name(),True) parentMaterial = EditorLibrary.load_asset(parentMaterialPath) unreal.MaterialEditingLibrary.set_material_instance_parent(NewMaterial,parentMaterial) #SetTextureParameterValueEditorOnly(FMaterialParameterInfo("Diffuse"), GetTextureByName(Textures[animaMat->mDiffuseIndex].mName, ConnectionSlot:iffuseSlot)); ''' #ue4 functions ''' set_material_instance_scalar_parameter_value(instance, parameter_name, value) set_material_instance_texture_parameter_value(instance, parameter_name, value) set_material_instance_vector_parameter_value(instance, parameter_name, value) update_material_instance(instance) unreal.EditorAssetLibrary.checkout_asset(asset_to_checkout) .does_asset_exist(asset_path) .duplicate_asset(source_asset_path, destination_asset_path) .duplicate_loaded_asset(source_asset, destination_asset_path) .get_path_name_for_loaded_asset(loaded_asset) .set_metadata_tag(object, tag, value) .checkout_asset(asset_to_checkout) .make_directory(directory_path) .rename_asset(source_asset_path, destination_asset_path) .sync_browser_to_objects(asset_paths) .load_asset(asset_path) ''' #checks to create ''' material naming conventions mesh naming conventions + object to mesh name very small objects units ''' #sample Code ''' ##import all .jpg files found in a directory into UE4 texturedir = "/project/" #folder from which all textures should be imported files = [f for f in listdir(texturedir) if isfile(join(dir, f)) and f[-3:]=='jpg'] for f in files: print join(dir, f) AssetImportTask = unreal.AssetImportTask() AssetImportTask.set_editor_property('filename', join(dir, f)) AssetImportTask.set_editor_property('destination_path', '/project/') AssetImportTask.set_editor_property('save', True) import_tasks.append(AssetImportTask) AssetTools.import_asset_tasks(import_tasks) ##################printing to the log unreal.log_error() unreal.log_warning() unreal.log() ####################### display progressbar total_frames = 100 text_label = "Working!" with unreal.ScopedSlowTask(total_frames, text_label) as slow_task: slow_task.make_dialog(True) # Makes the dialog visible, if it isn't already for i in range(total_frames): if slow_task.should_cancel(): # True if the user has pressed Cancel in the UI break slow_task.enter_progress_frame(1) # Advance progress by one frame. # You can also update the dialog text in this call, if you want. ... # Now do work for the current frame here! ''' #valid filename notes ''' Just to further complicate things, you are not guaranteed to get a valid filename just by removing invalid characters. Since allowed characters differ on different filenames, a conservative approach could end up turning a valid name into an invalid one. You may want to add special handling for the cases where: The string is all invalid characters (leaving you with an empty string) You end up with a string with a special meaning, eg "." or ".." On windows, certain device names are reserved. For instance, you can't create a file named "nul", "nul.txt" (or nul.anything in fact) The reserved names are: CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9 You can probably work around these issues by prepending some string to the filenames that can never result in one of these cases, and stripping invalid characters. '''
# coding: utf-8 import unreal import argparse print("VRM4U python begin") print (__file__) parser = argparse.ArgumentParser() parser.add_argument("-rigSrc") parser.add_argument("-rigDst") args = parser.parse_args() #print(args.vrm) ###### ## rig 取得 reg = unreal.AssetRegistryHelpers.get_asset_registry(); a = reg.get_all_assets(); for aa in a: if (aa.get_editor_property("object_path") == args.rigSrc): rigSrc = aa.get_asset() if (aa.get_editor_property("object_path") == args.rigDst): rigDst = aa.get_asset() print(rigSrc) print(rigDst) modSrc = rigSrc.get_hierarchy_modifier() modDst = rigDst.get_hierarchy_modifier() conSrc = rigSrc.controller conDst = rigDst.controller graSrc = conSrc.get_graph() graDst = conDst.get_graph() modDst.initialize() print(rig[3]) meta = vv rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() rig = rigs[0] h_mod = rig.get_hierarchy_modifier() elements = h_mod.get_selection() c = rig.controller g = c.get_graph() n = g.get_nodes() print(n) #c.add_branch_node() #c.add_array_pin() a:unreal.RigUnit_CollectionItems = unreal.RigUnit_CollectionItems() print(a) # 配列ノード追加 collectionItem_forControl:unreal.RigVMStructNode = None collectionItem_forBone:unreal.RigVMStructNode = None for node in n: if (node.get_node_title() == 'Items'): #print(node.get_node_title()) #node = unreal.RigUnit_CollectionItems.cast(node) pin = node.find_pin('Items') print(pin.get_array_size()) print(pin.get_default_value()) if (pin.get_array_size() < 40): continue if 'Type=Bone' in pin.get_default_value(): collectionItem_forBone= node if 'Type=Control' in pin.get_default_value(): collectionItem_forControl = node #nn = unreal.EditorFilterLibrary.by_class(n,unreal.RigUnit_CollectionItems.static_class()) # controller array if (collectionItem_forControl == None): collectionItem_forControl = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute') items_forControl = collectionItem_forControl.find_pin('Items') c.clear_array_pin(items_forControl.get_pin_path()) # bone array if (collectionItem_forBone == None): collectionItem_forBone = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute') items_forBone = collectionItem_forBone.find_pin('Items') c.clear_array_pin(items_forBone.get_pin_path()) ## h_mod rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() rig = rigs[0] h_mod = rig.get_hierarchy_modifier() ## meta 取得 reg = unreal.AssetRegistryHelpers.get_asset_registry(); a = reg.get_all_assets(); for aa in a: if (aa.get_editor_property("object_path") == args.vrm): v:unreal.VrmAssetListObject = aa vv = v.get_asset().vrm_meta_object print(vv) meta = vv for bone_h in meta.humanoid_bone_table: bone_m = meta.humanoid_bone_table[bone_h] try: i = humanoidBoneList.index(bone_h.lower()) except: i = -1 if (i >= 0): tmp = '(Type=Bone,Name=' tmp += "{}".format(bone_m).lower() tmp += ')' c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp) #print(bone_m) tmp = '(Type=Control,Name=' tmp += "{}".format(bone_h).lower() + '_c' tmp += ')' c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp) #print(bone_h) #for e in h_mod.get_elements(): # if (e.type == unreal.RigElementType.CONTROL): # tmp = '(Type=Control,Name=' # tmp += "{}".format(e.name) # tmp += ')' # c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp) # print(e.name) # if (e.type == unreal.RigElementType.BONE): # tmp = '(Type=Bone,Name=' # tmp += "{}".format(e.name) # tmp += ')' # c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp) # print(e.name) #print(i.get_all_pins_recursively()) #ii:unreal.RigUnit_CollectionItems = n[1] #pp = ii.get_editor_property('Items') #print(pp) #print(collectionItem.get_all_pins_recursively()[0]) #i.get_editor_property("Items") #c.add_array_pin("Execute") # arrayを伸ばす #i.get_all_pins_recursively()[0].get_pin_path() #c.add_array_pin(i.get_all_pins_recursively()[0].get_pin_path(), default_value='(Type=Bone,Name=Global)') #rig = rigs[10]
# Should be used with internal UE API in later versions of UE """ Automatically create material instances based on texture names (as they are similar to material names) """ import unreal import os OVERWRITE_EXISTING = False def set_material_instance_texture(material_instance_asset, material_parameter, texture_path): if not unreal.editor_asset_library.does_asset_exist(texture_path): unreal.log_warning("Can't find texture: " + texture_path) return False tex_asset = unreal.editor_asset_library.find_asset_data(texture_path).get_asset() return unreal.material_editing_library.set_material_instance_texture_parameter_value(material_instance_asset, material_parameter, tex_asset) base_material = unreal.editor_asset_library.find_asset_data("/project/") AssetTools = unreal.AssetToolsHelpers.get_asset_tools() MaterialEditingLibrary = unreal.material_editing_library EditorAssetLibrary = unreal.editor_asset_library def create_material_instance(material_instance_folder, texture_folder, texture_name): texture_base_name = "_".join(texture_name.split("_")[1:-1]).replace("RT", "").replace("LT", "") material_instance_name = "MI_" + texture_base_name material_instance_path = os.path.join(material_instance_folder, material_instance_name) if EditorAssetLibrary.does_asset_exist(material_instance_path): # material_instance_asset = EditorAssetLibrary.find_asset_data(material_instance_path).get_asset() unreal.log("Asset already exists") if OVERWRITE_EXISTING: EditorAssetLibrary.delete_asset(material_instance_path) else: return material_instance_asset = AssetTools.create_asset(material_instance_name, material_instance_folder, unreal.MaterialInstanceConstant, unreal.MaterialInstanceConstantFactoryNew()) # Set parent material MaterialEditingLibrary.set_material_instance_parent(material_instance_asset, base_material.get_asset()) base_color_texture = os.path.join(texture_folder, "T_" + texture_base_name + "_BC").replace("\\", "/") if EditorAssetLibrary.does_asset_exist(base_color_texture): set_material_instance_texture(material_instance_asset, "Base Color", base_color_texture) print(base_color_texture) mask_texture = os.path.join(texture_folder, "T_" + texture_base_name + "_M").replace("\\", "/") if EditorAssetLibrary.does_asset_exist(mask_texture): set_material_instance_texture(material_instance_asset, "Mask", mask_texture) normal_texture = os.path.join(texture_folder, "T_" + texture_base_name + "_N").replace("\\", "/") if EditorAssetLibrary.does_asset_exist(normal_texture): set_material_instance_texture(material_instance_asset, "Normal", normal_texture) roughness_texture = os.path.join(texture_folder, "T_" + texture_base_name + "_R").replace("\\", "/") if EditorAssetLibrary.does_asset_exist(roughness_texture): set_material_instance_texture(material_instance_asset, "Roughness", roughness_texture) EditorAssetLibrary.save_asset(material_instance_path) asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() asset_root_dir = '/project/' assets = asset_registry.get_assets_by_path(asset_root_dir, recursive=True) handled_texture_dirs = [] for asset in assets: if asset.asset_class == "Texture2D": textures_path = str(asset.package_path) if textures_path in handled_texture_dirs: continue # Handling folders with different sub-folders for Textures and Materials if textures_path.endswith("Texture") or textures_path.endswith("Textures"): material_path = os.path.join(os.path.dirname(textures_path), "Materials").replace("\\", "/") else: material_path = textures_path print(material_path) create_material_instance(material_path, textures_path, str(asset.asset_name)) handled_texture_dirs.append(textures_path)
#!/project/ python3 """ Complete Character Creation Master Script ======================================== This master script orchestrates the creation of the complete 2D character system for the Warrior_Blue character including all components, logic, and test environment. This script should be executed within Unreal Engine's Python environment. Author: Claude Code Assistant """ import unreal import sys import os def main(): """Main execution function""" print("=" * 60) print("WARRIOR CHARACTER SYSTEM CREATION") print("=" * 60) try: # Step 1: Create Character Blueprint print("\n[STEP 1] Creating Character Blueprint...") if not create_character_blueprint(): raise Exception("Failed to create Character Blueprint") print("✓ Character Blueprint created successfully") # Step 2: Setup Input Mappings print("\n[STEP 2] Setting up Input Mappings...") if not setup_input_mappings(): raise Exception("Failed to setup Input Mappings") print("✓ Input Mappings configured successfully") # Step 3: Create Game Mode Blueprint print("\n[STEP 3] Creating Game Mode...") if not create_game_mode(): raise Exception("Failed to create Game Mode") print("✓ Game Mode created successfully") # Step 4: Create Test Level print("\n[STEP 4] Creating Test Level...") if not create_test_level(): raise Exception("Failed to create Test Level") print("✓ Test Level created successfully") # Step 5: Configure Character Components print("\n[STEP 5] Configuring Character Components...") if not configure_character_components(): raise Exception("Failed to configure Character Components") print("✓ Character Components configured successfully") print("\n" + "=" * 60) print("✓ COMPLETE CHARACTER SYSTEM CREATED SUCCESSFULLY!") print("=" * 60) print("\nYour character system includes:") print("- WarriorCharacter Blueprint (/project/)") print("- Input mappings for WASD movement and attacks") print("- WarriorGameMode Blueprint (/project/)") print("- TestLevel map (/project/)") print("- Configured character with animations and movement") print("\nTo test: Open TestLevel and play the game!") return True except Exception as e: print(f"\n✗ ERROR: {e}") print("Character system creation failed!") return False def create_character_blueprint(): """Create the main character Blueprint""" try: # Create Blueprint based on PaperCharacter asset_tools = unreal.AssetToolsHelpers.get_asset_tools() # Create Blueprint factory blueprint_factory = unreal.BlueprintFactory() blueprint_factory.set_editor_property('parent_class', unreal.PaperCharacter) # Create the Blueprint character_bp = asset_tools.create_asset( 'WarriorCharacter', '/project/', unreal.Blueprint, blueprint_factory ) if not character_bp: return False # Get the default object to configure properties default_object = character_bp.get_default_object() if default_object: # Configure movement component movement_comp = default_object.get_character_movement() if movement_comp: movement_comp.set_editor_property('max_walk_speed', 300.0) movement_comp.set_editor_property('jump_z_velocity', 400.0) movement_comp.set_editor_property('gravity_scale', 1.0) # Enable 2D constraint movement_comp.set_editor_property('plane_constraint_enabled', True) movement_comp.set_editor_property('plane_constraint_normal', unreal.Vector(0, 1, 0)) # Configure the flipbook component with idle animation flipbook_comp = default_object.get_sprite() if flipbook_comp: idle_animation = unreal.EditorAssetLibrary.load_asset('/project/') if idle_animation: flipbook_comp.set_editor_property('source_flipbook', idle_animation) # Save the Blueprint unreal.EditorAssetLibrary.save_asset(character_bp.get_path_name()) return True except Exception as e: print(f"Exception in create_character_blueprint: {e}") return False def setup_input_mappings(): """Setup input mappings for the character""" try: input_settings = unreal.InputSettings.get_input_settings() # Clear existing mappings input_settings.remove_all_action_mappings() input_settings.remove_all_axis_mappings() # Action Mappings for attacks and jump actions = [ ('Jump', unreal.Key.SPACE), ('AttackUp', unreal.Key.UP), ('AttackDown', unreal.Key.DOWN), ('AttackLeft', unreal.Key.LEFT), ('AttackRight', unreal.Key.RIGHT), ('Attack', unreal.Key.LEFT_MOUSE_BUTTON), ] for action_name, key in actions: mapping = unreal.InputActionKeyMapping() mapping.action_name = action_name mapping.key = key input_settings.add_action_mapping(mapping) # Axis Mappings for movement axes = [ ('MoveRight', unreal.Key.D, 1.0), ('MoveRight', unreal.Key.A, -1.0), ('MoveUp', unreal.Key.W, 1.0), ('MoveUp', unreal.Key.S, -1.0), ] for axis_name, key, scale in axes: mapping = unreal.InputAxisKeyMapping() mapping.axis_name = axis_name mapping.key = key mapping.scale = scale input_settings.add_axis_mapping(mapping) # Save input settings input_settings.save_key_mappings() return True except Exception as e: print(f"Exception in setup_input_mappings: {e}") return False def create_game_mode(): """Create a game mode that uses our character""" try: asset_tools = unreal.AssetToolsHelpers.get_asset_tools() # Create Game Mode Blueprint gamemode_factory = unreal.BlueprintFactory() gamemode_factory.set_editor_property('parent_class', unreal.GameModeBase) gamemode_bp = asset_tools.create_asset( 'WarriorGameMode', '/project/', unreal.Blueprint, gamemode_factory ) if not gamemode_bp: return False # Configure the game mode to use our character default_object = gamemode_bp.get_default_object() if default_object: character_bp = unreal.EditorAssetLibrary.load_asset('/project/') if character_bp: character_class = character_bp.get_blueprint_generated_class() if character_class: default_object.set_editor_property('default_pawn_class', character_class) # Save the game mode unreal.EditorAssetLibrary.save_asset(gamemode_bp.get_path_name()) return True except Exception as e: print(f"Exception in create_game_mode: {e}") return False def create_test_level(): """Create a test level with the character""" try: # Create new level asset_tools = unreal.AssetToolsHelpers.get_asset_tools() # Create a new world/level world_factory = unreal.WorldFactory() level_asset = asset_tools.create_asset( 'TestLevel', '/project/', unreal.World, world_factory ) if not level_asset: print("Failed to create level asset, trying alternative method...") # Alternative method - create level directly unreal.EditorLevelLibrary.new_level('/project/') # Load the level to edit it success = unreal.EditorLevelLibrary.load_level('/project/') if not success: print("Warning: Could not load level for editing") # Add basic geometry add_level_geometry() # Set the game mode for this level set_level_game_mode() # Save the level unreal.EditorLevelLibrary.save_current_level() return True except Exception as e: print(f"Exception in create_test_level: {e}") return False def add_level_geometry(): """Add basic geometry to the level""" try: # Add floor floor_actor = unreal.EditorLevelLibrary.spawn_actor_from_class( unreal.StaticMeshActor, unreal.Vector(0, 0, -50), unreal.Rotator(0, 0, 0) ) if floor_actor: mesh_comp = floor_actor.get_component_by_class(unreal.StaticMeshComponent) if mesh_comp: cube_mesh = unreal.EditorAssetLibrary.load_asset('/project/') if cube_mesh: mesh_comp.set_static_mesh(cube_mesh) floor_actor.set_actor_scale3d(unreal.Vector(20, 20, 1)) # Add some platforms platform_positions = [ unreal.Vector(200, 0, 50), unreal.Vector(400, 0, 100), unreal.Vector(-200, 0, 50), unreal.Vector(-400, 0, 100) ] for pos in platform_positions: platform = unreal.EditorLevelLibrary.spawn_actor_from_class( unreal.StaticMeshActor, pos, unreal.Rotator(0, 0, 0) ) if platform: mesh_comp = platform.get_component_by_class(unreal.StaticMeshComponent) if mesh_comp: cube_mesh = unreal.EditorAssetLibrary.load_asset('/project/') if cube_mesh: mesh_comp.set_static_mesh(cube_mesh) platform.set_actor_scale3d(unreal.Vector(3, 3, 0.5)) except Exception as e: print(f"Exception in add_level_geometry: {e}") def set_level_game_mode(): """Set the game mode for the current level""" try: # Get world settings world = unreal.EditorLevelLibrary.get_editor_world() if world: world_settings = world.get_world_settings() if world_settings: gamemode_bp = unreal.EditorAssetLibrary.load_asset('/project/') if gamemode_bp: gamemode_class = gamemode_bp.get_blueprint_generated_class() if gamemode_class: world_settings.set_editor_property('default_game_mode_class', gamemode_class) except Exception as e: print(f"Exception in set_level_game_mode: {e}") def configure_character_components(): """Configure the character's components and animations""" try: # Load the character Blueprint character_bp = unreal.EditorAssetLibrary.load_asset('/project/') if not character_bp: return False # Get default object default_object = character_bp.get_default_object() if not default_object: return False # Configure collision capsule_comp = default_object.get_capsule_component() if capsule_comp: capsule_comp.set_editor_property('capsule_half_height', 50.0) capsule_comp.set_editor_property('capsule_radius', 25.0) # Ensure flipbook component has the idle animation flipbook_comp = default_object.get_sprite() if flipbook_comp: idle_anim = unreal.EditorAssetLibrary.load_asset('/project/') if idle_anim: flipbook_comp.set_editor_property('source_flipbook', idle_anim) # Save changes unreal.EditorAssetLibrary.save_asset(character_bp.get_path_name()) return True except Exception as e: print(f"Exception in configure_character_components: {e}") return False # Execute the main function if run directly if __name__ == "__main__": success = main() exit(0 if success else 1)
# Copyright (c) <2021> Side Effects Software Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. The name of Side Effects Software may not be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN # NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ Example script that instantiates an HDA using the API and then setting some parameter values after instantiation but before the first cook. """ import unreal _g_wrapper = None def get_test_hda_path(): return '/project/.pig_head_subdivider_v01' def get_test_hda(): return unreal.load_object(None, get_test_hda_path()) def on_post_instantiation(in_wrapper): print('on_post_instantiation') # in_wrapper.on_post_instantiation_delegate.remove_callable(on_post_instantiation) # Set some parameters to create instances and enable a material in_wrapper.set_bool_parameter_value('add_instances', True) in_wrapper.set_int_parameter_value('num_instances', 8) in_wrapper.set_bool_parameter_value('addshader', True) def run(): # get the API singleton api = unreal.HoudiniPublicAPIBlueprintLib.get_api() global _g_wrapper # instantiate an asset with auto-cook enabled _g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform()) # Bind on_post_instantiation (before the first cook) callback to set parameters _g_wrapper.on_post_instantiation_delegate.add_callable(on_post_instantiation) if __name__ == '__main__': run()
# Copyright Epic Games, Inc. All Rights Reserved import os import argparse import json import unreal from deadline_rpc import BaseRPC from mrq_cli_modes import ( render_queue_manifest, render_current_sequence, render_queue_asset, utils, ) class MRQRender(BaseRPC): """ Class to execute deadline MRQ renders using RPC """ def __init__(self, *args, **kwargs): """ Constructor """ super(MRQRender, self).__init__(*args, **kwargs) self._render_cmd = ["mrq_cli.py"] # Keep track of the task data self._shot_data = None self._queue = None self._manifest = None self._sequence_data = None def _get_queue(self): """ Render a MRQ queue asset :return: MRQ queue asset name """ if not self._queue: self._queue = self.proxy.get_job_extra_info_key_value("queue_name") return self._queue def _get_sequence_data(self): """ Get sequence data :return: Sequence data """ if not self._sequence_data: self._sequence_data = self.proxy.get_job_extra_info_key_value( "sequence_render" ) return self._sequence_data def _get_serialized_pipeline(self): """ Get Serialized pipeline from Deadline :return: """ if not self._manifest: serialized_pipeline = self.proxy.get_job_extra_info_key_value( "serialized_pipeline" ) if not serialized_pipeline: return unreal.log( f"Executing Serialized Pipeline: `{serialized_pipeline}`" ) # create temp manifest folder movieRenderPipeline_dir = os.path.join( unreal.SystemLibrary.get_project_saved_directory(), "MovieRenderPipeline", "TempManifests", ) if not os.path.exists(movieRenderPipeline_dir ): os.makedirs(movieRenderPipeline_dir ) # create manifest file manifest_file = unreal.Paths.create_temp_filename( movieRenderPipeline_dir , prefix='TempManifest', extension='.utxt') unreal.log(f"Saving Manifest file `{manifest_file}`") # Dump the manifest data into the manifest file with open(manifest_file, "w") as manifest: manifest.write(serialized_pipeline) self._manifest = manifest_file return self._manifest def execute(self): """ Starts the render execution """ # shots are listed as a dictionary of task id -> shotnames # i.e {"O": "my_new_shot"} or {"20", "shot_1,shot_2,shot_4"} # Get the task data and cache it if not self._shot_data: self._shot_data = json.loads( self.proxy.get_job_extra_info_key_value("shot_info") ) # Get any output overrides output_dir = self.proxy.get_job_extra_info_key_value( "output_directory_override" ) # Resolve any path mappings in the directory name. The server expects # a list of paths, but we only ever expect one. So wrap it in a list # if we have an output directory if output_dir: output_dir = self.proxy.check_path_mappings([output_dir]) output_dir = output_dir[0] # Get the filename format filename_format = self.proxy.get_job_extra_info_key_value( "filename_format_override" ) # Resolve any path mappings in the filename. The server expects # a list of paths, but we only ever expect one. So wrap it in a list if filename_format: filename_format = self.proxy.check_path_mappings([filename_format]) filename_format = filename_format[0] # get the shots for the current task current_task_data = self._shot_data.get(str(self.current_task_id), None) if not current_task_data: self.proxy.fail_render("There are no task data to execute!") return shots = current_task_data.split(",") if self._get_queue(): return self.render_queue( self._get_queue(), shots, output_dir_override=output_dir if output_dir else None, filename_format_override=filename_format if filename_format else None ) if self._get_serialized_pipeline(): return self.render_serialized_pipeline( self._get_serialized_pipeline(), shots, output_dir_override=output_dir if output_dir else None, filename_format_override=filename_format if filename_format else None ) if self._get_sequence_data(): render_data = json.loads(self._get_sequence_data()) sequence = render_data.get("sequence_name") level = render_data.get("level_name") mrq_preset = render_data.get("mrq_preset_name") return self.render_sequence( sequence, level, mrq_preset, shots, output_dir_override=output_dir if output_dir else None, filename_format_override=filename_format if filename_format else None ) def render_queue( self, queue_path, shots, output_dir_override=None, filename_format_override=None ): """ Executes a render from a queue :param str queue_path: Name/path of the queue asset :param list shots: Shots to render :param str output_dir_override: Movie Pipeline output directory :param str filename_format_override: Movie Pipeline filename format override """ unreal.log(f"Executing Queue asset `{queue_path}`") unreal.log(f"Rendering shots: {shots}") # Get an executor instance executor = self._get_executor_instance() # Set executor callbacks # Set shot finished callbacks executor.on_individual_shot_work_finished_delegate.add_callable( self._on_individual_shot_finished_callback ) # Set executor finished callbacks executor.on_executor_finished_delegate.add_callable( self._on_job_finished ) executor.on_executor_errored_delegate.add_callable(self._on_job_failed) # Render queue with executor render_queue_asset( queue_path, shots=shots, user=self.proxy.get_job_user(), executor_instance=executor, output_dir_override=output_dir_override, output_filename_override=filename_format_override ) def render_serialized_pipeline( self, manifest_file, shots, output_dir_override=None, filename_format_override=None ): """ Executes a render using a manifest file :param str manifest_file: serialized pipeline used to render a manifest file :param list shots: Shots to render :param str output_dir_override: Movie Pipeline output directory :param str filename_format_override: Movie Pipeline filename format override """ unreal.log(f"Rendering shots: {shots}") # Get an executor instance executor = self._get_executor_instance() # Set executor callbacks # Set shot finished callbacks executor.on_individual_shot_work_finished_delegate.add_callable( self._on_individual_shot_finished_callback ) # Set executor finished callbacks executor.on_executor_finished_delegate.add_callable( self._on_job_finished ) executor.on_executor_errored_delegate.add_callable(self._on_job_failed) render_queue_manifest( manifest_file, shots=shots, user=self.proxy.get_job_user(), executor_instance=executor, output_dir_override=output_dir_override, output_filename_override=filename_format_override ) def render_sequence( self, sequence, level, mrq_preset, shots, output_dir_override=None, filename_format_override=None ): """ Executes a render using a sequence level and map :param str sequence: Level Sequence name :param str level: Level :param str mrq_preset: MovieRenderQueue preset :param list shots: Shots to render :param str output_dir_override: Movie Pipeline output directory :param str filename_format_override: Movie Pipeline filename format override """ unreal.log( f"Executing sequence `{sequence}` with map `{level}` " f"and mrq preset `{mrq_preset}`" ) unreal.log(f"Rendering shots: {shots}") # Get an executor instance executor = self._get_executor_instance() # Set executor callbacks # Set shot finished callbacks executor.on_individual_shot_work_finished_delegate.add_callable( self._on_individual_shot_finished_callback ) # Set executor finished callbacks executor.on_executor_finished_delegate.add_callable( self._on_job_finished ) executor.on_executor_errored_delegate.add_callable(self._on_job_failed) render_current_sequence( sequence, level, mrq_preset, shots=shots, user=self.proxy.get_job_user(), executor_instance=executor, output_dir_override=output_dir_override, output_filename_override=filename_format_override ) @staticmethod def _get_executor_instance(): """ Gets an instance of the movie pipeline executor :return: Movie Pipeline Executor instance """ return utils.get_executor_instance(False) def _on_individual_shot_finished_callback(self, shot_params): """ Callback to execute when a shot is done rendering :param shot_params: Movie pipeline shot params """ unreal.log("Executing On individual shot callback") # Since MRQ cannot parse certain parameters/arguments till an actual # render is complete (e.g. local version numbers), we will use this as # an opportunity to update the deadline proxy on the actual frame # details that were rendered file_patterns = set() # Iterate over all the shots in the shot list (typically one shot as # this callback is executed) on a shot by shot bases. for shot in shot_params.shot_data: for pass_identifier in shot.render_pass_data: # only get the first file paths = shot.render_pass_data[pass_identifier].file_paths # make sure we have paths to iterate on if len(paths) < 1: continue # we only need the ext from the first file ext = os.path.splitext(paths[0])[1].replace(".", "") # Make sure we actually have an extension to use if not ext: continue # Get the current job output settings output_settings = shot_params.job.get_configuration().find_or_add_setting_by_class( unreal.MoviePipelineOutputSetting ) resolve_params = unreal.MoviePipelineFilenameResolveParams() # Set the camera name from the shot data resolve_params.camera_name_override = shot_params.shot_data[ 0 ].shot.inner_name # set the shot name from the shot data resolve_params.shot_name_override = shot_params.shot_data[ 0 ].shot.outer_name # Get the zero padding configuration resolve_params.zero_pad_frame_number_count = ( output_settings.zero_pad_frame_numbers ) # Update the formatting of frame numbers based on the padding. # Deadline uses # (* padding) to display the file names in a job resolve_params.file_name_format_overrides[ "frame_number" ] = "#" * int(output_settings.zero_pad_frame_numbers) # Update the extension resolve_params.file_name_format_overrides["ext"] = ext # Set the job on the resolver resolve_params.job = shot_params.job # Set the initialization time on the resolver resolve_params.initialization_time = ( unreal.MoviePipelineLibrary.get_job_initialization_time( shot_params.pipeline ) ) # Set the shot overrides resolve_params.shot_override = shot_params.shot_data[0].shot combined_path = unreal.Paths.combine( [ output_settings.output_directory.path, output_settings.file_name_format, ] ) # Resolve the paths # The returned values are a tuple with the resolved paths as the # first index. Get the paths and add it to a list ( path, _, ) = unreal.MoviePipelineLibrary.resolve_filename_format_arguments( combined_path, resolve_params ) # Make sure we are getting the right type from resolved # arguments if isinstance(path, str): # Sanitize the paths path = os.path.normpath(path).replace("\\", "/") file_patterns.add(path) elif isinstance(path, list): file_patterns.update( set( [ os.path.normpath(p).replace("\\", "/") for p in path ] ) ) else: raise RuntimeError( f"Expected the shot file paths to be a " f"string or list but got: {type(path)}" ) if file_patterns: unreal.log(f'Updating remote filenames: {", ".join(file_patterns)}') # Update the paths on the deadline job self.proxy.update_job_output_filenames(list(file_patterns)) def _on_job_finished(self, executor=None, success=None): """ Callback to execute on executor finished """ # TODO: add th ability to set the output directory for the task unreal.log(f"Task {self.current_task_id} complete!") self.task_complete = True def _on_job_failed(self, executor, pipeline, is_fatal, error): """ Callback to execute on job failed """ unreal.log_error(f"Is fatal job error: {is_fatal}") unreal.log_error( f"An error occurred executing task `{self.current_task_id}`: \n\t{error}" ) self.proxy.fail_render(error) if __name__ == "__main__": parser = argparse.ArgumentParser( description="This parser is used to run an mrq render with rpc" ) parser.add_argument( "--port", type=int, default=None, help="Port number for rpc server" ) parser.add_argument( "--verbose", action="store_true", help="Enable verbose logging" ) arguments = parser.parse_args() MRQRender(port=arguments.port, verbose=arguments.verbose)
# -*- coding: utf-8 -*- """ """ from __future__ import division from __future__ import print_function from __future__ import absolute_import __author__ = 'timmyliang' __email__ = '[email protected]' __date__ = '2020-07-21 19:23:46' import unreal import json from collections import OrderedDict from Qt import QtCore, QtWidgets, QtGui from dayu_widgets import dayu_theme from dayu_widgets.toast import MToast from dayu_widgets.combo_box import MComboBox from dayu_widgets.mixin import property_mixin, cursor_mixin, focus_shadow_mixin def alert(msg=u"msg", title=u"警告", icon=QtWidgets.QMessageBox.Warning, button_text=u"确定"): # NOTE 生成 Qt 警告窗口 msg_box = QtWidgets.QMessageBox() msg_box.setIcon(icon) msg_box.setWindowTitle(title) msg_box.setText(msg) msg_box.addButton(button_text, QtWidgets.QMessageBox.AcceptRole) unreal.parent_external_window_to_slate(msg_box.winId()) dayu_theme.apply(msg_box) msg_box.exec_() toast_dict = { "error": MToast.error, "info": MToast.info, "success": MToast.success, "warning": MToast.warning, } def toast(text="", typ=""): # NOTE 获取鼠标的位置弹出屏幕居中的 MToast 警告 global MESSAGE_TOAST MESSAGE_TOAST = QtWidgets.QWidget() pos = QtGui.QCursor.pos() desktop = QtWidgets.QApplication.desktop() MESSAGE_TOAST.setGeometry(desktop.screenGeometry(pos)) toast_dict.get(typ,MToast.error)(parent=MESSAGE_TOAST, text=text) def ui_PyInit(widget): if not hasattr(widget,"children"): return # NOTE 初始化 PyInit 中配置的方法 data = widget.property("PyInit") if data: try: data = json.loads(data,object_pairs_hook=OrderedDict) for method,param in data['method'].items(): param = param if isinstance(param,list) else [param] getattr(widget,method)(*param) except: pass for child in widget.children(): ui_PyInit(child)
# coding: utf-8 from asyncio.windows_events import NULL from platform import java_ver import unreal import argparse print("VRM4U python begin") print (__file__) parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") parser.add_argument("-meta") args = parser.parse_args() print(args.vrm) reg = unreal.AssetRegistryHelpers.get_asset_registry(); ## rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r #rig = rigs[10] hierarchy = unreal.ControlRigBlueprintLibrary.get_hierarchy(rig) h_con = hierarchy.get_controller() r_con = rig.get_controller() graph = r_con.get_graph() node = graph.get_nodes() def checkAndSwapPinBoneToContorl(pin): subpins = pin.get_sub_pins() #print(subpins) if (len(subpins) != 2): return; typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') #if (typePin==None or namePin==None): if (typePin==None): return; #if (typePin.get_default_value() == '' or namePin.get_default_value() == ''): if (typePin.get_default_value() == ''): return; if (typePin.get_default_value() != 'Bone'): return; print(typePin.get_default_value() + ' : ' + namePin.get_default_value()) r_con.set_pin_default_value(typePin.get_pin_path(), 'Control', True, False) print('swap end') #end check pin bonePin = None controlPin = None while(len(hierarchy.get_bones()) > 0): e = hierarchy.get_bones()[-1] h_con.remove_all_parents(e) h_con.remove_element(e) h_con.import_bones(unreal.ControlRigBlueprintLibrary.get_preview_mesh(rig).skeleton) ## for n in node: pins = n.get_pins() for pin in pins: if (pin.is_array()): if (pin.get_array_size() > 40): # long bone list typePin = pin.get_sub_pins()[0].find_sub_pin('Type') if (typePin != None): if (typePin.get_default_value() == 'Bone'): bonePin = pin continue if (typePin.get_default_value() == 'Control'): if ('Name="pelvis"' in r_con.get_pin_default_value(n.find_pin('Items').get_pin_path())): controlPin = pin continue for item in pin.get_sub_pins(): checkAndSwapPinBoneToContorl(item) else: checkAndSwapPinBoneToContorl(pin) for e in hierarchy.get_controls(): tmp = "{}".format(e.name) if (tmp.endswith('_ctrl') == False): continue if (tmp.startswith('thumb_0') or tmp.startswith('index_0') or tmp.startswith('middle_0') or tmp.startswith('ring_0') or tmp.startswith('pinky_0')): print('') else: continue c = hierarchy.find_control(e) print(e.name) #ttt = unreal.RigComputedTransform(transform=[[0.0, 0.0, 2.0], [90.0, 0.0, 0.0], [0.03, 0.03, 0.25]]) #ttt = unreal.RigComputedTransform(transform=[[0.0, 0.0, 2.0], [90.0, 0.0, 0.0], [0.03, 0.03, 0.25]]) ttt = unreal.Transform(location=[0.0, 0.0, 2.0], rotation=[0.0, 0.0, 90.0], scale=[0.03, 0.03, 0.25]) hierarchy.set_control_shape_transform(e, ttt, True) ''' shape = c.get_editor_property('shape') init = shape.get_editor_property('initial') #init = shape.get_editor_property('current') local = init.get_editor_property('local') local = ttt init.set_editor_property('local', local) gl = init.get_editor_property('global_') gl = ttt init.set_editor_property('global_', gl) shape.set_editor_property('initial', init) shape.set_editor_property('current', init) c.set_editor_property('shape', shape) ''' ### swapBoneTable = [ ["Root",""], ["Pelvis","hips"], ["spine_01","spine"], ["spine_02","chest"], ["spine_03","upperChest"], ["clavicle_l","leftShoulder"], ["UpperArm_L","leftUpperArm"], ["lowerarm_l","leftLowerArm"], ["Hand_L","leftHand"], ["index_01_l","leftIndexProximal"], ["index_02_l","leftIndexIntermediate"], ["index_03_l","leftIndexDistal"], ["middle_01_l","leftMiddleProximal"], ["middle_02_l","leftMiddleIntermediate"], ["middle_03_l","leftMiddleDistal"], ["pinky_01_l","leftLittleProximal"], ["pinky_02_l","leftLittleIntermediate"], ["pinky_03_l","leftLittleDistal"], ["ring_01_l","leftRingProximal"], ["ring_02_l","leftRingIntermediate"], ["ring_03_l","leftRingDistal"], ["thumb_01_l","leftThumbProximal"], ["thumb_02_l","leftThumbIntermediate"], ["thumb_03_l","leftThumbDistal"], ["lowerarm_twist_01_l",""], ["upperarm_twist_01_l",""], ["clavicle_r","rightShoulder"], ["UpperArm_R","rightUpperArm"], ["lowerarm_r","rightLowerArm"], ["Hand_R","rightHand"], ["index_01_r","rightIndexProximal"], ["index_02_r","rightIndexIntermediate"], ["index_03_r","rightIndexDistal"], ["middle_01_r","rightMiddleProximal"], ["middle_02_r","rightMiddleIntermediate"], ["middle_03_r","rightMiddleDistal"], ["pinky_01_r","rightLittleProximal"], ["pinky_02_r","rightLittleIntermediate"], ["pinky_03_r","rightLittleDistal"], ["ring_01_r","rightRingProximal"], ["ring_02_r","rightRingIntermediate"], ["ring_03_r","rightRingDistal"], ["thumb_01_r","rightThumbProximal"], ["thumb_02_r","rightThumbIntermediate"], ["thumb_03_r","rightThumbDistal"], ["lowerarm_twist_01_r",""], ["upperarm_twist_01_r",""], ["neck_01","neck"], ["head","head"], ["Thigh_L","leftUpperLeg"], ["calf_l","leftLowerLeg"], ["calf_twist_01_l",""], ["Foot_L","leftFoot"], ["ball_l","leftToes"], ["thigh_twist_01_l",""], ["Thigh_R","rightUpperLeg"], ["calf_r","rightLowerLeg"], ["calf_twist_01_r",""], ["Foot_R","rightFoot"], ["ball_r","rightToes"], ["thigh_twist_01_r",""], ["index_metacarpal_l",""], ["index_metacarpal_r",""], ["middle_metacarpal_l",""], ["middle_metacarpal_r",""], ["ring_metacarpal_l",""], ["ring_metacarpal_r",""], ["pinky_metacarpal_l",""], ["pinky_metacarpal_r",""], #custom ["eye_l", "leftEye"], ["eye_r", "rightEye"], ] humanoidBoneList = [ "hips", "leftUpperLeg", "rightUpperLeg", "leftLowerLeg", "rightLowerLeg", "leftFoot", "rightFoot", "spine", "chest", "upperChest", # 9 optional "neck", "head", "leftShoulder", "rightShoulder", "leftUpperArm", "rightUpperArm", "leftLowerArm", "rightLowerArm", "leftHand", "rightHand", "leftToes", "rightToes", "leftEye", "rightEye", "jaw", "leftThumbProximal", # 24 "leftThumbIntermediate", "leftThumbDistal", "leftIndexProximal", "leftIndexIntermediate", "leftIndexDistal", "leftMiddleProximal", "leftMiddleIntermediate", "leftMiddleDistal", "leftRingProximal", "leftRingIntermediate", "leftRingDistal", "leftLittleProximal", "leftLittleIntermediate", "leftLittleDistal", "rightThumbProximal", "rightThumbIntermediate", "rightThumbDistal", "rightIndexProximal", "rightIndexIntermediate", "rightIndexDistal", "rightMiddleProximal", "rightMiddleIntermediate", "rightMiddleDistal", "rightRingProximal", "rightRingIntermediate", "rightRingDistal", "rightLittleProximal", "rightLittleIntermediate", "rightLittleDistal", #54 ] for i in range(len(humanoidBoneList)): humanoidBoneList[i] = humanoidBoneList[i].lower() for i in range(len(swapBoneTable)): swapBoneTable[i][0] = swapBoneTable[i][0].lower() swapBoneTable[i][1] = swapBoneTable[i][1].lower() ### 全ての骨 modelBoneElementList = [] modelBoneNameList = [] for e in hierarchy.get_bones(): if (e.type == unreal.RigElementType.BONE): modelBoneElementList.append(e) modelBoneNameList.append("{}".format(e.name)) ## meta 取得 reg = unreal.AssetRegistryHelpers.get_asset_registry(); a = reg.get_all_assets(); if (args.meta): for aa in a: print(aa.get_editor_property("package_name")) print(aa.get_editor_property("asset_name")) if ((unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("package_name"))+"."+unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("asset_name"))) == unreal.StringLibrary.conv_name_to_string(args.meta)): #if (aa.get_editor_property("object_path") == args.meta): v:unreal.VrmMetaObject = aa vv = aa.get_asset() break if (vv == None): for aa in a: if ((unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("package_name"))+"."+unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("asset_name"))) == unreal.StringLibrary.conv_name_to_string(args.meta)): #if (aa.get_editor_property("object_path") == args.vrm): v:unreal.VrmAssetListObject = aa vv = v.get_asset().vrm_meta_object break meta = vv # Backwards Bone Names allBackwardsNode = [] def r_nodes(node): b = False try: allBackwardsNode.index(node) except: b = True if (b == True): allBackwardsNode.append(node) linknode = node.get_linked_source_nodes() for n in linknode: r_nodes(n) linknode = node.get_linked_target_nodes() for n in linknode: r_nodes(n) for n in node: if (n.get_node_title() == 'Backwards Solve'): r_nodes(n) print(len(allBackwardsNode)) print(len(node)) def boneOverride(pin): subpins = pin.get_sub_pins() if (len(subpins) != 2): return typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') if (typePin==None): return if (namePin==None): return controlName = namePin.get_default_value() if (controlName==''): return if (controlName.endswith('_ctrl')): return if (controlName.endswith('_space')): return r_con.set_pin_default_value(typePin.get_pin_path(), 'Bone', True, False) table = [i for i in swapBoneTable if i[0]==controlName] if (len(table) == 0): # use node or no control return if (table[0][0] == 'root'): metaTable = "{}".format(hierarchy.get_bones()[0].name) else: metaTable = meta.humanoid_bone_table.get(table[0][1]) if (metaTable == None): metaTable = 'None' #print(table[0][1]) #print('<<') #print(controlName) #print('<<<') #print(metaTable) r_con.set_pin_default_value(namePin.get_pin_path(), metaTable, True, False) #for e in meta.humanoid_bone_table: for n in allBackwardsNode: pins = n.get_pins() for pin in pins: if (pin.is_array()): # finger 無変換チェック linknode = n.get_linked_target_nodes() if (len(linknode) == 1): if (linknode[0].get_node_title()=='At'): continue for p in pin.get_sub_pins(): boneOverride(p) else: boneOverride(pin) #sfsdjfkasjk ### 骨名対応表。Humanoid名 -> Model名 humanoidBoneToModel = {"" : ""} humanoidBoneToModel.clear() humanoidBoneToMannequin = {"" : ""} humanoidBoneToMannequin.clear() # humanoidBone -> modelBone のテーブル作る for searchHumanoidBone in humanoidBoneList: bone_h = None for e in meta.humanoid_bone_table: if ("{}".format(e).lower() == searchHumanoidBone): bone_h = e; break; if (bone_h==None): # not found continue bone_m = meta.humanoid_bone_table[bone_h] try: i = modelBoneNameList.index(bone_m) except: i = -1 if (i < 0): # no bone continue humanoidBoneToModel["{}".format(bone_h).lower()] = "{}".format(bone_m) #humanoidBoneToMannequin["{}".format(bone_h).lower()] = "{}".format(bone_m).lower(bone_h) #print(humanoidBoneToModel) #print(bonePin) #print(controlPin) if (bonePin != None and controlPin !=None): r_con.clear_array_pin(bonePin.get_pin_path()) r_con.clear_array_pin(controlPin.get_pin_path()) #c.clear_array_pin(v.get_pin_path()) #tmp = '(Type=Control,Name=' #tmp += "{}".format('aaaaa') #tmp += ')' #r_con.add_array_pin(bonePin.get_pin_path(), default_value=tmp) for e in swapBoneTable: try: i = 0 humanoidBoneToModel[e[1]] except: i = -1 if (i < 0): # no bone continue #e[0] -> grayman #e[1] -> humanoid #humanoidBoneToModel[e[1]] -> modelBone bone = unreal.RigElementKey(unreal.RigElementType.BONE, humanoidBoneToModel[e[1]]) space = unreal.RigElementKey(unreal.RigElementType.NULL, "{}_s".format(e[0])) #print('aaa') #print(bone) #print(space) #p = hierarchy.get_first_parent(humanoidBoneToModel[result[0][1]]) t = hierarchy.get_global_transform(bone) #print(t) hierarchy.set_global_transform(space, t, True) if (bonePin != None and controlPin !=None): tmp = '(Type=Control,Name=' tmp += "{}".format(e[0]) tmp += ')' r_con.add_array_pin(controlPin.get_pin_path(), default_value=tmp, setup_undo_redo=False) tmp = '(Type=Bone,Name=' tmp += "\"{}\"".format(humanoidBoneToModel[e[1]]) tmp += ')' r_con.add_array_pin(bonePin.get_pin_path(), default_value=tmp, setup_undo_redo=False) # for bone name space namePin = bonePin.get_sub_pins()[-1].find_sub_pin('Name') r_con.set_pin_default_value(namePin.get_pin_path(), "{}".format(humanoidBoneToModel[e[1]]), True, False) # skip invalid bone, controller # disable node def disableNode(toNoneNode): print(toNoneNode) print("gfgf") pins = toNoneNode.get_pins() for pin in pins: typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') if (typePin==None or namePin==None): continue print(f'DisablePin {typePin.get_default_value()} : {namePin.get_default_value()}') # control key = unreal.RigElementKey(unreal.RigElementType.CONTROL, "{}".format(namePin.get_default_value())) # disable node r_con.set_pin_default_value(namePin.get_pin_path(), 'None', True, False) if (typePin.get_default_value() == 'Control'): #disable control if (hierarchy.contains(key) == True): settings = h_con.get_control_settings(key) if ("5.1." in unreal.SystemLibrary.get_engine_version()): settings.set_editor_property('shape_visible', False) else: settings.set_editor_property('shape_enabled', False) ttt = hierarchy.get_global_control_shape_transform(key, True) ttt.scale3d.set(0.001, 0.001, 0.001) hierarchy.set_control_shape_transform(key, ttt, True) h_con.set_control_settings(key, settings) for n in node: pins = n.get_pins() for pin in pins: if (pin.is_array()): continue else: typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') if (typePin==None or namePin==None): continue if (typePin.get_default_value() != 'Bone'): continue if (namePin.is_u_object() == True): continue if (len(n.get_linked_source_nodes()) > 0): continue key = unreal.RigElementKey(unreal.RigElementType.BONE, namePin.get_default_value()) if (hierarchy.contains(key) == True): continue print(f'disable linked node from {typePin.get_default_value()} : {namePin.get_default_value()}') for toNoneNode in n.get_linked_target_nodes(): disableNode(toNoneNode) ## morph # -vrm vrm -rig rig -debugeachsave 0 #args.vrm #args.rig command = 'VRM4U_CreateMorphTargetControllerUE5.py ' + '-vrm ' + args.vrm + ' -rig ' + args.rig + ' -debugeachsave 0' print(command) unreal.PythonScriptLibrary.execute_python_command(command) unreal.ControlRigBlueprintLibrary.recompile_vm(rig)
import unreal import importlib import os import sys sys.path.insert(1, os.path.join(unreal.SystemLibrary.get_project_directory(), os.pardir, 'PythonCode')) import subprocess menu_owner = "ExampleOwnerName" tool_menus = unreal.ToolMenus.get() owning_menu_name = "LevelEditor.LevelEditorToolBar.PlayToolBar" python_code_directory = os.path.join(unreal.SystemLibrary.get_project_directory(), os.pardir, 'PythonCode') import Prefixer @unreal.uclass() class example_SubMenuEntry(unreal.ToolMenuEntryScript): def init_as_toolbar_button(self): self.data.menu = owning_menu_name self.data.advanced.entry_type = unreal.MultiBlockType.TOOL_BAR_COMBO_BUTTON self.data.icon = unreal.ScriptSlateIcon("EditorStyle", "MaterialEditor.CameraHome") self.data.advanced.style_name_override = "CalloutToolbar" def Run(): if True: # Testing stuff tool_menus.unregister_owner_by_name( menu_owner) # For Testing: Allow iterating on this menu python file without restarting editor # Create the python menu on the tool bar entry = example_SubMenuEntry() contextMenu = tool_menus.extend_menu("ContentBrowser.AssetContextMenu") entry.init_as_toolbar_button() entry.init_entry(menu_owner, owning_menu_name, "", "exampleToolbarEntry", "Python", "Python Quick Links") # First add an option to open the code directory sub_menu = tool_menus.register_menu(owning_menu_name + ".exampleToolbarEntry", "", unreal.MultiBoxType.MENU, False) sub_entry = unreal.ToolMenuEntryExtensions.init_menu_entry( menu_owner, "OpenCodeFolder", "Open Code Folder", "Open the directory the python code is stored in", unreal.ToolMenuStringCommandType.PYTHON, "", "exec(open(\"" + python_code_directory + "\"+'/OpenFolders.py').read())") sub_menu.add_menu_entry("", sub_entry) # Create second entry that opens the webpage for the python API sub_entry = unreal.ToolMenuEntryExtensions.init_menu_entry( menu_owner, "PythonAPIdocumentation", "Python API documentation", "Link to the API documenation for quick reference", unreal.ToolMenuStringCommandType.PYTHON, "", "unreal.SystemLibrary.launch_url(\"https://docs.unrealengine.com/5.0/en-US/PythonAPI/\")") sub_menu.add_menu_entry("", sub_entry) # Add the button to the dynamic right hand click menu on the assets for the prefixer tool contextMenu.add_dynamic_section("DynamicActorSection", dynamicActorSection()) toolbar = tool_menus.extend_menu(owning_menu_name) toolbar.add_menu_entry_object(entry) tool_menus.refresh_all_widgets() # A dynamic section for more advanced control over visibility. You can use a normal section with add_section @unreal.uclass() class dynamicActorSection(unreal.ToolMenuSectionDynamic): @unreal.ufunction(override=True) def construct_sections(self, menu, context): menu.add_section("ExampleSectionID", "Python Tasks Section") AddEntries(menu, "ExampleSectionID") # Adds options directly to the context menu @unreal.uclass() class example_entry_script(unreal.ToolMenuEntryScript): @unreal.ufunction(override=True) def execute(self, context): prefixer.runprefixer() def AddEntries(menu, section_name): entry = example_entry_script() entry.data.icon = unreal.ScriptSlateIcon("EditorStyle", "Persona.ToggleReferencePose") entry.init_entry(menu_owner, "LevelEditor.AssetContextMenu", section_name, "ExampleEntryID", "Add Prefix", "Example Entry Tooltip.") menu.add_menu_entry_object(entry) Run()
# -*- coding: utf-8 -*- import unreal def do_some_things(*args, **kwargs): unreal.log("do_some_things start:") for arg in args: unreal.log(arg) unreal.log("do_some_things end.")
# -*- coding: utf-8 -*- """ Initialize unreal Qt Environment """ from __future__ import division from __future__ import print_function from __future__ import absolute_import __author__ = "timmyliang" __email__ = "[email protected]" __date__ = "2020-05-30 21:47:47" import os import sys import imp import json import codecs import platform import posixpath import traceback import subprocess from subprocess import PIPE, Popen from threading import Thread from functools import partial from collections import OrderedDict, defaultdict startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW startupinfo.wShowWindow = subprocess.SW_HIDE try: from queue import Queue, Empty except ImportError: from Queue import Queue, Empty # python 2.x import unreal DIR = os.path.dirname(__file__) CONTENT = os.path.dirname(DIR) PyToolkit = os.path.join(CONTENT, "PyToolkit") VENDOR = os.path.join(CONTENT, "_vendor") CONFIG = os.path.join(PyToolkit, "_config") PYTHON = os.path.join(PyToolkit, "Python") menu_py = os.path.join(CONFIG, "menu.py") MENU_MODULE = imp.load_source("__menu__", menu_py) if os.path.exists(menu_py) else None MENU_ADD_TIME = 0.2 def can_import(module): try: __import__(module) except ImportError: return False return True def read_json(json_path): import codecs try: with codecs.open(json_path, "r", encoding="utf-8") as f: data = json.load(f, object_pairs_hook=OrderedDict) except: import traceback traceback.print_exc() data = {} return data def read_config_json(config): return read_json(os.path.join(CONFIG, "%s.json" % config)) def add_vendor_path(): config_path = os.path.join(VENDOR, "vendor.json") vendor = read_json(config_path) version = "py%s" % sys.version[:3] module_data = defaultdict(list) for package, collections in vendor.items(): module = collections.get("module") package_folder = os.path.join(VENDOR, package) for f in collections.get("folders", {}): path = os.path.join(package_folder, f) module_data[module].append(os.path.abspath(path)) if [k for k in collections if k.startswith("py")]: collections = collections.get(version) if collections: for f in collections.get("folders", {}): path = os.path.join(package_folder, f) module_data[module].append(os.path.abspath(path)) for module, paths in module_data.items(): if not can_import(module): sys.path = paths + sys.path add_vendor_path() from Qt import QtCore, QtWidgets, QtGui from dayu_widgets import dayu_theme import six sys_lib = unreal.SystemLibrary menus = unreal.ToolMenus.get() FORMAT_ARGS = {"Content": CONTENT, "PyToolkit": PyToolkit} COMMAND_TYPE = { "COMMAND": unreal.ToolMenuStringCommandType.COMMAND, "PYTHON": unreal.ToolMenuStringCommandType.PYTHON, "CUSTOM": unreal.ToolMenuStringCommandType.CUSTOM, } INSERT_TYPE = { "AFTER": unreal.ToolMenuInsertType.AFTER, "BEFORE": unreal.ToolMenuInsertType.BEFORE, "DEFAULT": unreal.ToolMenuInsertType.DEFAULT, "FIRST": unreal.ToolMenuInsertType.FIRST, } MENU_TYPE = { "BUTTON_ROW": unreal.MultiBoxType.BUTTON_ROW, "MENU": unreal.MultiBoxType.MENU, "MENU_BAR": unreal.MultiBoxType.MENU_BAR, "TOOL_BAR": unreal.MultiBoxType.TOOL_BAR, "UNIFORM_TOOL_BAR": unreal.MultiBoxType.UNIFORM_TOOL_BAR, "VERTICAL_TOOL_BAR": unreal.MultiBoxType.VERTICAL_TOOL_BAR, } ENTRY_TYPE = { "BUTTON_ROW": unreal.MultiBlockType.BUTTON_ROW, "EDITABLE_TEXT": unreal.MultiBlockType.EDITABLE_TEXT, "HEADING": unreal.MultiBlockType.HEADING, "MENU_ENTRY": unreal.MultiBlockType.MENU_ENTRY, "NONE": unreal.MultiBlockType.NONE, "TOOL_BAR_BUTTON": unreal.MultiBlockType.TOOL_BAR_BUTTON, "TOOL_BAR_COMBO_BUTTON": unreal.MultiBlockType.TOOL_BAR_COMBO_BUTTON, "WIDGET": unreal.MultiBlockType.WIDGET, } ACTION_TYPE = { "BUTTON": unreal.UserInterfaceActionType.BUTTON, "CHECK": unreal.UserInterfaceActionType.CHECK, "COLLAPSED_BUTTON": unreal.UserInterfaceActionType.COLLAPSED_BUTTON, "NONE": unreal.UserInterfaceActionType.NONE, "RADIO_BUTTON": unreal.UserInterfaceActionType.RADIO_BUTTON, "TOGGLE_BUTTON": unreal.UserInterfaceActionType.TOGGLE_BUTTON, } def handle_menu(data): """ handle_menu 递归生成菜单 """ menu = data.get("menu") if not menu: return for section, config in data.get("section", {}).items(): config = config if isinstance(config, dict) else {"label": config} config.setdefault("label", "untitle") # NOTE 如果存在 insert_type 需要将字符串转换 insert = INSERT_TYPE.get(config.get("insert_type", "").upper()) if insert: config["insert_type"] = insert insert_name = config.get("insert_name") config["insert_name"] = insert_name if insert_name else "None" menu.add_section(section, **config) for prop, value in data.get("property", {}).items(): if prop == "menu_owner" or value == "": continue elif prop == "menu_type": value = MENU_TYPE.get(value.upper()) menu.set_editor_property(prop, value) for entry_name, config in data.get("entry", {}).items(): label = config.get("label", "untitle") prop = config.get("property", {}) for k in prop.copy(): v = prop.pop(k) if v and k in ["name", "tutorial_highlight_name"]: prop[k] = v if k == "insert_position": position = INSERT_TYPE.get(v.get("position", "").upper()) v["position"] = ( position if position else unreal.ToolMenuInsertType.FIRST ) v["name"] = v.get("name", "") prop[k] = unreal.ToolMenuInsert(**v) elif k == "type": typ = ENTRY_TYPE.get(str(v).upper()) prop[k] = typ if typ else unreal.MultiBlockType.MENU_ENTRY elif k == "user_interface_action_type": typ = ACTION_TYPE.get(str(v).upper()) typ and prop.update({k: typ}) elif k == "script_object": script_class = getattr(MENU_MODULE, v, None) if script_class and issubclass( script_class, unreal.ToolMenuEntryScript ): script_object = script_class() context = unreal.ToolMenuContext() script_label = str(script_object.get_label(context)) if not script_label: @unreal.uclass() class RuntimeScriptClass(script_class): label = unreal.uproperty(str) @unreal.ufunction(override=True) def get_label(self, context): return self.label script_object = RuntimeScriptClass() script_object.label = label prop[k] = script_object prop.setdefault("name", entry_name) prop.setdefault("type", unreal.MultiBlockType.MENU_ENTRY) entry = unreal.ToolMenuEntry(**prop) entry.set_label(label) typ = COMMAND_TYPE.get(config.get("type", "").upper(), 0) command = config.get("command", "").format(**FORMAT_ARGS) entry.set_string_command(typ, "", string=command) menu.add_menu_entry(config.get("section", ""), entry) for entry_name, config in data.get("sub_menu", {}).items(): init = config.get("init", {}) owner = menu.get_name() section_name = init.get("section", "") name = init.get("name", entry_name) label = init.get("label", "") tooltip = init.get("tooltip", "") sub_menu = menu.add_sub_menu(owner, section_name, name, label, tooltip) config.setdefault("menu", sub_menu) handle_menu(config) def create_menu(): # NOTE Read menu json settings menu_json = read_config_json("menu") fail_menus = {} # NOTE https://forums.unrealengine.com/development-discussion/python-scripting/1767113-making-menus-in-py for tool_menu, config in menu_json.items(): menu = menus.find_menu(tool_menu) if not menu: fail_menus.update({tool_menu: config}) continue config.setdefault("menu", menu) handle_menu(config) menus.refresh_all_widgets() return fail_menus def run_py(path): if os.path.isfile(path) and path.endswith(".py"): command = 'py "%s"' % path sys_lib.execute_console_command(None, command) else: for root, _, files in os.walk(path): for f in files: if not f.endswith(".py"): continue command = 'py "%s"' % posixpath.join(root, f).replace("\\", "/") sys_lib.execute_console_command(None, command) def slate_deco(func): def wrapper(self, single=True, *args, **kwargs): if single: # TODO crash for win in QtWidgets.QApplication.allWidgets(): if win is self: continue elif self.__class__.__name__ in str(type(win)): win.deleteLater() win.close() res = func(self, *args, **kwargs) # NOTE https://forums.unrealengine.com/unreal-engine/unreal-studio/1526501-how-to-get-the-main-window-of-the-editor-to-parent-qt-or-pyside-application-to-it unreal.parent_external_window_to_slate(self.winId()) dayu_theme.apply(self) return res return wrapper if __name__ == "__main__": # NOTE This part is for the initial setup. Need to run once to spawn the application. unreal_app = QtWidgets.QApplication.instance() if not unreal_app: unreal_app = QtWidgets.QApplication([]) def __QtAppTick__(delta_seconds): QtWidgets.QApplication.sendPostedEvents() tick_handle = unreal.register_slate_post_tick_callback(__QtAppTick__) __QtAppQuit__ = partial(unreal.unregister_slate_post_tick_callback, tick_handle) unreal_app.aboutToQuit.connect(__QtAppQuit__) # NOTE override show method QtWidgets.QWidget.show = slate_deco(QtWidgets.QWidget.show) with open(os.path.join(CONFIG, "main.css"), "r") as f: unreal_app.setStyleSheet(f.read()) fail_menus = create_menu() if fail_menus: global __tick_menu_elapsed__ __tick_menu_elapsed__ = 0 def timer_add_menu(menu_dict, delta): global __tick_menu_elapsed__ __tick_menu_elapsed__ += delta # NOTE avoid frequently executing if __tick_menu_elapsed__ < MENU_ADD_TIME: return __tick_menu_elapsed__ = 0 # NOTE all menu added the clear the tick callback if not menu_dict: global __py_add_menu_tick__ unreal.unregister_slate_post_tick_callback(__py_add_menu_tick__) return flag = False menu_list = [] for tool_menu, config in menu_dict.items(): menu = menus.find_menu(tool_menu) if not menu: continue menu_list.append(tool_menu) flag = True config.setdefault("menu", menu) handle_menu(config) if flag: [menu_dict.pop(m) for m in menu_list] menus.refresh_all_widgets() # NOTE register custom menu callback = partial(timer_add_menu, fail_menus) global __py_add_menu_tick__ __py_add_menu_tick__ = unreal.register_slate_post_tick_callback(callback) __QtAppQuit__ = partial( unreal.unregister_slate_post_tick_callback, __py_add_menu_tick__ ) unreal_app.aboutToQuit.connect(__QtAppQuit__) setting = read_config_json("setting") if setting.get("hook"): # NOTE 调用 hook 下的脚本 path = os.path.join(PyToolkit, "_hook") os.path.isdir(path) and run_py(path) if setting.get("blueprint"): # NOTE 执行 BP 目录下所有的 python 脚本 注册蓝图 path = os.path.join(PyToolkit, "BP") os.path.isdir(path) and run_py(path) hotkey_enabled = setting.get("hotkey") if hotkey_enabled: os_config = { "Windows": "Win64", "Linux": "Linux", "Darwin": "Mac", } os_platform = os_config.get(platform.system()) if not os_platform: raise OSError("Unsupported platform '{}'".format(platform.system())) PYTHON = "Python" if six.PY2 else "Python3" ThirdParty = os.path.join(sys.executable, "..", "..", "ThirdParty") interpreter = os.path.join(ThirdParty, PYTHON, os_platform, "python.exe") interpreter = os.path.abspath(interpreter) exec_file = os.path.join(PyToolkit, "_key_listener", "__listener__.py") msg = "lost path \n%s\n%s" % (interpreter, exec_file) assert os.path.exists(interpreter) and os.path.exists(exec_file), msg # NOTE spawn a Python process for keyboard listening # NOTE https://stackoverflow.com/project/ ON_POSIX = "posix" in sys.builtin_module_names p = Popen( [interpreter, exec_file], shell=False, stdout=PIPE, stderr=PIPE, bufsize=1, close_fds=ON_POSIX, startupinfo=startupinfo, ) unreal_app.aboutToQuit.connect(p.terminate) def enqueue_output(p, queue): for line in iter(p.stdout.readline, b""): queue.put(line) p.stdout.close() q = Queue() t = Thread(target=enqueue_output, args=(p, q)) t.daemon = True # thread dies with the program t.start() hotkey_config = read_config_json("hotkey") callbacks = { "COMMAND": lambda command: sys_lib.execute_console_command(None, command), "PYTHON": lambda command: eval(command), } def get_foreground_window_pid(): from ctypes import wintypes, windll, byref # NOTE https://stackoverflow.com/project/ h_wnd = windll.user32.GetForegroundWindow() pid = wintypes.DWORD() windll.user32.GetWindowThreadProcessId(h_wnd, byref(pid)) return pid.value def __hotkey_tick__(delta_seconds): try: line = q.get_nowait() except Empty: return if not line or delta_seconds > 0.1: return if platform.system() == "Windows": pid = get_foreground_window_pid() if pid != os.getpid(): return # line = str(line.strip(), "utf-8") line = line.strip() if six.PY2 else str(line.strip(), "utf-8") config = hotkey_config.get(line) if not config: return typ = config.get("type", "").upper() callback = callbacks.get(typ) if not callback: return command = config.get("command", "").format(**FORMAT_ARGS) callback(command) tick_handle = unreal.register_slate_post_tick_callback(__hotkey_tick__) __QtAppQuit__ = partial(unreal.unregister_slate_post_tick_callback, tick_handle) unreal_app.aboutToQuit.connect(__QtAppQuit__)
import sys import os ''' yes, this is ugly ''' if os.path.exists("/shared"): sys.path.append("/shared") if os.path.exists("/project/"): sys.path.append("/project/") elif os.path.exists("./shared"): sys.path.append("./shared") if os.path.exists("/project/-packages"): sys.path.append("/project/-packages") import unreal import helper from helper import UnrealBridge import time class MindfulUE(UnrealBridge): def __init__(self, status_file_path="/project/.json") -> None: super().__init__(status_file_path) print("MindfulUE initialized") unreal.MindfulLib.add_notifier(unreal.EditorLevelLibrary.get_editor_world()) #this name will adjusted extetnally #if it's set to just "modifier script name", we asuume there is no modifier script self.mod_script_name = "MODIFIERSCRIPTNAME" print("binding tick callback") tickHandle = unreal.register_slate_pre_tick_callback(self.testRegistry) def run_level_modifier(self): if self.mod_script_name != "MODIFIER"+"SCRIPTNAME": unreal.SystemLibrary.execute_console_command(None,"py " + self.mod_script_name) def tick(self, deltaTime): if self.is_in_begin_play(): self.set_ue_condition_tag("end_play", 0) elif self.is_in_end_play(): self.set_ue_condition_tag("begin_play", 0) if not self.is_engine_playing(): self.set_ue_condition_tag("ready", 1) # self.run_level_modifier() if self.is_requesting_play() and not self.is_engine_playing(): self.set_ue_condition_tag("playing", 1) unreal.log_warning("Starting PIE session...") unreal.MindfulLib.start_life() if self.is_requesting_stop(): self.reset_ue_tags() unreal.log_warning("Life ended. Stopping PIE session...") unreal.MindfulLib.stop_life() def testRegistry(self, deltaTime): asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() if asset_registry.is_loading_assets(): unreal.log_warning("still loading...") else: self.update_ue_state() self.tick(deltaTime) MindfulUE()
""" Metadata is a powerful tool when managing assets in Unreal. Instead of searching/recursing through folders we can search and filter for assets by their metadata values. This module includes examples to make use of and extend the functionality of metadata PRE-REQUISITE: Metadata names must be declared first in the Asset Registry for your given Unreal Project You can add / manage your metadata names in the Game Project's Settings -> Asset Registry -> Metadata Plugins can also deliver metadata in the `Config/Default<plugin_name>.ini` file """ import typing import unreal from recipebook.unreal_systems import ( asset_registry_helper, asset_registry, EditorAssetLibrary ) # Arbitrary metadata example: let's pretend we're tracking assets! # NOTE: # these constants should be 1:1 with what's declared in your Project's Asset Registry # Any metadata names only declared in Python are not discoverable by the Asset Registry META_IS_MANAGED_ASSET = "managed_asset" # all assets we create via Python will have this tag META_ASSET_TYPE = "asset_type" # maybe it's a 'character' or an 'environment' asset META_ASSET_GROUP = "asset_group" # we can use this to collect multiple assets under the same group META_ASSET_NAME = "asset_name" # the official name of our asset META_ASSET_AUTHOR = "asset_author" META_ASSET_VERSION = "asset_version" # what version number is this asset currently set to? # Unreal stores metadata as strings # this dict maps metadata names we want to be non-strings # we can use this to get metadata as their expected type (such as an int or bool) METADATA_TYPE_MAP = { META_IS_MANAGED_ASSET: bool, META_ASSET_VERSION: int } def set_metadata(asset, key, value): """ Setting Metadata is done on a loaded unreal.Object reference parameters: asset: the asset to save the metadata to key: the metadata key name value: the metadata value """ EditorAssetLibrary.set_metadata_tag(asset, key, str(value)) def get_metadata(asset, key, default=None): """ Getting Metadata can be done on a loaded unreal.Object reference OR unreal.AssetData using METADATA_TYPE_MAP we can automatically convert our metadata into their intended types (if not string) parameters: asset: the asset to get the metadata from key: the metadata key name default: the default value to assume if the metadata is not set Return: the metadata value in its expected type (if mapped in METADATA_TYPE_MAP) """ # Get the metadata value from the loaded asset or an AssetData instance if isinstance(asset, unreal.AssetData): value = asset.get_tag_value(key) else: value = unreal.EditorAssetLibrary.get_metadata_tag(asset, key) # If the metadata was found & valid let's convert it! if value and value.lower() != "none": # Get this metadata key's expected value type, default is str (as-is) value_type = METADATA_TYPE_MAP.get(key, str) if value_type == bool: # bools are a special case as bool(str) only checks for length return value.lower() == "true" else: # most singular value types may be directly converted return value_type(value) def find_assets_by_metadata(meta_dict=None, class_names=["object"], parent_path="") -> typing.List[unreal.AssetData]: """ Find assets in the Content Browser based on a given dict of metadata {key:value} pairs use 'parent_path' to only return results that live under that asset path """ meta_dict = meta_dict or dict() # create a basic Asset Registry filter based on the class_names # include the parent path if provided base_filter = unreal.ARFilter( class_names=class_names, recursive_classes=True, package_paths=[parent_path] if parent_path else [], recursive_paths=True, ) # Start with the first Metadata Query if provided first_filter = base_filter if meta_dict: first_key = list(meta_dict.keys())[0] first_value = meta_dict.pop(first_key) query = [unreal.TagAndValue(first_key, str(first_value))] first_filter = asset_registry_helper.set_filter_tags_and_values(base_filter, query) # Get the initial search results results = asset_registry.get_assets(first_filter) or [] for key, value in meta_dict.items(): # Create a new ARFilter based on the {key:value} pair query = [unreal.TagAndValue(key, str(value))] meta_filter = asset_registry_helper.set_filter_tags_and_values(base_filter, query) # reduce the results to only those matching the given metadata results = asset_registry.run_assets_through_filter(results, meta_filter) or [] # return the results as a Python list as it might currently be an unreal.Array return list(results) def metadata_startup(): """ Register the metadata names to the Asset Registry during Editor startup Using this method ensures the Metadata components of any tools we build will work properly. While it is possible to declare these in the plugin's INI file this method has been more reliable in my experience when making tools. It also allows us to set the metadata from the same code """ # the metadata keys to register to the Asset Registry metadata_keys = [ META_IS_MANAGED_ASSET, META_ASSET_TYPE, META_ASSET_GROUP, META_ASSET_NAME, META_ASSET_AUTHOR, META_ASSET_VERSION ] # this custom c++ function exposes the ability to add metadata keys directly to the Asset Registry unreal.PythonUtilsLibrary.register_metadata_tags(metadata_keys)
import unreal import argparse import json def get_scriptstruct_by_node_name(node_name): control_rig_blueprint = unreal.load_object(None, '/project/') rig_vm_graph = control_rig_blueprint.get_model() nodes = rig_vm_graph.get_nodes() for node in nodes: if node.get_node_path() == node_name: return node.get_script_struct() last_construction_link = 'PrepareForExecution' def create_construction(bone_name): global last_construction_link control_name = bone_name + '_ctrl' get_bone_transform_node_name = "RigUnit_Construction_GetTransform_" + bone_name set_control_transform_node_name = "RigtUnit_Construction_SetTransform_" + control_name rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(137.732236, -595.972187), get_bone_transform_node_name) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item', '(Type=Bone)') rig_controller.set_pin_expansion(get_bone_transform_node_name + '.Item', True) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(get_bone_transform_node_name + '.bInitial', 'True') rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item.Name', bone_name, True) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item.Type', 'Bone', True) rig_controller.set_node_selection([get_bone_transform_node_name]) try: rig_controller.add_template_node('Set Transform::Execute(in Item,in Space,in bInitial,in Value,in Weight,in bPropagateToChildren,io ExecuteContext)', unreal.Vector2D(526.732236, -608.972187), set_control_transform_node_name) except Exception as e: set_transform_scriptstruct = get_scriptstruct_by_node_name("SetTransform") rig_controller.add_unit_node(set_transform_scriptstruct, 'Execute', unreal.Vector2D(526.732236, -608.972187), set_control_transform_node_name) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item', '(Type=Bone,Name="None")') rig_controller.set_pin_expansion(set_control_transform_node_name + '.Item', False) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(set_control_transform_node_name + '.bInitial', 'True') rig_controller.set_pin_default_value(set_control_transform_node_name + '.Weight', '1.000000') rig_controller.set_pin_default_value(set_control_transform_node_name + '.bPropagateToChildren', 'True') rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item.Name', control_name, True) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item.Type', 'Control', True) try: rig_controller.add_link(get_bone_transform_node_name + '.Transform', set_control_transform_node_name + '.Value') except: try: rig_controller.add_link(get_bone_transform_node_name + '.Transform', set_control_transform_node_name + '.Transform') except Exception as e: print("ERROR: CreateControlRig.py, line 45: rig_controller.add_link(): " + str(e)) rig_controller.set_node_position_by_name(set_control_transform_node_name, unreal.Vector2D(512.000000, -656.000000)) rig_controller.add_link(last_construction_link + '.ExecuteContext', set_control_transform_node_name + '.ExecuteContext') last_construction_link = set_control_transform_node_name last_backward_solver_link = 'InverseExecution.ExecuteContext' def create_backward_solver(bone_name): global last_backward_solver_link control_name = bone_name + '_ctrl' get_bone_transform_node_name = "RigUnit_BackwardSolver_GetTransform_" + bone_name set_control_transform_node_name = "RigtUnit_BackwardSolver_SetTransform_" + control_name #rig_controller.add_link('InverseExecution.ExecuteContext', 'RigUnit_SetTransform_3.ExecuteContext') rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(-636.574629, -1370.167943), get_bone_transform_node_name) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item', '(Type=Bone)') rig_controller.set_pin_expansion(get_bone_transform_node_name + '.Item', True) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item.Name', bone_name, True) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item.Type', 'Bone', True) try: rig_controller.add_template_node('Set Transform::Execute(in Item,in Space,in bInitial,in Value,in Weight,in bPropagateToChildren,io ExecuteContext)', unreal.Vector2D(-190.574629, -1378.167943), set_control_transform_node_name) except: set_transform_scriptstruct = get_scriptstruct_by_node_name("SetTransform") rig_controller.add_unit_node(set_transform_scriptstruct, 'Execute', unreal.Vector2D(-190.574629, -1378.167943), set_control_transform_node_name) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item', '(Type=Bone,Name="None")') rig_controller.set_pin_expansion(set_control_transform_node_name + '.Item', False) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(set_control_transform_node_name + '.bInitial', 'False') rig_controller.set_pin_default_value(set_control_transform_node_name + '.Weight', '1.000000') rig_controller.set_pin_default_value(set_control_transform_node_name + '.bPropagateToChildren', 'True') rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item.Name', control_name, True) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item.Type', 'Control', True) #rig_controller.set_pin_default_value(set_control_transform_node_name + '.Transform', '(Rotation=(X=0.000000,Y=0.000000,Z=0.000000,W=-1.000000),Translation=(X=0.551784,Y=-0.000000,Z=72.358307),Scale3D=(X=1.000000,Y=1.000000,Z=1.000000))', True) try: rig_controller.add_link(get_bone_transform_node_name + '.Transform', set_control_transform_node_name + '.Value') except: try: rig_controller.add_link(get_bone_transform_node_name + '.Transform', set_control_transform_node_name + '.Transform') except Exception as e: print("ERROR: CreateControlRig.py, line 84: rig_controller.add_link(): " + str(e)) rig_controller.add_link(last_backward_solver_link, set_control_transform_node_name + '.ExecuteContext') last_backward_solver_link = set_control_transform_node_name + '.ExecuteContext' def create_control(bone_name): control_name = bone_name + '_ctrl' default_setting = unreal.RigControlSettings() default_setting.shape_name = 'Box_Thin' default_setting.control_type = unreal.RigControlType.EULER_TRANSFORM default_value = hierarchy.make_control_value_from_euler_transform( unreal.EulerTransform(scale=[1, 1, 1])) key = unreal.RigElementKey(type=unreal.RigElementType.BONE, name=bone_name) rig_control_element = hierarchy.find_control(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name)) control_key = rig_control_element.get_editor_property('key') print(rig_control_element) if control_key.get_editor_property('name') != "": control_key = rig_control_element.get_editor_property('key') else: try: control_key = hierarchy_controller.add_control(control_name, unreal.RigElementKey(), default_setting, default_value, True, True) except: control_key = hierarchy_controller.add_control(control_name, unreal.RigElementKey(), default_setting, default_value, True) transform = hierarchy.get_global_transform(key, True) hierarchy.set_control_offset_transform(control_key, transform, True) if bone_name in control_list: create_direct_control(bone_name) elif bone_name in effector_list: create_effector(bone_name) create_construction(bone_name) create_backward_solver(bone_name) effector_get_transform_widget_height = 0 def create_direct_control(bone_name): global next_forward_execute global effector_get_transform_widget_height #effector_get_transform_widget_height += 250 control_name = bone_name + '_ctrl' get_control_transform_node_name = "RigUnit_DirectControl_GetTransform_" + bone_name set_bone_transform_node_name = "RigtUnit_DirectControl_SetTransform_" + control_name rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(101.499447, -244.500249), get_control_transform_node_name) rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item', '(Type=Bone)') rig_controller.set_pin_expansion(get_control_transform_node_name + '.Item', True) rig_controller.set_pin_default_value(get_control_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item.Name', control_name, True) rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item.Type', 'Control', True) try: rig_controller.add_template_node('Set Transform::Execute(in Item,in Space,in bInitial,in Value,in Weight,in bPropagateToChildren,io ExecuteContext)', unreal.Vector2D(542.832780, -257.833582), set_bone_transform_node_name) except: set_transform_scriptstruct = get_scriptstruct_by_node_name("SetTransform") rig_controller.add_unit_node(set_transform_scriptstruct, 'Execute', unreal.Vector2D(542.832780, -257.833582), set_bone_transform_node_name) rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item', '(Type=Bone,Name="None")') rig_controller.set_pin_expansion(set_bone_transform_node_name + '.Item', False) rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(set_bone_transform_node_name + '.bInitial', 'False') rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Weight', '1.000000') rig_controller.set_pin_default_value(set_bone_transform_node_name + '.bPropagateToChildren', 'True') rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item.Name', bone_name, True) rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item.Type', 'Bone', True) try: rig_controller.add_link(get_control_transform_node_name + '.Transform', set_bone_transform_node_name + '.Value') except: try: rig_controller.add_link(get_control_transform_node_name + '.Transform', set_bone_transform_node_name + '.Transform') except Exception as e: print("ERROR: CreateControlRig.py: rig_controller.add_Link(): " + str(e)) rig_controller.add_link(next_forward_execute, set_bone_transform_node_name + '.ExecuteContext') next_forward_execute = set_bone_transform_node_name + '.ExecuteContext' # def create_preferred_angle_control(bone_name): # global next_forward_execute # global effector_get_transform_widget_height # #effector_get_transform_widget_height += 250 # control_name = bone_name + '_ctrl' # get_control_transform_node_name = "RigUnit_PreferredAngle_GetTransform_" + bone_name # set_bone_transform_node_name = "RigtUnit_PreferredAngle_SetTransform_" + control_name # rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(101.499447, -244.500249), get_control_transform_node_name) # rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item', '(Type=Bone)') # rig_controller.set_pin_expansion(get_control_transform_node_name + '.Item', True) # rig_controller.set_pin_default_value(get_control_transform_node_name + '.Space', 'GlobalSpace') # rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item.Name', control_name, True) # rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item.Type', 'Control', True) # try: # rig_controller.add_template_node('Set Transform::Execute(in Item,in Space,in bInitial,in Value,in Weight,in bPropagateToChildren,io ExecuteContext)', unreal.Vector2D(542.832780, -257.833582), set_bone_transform_node_name) # except: # set_transform_scriptstruct = get_scriptstruct_by_node_name("SetTransform") # rig_controller.add_unit_node(set_transform_scriptstruct, 'Execute', unreal.Vector2D(542.832780, -257.833582), set_bone_transform_node_name) # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item', '(Type=Bone,Name="None")') # rig_controller.set_pin_expansion(set_bone_transform_node_name + '.Item', False) # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Space', 'GlobalSpace') # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.bInitial', 'False') # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Weight', '1.000000') # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.bPropagateToChildren', 'True') # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item.Name', bone_name, True) # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item.Type', 'Bone', True) # try: # rig_controller.add_link(get_control_transform_node_name + '.Transform', set_bone_transform_node_name + '.Value') # except: # try: # rig_controller.add_link(get_control_transform_node_name + '.Transform', set_bone_transform_node_name + '.Transform') # except Exception as e: # print("ERROR: CreateControlRig.py: rig_controller.add_Link(): " + str(e)) # rig_controller.add_link(next_forward_execute, set_bone_transform_node_name + '.ExecuteContext') # next_forward_execute = set_bone_transform_node_name + '.ExecuteContext' def create_effector(bone_name): global effector_get_transform_widget_height effector_get_transform_widget_height += 250 control_name = bone_name + '_ctrl' get_transform_name = control_name + '_RigUnit_GetTransform' pin_name = rig_controller.insert_array_pin('PBIK.Effectors', -1, '') print(pin_name) rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(-122.733358, effector_get_transform_widget_height), get_transform_name) rig_controller.set_pin_default_value(get_transform_name + '.Item', '(Type=Bone)') rig_controller.set_pin_expansion(get_transform_name + '.Item', True) rig_controller.set_pin_default_value(get_transform_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(get_transform_name + '.Item.Name', control_name, True) rig_controller.set_pin_default_value(get_transform_name + '.Item.Type', 'Control', True) rig_controller.set_node_selection([get_transform_name]) rig_controller.add_link(get_transform_name + '.Transform', pin_name + '.Transform') rig_controller.set_pin_default_value(pin_name + '.Bone', bone_name, False) if(bone_name in guide_list): rig_controller.set_pin_default_value(pin_name + '.StrengthAlpha', '0.200000', False) parser = argparse.ArgumentParser(description = 'Creates a Control Rig given a SkeletalMesh') parser.add_argument('--skeletalMesh', help='Skeletal Mesh to Use') parser.add_argument('--dtuFile', help='DTU File to use') args = parser.parse_args() asset_name = args.skeletalMesh.split('.')[1] + '_CR' package_path = args.skeletalMesh.rsplit('/', 1)[0] blueprint = unreal.load_object(name = package_path + '/' + asset_name , outer = None) if not blueprint: blueprint = unreal.AssetToolsHelpers.get_asset_tools().create_asset(asset_name=asset_name, package_path=package_path, asset_class=unreal.ControlRigBlueprint, factory=unreal.ControlRigBlueprintFactory()) #blueprint = unreal.load_object(name = '/project/.NewControlRigBlueprint', outer = None) if blueprint: # Turn off notifications or each change will compile the RigVM blueprint.suspend_notifications(True) library = blueprint.get_local_function_library() library_controller = blueprint.get_controller(library) hierarchy = blueprint.hierarchy hierarchy_controller = hierarchy.get_controller() rig_controller = blueprint.get_controller_by_name('RigVMModel') if rig_controller is None: rig_controller = blueprint.get_controller() #rig_controller.set_node_selection(['RigUnit_BeginExecution']) hierarchy_controller.import_bones_from_asset(args.skeletalMesh, 'None', True, False, True) # Remove Existing Nodes graph = rig_controller.get_graph() node_count = len(graph.get_nodes()) while node_count > 0: rig_controller.remove_node(graph.get_nodes()[-1]) node_count = node_count - 1 # Create Full Body IK Node rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_BeginExecution', 'Execute', unreal.Vector2D(22.229613, 60.424645), 'BeginExecution') rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_PrepareForExecution', 'Execute', unreal.Vector2D(-216.659278, -515.130927), 'PrepareForExecution') rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_InverseExecution', 'Execute', unreal.Vector2D(-307.389434, -270.395477), 'InverseExecution') rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_PBIK', 'Execute', unreal.Vector2D(370.599976, 42.845032), 'PBIK') rig_controller.set_pin_default_value('PBIK.Settings', '(Iterations=20,MassMultiplier=1.000000,MinMassMultiplier=0.200000,bStartSolveFromInputPose=True)') rig_controller.set_pin_expansion('PBIK.Settings', False) rig_controller.set_pin_default_value('PBIK.Debug', '(DrawScale=1.000000)') rig_controller.set_pin_expansion('PBIK.Debug', False) rig_controller.set_node_selection(['PBIK']) rig_controller.set_pin_default_value('PBIK.Root', 'hip', False) rig_controller.insert_array_pin('PBIK.BoneSettings', -1, '') rig_controller.set_pin_default_value('PBIK.BoneSettings.0.Bone', 'pelvis', False) rig_controller.set_pin_default_value('PBIK.BoneSettings.0.RotationStiffness', '0.900000', False) rig_controller.set_pin_default_value('PBIK.BoneSettings.0.PositionStiffness', '0.900000', False) next_forward_execute = 'BeginExecution.ExecuteContext' #rig_controller.add_link('BeginExecution.ExecuteContext', 'PBIK.ExecuteContext') # Get Bone list for character dtu_data = json.load(open(args.dtuFile.replace('\"', ''))) limits = dtu_data['LimitData'] bones_in_dtu = ['root'] for bone_limits in limits.values(): bone_limit_name = bone_limits[0] #print(bone_limit_name) bones_in_dtu.append(bone_limit_name) # Create Effectors, order matters. Child controls should be after Parent Control effector_list = ['pelvis', 'l_foot', 'r_foot', 'spine4', 'l_hand', 'r_hand'] # G9 effector_list+= ['chestUpper', 'head', 'lFoot', 'rFoot', 'lHand', 'rHand'] #G8 effector_list = [bone for bone in effector_list if bone in bones_in_dtu] #print(effector_list) # These controls are mid chain and don't have full weight guide_list = ['l_shin', 'r_shin', 'l_forearm', 'r_forearm'] # G9 guide_list+= ['lShin', 'rShin', 'lForearmBend', 'rForearmBend'] # G8 guide_list = [bone for bone in guide_list if bone in bones_in_dtu] # These controls are for bones that shouldn't move much on their own, but user can rotate them suggested_rotation_list = ['l_shoulder', 'r_shoulder'] # G9 suggested_rotation_list+= ['lCollar', 'rCollar'] # G8 suggested_rotation_list = [bone for bone in suggested_rotation_list if bone in bones_in_dtu] # This is for controls outside of Full Body IK control_list = ['root', 'hip'] control_list = [bone for bone in control_list if bone in bones_in_dtu] for effector_name in control_list + effector_list + guide_list: create_control(effector_name) parent_list = { 'root':['hip', 'l_foot', 'r_foot', 'l_shin', 'r_shin', 'lFoot', 'rFoot', 'lShin', 'rShin'], 'hip':['pelvis'], 'pelvis':['spine4', 'chestUpper'], 'spine4':['head', 'l_hand', 'r_hand', 'l_forearm', 'r_forearm'], 'chestUpper':['head', 'lHand', 'rHand', 'lForearmBend', 'rForearmBend'] } for parent_bone, child_bone_list in parent_list.items(): if not parent_bone in bones_in_dtu: continue filtered_child_bone_list = [bone for bone in child_bone_list if bone in bones_in_dtu] for child_bone in child_bone_list: hierarchy_controller.set_parent(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name= child_bone + '_ctrl'), unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name= parent_bone + '_ctrl'), True) hierarchy.set_local_transform(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=child_bone + '_ctrl'), unreal.Transform(location=[0.000000,0.000000,0.000000],rotation=[0.000000,0.000000,-0.000000],scale=[1.000000,1.000000,1.000000]), True, True) skeletal_mesh = unreal.load_object(name = args.skeletalMesh, outer = None) skeletal_mesh_import_data = skeletal_mesh.get_editor_property('asset_import_data') skeletal_mesh_force_front_x = skeletal_mesh_import_data.get_editor_property('force_front_x_axis') stiff_limits = ['l_shoulder', 'r_shoulder'] stiff_limits+= ['lCollar', 'rCollar'] exclude_limits = ['root', 'hip', 'pelvis'] for bone_limits in limits.values(): # Get the name of the bone bone_limit_name = bone_limits[0] # Add twist bones to the exlude list if 'twist' in bone_limit_name.lower(): exluded_bone_settings = rig_controller.insert_array_pin('PBIK.ExcludedBones', -1, '') rig_controller.set_pin_default_value(exluded_bone_settings, bone_limit_name, False) # Get the bone limits bone_limit_x_min = bone_limits[2] bone_limit_x_max = bone_limits[3] bone_limit_y_min = bone_limits[4] * -1.0 bone_limit_y_max = bone_limits[5] * -1.0 bone_limit_z_min = bone_limits[6] * -1.0 bone_limit_z_max = bone_limits[7] * -1.0 # update the axis if force front was used (facing right) if skeletal_mesh_force_front_x: bone_limit_y_min = bone_limits[2] * -1.0 bone_limit_y_max = bone_limits[3] * -1.0 bone_limit_z_min = bone_limits[4] * -1.0 bone_limit_z_max = bone_limits[5] * -1.0 bone_limit_x_min = bone_limits[6] bone_limit_x_max = bone_limits[7] if not bone_limit_name in exclude_limits: #if not bone_limit_name == "l_shin": continue limit_bone_settings = rig_controller.insert_array_pin('PBIK.BoneSettings', -1, '') rig_controller.set_pin_default_value(limit_bone_settings + '.Bone', bone_limit_name, False) x_delta = abs(bone_limit_x_max - bone_limit_x_min) y_delta = abs(bone_limit_y_max - bone_limit_y_min) z_delta = abs(bone_limit_z_max - bone_limit_z_min) if(x_delta < 15.0): rig_controller.set_pin_default_value(limit_bone_settings + '.X', 'Locked', False) elif (x_delta > 90.0): rig_controller.set_pin_default_value(limit_bone_settings + '.X', 'Free', False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.X', 'Free', False) if(y_delta < 15.0): rig_controller.set_pin_default_value(limit_bone_settings + '.Y', 'Locked', False) elif (y_delta > 90.0): rig_controller.set_pin_default_value(limit_bone_settings + '.Y', 'Free', False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.Y', 'Free', False) if(z_delta < 15.0): rig_controller.set_pin_default_value(limit_bone_settings + '.Z', 'Locked', False) elif (z_delta > 90.0): rig_controller.set_pin_default_value(limit_bone_settings + '.Z', 'Free', False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.Z', 'Free', False) # rig_controller.set_pin_default_value(limit_bone_settings + '.X', 'Limited', False) # rig_controller.set_pin_default_value(limit_bone_settings + '.Y', 'Limited', False) # rig_controller.set_pin_default_value(limit_bone_settings + '.Z', 'Limited', False) # It feels like Min\Max angel aren't the actual extents, but the amount of rotation allowed. So they shoudl be 0 to abs(min, max) # I think there's a bug if a min rotation is more negative than max is positive, the negative gets clamped to the relative positive. rig_controller.set_pin_default_value(limit_bone_settings + '.MinX', str(min(bone_limit_x_max, bone_limit_x_min)), False) rig_controller.set_pin_default_value(limit_bone_settings + '.MaxX', str(max(bone_limit_x_max, abs(bone_limit_x_min))), False) rig_controller.set_pin_default_value(limit_bone_settings + '.MinY', str(min(bone_limit_y_max, bone_limit_y_min)), False) rig_controller.set_pin_default_value(limit_bone_settings + '.MaxY', str(max(bone_limit_y_max, abs(bone_limit_y_min))), False) rig_controller.set_pin_default_value(limit_bone_settings + '.MinZ', str(min(bone_limit_z_max, bone_limit_z_min)), False) rig_controller.set_pin_default_value(limit_bone_settings + '.MaxZ', str(max(bone_limit_z_max, abs(bone_limit_z_min))), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MinX', str(min(bone_limit_z_max, bone_limit_z_min)), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MaxX', str(max(bone_limit_z_max, bone_limit_z_min)), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MinY', str(min(bone_limit_x_max, bone_limit_x_min)), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MaxY', str(max(bone_limit_x_max, bone_limit_x_min)), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MinZ', str(min(bone_limit_y_max, bone_limit_y_min)), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MaxZ', str(max(bone_limit_y_max, bone_limit_y_min)), False) if bone_limit_name in stiff_limits: rig_controller.set_pin_default_value(limit_bone_settings + '.PositionStiffness', '0.800000', False) rig_controller.set_pin_default_value(limit_bone_settings + '.RotationStiffness', '0.800000', False) # Figure out preferred angles, the primary angle is the one that turns the furthest from base pose rig_controller.set_pin_default_value(limit_bone_settings + '.bUsePreferredAngles', 'true', False) x_max_rotate = max(abs(bone_limit_x_min), abs(bone_limit_x_max)) y_max_rotate = max(abs(bone_limit_y_min), abs(bone_limit_y_max)) z_max_rotate = max(abs(bone_limit_z_min), abs(bone_limit_z_max)) #print(bone_limit_name, x_max_rotate, y_max_rotate, z_max_rotate) if bone_limit_name in suggested_rotation_list: rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.X', "0.0", False) rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Y', "0.0", False) rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Z', "0.0", False) create_control(bone_limit_name) to_euler_name = "Preferred_Angles_To_Euler_" + bone_limit_name get_transform_name = "Preferred_Angles_GetRotator_" + bone_limit_name rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetControlRotator', 'Execute', unreal.Vector2D(-344.784477, 4040.400172), get_transform_name) rig_controller.set_pin_default_value(get_transform_name + '.Space', 'GlobalSpace') #rig_controller.set_pin_default_value(get_transform_name + '.bInitial', 'False') rig_controller.set_pin_default_value(get_transform_name + '.Control', bone_limit_name + '_ctrl', True) #rig_controller.set_pin_default_value(get_transform_name + '.Item.Type', 'Control', True) #rig_controller.add_unit_node_from_struct_path('/project/.RigVMFunction_MathQuaternionToEuler', 'Execute', unreal.Vector2D(9.501237, 4176.400172), to_euler_name) #rig_controller.add_link(get_transform_name + '.Transform.Rotation', to_euler_name + '.Value') rig_controller.add_link(get_transform_name + '.Rotator.Roll', limit_bone_settings + '.PreferredAngles.X') rig_controller.add_link(get_transform_name + '.Rotator.Pitch', limit_bone_settings + '.PreferredAngles.Y') rig_controller.add_link(get_transform_name + '.Rotator.Yaw', limit_bone_settings + '.PreferredAngles.Z') else: limit_divider = 1.0 if x_max_rotate > y_max_rotate and x_max_rotate > z_max_rotate: if abs(bone_limit_x_min) > abs(bone_limit_x_max): rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.X', str(bone_limit_x_min / limit_divider), False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.X', str(bone_limit_x_max / limit_divider), False) if y_max_rotate > x_max_rotate and y_max_rotate > z_max_rotate: if abs(bone_limit_y_min) > abs(bone_limit_y_max): rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Y', str(bone_limit_y_min / limit_divider), False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Y', str(bone_limit_y_max / limit_divider), False) if z_max_rotate > x_max_rotate and z_max_rotate > y_max_rotate: if abs(bone_limit_z_min) > abs(bone_limit_z_max): rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Z', str(bone_limit_z_min / limit_divider), False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Z', str(bone_limit_z_max / limit_divider), False) # rig_controller.set_pin_default_value('PBIK.BoneSettings.0.Bone', 'pelvis', False) # rig_controller.set_pin_default_value('PBIK.BoneSettings.0.RotationStiffness', '0.900000', False) # rig_controller.set_pin_default_value('PBIK.BoneSettings.0.PositionStiffness', '0.900000', False) # Attach the node to execute rig_controller.add_link(next_forward_execute, 'PBIK.ExecuteContext') unreal.ControlRigBlueprintLibrary.set_preview_mesh(blueprint, skeletal_mesh) # Turn on notifications and force a recompile blueprint.suspend_notifications(False) unreal.ControlRigBlueprintLibrary.recompile_vm(blueprint) #rig_controller.add_link('RigUnit_BeginExecution.ExecuteContext', 'PBIK.ExecuteContext')
# This script describes the different ways of setting variant thumbnails via the Python API import unreal def import_texture(filename, contentpath): task = unreal.AssetImportTask() task.set_editor_property('filename', filename) task.set_editor_property('destination_path', contentpath) task.automated = True asset_tools = unreal.AssetToolsHelpers.get_asset_tools() asset_tools.import_asset_tasks([task]) asset_paths = task.get_editor_property("imported_object_paths") if not asset_paths: unreal.log_warning("No assets were imported!") return None return unreal.load_asset(asset_paths[0]) if __name__ == "__main__": lvs = unreal.VariantManagerLibrary.create_level_variant_sets_asset("LVS", "/Game/") lvs_actor = unreal.VariantManagerLibrary.create_level_variant_sets_actor(lvs) if lvs is None or lvs_actor is None: print ("Failed to spawn either the LevelVariantSets asset or the LevelVariantSetsActor!") quit() var_set1 = unreal.VariantSet() var_set1.set_display_text("My VariantSet") varTexture = unreal.Variant() varTexture.set_display_text("From texture") varPath = unreal.Variant() varPath.set_display_text("From path") varCam = unreal.Variant() varCam.set_display_text("From cam") varViewport = unreal.Variant() varViewport.set_display_text("From viewport") lvs.add_variant_set(var_set1) var_set1.add_variant(varTexture) var_set1.add_variant(varPath) var_set1.add_variant(varCam) var_set1.add_variant(varViewport) # Set thumbnail from an unreal texture texture = import_texture("/project/.jpg", "/project/") if texture: varTexture.set_thumbnail_from_texture(texture) var_set1.set_thumbnail_from_texture(texture) # Set thumbnail directly from a filepath varPath.set_thumbnail_from_file("/project/.png") # Set thumbnail from camera transform and properties trans = unreal.Transform() fov = 50 minZ = 50 gamma = 2.2 varCam.set_thumbnail_from_camera(lvs_actor, trans, fov, minZ, gamma) # Set thumbnail directly from the active editor viewport varViewport.set_thumbnail_from_editor_viewport()
# Copyright Epic Games, Inc. All Rights Reserved. import os import unreal import subprocess as sp #------------------------------------------------------------------------------- class _PlatformBase(unreal.Platform): def _read_env(self): yield from () def _get_version_ue4(self): import re dot_cs = self.get_unreal_context().get_engine().get_dir() dot_cs /= "Source/project/.cs" needles = ( ("DefaultWindowsSdkVersion", re.compile(r'DefaultWindowsSdkVersion\s+=\s+("|[\w.]+\("|)([^"]+)"?\)?\s*;')), ("VersionNumber", re.compile(r'^\s+VersionNumber.Parse\(("([^"]+))')), ) versions = [] try: with open(dot_cs, "rt") as lines: for line in lines: for seed, needle in needles: if seed not in line: continue m = needle.search(line) if m: versions.append(m.group(2)) except FileNotFoundError: return return self._get_version_string(versions) def _get_version_ue5(self): # Extract the Windows SDK version dot_cs = self.get_unreal_context().get_engine().get_dir() dot_cs /= "Source/project/" version = self._get_version_ue5_path(dot_cs / "MicrosoftPlatformSDK.Versions.cs") return version or self._get_version_ue5_path(dot_cs / "MicrosoftPlatformSDK.cs") def _get_version_ue5_path(self, dot_cs): import re needle = re.compile(r'VersionNumber.Parse\("([\d.]+)"') versions = [] try: with open(dot_cs, "rt") as lines: for line in (x for x in lines if "VersionNumber" in x): if m := needle.search(line): versions.append(m.group(1)) break except FileNotFoundError: pass if not versions: if sdk_version := self._get_version_helper_ue5(dot_cs): versions.append(sdk_version) else: return # Extract the Visual Studio toolchain version vs_version = self._get_vs_toolchain_version_string(dot_cs) if not vs_version: vs_version = self._get_vs_toolchain_version_string(dot_cs.parent / "UEBuildWindows.cs") if not vs_version: return versions.append(vs_version) return self._get_version_string(versions) def _get_vs_toolchain_version_string(self, dot_cs): import re try: with open(dot_cs, "rt") as lines: line_iter = iter(lines) for line in line_iter: if "PreferredVisualCppVersions" in line: break else: return version = None for line in line_iter: if "}" in line: break elif m := re.match(r'^\s+VersionNumberRange\.Parse\(.+, "([^"]+)', line): version = m.group(1) break return version except FileNotFoundError: return def _get_version_string(self, versions): msvc_versions = list(x for x in versions if x >= "14.") if not msvc_versions: return sdk_versions = list(x for x in versions if x.startswith("10.")) if not sdk_versions: return return max(sdk_versions) + "-" + max(msvc_versions) #------------------------------------------------------------------------------- class Platform(_PlatformBase): name = "Win64" config_name = "Windows" autosdk_name = None vs_transport = "Default" def _get_cook_form(self, target): if target == "game": return "Windows" if self.get_unreal_context().get_engine().get_version_major() > 4 else "WindowsNoEditor" if target == "client": return "WindowsClient" if target == "server": return "WindowsServer" def _launch(self, exec_context, stage_dir, binary_path, args): if stage_dir: base_dir = binary_path.replace("\\", "/").split("/") base_dir = "/".join(base_dir[-4:-1]) base_dir = stage_dir + base_dir if not os.path.isdir(base_dir): raise EnvironmentError(f"Failed to find base directory '{base_dir}'") args = (*args, "-basedir=" + base_dir) cmd = exec_context.create_runnable(binary_path, *args) cmd.launch() return (cmd.get_pid(), None) def _kill(self, target): target_name = None context = self.get_unreal_context() if target == "editor": ue_version = context.get_engine().get_version_major() target_name = "UE4Editor" if ue_version == 4 else "UnrealEditor" elif target: target_type = unreal.TargetType.parse(target) target_name = context.get_target_by_type(target_type).get_name() if target_name: print(f"Terminating {target_name}*.exe") sp.run(rf'taskkill.exe /f /fi "imagename eq {target_name}*"') else: self._kill("client") self._kill("game")
#from typing_extensions import Self from typing_extensions import Self import unreal class wrapped_sb_bp : dir :str bp_class :object loaded_bp :object name :str def get_selected_asset_dir() -> str : selected_asset = unreal.EditorUtilityLibrary.get_selected_assets()[0] str_selected_asset = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(selected_asset) path = str_selected_asset.rsplit('/', 1)[0] return path def get_bp_c_by_name(__bp_dir:str): __bp_c = __bp_dir + '_C' return __bp_c def get_bp_mesh_comp_by_name (__bp_c:str, __seek_comp_name:str) : loaded_bp_c = unreal.EditorAssetLibrary.load_blueprint_class(__bp_c) bp_c_obj = unreal.get_default_object(loaded_bp_c) loaded_comp = bp_c_obj.get_editor_property(__seek_comp_name) return loaded_comp #인풋으로 받는 __bp_c 아규먼트 '/direc/*_Bluperint.*_Blueprint_c' << 와 같은 포맷으로 받아야함 ##asset_path를 str로 끌어왔을 경우 상단의 get_bp_c_by_name 함수 이용하여 class로 한번 더 래핑해주세요. ###__seek_comp_name 아규먼트 동작 안하면 아래의 함수를 사용하세요. def get_bp_instance (__bp_c:str) : loaded_bp_c = unreal.EditorAssetLibrary.load_blueprint_class(__bp_c) bp_c_obj = unreal.get_default_object(loaded_bp_c) return bp_c_obj #Object화된 Blueprint instance를 반환 #컴포넌트는 반환된 bp_c_obj.get_editor_property('찾고자 하는 컴포넌트 이름')으로 끌어다 쓰세요. def get_bp_comp_by_name (__bp_c: str, __seek: str) : #source_mesh = ue.load_asset(__mesh_dir) loaded_bp_c = unreal.EditorAssetLibrary.load_blueprint_class(__bp_c) bp_c_obj = unreal.get_default_object(loaded_bp_c) loaded_comp = bp_c_obj.get_editor_property(__seek) return loaded_comp
import unreal from typing import Optional def get_asset_actor_by_label(label: str) -> Optional[unreal.Actor]: """ Gets the asset actor by the given label. Args: label (str): The label of the actor. """ actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) for actor in actor_subsystem.get_all_level_actors(): # type: ignore if label == actor.get_actor_label(): return actor def delete_asset_actor_with_label(label: str): """ Deletes the actor with the given label. Args: label (str): The label of the actor. """ actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) for actor in actor_subsystem.get_all_level_actors(): # type: ignore if label == actor.get_actor_label(): actor_subsystem.destroy_actor(actor) # type: ignore def spawn_asset_in_level( label: str, asset: unreal.Object, location: Optional[list] = None, rotation: Optional[list] = None, scale: Optional[list] = None, replace_existing: bool = False ) -> unreal.Actor: """ Spawns the asset in the level. Args: label (str): The label of the actor. asset (unreal.Object): The asset object to spawn. location (list): The world location in the level to spawn the actor. rotation (list): The world rotation in degrees in the level to spawn the actor. scale (list): The scale of the actor. replace_existing (bool, optional): If true, this will delete any existing actor with this label before spawning it. Defaults to False. """ if not location: location = [0.0, 0.0, 0.0] if not rotation: rotation = [0.0, 0.0, 0.0] if not scale: scale = [1.0, 1.0, 1.0] actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) # if we want to replace the existing actor, delete it first if replace_existing: delete_asset_actor_with_label(label) # spawn the actor at the origin since this method does not support scale actor = actor_subsystem.spawn_actor_from_object( # type: ignore asset, location=unreal.Vector(0.0, 0.0, 0.0), transient=False ) actor.set_actor_label(asset.get_name()) # now make the transform changes, since this can do scale, rotation, and location actor.set_actor_transform( new_transform=unreal.Transform( location=unreal.Vector(x=location[0], y=location[1], z=location[2]), rotation=unreal.Rotator(roll=rotation[0], pitch=rotation[1], yaw=rotation[2]), scale=unreal.Vector(x=scale[0], y=scale[1], z=scale[2]) ), sweep=False, teleport=True ) return actor
import os import re import subprocess import time from pathlib import Path import unreal import winsound from mods.liana.helpers import * from mods.liana.valorant import * # BigSets all_textures = [] all_blueprints = {} object_types = [] all_level_paths = [] AssetTools = unreal.AssetToolsHelpers.get_asset_tools() ## Returns a array with all OverrideMaterials def create_override_material(data): material_array = [] for mat in data["Properties"]["OverrideMaterials"]: if not mat: material_array.append(None) continue object_name = return_object_name(mat["ObjectName"]) if object_name == "Stone_M2_Steps_MI1": object_name = "Stone_M2_Steps_MI" if "MaterialInstanceDynamic" in object_name: material_array.append(None) continue material_array.append(unreal.load_asset( f'/project/{object_name}')) return material_array def extract_assets(settings: Settings): ## Extracting Assets on umodel asset_objects = settings.selected_map.folder_path.joinpath("all_assets.txt") args = [settings.umodel.__str__(), f"-path={settings.paks_path.__str__()}", f"-game=valorant", f"-aes={settings.aes}", f"-files={asset_objects}", "-export", f"-{settings.texture_format.replace('.', '')}", f"-out={settings.assets_path.__str__()}"] subprocess.call(args, stderr=subprocess.DEVNULL) def extract_data( settings: Settings, export_directory: str, asset_list_txt: str = ""): ## Extracts the data from CUE4Parse (Json's) args = [settings.cue4extractor.__str__(), "--game-directory", settings.paks_path.__str__(), "--aes-key", settings.aes, "--export-directory", export_directory.__str__(), "--map-name", settings.selected_map.name, "--file-list", asset_list_txt, "--game-umaps", settings.umap_list_path.__str__() ] subprocess.call(args) def get_map_assets(settings: Settings): ## Handles the extraction of the assets and filters them by type umaps = [] if check_export(settings): extract_data( settings, export_directory=settings.selected_map.umaps_path) extract_assets(settings) umaps = get_files( path=settings.selected_map.umaps_path.__str__(), extension=".json") umap: Path object_list = list() actor_list = list() materials_ovr_list = list() materials_list = list() for umap in umaps: umap_json, asd = filter_umap(read_json(umap)) object_types.append(asd) # save json save_json(umap.__str__(), umap_json) # get objects umap_objects, umap_materials, umap_actors = get_objects(umap_json, umap) actor_list.append(umap_actors) object_list.append(umap_objects) materials_ovr_list.append(umap_materials) # ACTORS actor_txt = save_list(filepath=settings.selected_map.folder_path.joinpath( f"_assets_actors.txt"), lines=actor_list) extract_data( settings, export_directory=settings.selected_map.actors_path, asset_list_txt=actor_txt) actors = get_files( path=settings.selected_map.actors_path.__str__(), extension=".json") for ac in actors: actor_json = read_json(ac) actor_objects, actor_materials, local4list = get_objects(actor_json, umap) object_list.append(actor_objects) materials_ovr_list.append(actor_materials) # next object_txt = save_list(filepath=settings.selected_map.folder_path.joinpath( f"_assets_objects.txt"), lines=object_list) mats_ovr_txt = save_list(filepath=settings.selected_map.folder_path.joinpath( f"_assets_materials_ovr.txt"), lines=materials_ovr_list) extract_data( settings, export_directory=settings.selected_map.objects_path, asset_list_txt=object_txt) extract_data( settings, export_directory=settings.selected_map.materials_ovr_path, asset_list_txt=mats_ovr_txt) # --------------------------------------------------------------------------------------- models = get_files( path=settings.selected_map.objects_path.__str__(), extension=".json") model: Path for model in models: model_json = read_json(model) # save json save_json(model.__str__(), model_json) # get object materials model_materials = get_object_materials(model_json) # get object textures # ... materials_list.append(model_materials) save_list(filepath=settings.selected_map.folder_path.joinpath("all_assets.txt"), lines=[ [ path_convert(path) for path in _list ] for _list in object_list + materials_list + materials_ovr_list ]) mats_txt = save_list(filepath=settings.selected_map.folder_path.joinpath( f"_assets_materials.txt"), lines=materials_list) extract_data( settings, export_directory=settings.selected_map.materials_path, asset_list_txt=mats_txt) extract_assets(settings) with open(settings.selected_map.folder_path.joinpath('exported.yo').__str__(), 'w') as out_file: out_file.write(write_export_file()) with open(settings.assets_path.joinpath('exported.yo').__str__(), 'w') as out_file: out_file.write(write_export_file()) else: umaps = get_files( path=settings.selected_map.umaps_path.__str__(), extension=".json") return umaps def set_material( ue_material, settings: Settings, mat_data: actor_defs, ): ## Sets the material parameters to the material if not mat_data.props: return mat_props = mat_data.props set_textures(mat_props, ue_material, settings=settings) set_all_settings(mat_props, ue_material) # fix this if "BasePropertyOverrides" in mat_props: base_prop_override = set_all_settings(mat_props["BasePropertyOverrides"], unreal.MaterialInstanceBasePropertyOverrides()) set_unreal_prop(ue_material, "BasePropertyOverrides", base_prop_override) unreal.MaterialEditingLibrary.update_material_instance(ue_material) if "StaticParameters" in mat_props: if "StaticSwitchParameters" in mat_props["StaticParameters"]: for param in mat_props["StaticParameters"]["StaticSwitchParameters"]: param_name = param["ParameterInfo"]["Name"].lower() param_value = param["Value"] unreal.MaterialEditingLibrary.set_material_instance_static_switch_parameter_value( ue_material, param_name, bool(param_value)) ## Unreal doesn't support mask parameters switch lolz so have to do this if "StaticComponentMaskParameters" in mat_props["StaticParameters"]: for param in mat_props["StaticParameters"]["StaticComponentMaskParameters"]: mask_list = ["R", "G", "B"] for mask in mask_list: value = param[mask] unreal.MaterialEditingLibrary.set_material_instance_static_switch_parameter_value( ue_material, mask, bool(value)) if "ScalarParameterValues" in mat_props: for param in mat_props["ScalarParameterValues"]: param_name = param['ParameterInfo']['Name'].lower() param_value = param["ParameterValue"] set_material_scalar_value(ue_material, param_name, param_value) if "VectorParameterValues" in mat_props: for param in mat_props["VectorParameterValues"]: param_name = param['ParameterInfo']['Name'].lower() param_value = param["ParameterValue"] set_material_vector_value(ue_material, param_name, get_rgb(param_value)) def set_textures(mat_props: dict, material_reference, settings: Settings): ## Sets the textures to the material set_texture_param = unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value if not has_key("TextureParameterValues", mat_props): return for tex_param in mat_props["TextureParameterValues"]: tex_game_path = get_texture_path(s=tex_param, f=settings.texture_format) if not tex_game_path: continue tex_local_path = settings.assets_path.joinpath(tex_game_path).__str__() param_name = tex_param['ParameterInfo']['Name'].lower() tex_name = Path(tex_local_path).stem if Path(tex_local_path).exists(): loaded_texture = unreal.load_asset( f'/project/{tex_name}') if not loaded_texture: continue set_texture_param(material_reference, param_name, loaded_texture) unreal.MaterialEditingLibrary.update_material_instance(material_reference) def settings_create_ovr_material(mat_dict: list): ## No clue (?) but not gonna bother rn no idea why i didnt use the first ovr material func material_array = [] loaded = None for mat in mat_dict: if not mat: material_array.append(None) continue object_name = return_object_name(mat["ObjectName"]) if "MaterialInstanceDynamic" in object_name: material_array.append(None) continue loaded = unreal.load_asset(f'/project/{object_name}') if loaded == None: loaded = unreal.load_asset(f'/project/{object_name}') material_array.append(loaded) return material_array def set_all_settings(asset_props: dict, component_reference): ## Sets all the settings to the component (material, mesh, etc) from "Properties" using some weird black magic if not asset_props: return for setting in asset_props: value_setting = asset_props[setting] try: editor_property = component_reference.get_editor_property(setting) except: continue class_name = type(editor_property).__name__ type_value = type(value_setting).__name__ if type_value == "int" or type_value == "float" or type_value == "bool": if setting == "InfluenceRadius" and value_setting == 0: set_unreal_prop(component_reference, setting, 14680) continue set_unreal_prop(component_reference, setting, value_setting) continue if "::" in value_setting: value_setting = value_setting.split("::")[1] # Try to make these automatic? with 'unreal.classname.value"? if class_name == "LinearColor": set_unreal_prop(component_reference, setting, unreal.LinearColor(r=value_setting['R'], g=value_setting['G'], b=value_setting['B'])) continue if class_name == "Vector4": set_unreal_prop(component_reference, setting, unreal.Vector4(x=value_setting['X'], y=value_setting['Y'], z=value_setting['Z'], w=value_setting['W'])) continue if "Color" in class_name: set_unreal_prop(component_reference, setting, unreal.Color(r=value_setting['R'], g=value_setting['G'], b=value_setting['B'], a=value_setting['A'])) continue if type_value == "dict": if setting == "IESTexture": set_unreal_prop(component_reference, setting, get_ies_texture(value_setting)) continue if setting == "Cubemap": set_unreal_prop(component_reference, setting, get_cubemap_texture(value_setting)) continue if setting == "DecalMaterial": component_reference.set_decal_material(get_mat(value_setting)) continue if setting == "DecalSize": set_unreal_prop(component_reference, setting, unreal.Vector(value_setting["X"], value_setting["Y"], value_setting["Z"])) continue if setting == "StaticMesh": mesh_loaded = mesh_to_asset(value_setting, "StaticMesh ", "Meshes") set_unreal_prop(component_reference, setting, mesh_loaded) continue if setting == "BoxExtent": set_unreal_prop(component_reference, 'box_extent', unreal.Vector(x=value_setting['X'], y=value_setting['Y'], z=value_setting['Z'])), continue if setting == "LightmassSettings": set_unreal_prop(component_reference, 'lightmass_settings', get_light_mass(value_setting, component_reference.get_editor_property( 'lightmass_settings'))) continue continue if type_value == "list": if setting == "OverrideMaterials": mat_override = settings_create_ovr_material(value_setting) set_unreal_prop(component_reference, setting, mat_override) continue continue python_unreal_value = return_python_unreal_enum(value_setting) try: value = eval(f'unreal.{class_name}.{python_unreal_value}') except: continue set_unreal_prop(component_reference, setting, value) return component_reference def get_light_mass(light_mass: dict, light_mass_reference): blacklist_lmass = ['bLightAsBackFace', 'bUseTwoSidedLighting'] ## Sets the lightmass settings to the component for l_mass in light_mass: if l_mass in blacklist_lmass: continue value_setting = light_mass[l_mass] first_name = l_mass if l_mass[0] == "b": l_mass = l_mass[1:] value = re.sub(r'(?<!^)(?=[A-Z])', '_', l_mass) set_unreal_prop(light_mass_reference, value, value_setting) return light_mass_reference def import_light(light_data: actor_defs, all_objs: list): ## Imports the light actors to the World light_type_replace = light_data.type.replace("Component", "") if not light_data.transform: light_data.transform = get_scene_transform(light_data.scene_props) # light_data.transform = get_scene_parent(light_data.data,light_data.outer,all_objs) if not light_data.transform: return light = unreal.EditorLevelLibrary.spawn_actor_from_class(eval(f'unreal.{light_type_replace}'), light_data.transform.translation, light_data.transform.rotation.rotator()) light.set_folder_path(f'Lights/{light_type_replace}') light.set_actor_label(light_data.name) light.set_actor_scale3d(light_data.transform.scale3d) light_component = unreal.BPFL.get_component(light) if type(light_component) == unreal.BrushComponent: light_component = light if hasattr(light_component, "settings"): set_unreal_prop(light_component, "Unbound", True) set_unreal_prop(light_component, "Priority", 1.0) set_all_settings(light_data.props["Settings"], light_component.settings) set_all_settings(light_data.props, light_component) def import_decal(decal_data: actor_defs): ## Imports the decal actors to the World if not decal_data.transform or has_key("Template", decal_data.data): return decal = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.DecalActor, decal_data.transform.translation, decal_data.transform.rotation.rotator()) decal.set_folder_path(f'Decals') decal.set_actor_label(decal_data.name) decal.set_actor_scale3d(decal_data.transform.scale3d) decal_component = decal.decal if type(decal_data) == dict: decal_component.set_decal_material(get_mat(actor_def=decal_data["DecalMaterial"])) set_all_settings(decal_data.props, decal_component) ## fix this so it stops returning #some bps are not spawning because of attachparent ig fix it later def fix_actor_bp(actor_data: actor_defs, settings: Settings): ## Fixes spawned blueprints with runtime-changed components try: component = unreal.BPFL.get_component_by_name(all_blueprints[actor_data.outer], actor_data.name) except: return if not component: return if has_key("StaticMesh", actor_data.props): loaded = mesh_to_asset(actor_data.props["StaticMesh"], "StaticMesh ", "Meshes") component.set_editor_property('static_mesh', loaded) if has_key("OverrideMaterials", actor_data.props): if settings.import_materials: mat_override = create_override_material(actor_data.data) if mat_override and "Barrier" not in actor_data.name: unreal.BPFL.set_override_material(all_blueprints[actor_data.outer], actor_data.name, mat_override) if not has_key("AttachParent", actor_data.props): return transform = has_transform(actor_data.props) if type(transform) != bool: if has_key("RelativeScale3D", actor_data.props): component = unreal.BPFL.get_component_by_name(all_blueprints[actor_data.outer], actor_data.name) set_unreal_prop(component, "relative_scale3d", transform.scale3d) if has_key("RelativeLocation", actor_data.props): component = unreal.BPFL.get_component_by_name(all_blueprints[actor_data.outer], actor_data.name) set_unreal_prop(component, "relative_location", transform.translation) if has_key("RelativeRotation", actor_data.props): component = unreal.BPFL.get_component_by_name(all_blueprints[actor_data.outer], actor_data.name) set_unreal_prop(component, "relative_rotation", transform.rotation.rotator()) def import_mesh(mesh_data: actor_defs, settings: Settings, map_obj: MapObject): ## Imports the mesh actor to the world override_vertex_colors = [] if has_key("Template", mesh_data.data): fix_actor_bp(mesh_data, settings) return if not has_key("StaticMesh", mesh_data.props): return transform = get_transform(mesh_data.props) if not transform: return unreal_mesh_type = unreal.StaticMeshActor if map_obj.is_instanced(): unreal_mesh_type = unreal.HismActor mesh_actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal_mesh_type, location=unreal.Vector(), rotation=unreal.Rotator()) mesh_actor.set_actor_label(mesh_data.outer) if has_key("LODData", mesh_data.data): override_vertex_colors = get_override_vertex_color(mesh_data.data) if map_obj.is_instanced(): component = mesh_actor.hism_component mesh_actor.set_folder_path('Meshes/Instanced') for inst_index in mesh_data.data["PerInstanceSMData"]: component.add_instance(get_transform(inst_index)) else: component = mesh_actor.static_mesh_component folder_name = 'Meshes/Static' if map_obj.umap.endswith('_VFX'): folder_name = 'Meshes/VFX' mesh_actor.set_folder_path(folder_name) set_all_settings(mesh_data.props, component) component.set_world_transform(transform, False, False) if len(override_vertex_colors) > 0: unreal.BPFL.paint_sm_vertices(component, override_vertex_colors, map_obj.model_path) if has_key("OverrideMaterials", mesh_data.props): if not settings.import_materials: return mat_override = create_override_material(mesh_data.data) if mat_override: set_unreal_prop(component, "override_materials", mat_override) def set_mesh_build_settings(settings: Settings): ## Sets the build settings for the mesh since umodel exports it with wrong LMapCoordinateIndex and LMapResolution and Collision obviously light_res_multiplier = settings.manual_lmres_mult objects_path = settings.selected_map.objects_path list_objects = objects_path for m_object in os.listdir(list_objects): object_json = read_json(objects_path.joinpath(m_object)) for o_object in object_json: key = actor_defs(o_object) if key.type == "StaticMesh": light_map_res = round(256 * light_res_multiplier / 4) * 4 light_map_coord = 1 if has_key("LightMapCoordinateIndex", key.props): light_map_coord = key.props["LightMapCoordinateIndex"] if has_key("LightMapResolution", key.props): light_map_res = round(key.props["LightMapResolution"] * light_res_multiplier / 4) * 4 mesh_load = unreal.load_asset(f"/project/{key.name}") if mesh_load: cast_mesh = unreal.StaticMesh.cast(mesh_load) actual_coord = cast_mesh.get_editor_property("light_map_coordinate_index") actual_resolution = cast_mesh.get_editor_property("light_map_resolution") if actual_coord != light_map_coord: set_unreal_prop(cast_mesh, "light_map_coordinate_index", light_map_coord) if actual_resolution != light_map_res: set_unreal_prop(cast_mesh, "light_map_resolution", light_map_res) if key.type == "BodySetup": if has_key("CollisionTraceFlag", key.props): col_trace = re.sub('([A-Z])', r'_\1', key.props["CollisionTraceFlag"]) mesh_load = unreal.load_asset(f"/project/{key.outer}") if mesh_load: cast_mesh = unreal.StaticMesh.cast(mesh_load) body_setup = cast_mesh.get_editor_property("body_setup") str_collision = 'CTF_' + col_trace[8:len(col_trace)].upper() set_unreal_prop(body_setup, "collision_trace_flag", eval(f'unreal.CollisionTraceFlag.{str_collision}')) set_unreal_prop(cast_mesh, "body_setup", body_setup) def import_umap(settings: Settings, umap_data: dict, umap_name: str): ## Imports a umap according to filters and settings selected // at the moment i don't like it since ## it's a bit messy and i don't like the way i'm doing it but it works ## Looping before the main_import just for blueprints to be spawned first, no idea how to fix it lets stay like this atm objects_to_import = filter_objects(umap_data, umap_name) if settings.import_blueprints: for objectIndex, object_data in enumerate(objects_to_import): object_type = get_object_type(object_data) if object_type == "blueprint": import_blueprint(actor_defs(object_data), objects_to_import) for objectIndex, object_data in enumerate(objects_to_import): object_type = get_object_type(object_data) actor_data_definition = actor_defs(object_data) if object_type == "mesh" and settings.import_Mesh: map_object = MapObject(settings=settings, data=object_data, umap_name=umap_name, umap_data=umap_data) import_mesh(mesh_data=actor_data_definition, settings=settings, map_obj=map_object) if object_type == "decal" and settings.import_decals: import_decal(actor_data_definition) if object_type == "light" and settings.import_lights: import_light(actor_data_definition, objects_to_import) def level_streaming_setup(): ## Sets up the level streaming for the map if using the streaming option world = unreal.EditorLevelLibrary.get_editor_world() for level_path in all_level_paths: unreal.EditorLevelUtils.add_level_to_world(world, level_path, unreal.LevelStreamingAlwaysLoaded) def import_blueprint(bp_actor: actor_defs, umap_data: list): ## Imports a blueprint actor from the umap transform = bp_actor.transform if not transform: transform = get_scene_transform(bp_actor.scene_props) if type(transform) == bool: transform = get_transform(bp_actor.props) if not transform: return bp_name = bp_actor.type[0:len(bp_actor.type) - 2] loaded_bp = unreal.load_asset(f"/project/{bp_name}.{bp_name}") actor = unreal.EditorLevelLibrary.spawn_actor_from_object(loaded_bp, transform.translation, transform.rotation.rotator()) if not actor: return all_blueprints[bp_actor.name] = actor actor.set_actor_label(bp_actor.name) actor.set_actor_scale3d(transform.scale3d) def create_new_level(map_name): ## Creates a new level with the map name new_map = map_name.split('_')[0] map_path = (f"/project/{new_map}/{map_name}") loaded_map = unreal.load_asset(map_path) sub_system_editor = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem) unreal.LevelEditorSubsystem.new_level(sub_system_editor, map_path) all_level_paths.append(map_path) def get_override_vertex_color(mesh_data: dict): ## Gets the override vertex color from the mesh data lod_data = mesh_data["LODData"] vtx_array = [] for lod in lod_data: if has_key("OverrideVertexColors", lod): vertex_to_convert = lod["OverrideVertexColors"]["Data"] for rgba_hex in vertex_to_convert: vtx_array.append(unreal.BPFL.return_from_hex(rgba_hex)) return vtx_array def import_all_textures_from_material(material_data: dict, settings: Settings): ## Imports all the textures from a material json first mat_info = actor_defs(material_data[0]) if mat_info.props: if has_key("TextureParameterValues", mat_info.props): tx_parameters = mat_info.props["TextureParameterValues"] for tx_param in tx_parameters: tex_game_path = get_texture_path(s=tx_param, f=settings.texture_format) if not tex_game_path: continue tex_local_path = settings.assets_path.joinpath(tex_game_path).__str__() if tex_local_path not in all_textures: all_textures.append(tex_local_path) def create_material(material_data: list, settings: Settings): ## Creates a material from the material data mat_data = material_data[0] mat_data = actor_defs(mat_data) parent = "BaseEnv_MAT_V4" if not mat_data.props: return loaded_material = unreal.load_asset(f"/project/{mat_data.name}.{mat_data.name}") if not loaded_material: loaded_material = AssetTools.create_asset(mat_data.name, '/project/', unreal.MaterialInstanceConstant, unreal.MaterialInstanceConstantFactoryNew()) if has_key("Parent", mat_data.props): parent = return_parent(mat_data.props["Parent"]["ObjectName"]) material_instance = unreal.MaterialInstanceConstant.cast(loaded_material) set_unreal_prop(material_instance, "parent", import_shader(parent)) set_material(settings=settings, mat_data=mat_data, ue_material=loaded_material) def import_all_meshes(settings: Settings): ## Imports all the meshes from the map first accordingly. all_meshes = [] obj_path = settings.selected_map.folder_path.joinpath("_assets_objects.txt") with open(obj_path, 'r') as file: lines = file.read().splitlines() exp_path = str(settings.assets_path) for line in lines: if is_blacklisted(line.split('\\')[-1]): continue line_arr = line.split('\\') if line_arr[0] == "Engine": continue else: line_arr.pop(0) line_arr.pop(0) joined_lines_back = "\\".join(line_arr) full_path = exp_path + '\\Game\\' + joined_lines_back + ".pskx" if full_path not in all_meshes: all_meshes.append(full_path) # import unreal.BPFL.import_meshes(all_meshes, str(settings.selected_map.objects_path)) def imports_all_textures(settings: Settings): ## Imports all the texture from materials. mat_path = settings.selected_map.materials_path mat_ovr_path = settings.selected_map.materials_ovr_path for path_mat in os.listdir(mat_path): mat_json = read_json(mat_path.joinpath(path_mat)) import_all_textures_from_material(mat_json, settings) for path_ovr_mat in os.listdir(mat_ovr_path): mat_ovr_json = read_json(mat_ovr_path.joinpath(path_ovr_mat)) import_all_textures_from_material(mat_ovr_json, settings) unreal.BPFL.import_textures(all_textures) def create_bp(full_data: dict, bp_name: str, settings: Settings): ## Creates a blueprint from the json data BlacklistBP = ["SoundBarrier", "SpawnBarrierProjectile", "BP_UnwalkableBlockingVolumeCylinder", 'BP_StuckPickupVolume', "BP_BlockingVolume", "TargetingBlockingVolume_Box", "directional_look_up"] # BlacklistBP = ['SpawnBarrier','SoundBarrier','SpawnBarrierProjectile','Gumshoe_CameraBlockingVolumeParent_Box','DomeBuyMarker','BP_StuckPickupVolume','BP_LevelBlockingVolume','BP_TargetingLandmark','BombSpawnLocation'] bp_name = bp_name.split('.')[0] bp_actor = unreal.load_asset(f'/project/{bp_name}') if not bp_actor and bp_name not in BlacklistBP: bp_actor = AssetTools.create_asset(bp_name, '/project/', unreal.Blueprint, unreal.BlueprintFactory()) else: return data = full_data["Nodes"] if len(data) == 0: return root_scene = full_data["SceneRoot"] default_scene_root = root_scene[0].split('.')[-1] game_objects = full_data["GameObjects"] nodes_root = full_data["ChildNodes"] for idx, bpc in enumerate(data): if bpc["Name"] == default_scene_root: del data[idx] data.insert(len(data), bpc) break data.reverse() nodes_array = [] for bp_node in data: if bp_node["Name"] in nodes_root: continue component_name = bp_node["Properties"]["ComponentClass"]["ObjectName"].replace( "Class ", "") try: unreal_class = eval(f'unreal.{component_name}') except: continue properties = bp_node["Properties"] if has_key("ChildNodes", properties): nodes_array = handle_child_nodes(properties["ChildNodes"], data, bp_actor) comp_internal_name = properties["InternalVariableName"] component = unreal.BPFL.create_bp_comp( bp_actor, unreal_class, comp_internal_name, nodes_array) if has_key("CompProps", properties): properties = properties["CompProps"] set_mesh_settings(properties, component) set_all_settings(properties, component) for game_object in game_objects: if bp_name == "SpawnBarrier": continue component = unreal.BPFL.create_bp_comp(bp_actor, unreal.StaticMeshComponent, "GameObjectMesh", nodes_array) set_all_settings(game_object["Properties"], component) set_mesh_settings(game_object["Properties"], component) def set_mesh_settings(mesh_properties: dict, component): set_all_settings(mesh_properties, component) transform = get_transform(mesh_properties) if has_key("RelativeRotation", mesh_properties): set_unreal_prop(component, "relative_rotation", transform.rotation.rotator()) if has_key("RelativeLocation", mesh_properties): set_unreal_prop(component, "relative_location", transform.translation) if has_key("RelativeScale3D", mesh_properties): set_unreal_prop(component, "relative_scale3d", transform.scale3d) def handle_child_nodes(child_nodes_array: dict, entire_data: list, bp_actor): ## Handles the child nodes of the blueprint since they are not in order. local_child_array = [] for child_node in child_nodes_array: child_obj_name = child_node["ObjectName"] child_name = child_obj_name.split('.')[-1] for c_node in entire_data: component_name = c_node["Properties"]["ComponentClass"]["ObjectName"].replace( "Class ", "") try: unreal_class = eval(f'unreal.{component_name}') except: continue internal_name = c_node["Properties"]["InternalVariableName"] if "TargetViewMode" in internal_name or "Decal1" in internal_name or "SM_Barrier_Back_VisionBlocker" in internal_name: continue if c_node["Name"] == child_name: u_node, comp_node = unreal.BPFL.create_node( bp_actor, unreal_class, internal_name) local_child_array.append(u_node) set_all_settings(c_node["Properties"]["CompProps"], comp_node) transform = has_transform(c_node["Properties"]["CompProps"]) if type(transform) != bool: comp_node.set_editor_property("relative_location", transform.translation) comp_node.set_editor_property("relative_rotation", transform.rotation.rotator()) comp_node.set_editor_property("relative_scale3d", transform.scale3d) break return local_child_array def import_all_blueprints(settings: Settings): ## Imports all the blueprints from the actors folder. bp_path = settings.selected_map.actors_path for bp in os.listdir(bp_path): bp_json = reduce_bp_json(read_json(settings.selected_map.actors_path.joinpath(bp))) create_bp(bp_json, bp, settings) def import_all_materials(settings: Settings): ## Imports all the materials from the materials folder. mat_path = settings.selected_map.materials_path mat_ovr_path = settings.selected_map.materials_ovr_path for path_mat in os.listdir(mat_path): mat_json = read_json(mat_path.joinpath(path_mat)) create_material(mat_json, settings) for path_ovr_mat in os.listdir(mat_ovr_path): mat_ovr_json = read_json(mat_ovr_path.joinpath(path_ovr_mat)) create_material(mat_ovr_json, settings) def import_map(setting): ## Main function first it sets some lighting settings ( have to revisit it for people who don't want the script to change their lighting settings) ## then it imports all meshes / textures / blueprints first and create materials from them. ## then each umap from the /maps folder is imported and the actors spawned accordingly. unreal.BPFL.change_project_settings() unreal.BPFL.execute_console_command('r.DefaultFeature.LightUnits 0') unreal.BPFL.execute_console_command('r.DynamicGlobalIlluminationMethod 0') all_level_paths.clear() settings = Settings(setting) umap_json_paths = get_map_assets(settings) if not settings.import_sublevel: create_new_level(settings.selected_map.name) clear_level() if settings.import_materials: txt_time = time.time() imports_all_textures(settings) print(f'Exported all textures in {time.time() - txt_time} seconds') mat_time = time.time() import_all_materials(settings) print(f'Exported all materials in {time.time() - mat_time} seconds') m_start_time = time.time() if settings.import_Mesh: import_all_meshes(settings) print(f'Exported all meshes in {time.time() - m_start_time} seconds') bp_start_time = time.time() if settings.import_blueprints: import_all_blueprints(settings) print(f'Exported all blueprints in {time.time() - bp_start_time} seconds') umap_json_path: Path actor_start_time = time.time() with unreal.ScopedSlowTask(len(umap_json_paths), "Importing levels") as slow_task: slow_task.make_dialog(True) idx = 0 for index, umap_json_path in reversed( list(enumerate(umap_json_paths))): umap_data = read_json(umap_json_path) umap_name = umap_json_path.stem slow_task.enter_progress_frame( work=1, desc=f"Importing level:{umap_name} {idx}/{len(umap_json_paths)} ") if settings.import_sublevel: create_new_level(umap_name) import_umap(settings=settings, umap_data=umap_data, umap_name=umap_name) if settings.import_sublevel: unreal.EditorLevelLibrary.save_current_level() idx = idx + 1 print("--- %s seconds to spawn actors ---" % (time.time() - actor_start_time)) if settings.import_sublevel: level_streaming_setup() if settings.import_Mesh: set_mesh_build_settings(settings=settings) # winsound.Beep(7500, 983)
from os import path import os.path as Path import unreal TEMP_FILE = "c:/project/.txt" CONTENT_CONFIG_NAME = "\Game" LEVEL_ROOT_PATH = "Levels" INI_MAPCOOK_STR = "+MapsToCook=(FilePath=\"DIR_STRING\")" pack_level_folders = [ "AutoDungeon", # "Tower/Tower02", # "Tower/Tower03", # "Tower/Tower04", # "Tower/Tower05", # "Village/Village02", "Theme/project/", "Theme/ThemeBlackTower" ] unreal.log("--Python build config maplist:") #help(unreal.BlueprintFileUtilsBPLibrary) contentPath = unreal.SystemLibrary.get_project_content_directory() lines = [] for iter in pack_level_folders: level_path = Path.join(contentPath, LEVEL_ROOT_PATH, iter) unreal.log(level_path) found_paths = unreal.BlueprintFileUtilsBPLibrary.find_recursive( level_path, "*.umap", True, False) if found_paths: for it_fp in found_paths: filename = it_fp.strip(contentPath).strip(".umap") filename = Path.normpath(Path.join(CONTENT_CONFIG_NAME, filename)) #unreal.log(" - - " + Path.normpath(filename)) filename = INI_MAPCOOK_STR.replace("DIR_STRING", filename) lines.append(filename+"\n") unreal.log(" :" + filename) file = open(TEMP_FILE, 'w') file.writelines(lines) file.close() #INI_MAPCOOK_STR. #contentPath
import unreal MEL = unreal.MaterialEditingLibrary EAL = unreal.EditorAssetLibrary from pamux_unreal_tools.utils.node_pos import NodePos, CurrentNodePos from pamux_unreal_tools.base.material_expression.material_expression_sockets_base import OutSocket from pamux_unreal_tools.generated.material_expression_wrappers import NamedRerouteDeclaration class MaterialExpressionContainerBase: # unreal.Material | unreal.MaterialFunction def __init__(self, unrealAsset, f_create_material_expression, f_delete_all_material_expression, f_layout_expression, should_recompile: bool = False) -> None: self.builder = None self.unrealAsset: unreal.Material | unreal.MaterialFunction = unrealAsset self.f_create_material_expression = f_create_material_expression self.f_delete_all_material_expression = f_delete_all_material_expression self.f_layout_expression = f_layout_expression self.should_recompile = should_recompile def deleteAllMaterialExpressions(self) -> None: self.f_delete_all_material_expression(self.unrealAsset) def createMaterialExpression(self, expression_class: unreal.Class, node_pos: NodePos = None) -> unreal.MaterialExpression: if node_pos is None: node_pos = CurrentNodePos return self.f_create_material_expression(self.unrealAsset, expression_class, node_pos.x, node_pos.y) def save(self) -> None: # self.f_layout_expression(self.unrealAsset) if self.should_recompile: MEL.recompile_material(self.unrealAsset) EAL.save_loaded_asset(self.unrealAsset, False) def getDefaultScalarParameterValue(self, parameter_name: str) -> float: return MEL.get_material_default_scalar_parameter_value(self.unrealAsset, parameter_name) def getDefaultStaticSwitchParameterValue(self, parameter_name: str) -> bool: return MEL.get_material_default_static_switch_parameter_value(self.unrealAsset, parameter_name) def getDefaultTextureParameterValue(self, parameter_name: str) -> unreal.Texture: return MEL.get_material_default_texture_parameter_value(self.unrealAsset, parameter_name) def add_rt(self, name: str, outSocket: OutSocket) -> NamedRerouteDeclaration: rt = NamedRerouteDeclaration(name, outSocket) rt.material_expression_editor_x.set(outSocket.material_expression.material_expression_editor_x.get() + NodePos.DeltaX) return rt
# Copyright (c) <2021> Side Effects Software Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. The name of Side Effects Software may not be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN # NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ An example script that uses the API to instantiate two HDAs. The first HDA will be used as an input to the second HDA. For the second HDA we set 2 inputs: an asset input (the first instantiated HDA) and a curve input (a helix). The inputs are set during post instantiation (before the first cook). After the first cook and output creation (post processing) the input structure is fetched and logged. """ import math import unreal _g_wrapper1 = None _g_wrapper2 = None def get_copy_curve_hda_path(): return '/project/.copy_to_curve_1_0' def get_copy_curve_hda(): return unreal.load_object(None, get_copy_curve_hda_path()) def get_pig_head_hda_path(): return '/project/.pig_head_subdivider_v01' def get_pig_head_hda(): return unreal.load_object(None, get_pig_head_hda_path()) def configure_inputs(in_wrapper): print('configure_inputs') # Unbind from the delegate in_wrapper.on_post_instantiation_delegate.remove_callable(configure_inputs) # Create a geo input asset_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPIAssetInput) # Set the input objects/assets for this input # asset_input.set_input_objects((_g_wrapper1.get_houdini_asset_actor().houdini_asset_component, )) asset_input.set_input_objects((_g_wrapper1, )) # copy the input data to the HDA as node input 0 in_wrapper.set_input_at_index(0, asset_input) # We can now discard the API input object asset_input = None # Create a curve input curve_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPICurveInput) # Create a curve wrapper/helper curve_object = unreal.HoudiniPublicAPICurveInputObject(curve_input) # Make it a Nurbs curve curve_object.set_curve_type(unreal.HoudiniPublicAPICurveType.NURBS) # Set the points of the curve, for this example we create a helix # consisting of 100 points curve_points = [] for i in range(10): t = i / 10.0 * math.pi * 2.0 x = 100.0 * math.cos(t) y = 100.0 * math.sin(t) z = i * 10.0 curve_points.append(unreal.Transform([x, y, z], [0, 0, 0], [1, 1, 1])) curve_object.set_curve_points(curve_points) # Set the curve wrapper as an input object curve_input.set_input_objects((curve_object, )) # Copy the input data to the HDA as node input 1 in_wrapper.set_input_at_index(1, curve_input) # We can now discard the API input object curve_input = None def print_api_input(in_input): print('\t\tInput type: {0}'.format(in_input.__class__)) print('\t\tbKeepWorldTransform: {0}'.format(in_input.keep_world_transform)) print('\t\tbImportAsReference: {0}'.format(in_input.import_as_reference)) if isinstance(in_input, unreal.HoudiniPublicAPICurveInput): print('\t\tbCookOnCurveChanged: {0}'.format(in_input.cook_on_curve_changed)) print('\t\tbAddRotAndScaleAttributesOnCurves: {0}'.format(in_input.add_rot_and_scale_attributes_on_curves)) input_objects = in_input.get_input_objects() if not input_objects: print('\t\tEmpty input!') else: print('\t\tNumber of objects in input: {0}'.format(len(input_objects))) for idx, input_object in enumerate(input_objects): print('\t\t\tInput object #{0}: {1}'.format(idx, input_object)) if isinstance(input_object, unreal.HoudiniPublicAPICurveInputObject): print('\t\t\tbClosed: {0}'.format(input_object.is_closed())) print('\t\t\tCurveMethod: {0}'.format(input_object.get_curve_method())) print('\t\t\tCurveType: {0}'.format(input_object.get_curve_type())) print('\t\t\tReversed: {0}'.format(input_object.is_reversed())) print('\t\t\tCurvePoints: {0}'.format(input_object.get_curve_points())) def print_inputs(in_wrapper): print('print_inputs') # Unbind from the delegate in_wrapper.on_post_processing_delegate.remove_callable(print_inputs) # Fetch inputs, iterate over it and log node_inputs = in_wrapper.get_inputs_at_indices() parm_inputs = in_wrapper.get_input_parameters() if not node_inputs: print('No node inputs found!') else: print('Number of node inputs: {0}'.format(len(node_inputs))) for input_index, input_wrapper in node_inputs.items(): print('\tInput index: {0}'.format(input_index)) print_api_input(input_wrapper) if not parm_inputs: print('No parameter inputs found!') else: print('Number of parameter inputs: {0}'.format(len(parm_inputs))) for parm_name, input_wrapper in parm_inputs.items(): print('\tInput parameter name: {0}'.format(parm_name)) print_api_input(input_wrapper) def run(): # get the API singleton api = unreal.HoudiniPublicAPIBlueprintLib.get_api() global _g_wrapper1, _g_wrapper2 # instantiate the input HDA with auto-cook enabled _g_wrapper1 = api.instantiate_asset(get_pig_head_hda(), unreal.Transform()) # instantiate the copy curve HDA _g_wrapper2 = api.instantiate_asset(get_copy_curve_hda(), unreal.Transform()) # Configure inputs on_post_instantiation, after instantiation, but before first cook _g_wrapper2.on_post_instantiation_delegate.add_callable(configure_inputs) # Print the input state after the cook and output creation. _g_wrapper2.on_post_processing_delegate.add_callable(print_inputs) if __name__ == '__main__': run()
# -*- coding: utf-8 -*- """ UI to import Textures, Material Instance Constants and Static Meshes """ # mca python imports import os # PySide2 imports import unreal # software specific imports # mca python imports from mca.common import log from mca.common.pyqt import common_windows, messages, file_dialogs from mca.common.pyqt.qt_utils import listwidget_utils from mca.common.textio import yamlio from mca.common.modifiers import decorators from mca.ue.tools.assetimporter import local_prefs from mca.ue.assetlist import ue_assetlist from mca.ue.utils import asset_import, asset_utils, materials from mca.ue.texturetypes import texture_2d from mca.ue.paths import ue_path_utils, ue_paths from mca.ue.startup.configs import ue_consts from mca.ue.assettypes import py_material_instance, parent_materials, py_staticmesh logger = log.MCA_LOGGER class MATUnrealAssetImporter(common_windows.MCAMainWindow): """ UI for importing Textures and creating Material Instance Constants. """ VERSION = '1.0.0' def __init__(self, parent=None): root_path = os.path.dirname(os.path.realpath(__file__)) ui_path = os.path.join(root_path, 'ui', 'asset_importer.ui') super().__init__(title='Asset Importer', ui_path=ui_path, version=MATUnrealAssetImporter.VERSION, style='incrypt', parent=parent) # Material Dict self.mat_dict = {} # Get the local preferences self.prefs = local_prefs.AssetImportPreferences() self.ue_asset_list = ue_assetlist.UnrealAssetListToolBox() # Sets the UI properties - These are the user's settings self.set_ui_properties() ############################################ # Signals ############################################ self.ui.master_mca_comboBox.currentIndexChanged.connect(self.hide_show_checkboxes) self.ui.import_texture_pushButton.clicked.connect(self.import_from_list) self.ui.text_reimp_pushButton.clicked.connect(self.import_selected) self.ui.text_dir_pushButton.clicked.connect(self.import_textures_from_dir) self.ui.mat_cb_pushButton.clicked.connect(self.load_materials_from_content_browser_clicked) self.ui.mat_al_pushButton.clicked.connect(self.load_materials_from_asset_list_clicked) self.ui.mat_listWidget.itemSelectionChanged.connect(self.change_master_material) self.ui.create_mca_pushButton.clicked.connect(self.create_mca_inst_sel_clicked) self.ui.create_mca_all_pushButton.clicked.connect(self.create_mca_inst_all_clicked) self.ui.static_mesh_al_pushButton.clicked.connect(self.import_sm_asset_list_clicked) self.ui.static_mesh_dir_pushButton.clicked.connect(self.import_sm_asset_dir_clicked) self.ui.set_materials_pushButton.clicked.connect(self.sm_set_materials_clicked) ############################################ # Slots ############################################ def get_asset_from_asset_list(self): """ Returns the asset entry from the asset list. This is using the name in the of the asset from the combobox and looking up the asset from the asset list using the name. :return: Returns the asset entry from the asset list. :rtype: assetlist.MATAsset """ asset_data = self.ue_asset_list.asset_data if not asset_data: return return asset_data #### Textures ############ @decorators.track_fnc def refresh_asset_list(self): """ Refreshes the asset list and updates the UI This will refresh the 'type' and 'asset name' for the QComboboxes Then it will repopulate the QComboboxes with all the asset information. """ self.ue_asset_list.reload_asset_list() self.set_ui_properties() @decorators.track_fnc def import_from_list(self): """ Imports all the Textures from the art depot in to the game directory using the asset list comboboxes. """ # Dialog prompt result = messages.question_message('Asset Importer', 'Import selected asset?') if result != 'Yes': return # Gets the asset data from the asset name combobox asset_data = self.get_asset_from_asset_list() if not asset_data: return # Gets the Art side textures path art_textures_path = asset_data.textures_path # Look for vaild textures texture_list = [os.path.join(art_textures_path, x) for x in os.listdir(art_textures_path) if x.endswith('.tga') or x.endswith('.jpg') or x.endswith('.png')] # Get the game side textures path game_textures_path = asset_data.game_textures_path imported_textures = [] # import each Texture and set its default properties. for texture in texture_list: self.import_texture(texture, game_textures_path, asset_data.asset_name) imported_textures.append(texture) if imported_textures: self.load_materials_from_asset_list_clicked() @decorators.track_fnc def import_selected(self): """ Re-imports all selected textures in the Content Browser. """ # Dialog prompt result = messages.question_message('Asset Importer', 'Re-Import selected asset?') if result != 'Yes': return selection = asset_utils.selected() if not selection: messages.info_message('Asset Importer', 'Please select either an Albedo, Normal Map, ORME, or SSTD') return for texture in selection: if not isinstance(texture, texture_2d.PyTexture2D): logger.warning(f'{texture.get_name()} asset is not a supported texture by the asset importer') continue art_textures_path = texture.original_import_path game_textures_path = texture.original_import_path self.import_texture(art_textures_path, game_textures_path, texture.name, replace_existing=True) @decorators.track_fnc def import_textures_from_dir(self): """ Imports selected textures from the art depot in to the game directory using a Dialog prompt. """ # Open Dialog prompt results = file_dialogs.open_file_dialog(filters="Images (*.tga *.png *.jpg);;All Files *.*", parent=self) if not results: return # get the current Browser path game_textures_path = ue_path_utils.get_current_content_browser_path() # Go through the selected textures and make sure they are supported textures. for texture in results: texture_type = texture.split('_')[-1].split('.')[0] if texture_type.lower() not in ue_consts.TEXTURE_TYPES: texture_name = os.path.basename(texture) logger.warning(f'{texture_name} asset is not a supported texture by the asset importer') continue # If the texture is valid, import it. self.import_texture(texture, game_textures_path, os.path.basename(texture)[0].split('.')[0]) def import_texture(self, texture, game_textures_path, asset_name, replace_existing=False): """ Imports a single texture and sets its default properties. :param str texture: Full path to the texture. :param str game_textures_path: Path to the game texture's directory. This is where it will be imported. :param str asset_name: final name of the game texture. :param bool replace_existing: If true, it will force replace the existing texture. :return: Returns the imported game texture. :rtype: txture_2d.PyTexture2D """ # Update the ui preferences self.update_preferences() # import the textures options = asset_import.texture_2d_import_options() uasset = asset_import.import_asset(filename=texture, game_path=game_textures_path, asset_name=asset_name, import_options=options, replace_existing=replace_existing, save=True) uasset = asset_utils.PyNode(uasset) # Only set the properties and save if the asset is valid. if isinstance(uasset, texture_2d.PyTexture2D): uasset.set_editor_attributes() asset_utils.save_asset(uasset) return uasset ############## Materials ############## def populate_materials(self): """ Populates the parent materials in the combobox. """ masterial_list = py_material_instance.ParentMaterialMapping().get_parent_material_names() self.ui.master_mca_comboBox.clear() self.ui.master_mca_comboBox.addItems(masterial_list) if self.prefs.master_material: self.ui.master_mca_comboBox.setCurrentText(self.prefs.master_material) @decorators.track_fnc def load_materials_from_content_browser_clicked(self): """ When button is clicked, load the materials from the content browser and add them to the list widget. """ self.ui.mat_listWidget.clear() self.update_preferences() material_names = self.get_material_names_from_content_browser() if not material_names: return self.populate_materials_qlistwidget(material_names) @decorators.track_fnc def load_materials_from_asset_list_clicked(self): """ When button is clicked, load the materials from the asset list and add them to the list widget. """ self.ui.mat_listWidget.clear() self.update_preferences() material_names = self.get_material_names_from_asset_list() if not material_names: return self.populate_materials_qlistwidget(material_names) @decorators.track_fnc def create_mca_inst_sel_clicked(self): """ Creates a material instance from the selected entry in the QListWidget. Also sets the default properties and any extra properties from the selected checkboxes in the UI. """ self.update_preferences() # Dialog prompt result = messages.question_message('Create Material', 'Create the selected materials from the list?') if result != 'Yes': return # get the selected material from the QListWidget selection = listwidget_utils.get_qlist_widget_selected_items(self.ui.mat_listWidget) if not selection: return material_name = str(selection[0]) # Get the parent Material to set on the martial instance parent_material_name = self.ui.master_mca_comboBox.currentText() parent_material = materials.get_material(parent_material_name) # get the material instance class that specifically is used for the material instance with that parent material. material_inst = py_material_instance.ParentMaterialMapping.attr(parent_material_name) # Get the textures associated with the material texture_list = self.mat_dict.get(material_name, None) if not texture_list: logger.warning('No textures found for the material instance. ' 'There must be textures to create the material instance.') return # get the Material Folder to set on the material instance texture_path = os.path.dirname(texture_list[0].path) material_path = ue_path_utils.convert_texture_to_material_path(texture_path) # Create the material instance material_instance = material_inst.create(name=material_name, folder=material_path, parent_material=parent_material, texture_list=texture_list) material_instance.set_editor_properties() extra_properties = self.get_material_checkbox_properties() [material_instance.set_attr(str(x), True) for x in extra_properties] asset_utils.save_asset(material_instance) @decorators.track_fnc def create_mca_inst_all_clicked(self): """ Creates a material instances from all the entries in the QListWidget. Also sets the default properties and any extra properties from the selected checkboxes in the UI. """ self.update_preferences() # Dialog prompt result = messages.question_message('Create Materials', 'Create all materials from the list?') if result != 'Yes': return # get the selected material from the QListWidget items = listwidget_utils.get_qlist_widget_items(self.ui.mat_listWidget) if not items: return for item in items: material_name = str(item) # Get the parent Material to set on the martial instance # Get the textures associated with the material texture_list = self.mat_dict.get(material_name, None) if not texture_list: logger.warning('No textures found for the material instance. ' 'There must be textures to create the material instance.') return parent_material = parent_materials.get_parent_materials(texture_list) # get the material instance class that specifically is used for the # material instance with that parent material. material_inst = py_material_instance.ParentMaterialMapping.attr(parent_material.get_name()) # get the Material Folder to set on the material instance texture_path = os.path.dirname(texture_list[0].path) material_path = ue_path_utils.convert_texture_to_material_path(texture_path) # Create the material instance material_instance = material_inst.create(name=material_name, folder=material_path, parent_material=parent_material, texture_list=texture_list) material_instance.set_editor_properties() extra_properties = self.get_material_checkbox_properties() [material_instance.set_attr(str(x), True) for x in extra_properties] asset_utils.save_asset(material_instance) def get_material_checkbox_properties(self): """ Returns a list of all the properties that are checked in the UI. :return: Returns a list of all the properties that are checked in the UI. :rtype: list(str) """ # Get the mapping dictionary that maps the checkboxes to the checkbox properties. mapping = self.map_checkboxes() checkboxes = list(mapping.values()) properties = list(mapping.keys()) properties_list = [] # Go through each checkbox and check if it is visible and checked. for x, checkbox in enumerate(checkboxes): if checkbox.isVisible() and checkbox.isChecked(): properties_list.append(properties[x]) return properties_list def change_master_material(self): """ When a material is selected in the list widget, change the master material in the combobox. """ selection = listwidget_utils.get_qlist_widget_selected_items(self.ui.mat_listWidget) if not selection: return material_name = str(selection[0]) texture_list = self.mat_dict.get(material_name, None) if not texture_list: return master_material = parent_materials.get_parent_materials(texture_list) self.ui.master_mca_comboBox.setCurrentText(master_material.get_name()) def verify_materials_browser_path(self): """ Returns the texture path using the material path. :return: Returns the texture path using the material path. :rtype: str """ content_browser_path = ue_path_utils.get_current_content_browser_path() path = None if ue_path_utils.is_game_material_path(content_browser_path): path = content_browser_path elif ue_path_utils.is_game_texture_path(content_browser_path): path = ue_path_utils.convert_texture_to_material_path(content_browser_path) return path def get_material_names_from_content_browser(self): """ Returns the material names using the texture path :return: Returns the material names using the texture path :rtype: list(str) """ path = self.verify_materials_browser_path() if not path: # Dialog prompt msg = 'Please make sure you are in the "Textures" or "Materials" folder in the content browser.' messages.info_message('Get Material Names', msg) logger.warning(msg) return material_names = self.get_material_names(path) return material_names def get_material_names_from_asset_list(self): """ Return the material names using the textures directory and the asset comboboxes. :return: Return the material names using the textures directory and the asset comboboxes. :rtype: list(str) """ asset_data = self.get_asset_from_asset_list() materials_path = asset_data.game_material_path materials_path = ue_path_utils.convert_to_game_path(materials_path) material_names = self.get_material_names(materials_path) return material_names def get_material_names(self, material_folder_path): """ Return the material names using the textures directory. :param str material_folder_path: Game Directory for the Material Instances. :return: Return the material names using the textures directory. :rtype: list(str) """ material_dict = py_material_instance.create_mic_names(material_folder_path) if not material_dict: logger.warning('No Textures or Materials folder found in the content browser') return self.mat_dict = material_dict material_names = list(material_dict.keys()) return material_names def populate_materials_qlistwidget(self, material_list): """ Populates the Material List Widget. :param list(str) material_list: List of string names of materials. """ self.ui.mat_listWidget.addItems(material_list) self.ui.mat_listWidget.setCurrentRow(0) ################################################################ # Static Mesh ################################################################ def import_sm_asset_list_clicked(self): """ Imports an SM from the selected asset in the combobox. """ # Dialog prompt result = messages.question_message('Asset Importer', 'Import selected SM asset from the asset list?') if result != 'Yes': return # Gets the asset data from the asset name combobox asset_data = self.get_asset_from_asset_list() if not asset_data: return # Get the SM Art and Game paths art_sm = asset_data.sm_path path_manager = ue_path_utils.UEPathManager(art_sm) game_sm = path_manager.convert_art_path_to_game_path(remove_filename=True) asset_name = os.path.basename(art_sm).split('.')[0] self.import_sm(art_sm, game_sm, asset_name, replace_existing=True) def import_sm_asset_dir_clicked(self): """ Imports an SM from the selected asset in the directory dialog. """ # Open Dialog prompt results = file_dialogs.open_file_dialog(filters="All Files *.*", parent=self) if not results: return # get the current Browser path game_path = ue_path_utils.get_current_content_browser_path() sm = results[0] # Go through the selected textures and make sure they are supported textures. # If the texture is valid, import it. self.import_sm(sm_full_name=sm, game_path=game_path, asset_name=os.path.basename(sm).split('.')[0], replace_existing=True) def import_sm(self, sm_full_name, game_path, asset_name, replace_existing=False): """ Imports a single SM and sets its default properties. :param str sm_full_name: Full path to the asset. :param str game_path: Path to the game asset directory. This is where it will be imported. :param str asset_name: final name of the game asset. :param bool replace_existing: If true, it will force replace the existing asset. :return: Returns the imported game SM. :rtype: py_staticmesh.PyStaticMesh """ # Update the ui preferences self.update_preferences() # import the textures options = py_staticmesh.static_mesh_import_options() uasset = asset_import.import_asset(filename=sm_full_name, game_path=game_path, asset_name=asset_name, import_options=options, replace_existing=replace_existing, save=True) uasset = asset_utils.PyNode(uasset) # Only set the properties and save if the asset is valid. if isinstance(uasset, py_staticmesh.PyStaticMesh): uasset.set_materials() asset_utils.save_asset(uasset) return uasset def sm_set_materials_clicked(self): """ Using the materials in the material folder to set on the static mesh. """ self.update_preferences() # Dialog prompt result = messages.question_message('Set Materials', 'Set materials on selected Static Mesh?') if result != 'Yes': return assets = asset_utils.get_selected_assets() if not assets: return asset = assets[0] if not isinstance(asset, unreal.StaticMesh): return asset = asset_utils.PyNode(asset) asset.set_materials() asset_utils.save_asset(asset) ################################################################ def map_checkboxes(self): """ Returns a mapping connecting the checkboxes to their corresponding properties. :return: Returns a mapping connecting the checkboxes to their corresponding properties. :rtype: dict """ mapping = {} mapping.update({'Use Subsurface Profile': self.ui.sub_sur_1_checkBox}) mapping.update({'Use Subsurface Distance Fading': self.ui.sub_sur_2_checkBox}) mapping.update({'Use Emissive': self.ui.emissive_checkBox}) mapping.update({'Use Bent Normals': self.ui.bn_checkBox}) mapping.update({'Use Filigree': self.ui.fillgri_checkBox}) mapping.update({'Use Detail Texture': self.ui.detail_texture_checkBox}) mapping.update({'Use Iridescent': self.ui.iridescent_checkBox}) mapping.update({'Fuzzy Clothing': self.ui.fuzzy_cloth_checkBox}) mapping.update({'Use Carbon Fiber': self.ui.cf_checkBox}) mapping.update({'Use Simple Decals': self.ui.decal_checkBox}) return mapping def property_mapping(self): """ Maps the property names and exported properties in the asset imported yaml file. :return: Returns a dictionary of property names and exported properties in the asset imported yaml file. :rtype: dict """ mapping = {} mapping.update({'Use Subsurface Profile': 'subsurface_profile'}) mapping.update({'Use Subsurface Distance Fading': 'use_subsurface_distance_fading'}) mapping.update({'Use Emissive': 'use_emissive'}) mapping.update({'Use Bent Normals':'use_bent_normals'}) mapping.update({'Use Filigree': 'use_filigree'}) mapping.update({'Use Detail Texture': 'use_detail_texture'}) mapping.update({'Use Iridescent': 'use_iridescent'}) mapping.update({'Fuzzy Clothing': 'use_fuzzy_clothing'}) mapping.update({'Use Carbon Fiber': 'use_carbon_fiber'}) mapping.update({'Use Simple Decals': 'use_simple_decals'}) return mapping def get_material_properties(self): """ Returns the material properties' dictionary. :return: Returns the material properties' dictionary. :rtype: dict """ # Get the parent material name parent_material = self.ui.master_mca_comboBox.currentText() # Get the local properties path for the material instance with the above parent material, # in the local document's folder. local_path = ue_paths.get_local_tool_prefs_folder(py_material_instance.PROPERTIES_FOLDER) full_path = os.path.join(local_path, parent_material + py_material_instance.MATERIAL_PROPERTIES_EXT) # If the local properties path does not exist, attempt to copy the file from Common\Tools\Unreal. if not os.path.exists(full_path): common_path = ue_paths.get_tool_prefs_folder(py_material_instance.PROPERTIES_FOLDER) common_full_path = os.path.join(common_path, parent_material + py_material_instance.MATERIAL_PROPERTIES_EXT) logger.warning(f'Could not find {full_path}, Attempting to use the common default properties') if os.path.exists(common_full_path): common_dict = yamlio.read_yaml_file(common_full_path) if not os.path.exists(local_path): os.makedirs(local_path) yamlio.write_to_yaml_file(common_dict, full_path) return common_dict if not os.path.exists(full_path): logger.warning(f'Could not find {full_path}') return return yamlio.read_yaml_file(full_path) def hide_show_checkboxes(self): """ Either hides or shows the checkboxes depending on parent material. """ self.update_preferences() settings = self.get_material_properties() properties = self.property_mapping() mapping = self.map_checkboxes() checkboxes = list(mapping.values()) [x.setVisible(False) for x in checkboxes] for property_name, setting in settings['options'].items(): checkbox = mapping.get(property_name, None) if not checkbox: continue prop_name = properties.get(property_name, None) value = self.prefs.data.get(prop_name, None) checkbox.setVisible(True) if value: checkbox.setChecked(value) def blockSignals(self, block=True): """ Blocks signals :param bool block: True to block signals, False to unblock """ self.ui.master_mca_comboBox.blockSignals(block) def set_ui_properties(self, block=True): """ Sets the UI properties :param bool block: True to block signals, False to unblock """ self.blockSignals(block=block) self.set_checkboxes() self.populate_materials() self.hide_show_checkboxes() self.set_checkboxes() self.blockSignals(block=not block) def update_preferences(self): """ Updates the local preferences """ self.prefs.subsurface_profile = self.ui.sub_sur_1_checkBox.isChecked() self.prefs.use_subsurface_distance_fading = self.ui.sub_sur_2_checkBox.isChecked() self.prefs.use_emissive = self.ui.emissive_checkBox.isChecked() self.prefs.use_bent_normals = self.ui.bn_checkBox.isChecked() self.prefs.use_filigree = self.ui.fillgri_checkBox.isChecked() self.prefs.use_detail_texture = self.ui.detail_texture_checkBox.isChecked() self.prefs.use_iridescent = self.ui.iridescent_checkBox.isChecked() self.prefs.use_fuzzy_clothing = self.ui.fuzzy_cloth_checkBox.isChecked() self.prefs.use_carbon_fiber = self.ui.cf_checkBox.isChecked() self.prefs.use_simple_decals = self.ui.decal_checkBox.isChecked() try: self.prefs.write_file() except Exception as e: logger.exception('Failed to write preferences file') logger.error(e) def set_checkboxes(self): """ Sets the checkboxes from the preferences file. """ subsurface = self.prefs.subsurface_profile or False subsurface_fading = self.prefs.use_subsurface_distance_fading or False emissive = self.prefs.use_emissive or False bn = self.prefs.use_bent_normals or False fil = self.prefs.use_filigree or False dt = self.prefs.use_detail_texture or False ir = self.prefs.use_iridescent or False fuzzy = self.prefs.use_fuzzy_clothing or False carbon = self.prefs.use_carbon_fiber or False decals = self.prefs.use_simple_decals or False self.ui.sub_sur_1_checkBox.setChecked(subsurface) self.ui.sub_sur_2_checkBox.setChecked(subsurface_fading) self.ui.emissive_checkBox.setChecked(emissive) self.ui.bn_checkBox.setChecked(bn) self.ui.fillgri_checkBox.setChecked(fil) self.ui.detail_texture_checkBox.setChecked(dt) self.ui.iridescent_checkBox.setChecked(ir) self.ui.fuzzy_cloth_checkBox.setChecked(fuzzy) self.ui.cf_checkBox.setChecked(carbon) self.ui.decal_checkBox.setChecked(decals)
# coding: utf-8 import unreal import time import argparse parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") parser.add_argument("-debugeachsave") args = parser.parse_args() #print(args.vrm) ###### with unreal.ScopedSlowTask(1, "Convert MorphTarget") as slow_task_root: slow_task_root.make_dialog() rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r hierarchy = unreal.ControlRigBlueprintLibrary.get_hierarchy(rig) h_con = hierarchy.get_controller() print(unreal.SystemLibrary.get_engine_version()) if (unreal.SystemLibrary.get_engine_version()[0] == '5'): c = rig.get_controller() else: c = rig.controller g = c.get_graph() n = g.get_nodes() mesh = rig.get_preview_mesh() morphList = mesh.get_all_morph_target_names() morphListWithNo = morphList[:] morphListRenamed = [] morphListRenamed.clear() for i in range(len(morphList)): morphListWithNo[i] = '{}'.format(morphList[i]) print(morphListWithNo) bRemoveElement = False if ("5." in unreal.SystemLibrary.get_engine_version()): if ("5.0." in unreal.SystemLibrary.get_engine_version()): bRemoveElement = True else: bRemoveElement = True if (bRemoveElement): while(len(hierarchy.get_bones()) > 0): e = hierarchy.get_bones()[-1] h_con.remove_all_parents(e) h_con.remove_element(e) h_con.import_bones(unreal.ControlRigBlueprintLibrary.get_preview_mesh(rig).skeleton) h_con.import_curves(unreal.ControlRigBlueprintLibrary.get_preview_mesh(rig).skeleton) dset = rig.get_editor_property('rig_graph_display_settings') dset.set_editor_property('node_run_limit', 0) rig.set_editor_property('rig_graph_display_settings', dset) ###### root key = unreal.RigElementKey(unreal.RigElementType.NULL, 'MorphControlRoot_s') space = hierarchy.find_null(key) if (space.get_editor_property('index') < 0): space = h_con.add_null('MorphControlRoot_s', space_type=unreal.RigSpaceType.SPACE) else: space = key #a:unreal.RigUnit_CollectionItems = unreal.RigUnit_CollectionItems() #print(a) # 配列ノード追加 values_forCurve:unreal.RigVMStructNode = [] items_forControl:unreal.RigVMStructNode = [] items_forCurve:unreal.RigVMStructNode = [] for node in n: #print(node) #print(node.get_node_title()) # set curve num if (node.get_node_title() == 'For Loop'): #print(node) pin = node.find_pin('Count') #print(pin) c.set_pin_default_value(pin.get_pin_path(), str(len(morphList)), True, False) # curve name array pin if (node.get_node_title() == 'Select'): #print(node) pin = node.find_pin('Values') #print(pin) #print(pin.get_array_size()) #print(pin.get_default_value()) values_forCurve.append(pin) # items if (node.get_node_title() == 'Collection from Items'): if ("Type=Curve," in c.get_pin_default_value(node.find_pin('Items').get_pin_path())): items_forCurve.append(node.find_pin('Items')) elif (node.find_pin('Items').get_array_size() == 40): items_forControl.append(node.find_pin('Items')) print(items_forControl) print(values_forCurve) # reset controller for e in reversed(hierarchy.get_controls()): if (len(hierarchy.get_parents(e)) == 0): continue if (hierarchy.get_parents(e)[0].name == 'MorphControlRoot_s'): #if (str(e.name).rstrip('_c') in morphList): # continue print('delete') #print(str(e.name)) if (bRemoveElement): h_con.remove_element(e) # curve array for v in values_forCurve: c.clear_array_pin(v.get_pin_path(), False) for morph in morphList: tmp = "{}".format(morph) c.add_array_pin(v.get_pin_path(), default_value=tmp, setup_undo_redo=False) # curve controller for morph in morphListWithNo: name_c = "{}_c".format(morph) key = unreal.RigElementKey(unreal.RigElementType.CONTROL, name_c) settings = unreal.RigControlSettings() settings.shape_color = [1.0, 0.0, 0.0, 1.0] settings.control_type = unreal.RigControlType.FLOAT try: control = hierarchy.find_control(key) if (control.get_editor_property('index') < 0): k = h_con.add_control(name_c, space, settings, unreal.RigControlValue(), setup_undo=False) control = hierarchy.find_control(k) except: k = h_con.add_control(name_c, space, settings, unreal.RigControlValue(), setup_undo=False) control = hierarchy.find_control(k) shape_t = unreal.Transform(location=[0.0, 0.0, 0.0], rotation=[0.0, 0.0, 0.0], scale=[0.001, 0.001, 0.001]) hierarchy.set_control_shape_transform(k, shape_t, True) morphListRenamed.append(control.key.name) if (args.debugeachsave == '1'): try: unreal.EditorAssetLibrary.save_loaded_asset(rig) except: print('save error') #unreal.SystemLibrary.collect_garbage() # eye controller eyeControllerTable = [ "VRM4U_EyeUD_left", "VRM4U_EyeLR_left", "VRM4U_EyeUD_right", "VRM4U_EyeLR_right", ] # eye controller for eyeCon in eyeControllerTable: name_c = "{}_c".format(eyeCon) key = unreal.RigElementKey(unreal.RigElementType.CONTROL, name_c) settings = unreal.RigControlSettings() settings.shape_color = [1.0, 0.0, 0.0, 1.0] settings.control_type = unreal.RigControlType.FLOAT try: control = hierarchy.find_control(key) if (control.get_editor_property('index') < 0): k = h_con.add_control(name_c, space, settings, unreal.RigControlValue(), setup_undo=False) control = hierarchy.find_control(k) except: k = h_con.add_control(name_c, space, settings, unreal.RigControlValue(), setup_undo=False) control = hierarchy.find_control(k) shape_t = unreal.Transform(location=[0.0, 0.0, 0.0], rotation=[0.0, 0.0, 0.0], scale=[0.001, 0.001, 0.001]) hierarchy.set_control_shape_transform(k, shape_t, True) # curve Control array with unreal.ScopedSlowTask(len(items_forControl)*len(morphListRenamed), "Add Control") as slow_task: slow_task.make_dialog() for v in items_forControl: c.clear_array_pin(v.get_pin_path(), False) for morph in morphListRenamed: slow_task.enter_progress_frame(1) tmp = '(Type=Control,Name=' tmp += "{}".format(morph) tmp += ')' c.add_array_pin(v.get_pin_path(), default_value=tmp, setup_undo_redo=False) # curve Float array with unreal.ScopedSlowTask(len(items_forCurve)*len(morphList), "Add Curve") as slow_task: slow_task.make_dialog() for v in items_forCurve: c.clear_array_pin(v.get_pin_path(), False) for morph in morphList: slow_task.enter_progress_frame(1) tmp = '(Type=Curve,Name=' tmp += "{}".format(morph) tmp += ')' c.add_array_pin(v.get_pin_path(), default_value=tmp, setup_undo_redo=False)
from domain.import_asset_service import ImportAssetService from infrastructure.configuration.message import ImportedFilesMessage from infrastructure.logging.base_logging import BaseLogging import unreal class ImportAssetHandler: def __init__(self, _importAssetService: ImportAssetService, _logging: BaseLogging): self.importAssetService = _importAssetService self.logging = _logging def preview_assets(self, importAssetDto: unreal.ImportAssetStruct) -> unreal.Array(unreal.ImportedAssetData): return self.importAssetService.preview_assets(importAssetDto) def import_assets(self, assets: unreal.Array(unreal.ImportedAssetData)): tasks = [] meshes = self.filter_by_import_type(assets, unreal.AssetImportTypeEnum.MESHES) if len(meshes) > 0: tasks.extend(self.importAssetService.create_meshes(meshes)) sounds = self.filter_by_import_type(assets, unreal.AssetImportTypeEnum.SOUNDS) if len(sounds) > 0: tasks.extend(self.importAssetService.create_sounds(sounds)) textures = self.filter_by_import_type(assets, unreal.AssetImportTypeEnum.TEXTURES) if len(textures) > 0: tasks.extend(self.importAssetService.create_textures(textures)) if len(tasks) > 0: self.importAssetService.import_files(tasks) self.logging.log(ImportedFilesMessage().build_log_summary(self.transform_tasks_into_log(tasks))) def filter_by_import_type(self, assetsToImport: unreal.Array(unreal.ImportedAssetData), import_type: unreal.AssetImportTypeEnum): result = [] asset: unreal.ImportedAssetData for asset in assetsToImport: if asset.asset_type.value == import_type.value: result.append(asset) return result def transform_tasks_into_log(self, tasks): logStringsArray = [] task: unreal.AssetImportTask for task in tasks: logStringsArray.append("The file:{file_name} was imported at {destination} \n".format(file_name=task.get_editor_property("filename"), destination=task.get_editor_property("destination_path"))) return logStringsArray
import unreal ''' Creates a sequence for the given target camera This script is called by MRQ's StillRenderSetupAutomation. Args: asset_name(str): The name of the sequence to be created length_frames(int): The number of frames in the camera cut section. package_path(str): The location for the new sequence target_camera(unreal.CameraActor): The camera to use. Returns: unreal.LevelSequence: The created level sequence ''' def create_sequence_from_selection( asset_name, length_frames = 1, package_path = '/project/', target_camera = unreal.Object): # Create the sequence asset in the desired location sequence = unreal.AssetToolsHelpers.get_asset_tools().create_asset( asset_name, package_path, unreal.LevelSequence, unreal.LevelSequenceFactoryNew()) # Only one frame needed to render stills sequence.set_playback_end(1) binding = sequence.add_possessable(target_camera) try: camera = unreal.CameraActor.cast(target_camera) camera_cut_track = sequence.add_track(unreal.MovieSceneCameraCutTrack) # Add a camera cut track for this camera # Make sure the camera cut is stretched to the -1 mark camera_cut_section = camera_cut_track.add_section() camera_cut_section.set_start_frame(-1) camera_cut_section.set_end_frame(length_frames) camera_binding_id = unreal.MovieSceneObjectBindingID() camera_binding_id.set_editor_property("Guid", binding.get_id()) camera_cut_section.set_editor_property("CameraBindingID", camera_binding_id) # Add a current focal length track to the cine camera component camera_component = target_camera.get_cine_camera_component() camera_component_binding = sequence.add_possessable(camera_component) camera_component_binding.set_parent(binding) focal_length_track = camera_component_binding.add_track(unreal.MovieSceneFloatTrack) focal_length_track.set_property_name_and_path('CurrentFocalLength', 'CurrentFocalLength') focal_length_section = focal_length_track.add_section() focal_length_section.set_start_frame_bounded(0) focal_length_section.set_end_frame_bounded(0) except TypeError: unreal.log_error(f"Trex TypeError {str(sequence)}") # Log the output sequence with tag Trex for easy lookup unreal.log("Trex" + str(sequence)) return sequence
import unreal import os # Get the list of weapons from ADACA_extract weapons_dir = "C:/project/" weapons = [w.replace(".uasset", "") for w in os.listdir(weapons_dir) if (not w.startswith("Wep_")) and w.endswith(".uasset")] print(f"Weapons found: {weapons}") package_path = "/project/" factory = unreal.BlueprintFactory() factory.set_editor_property("ParentClass", unreal.Actor) asset_tools = unreal.AssetToolsHelpers.get_asset_tools() for weapon in weapons: print(f"Creating blueprint Actor class for {weapon}...") new_asset = (asset_tools.create_asset(weapon, package_path, None, factory)) # unreal.EditorAssetLibrary.save_loaded_asset(new_asset)
# -*- coding: utf-8 -*- """ 返回材质中所有的 MaterialExpression """ # Import future modules from __future__ import absolute_import from __future__ import division from __future__ import print_function __author__ = "timmyliang" __email__ = "[email protected]" __date__ = "2022-01-20 10:02:33" # Import local modules from collections import defaultdict import unreal from unreal import MaterialEditingLibrary as mat_lib MP_OPACITY = unreal.MaterialProperty.MP_OPACITY BLEND_TRANSLUCENT = unreal.BlendMode.BLEND_TRANSLUCENT def main(): expression_count = { cls.__name__:10 for cls in unreal.MaterialExpression.__subclasses__() } expression_count.update({ "MaterialExpressionMultiply":100, "MaterialExpressionLinearInterpolate":100, }) for material in unreal.EditorUtilityLibrary.get_selected_assets(): if not isinstance(material, unreal.Material): continue data = defaultdict(list) material_path = material.get_path_name() for expression_type,count in expression_count.items(): for index in range(count): path = "{0}:{typ}_{index}".format( material_path, index=index, typ=expression_type ) expression = unreal.load_object(None, path) if expression: data[expression_type].append(path) print(dict(data)) if __name__ == "__main__": main()
import unreal import configparser import os REBERU_CONTENT_FULL_PATH = f'{unreal.Paths.project_content_dir()}Reberu' REBERU_SETTINGS : unreal.ReberuSettings = unreal.ReberuSettings.get_default_object() EAL = unreal.EditorAssetLibrary ELL = unreal.EditorLevelLibrary EAS = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem) ASSET_TOOLS = unreal.AssetToolsHelpers.get_asset_tools() DA_FACTORY = unreal.DataAssetFactory() def create_room_data(room_bounds : unreal.RoomBounds, room_name): """ Creates a room data asset or updates the fields on the existing asset if it already exists. :param room_bounds: an instance of BP_RoomBounds that contains our room info :param room_name: the name of the room to create """ content_path = REBERU_SETTINGS.get_editor_property('reberu_path') asset_path = f"{content_path}/project/{room_name}" print(f'Creating Reberu Room asset with name {room_name} at {asset_path}') does_asset_exist = EAS.does_asset_exist(asset_path) if(does_asset_exist): unreal.log_warning(f'Asset already exists at: {asset_path}.') new_da : unreal.ReberuRoomData = EAS.load_asset(asset_path) EAS.checkout_loaded_asset(new_da) else: new_da : unreal.ReberuRoomData = ASSET_TOOLS.create_asset(f'DA_{room_name}', f'{content_path}/Rooms', unreal.ReberuRoomData, DA_FACTORY) if not new_da: unreal.log_error(f'Failed to create new data asset at path {content_path}/project/{room_name}') return False new_da.set_editor_property("RoomName", room_name) new_da.room = room_bounds.room new_da.room.box_extent = room_bounds.room_box.box_extent new_da.room.box_actor_transform = room_bounds.get_actor_transform() new_da.room.level = room_bounds.get_world() EAL.save_loaded_asset(new_da, False) ELL.destroy_actor(room_bounds) return True def restore_room_bounds(room_data : unreal.ReberuRoomData, bp_room_class): """ Creates a roombounds bp instance in the current level using the inputted data asset. :param room_data: room data asset to grab information from """ new_actor : unreal.RoomBounds = ELL.spawn_actor_from_class(bp_room_class, room_data.room.box_actor_transform.translation, room_data.room.box_actor_transform.rotation.rotator()) if not new_actor: unreal.log_error('failed to create new room bounds from room_data') return new_actor.room_box.set_box_extent(room_data.room.box_extent) new_actor.room = room_data.room return new_actor.get_name() def regenerate_door_ids(room_data : unreal.ReberuRoomData): """ Regenerates all ids for the doors on the inputted room asset. :param room_data: room data asset to grab information from """ if not room_data: return False EAS.checkout_loaded_asset(room_data) unreal.ReberuLibrary.regenerate_door_ids(room_data) EAL.save_loaded_asset(room_data)
# -*- coding: utf-8 -*- import random import unreal import json from Utilities.Utils import Singleton class ButtonDivisionExample(metaclass=Singleton): def __init__(self, json_path:str): self.json_path = json_path self.data:unreal.ChameleonData = unreal.PythonBPLib.get_chameleon_data(self.json_path) self.id = 0 self.colors = [[10, 10, 0.5, 1], [10, 10, 10, 1], [10, 0.5, 0.5, 1], [0.5, 0.5, 10, 1], [10, 10, 10, 1]] self.get_color_num = 0 def get_button_json(self, id: int): s = f'{{"SButton": {{ "Text": "PlaceHolder Button", "Aka": "button_{id}", "OnClick": "chameleon_button_division.new_button()"}}}}' return s def new_button(self): self.data.set_content_from_json(f"button_{self.id}", self.get_button_json(self.id+1)) self.id += 1 def get_parent_aka(self, aka:str): aka_to_path = {x: self.data.get_widget_path_from_aka(x) for x in self.data.get_all_akas()} current_path = self.data.get_widget_path_from_aka(aka) result = "" result_aka = "" for k, p in aka_to_path.items(): if p == current_path: continue if current_path.startswith(p): if len(p) > len(result): result = p result_aka = k return result_aka, result def pick_a_color(self): self.get_color_num += 1 return self.colors[self.get_color_num % len(self.colors)] def gen_child_json(self, id): def gen_button(button_aka, color): return {"Padding": 1, "SButton": {"Aka": button_aka, "Text": " " , "OnClick": f"chameleon_button_division.on_button_click('{button_aka}')" , "ButtonColorAndOpacity": color}} box_type = "SHorizontalBox" if id % 2 else "SVerticalBox" fill_type = "FillWidth" if box_type == "SHorizontalBox" else "FillHeight" item = {box_type: {"Aka": f"c_{id}", "Slots":[]}} item[box_type]["Slots"].append(gen_button(f"b_{id}_A", self.pick_a_color())) item[box_type]["Slots"][0][fill_type] = 0.618 item[box_type]["Slots"].append(gen_button(f"b_{id}_B", self.pick_a_color())) if random.random() > 0.5: item[box_type]["Slots"][0], item[box_type]["Slots"][1] = item[box_type]["Slots"][1], item[box_type]["Slots"][0] if random.random() > 0.8: item[box_type]["Slots"].append(gen_button(f"b_{id}_C", self.pick_a_color())) item[box_type]["Slots"][0][fill_type] = 1.618 return json.dumps(item) def on_button_click(self, button_aka:str): print(f"On_button_click: {button_aka}") button_path = self.data.get_widget_path_from_aka(button_aka) parent_aka, parent_path = self.get_parent_aka(button_aka) print(f"button_path: {button_path}") print(f"parent_aka: {parent_aka}, parent_path: {parent_path}") slot_id = button_path[button_path.rfind("/Slots_") + len("/Slots_"):button_path.rfind("/SButton"):] assert slot_id slot_id = int(slot_id) # insert self.id += 1 child_json = self.gen_child_json(self.id) self.data.insert_slot_from_json(parent_aka, child_json, slot_id) self.data.remove_widget_at(parent_aka, slot_id+1)
# -*- coding: utf-8 -*- import logging import unreal import inspect import types import Utilities from collections import Counter class attr_detail(object): def __init__(self, obj, name:str): self.name = name attr = None self.bCallable = None self.bCallable_builtin = None try: if hasattr(obj, name): attr = getattr(obj, name) self.bCallable = callable(attr) self.bCallable_builtin = inspect.isbuiltin(attr) except Exception as e: unreal.log(str(e)) self.bProperty = not self.bCallable self.result = None self.param_str = None self.bEditorProperty = None self.return_type_str = None self.doc_str = None self.property_rw = None if self.bCallable: self.return_type_str = "" if self.bCallable_builtin: if hasattr(attr, '__doc__'): docForDisplay, paramStr = _simplifyDoc(attr.__doc__) # print(f"~~~~~ attr: {self.name} docForDisplay: {docForDisplay} paramStr: {paramStr}") # print(attr.__doc__) try: sig = inspect.getfullargspec(getattr(obj, self.name)) # print("+++ ", sig) args = sig.args argCount = len(args) if "self" in args: argCount -= 1 except TypeError: argCount = -1 if "-> " in docForDisplay: self.return_type_str = docForDisplay[docForDisplay.find(')') + 1:] else: self.doc_str = docForDisplay[docForDisplay.find(')') + 1:] if argCount == 0 or (argCount == -1 and (paramStr == '' or paramStr == 'self')): # Method with No params if '-> None' not in docForDisplay or self.name in ["__reduce__", "_post_init"]: try: if name == "get_actor_time_dilation" and isinstance(obj, unreal.Object): # call get_actor_time_dilation will crash engine if actor is get from CDO and has no world. if obj.get_world(): # self.result = "{}".format(attr.__call__()) self.result = attr.__call__() else: self.result = "skip call, world == None." else: # self.result = "{}".format(attr.__call__()) self.result = attr.__call__() except: self.result = "skip call.." else: print(f"docForDisplay: {docForDisplay}, self.name: {self.name}") self.result = "skip call." else: self.param_str = paramStr self.result = "" else: logging.error("Can't find p") elif self.bCallable_other: if hasattr(attr, '__doc__'): if isinstance(attr.__doc__, str): docForDisplay, paramStr = _simplifyDoc(attr.__doc__) if name in ["__str__", "__hash__", "__repr__", "__len__"]: try: self.result = "{}".format(attr.__call__()) except: self.result = "skip call." else: # self.result = "{}".format(getattr(obj, name)) self.result = getattr(obj, name) def post(self, obj): if self.bOtherProperty and not self.result: try: self.result = getattr(obj, self.name) except: self.result = "skip call..." def apply_editor_property(self, obj, type_, rws, descript): self.bEditorProperty = True self.property_rw = "[{}]".format(rws) try: self.result = eval('obj.get_editor_property("{}")'.format(self.name)) except: self.result = "Invalid" def __str__(self): s = f"Attr: {self.name} paramStr: {self.param_str} desc: {self.return_type_str} result: {self.result}" if self.bProperty: s += ", Property" if self.bEditorProperty: s += ", Eidtor Property" if self.bOtherProperty: s += ", Other Property " if self.bCallable: s += ", Callable" if self.bCallable_builtin: s += ", Callable_builtin" if self.bCallable_other: s += ", bCallable_other" if self.bHasParamFunction: s+= ", bHasParamFunction" return s def check(self): counter = Counter([self.bOtherProperty, self.bEditorProperty, self.bCallable_other, self.bCallable_builtin]) # print("counter: {}".format(counter)) if counter[True] == 2: unreal.log_error(f"{self.name}: {self.bEditorProperty}, {self.bOtherProperty} {self.bCallable_builtin} {self.bCallable_other}") @property def bOtherProperty(self): if self.bProperty and not self.bEditorProperty: return True return False @property def bCallable_other(self): if self.bCallable and not self.bCallable_builtin: return True return False @property def display_name(self, bRichText=True): if self.bProperty: return f"\t{self.name}" else: # callable if self.param_str: return f"\t{self.name}({self.param_str}) {self.return_type_str}" else: if self.bCallable_other: return f"\t{self.name}" # __hash__, __class__, __eq__ 等 else: return f"\t{self.name}() {self.return_type_str}" @property def display_result(self) -> str: if self.bEditorProperty: return "{} {}".format(self.result, self.property_rw) else: return "{}".format(self.result) @property def bHasParamFunction(self): return self.param_str and len(self.param_str) != 0 def ll(obj): if not obj: return None if inspect.ismodule(obj): return None result = [] for x in dir(obj): attr = attr_detail(obj, x) result.append(attr) if hasattr(obj, '__doc__') and isinstance(obj, unreal.Object): editorPropertiesInfos = _getEditorProperties(obj.__doc__, obj) for name, type_, rws, descript in editorPropertiesInfos: # print(f"~~ {name} {type} {rws}, {descript}") index = -1 for i, v in enumerate(result): if v.name == name: index = i break if index != -1: this_attr = result[index] else: this_attr = attr_detail(obj, name) result.append(this_attr) # unreal.log_warning(f"Can't find editor property: {name}") this_attr.apply_editor_property(obj, type_, rws, descript) for i, attr in enumerate(result): attr.post(obj) return result def _simplifyDoc(content): def next_balanced(content, s="(", e = ")" ): s_pos = -1 e_pos = -1 balance = 0 for index, c in enumerate(content): match = c == s or c == e if not match: continue balance += 1 if c == s else -1 if c == s and balance == 1 and s_pos == -1: s_pos = index if c == e and balance == 0 and s_pos != -1 and e_pos == -1: e_pos = index return s_pos, e_pos return -1, -1 # bracketS, bracketE = content.find('('), content.find(')') if not content: return "", "" bracketS, bracketE = next_balanced(content, s='(', e = ')') arrow = content.find('->') funcDocPos = len(content) endSign = ['--', '\n', '\r'] for s in endSign: p = content.find(s) if p != -1 and p < funcDocPos: funcDocPos = p funcDoc = content[:funcDocPos] if bracketS != -1 and bracketE != -1: param = content[bracketS + 1: bracketE].strip() else: param = "" return funcDoc, param def _getEditorProperties(content, obj): # print("Content: {}".format(content)) lines = content.split('\r') signFound = False allInfoFound = False result = [] for line in lines: if not signFound and '**Editor Properties:**' in line: signFound = True if signFound: #todo re # nameS, nameE = line.find('``') + 2, line.find('`` ') nameS, nameE = line.find('- ``') + 4, line.find('`` ') if nameS == -1 or nameE == -1: continue typeS, typeE = line.find('(') + 1, line.find(')') if typeS == -1 or typeE == -1: continue rwS, rwE = line.find('[') + 1, line.find(']') if rwS == -1 or rwE == -1: continue name = line[nameS: nameE] type_str = line[typeS: typeE] rws = line[rwS: rwE] descript = line[rwE + 2:] allInfoFound = True result.append((name, type_str, rws, descript)) # print(name, type, rws) if signFound: if not allInfoFound: unreal.log_warning("not all info found {}".format(obj)) else: unreal.log_warning("can't find editor properties in {}".format(obj)) return result def log_classes(obj): print(obj) print("\ttype: {}".format(type(obj))) print("\tget_class: {}".format(obj.get_class())) if type(obj.get_class()) is unreal.BlueprintGeneratedClass: generatedClass = obj.get_class() else: generatedClass = unreal.PythonBPLib.get_blueprint_generated_class(obj) print("\tgeneratedClass: {}".format(generatedClass)) print("\tbp_class_hierarchy_package: {}".format(unreal.PythonBPLib.get_bp_class_hierarchy_package(generatedClass))) def is_selected_asset_type(types): selectedAssets = Utilities.Utils.get_selected_assets() for asset in selectedAssets: if type(asset) in types: return True; return False
import unreal from ueGear.controlrig.paths import CONTROL_RIG_FUNCTION_PATH from ueGear.controlrig.components import base_component, EPIC_control_01 from ueGear.controlrig.helpers import controls class Component(base_component.UEComponent): name = "test_Spine" mgear_component = "EPIC_spine_02" def __init__(self): super().__init__() self.functions = {'construction_functions': ['construct_FK_spine'], 'forward_functions': ['forward_FK_spine'], 'backwards_functions': ['backwards_FK_spine'], } self.cr_variables = {} # Control Rig Inputs self.cr_inputs = {'construction_functions': ['parent'], 'forward_functions': [], 'backwards_functions': [], } # Control Rig Outputs self.cr_output = {'construction_functions': ['root'], 'forward_functions': [], 'backwards_functions': [], } # mGear self.inputs = [] self.outputs = [] def create_functions(self, controller: unreal.RigVMController = None): if controller is None: return # calls the super method super().create_functions(controller) # Generate Function Nodes for evaluation_path in self.functions.keys(): # Skip the forward function creation if no joints are needed to be driven if evaluation_path == 'forward_functions' and self.metadata.joints is None: continue for cr_func in self.functions[evaluation_path]: new_node_name = f"{self.name}_{cr_func}" ue_cr_node = controller.get_graph().find_node_by_name(new_node_name) # Create Component if doesn't exist if ue_cr_node is None: ue_cr_ref_node = controller.add_external_function_reference_node(CONTROL_RIG_FUNCTION_PATH, cr_func, unreal.Vector2D(0.0, 0.0), node_name=new_node_name) # In Unreal, Ref Node inherits from Node ue_cr_node = ue_cr_ref_node else: # if exists, add it to the nodes self.nodes[evaluation_path].append(ue_cr_node) unreal.log_error(f" Cannot create function {new_node_name}, it already exists") continue self.nodes[evaluation_path].append(ue_cr_node) # Gets the Construction Function Node and sets the control name func_name = self.functions['construction_functions'][0] construct_func = base_component.get_construction_node(self, f"{self.name}_{func_name}") if construct_func is None: unreal.log_error(" Create Functions Error - Cannot find construct singleton node") controller.set_pin_default_value(construct_func.get_name() + '.control_name', self.metadata.fullname, False) def populate_bones(self, bones: list[unreal.RigBoneElement] = None, controller: unreal.RigVMController = None): """ Generates the Bone array node that will be utilised by control rig to drive the component """ if bones is None or len(bones) < 3: unreal.log_error("[Bone Populate] Failed no Bones found") return if controller is None: unreal.log_error("[Bone Populate] Failed no Controller found") return # Unique name for this skeleton node array array_node_name = f"{self.metadata.fullname}_RigUnit_ItemArray" # node doesn't exists, create the joint node if not controller.get_graph().find_node_by_name(array_node_name): self._init_master_joint_node(controller, array_node_name, bones) # Connects the Item Array Node to the functions. for evaluation_path in self.nodes.keys(): for function_node in self.nodes[evaluation_path]: controller.add_link(f'{array_node_name}.Items', f'{function_node.get_name()}.Joints') outpu_joint_node_name = self._init_output_joints(controller, bones) construction_func_name = self.nodes["construction_functions"][0].get_name() controller.add_link(f'{outpu_joint_node_name}.Items', f'{construction_func_name}.joint_outputs') node = controller.get_graph().find_node_by_name(array_node_name) self.add_misc_function(node) def _init_master_joint_node(self, controller, node_name: str, bones): """Create the bone node, that will contain a list of all the bones that need to be driven. """ # Creates an Item Array Node to the control rig controller.add_unit_node_from_struct_path( '/project/.RigUnit_ItemArray', 'Execute', unreal.Vector2D(-54.908936, 204.649109), node_name) default_values = "" for i, bone in enumerate(bones): bone_name = str(bone.key.name) default_values += f'(Type=Bone,Name="{bone_name}"),' # trims off the extr ',' default_values = default_values[:-1] # Populates and resizes the pin in one go controller.set_pin_default_value(f'{node_name}.Items', f'({default_values})', True, setup_undo_redo=True, merge_undo_action=True) def _init_output_joints(self, controller: unreal.RigVMController, bones): """Creates an array of joints that will be fed into the node and then drive the output pins TODO: Refactor this, as it is no longer needed due to relatives now existsing in the json file. """ # Unique name for this skeleton output array array_node_name = f"{self.metadata.fullname}_OutputSkeleton_RigUnit_ItemArray" # Create a lookup table of the bones, to speed up interactions bone_dict = {} for bone in bones: bone_dict[str(bone.key.name)] = bone # Checks if node exists, else creates node found_node = controller.get_graph().find_node_by_name(array_node_name) if not found_node: # Create the ItemArray node found_node = controller.add_unit_node_from_struct_path( '/project/.RigUnit_ItemArray', 'Execute', unreal.Vector2D(500.0, 500.0), array_node_name) # Do pins already exist on the node, if not then we will have to create them. Else we dont existing_pins = found_node.get_pins()[0].get_sub_pins() generate_new_pins = True if len(existing_pins) > 0: generate_new_pins = False pin_index = 0 # Loops over all the joint relatives to setup the array for jnt_name, jnt_index in self.metadata.joint_relatives.items(): joint_name = self.metadata.joints[jnt_index] found_bone = bone_dict.get(joint_name, None) if found_bone is None: unreal.log_error(f"[Init Output Joints] Cannot find bone {joint_name}") continue # No pins are found then we add new pins on the array to populate if generate_new_pins: # Add new Item to array controller.insert_array_pin(f'{array_node_name}.Items', -1, '') bone_name = joint_name # Set Item to be of bone type controller.set_pin_default_value(f'{array_node_name}.Items.{pin_index}.Type', 'Bone', False) # Set the pin to be a specific bone name controller.set_pin_default_value(f'{array_node_name}.Items.{pin_index}.Name', bone_name, False) pin_index += 1 node = controller.get_graph().find_node_by_name(array_node_name) self.add_misc_function(node) return array_node_name def populate_control_transforms(self, controller: unreal.RigVMController = None): """Updates the transform data for the controls generated, with the data from the mgear json file. """ construction_func_name = self.nodes["construction_functions"][0].get_name() default_values = "" for i, control_name in enumerate(self.metadata.controls): control_transform = self.metadata.control_transforms[control_name] quat = control_transform.rotation pos = control_transform.translation string_entry = (f"(Rotation=(X={quat.x},Y={quat.y},Z={quat.z},W={quat.w}), " f"Translation=(X={pos.x},Y={pos.y},Z={pos.z}), " f"Scale3D=(X=1.000000,Y=1.000000,Z=1.000000)),") default_values += string_entry # trims off the extr ',' default_values = default_values[:-1] controller.set_pin_default_value( f"{construction_func_name}.fk_world_transforms", f"({default_values})", True, setup_undo_redo=True, merge_undo_action=True) # Populate control names names = ",".join([name for name in self.metadata.controls]) controller.set_pin_default_value( f'{construction_func_name}.fk_world_keys', f"({names})", True, setup_undo_redo=True, merge_undo_action=True) self.populate_control_scale(controller) self.populate_control_shape_offset(controller) self.populate_control_colour(controller) def populate_control_scale(self, controller: unreal.RigVMController): """ Generates a scale value per a control """ import ueGear.controlrig.manager as ueMan # Generates the array node array_name = ueMan.create_array_node(f"{self.metadata.fullname}_control_scales", controller) array_node = controller.get_graph().find_node_by_name(array_name) self.add_misc_function(array_node) # connects the node of scales to the construction node construction_func_name = self.nodes["construction_functions"][0].get_name() controller.add_link(f'{array_name}.Array', f'{construction_func_name}.control_sizes') aabb_divisor = 4.0 """Magic number to try and get the maya control scale to be similar to that of unreal. As the mGear uses a square and ueGear uses a cirlce. """ default_values = "" # populate array for i, control_name in enumerate(self.metadata.controls): aabb = self.metadata.controls_aabb[control_name] unreal_size = [round(element / aabb_divisor, 4) for element in aabb[1]] # rudementary way to check if the bounding box might be flat, if it is then # the first value if applied onto the axis if unreal_size[0] == unreal_size[1] and unreal_size[2] < 0.02: unreal_size[2] = unreal_size[0] elif unreal_size[1] == unreal_size[2] and unreal_size[0] < 0.02: unreal_size[0] = unreal_size[1] elif unreal_size[0] == unreal_size[2] and unreal_size[1] < 0.02: unreal_size[1] = unreal_size[0] default_values += f'(X={unreal_size[0]},Y={unreal_size[1]},Z={unreal_size[2]}),' # trims off the extr ',' default_values = default_values[:-1] # Populates and resizes the pin in one go controller.set_pin_default_value( f'{array_name}.Values', f'({default_values})', True, setup_undo_redo=True, merge_undo_action=True) def populate_control_shape_offset(self, controller: unreal.RigVMController): """ As some controls have there pivot at the same position as the transform, but the control is actually moved away from that pivot point. We use the bounding box position as an offset for the control shape. """ import ueGear.controlrig.manager as ueMan # Generates the array node array_name = ueMan.create_array_node(f"{self.metadata.fullname}_control_offset", controller) array_node = controller.get_graph().find_node_by_name(array_name) self.add_misc_function(array_node) # connects the node of scales to the construction node construction_func_name = self.nodes["construction_functions"][0].get_name() controller.add_link(f'{array_name}.Array', f'{construction_func_name}.control_offsets') default_values = "" for i, control_name in enumerate(self.metadata.controls): aabb = self.metadata.controls_aabb[control_name] bb_center = aabb[0] string_entry = f'(X={bb_center[0]}, Y={bb_center[1]}, Z={bb_center[2]}),' default_values += string_entry # trims off the extr ',' default_values = default_values[:-1] controller.set_pin_default_value( f'{array_name}.Values', f'({default_values})', True, setup_undo_redo=True, merge_undo_action=True) def populate_control_colour(self, controller): cr_func = self.functions["construction_functions"][0] construction_node = f"{self.name}_{cr_func}" default_values = "" for i, control_name in enumerate(self.metadata.controls): colour = self.metadata.controls_colour[control_name] string_entry = f"(R={colour[0]}, G={colour[1]}, B={colour[2]}, A=1.0)," default_values += string_entry # trims off the extr ',' default_values = default_values[:-1] # Populates and resizes the pin in one go controller.set_pin_default_value( f'{construction_node}.control_colours', f"({default_values})", True, setup_undo_redo=True, merge_undo_action=True) class ManualComponent(Component): name = "Manual_EPIC_spine_02" def __init__(self): super().__init__() self.functions = {'construction_functions': ['manual_construct_FK_spine'], 'forward_functions': ['forward_FK_spine'], 'backwards_functions': ['backwards_FK_spine'], } self.is_manual = True # These are the roles that will be parented directly under the parent component. self.root_control_children = ["spinePosition", "ik0", "ik1", "fk0", "pelvis"] self.hierarchy_schematic_roles = {"ik0": ["tan", "tan0"], "ik1": ["tan1"] } def create_functions(self, controller: unreal.RigVMController): EPIC_control_01.ManualComponent.create_functions(self, controller) self.setup_dynamic_hierarchy_roles() def setup_dynamic_hierarchy_roles(self): """Manual controls have some dynamic control creation. This function sets up the control relationship for the dynamic control hierarchy.""" # Calculate the amount of fk's based on the division amount fk_count = self.metadata.settings['division'] for i in range(fk_count): parent_role = f"fk{i}" child_index = i+1 child_role = f"fk{child_index}" # end of the fk chain, parent the chest control if child_index >= fk_count: self.hierarchy_schematic_roles[parent_role] = ['chest'] continue self.hierarchy_schematic_roles[parent_role] = [child_role] # todo: Move this to Parent Class def initialize_hierarchy(self, hierarchy_controller: unreal.RigHierarchyController): """Performs the hierarchical restructuring of the internal components controls""" # Parent control hierarchy using roles for parent_role in self.hierarchy_schematic_roles.keys(): child_roles = self.hierarchy_schematic_roles[parent_role] parent_ctrl = self.control_by_role[parent_role] for child_role in child_roles: child_ctrl = self.control_by_role[child_role] hierarchy_controller.set_parent(child_ctrl.rig_key, parent_ctrl.rig_key) def generate_manual_controls(self, hierarchy_controller: unreal.RigHierarchyController): """Creates all the manual controls for the Spine""" # Stores the controls by Name control_table = dict() for control_name in self.metadata.controls: new_control = controls.CR_Control(name=control_name) # stored metadata values control_transform = self.metadata.control_transforms[control_name] control_colour = self.metadata.controls_colour[control_name] control_aabb = self.metadata.controls_aabb[control_name] control_offset = control_aabb[0] control_scale = [control_aabb[1][0] / 4.0, control_aabb[1][1] / 4.0, control_aabb[1][2] / 4.0] # Set the colour, required before build new_control.colour = control_colour new_control.shape_name = "Box_Thick" # Generate the Control new_control.build(hierarchy_controller) # Sets the controls position, and offset translation and scale of the shape new_control.set_transform(quat_transform=control_transform) new_control.shape_transform_global(pos=control_offset, scale=control_scale, rotation=[90,0,0]) control_table[control_name] = new_control # Stores the control by role, for loopup purposes later role = self.metadata.controls_role[control_name] self.control_by_role[role] = new_control self.initialize_hierarchy(hierarchy_controller) def populate_control_transforms(self, controller: unreal.RigVMController = None): fk_controls = [] ik_controls = [] # Groups all the controls into ik and fk lists for role_key in self.control_by_role.keys(): # Generates the list of fk controls if 'fk' in role_key or "chest" in role_key: control = self.control_by_role[role_key] fk_controls.append(control) else: control = self.control_by_role[role_key] ik_controls.append(control) construction_func_name = self.nodes["construction_functions"][0].get_name() # Populate control names # Converts RigElementKey into one long string of key data. def update_input_plug(plug_name, control_list): """ Simple helper function making the plug population reusable for ik and fk """ control_metadata = [] for entry in control_list: if entry.rig_key.type == unreal.RigElementType.CONTROL: t = "Control" if entry.rig_key.type == unreal.RigElementType.NULL: t = "Null" n = entry.rig_key.name entry = f'(Type={t}, Name="{n}")' control_metadata.append(entry) concatinated_controls = ",".join(control_metadata) controller.set_pin_default_value( f'{construction_func_name}.{plug_name}', f"({concatinated_controls})", True, setup_undo_redo=True, merge_undo_action=True) update_input_plug("fk_controls", fk_controls) update_input_plug("ik_controls", ik_controls)
import unreal textures:list[unreal.Texture2D] = unreal.EditorUtilityLibrary.get_selected_assets() if not textures: unreal.log_warning("No textures selected.") for texture in textures: texture.mip_gen_settings = unreal.TextureMipGenSettings.TMGS_SHARPEN4 texture.set_editor_property('mip_gen_settings', unreal.TextureMipGenSettings.TMGS_SHARPEN4) #texture.post_edit_change() print(f"Set Mip Gen Settings for {texture.get_name()} to TMGS_SHARPEN4")
import unreal import logging logger = logging.getLogger(__name__) from pamux_unreal_tools.base.material_expression.material_expression_editor_property_base import MaterialExpressionEditorPropertyBase from pamux_unreal_tools.base.material_expression.material_expression_sockets_base import InSocket, OutSocket from pamux_unreal_tools.base.material_expression.material_expression_base_base import MaterialExpressionBaseBase from pamux_unreal_tools.utils.build_stack import BuildStack from pamux_unreal_tools.utils.node_pos import NodePos class MaterialExpressionBase(MaterialExpressionBaseBase): def __init__(self, expression_class: unreal.Class, node_pos: NodePos = None) -> None: self.container = BuildStack.top() self.expression_class: unreal.Class = expression_class self.unrealAsset: unreal.MaterialExpression = self.container.createMaterialExpression(self.expression_class, node_pos) self.desc: MaterialExpressionEditorPropertyBase = None self.material_expression_editor_x: MaterialExpressionEditorPropertyBase = None self.material_expression_editor_y: MaterialExpressionEditorPropertyBase = None self.input: InSocket = None self.output: OutSocket = None def comesFrom(self, param1) -> bool: return self.input.comesFrom(param1) def connectTo(self, param1) -> bool: return self.output.connectTo(param1) @property def rt(self): return self.output.rt def add_rt(self, container_name:str = None, socket_name:str = None): return self.output.add_rt(container_name, socket_name)
import scripts.recording.takeRecorder as takeRecorder import unreal import scripts.utils.editorFuncs as editorFuncs # import assets_tools # import assets from typing import Dict, Any import scripts.popUp as popUp # tk = takeRecorder.TakeRecorder() # # Create an instance of EditorUtilityLibrary # global_editor_utility = unreal.EditorUtilityLibrary() # replay_actor = editorFuncs.get_actor_by_name("playLastActor") # # Check if the actor reference was found # if replay_actor is None: # raise ValueError("Actor 'playLastActor_C_1' not found in the current world.") # # Load the animation asset and ensure it’s of type AnimationSequence # animation_asset = unreal.load_asset("/project/") # # animation_asset = unreal.load_asset('/project/') # # Call the replay_anim function with the found actor and correct animation asset # tk.replay_anim( # replay_actor=replay_actor, # anim=animation_asset # ) def fetch_last_recording(take_recorder_panel): """ Fetch last recording. Returns: - level_sequence (unreal.LevelSequence): The last recorded level sequence. """ return take_recorder_panel.get_last_recorded_level_sequence() def fetch_last_animation(take_recorder_panel): """ Fetch last animation. Returns: - level_sequence (unreal.AnimSequence): The last recorded level sequence. """ last_record = fetch_last_recording(take_recorder_panel) if last_record is None: return None, None last_record = last_record.get_full_name() unrealTake = last_record.replace("LevelSequence ", "") unrealScene = unrealTake.split(".")[1] unrealTake = unrealTake.split(".")[0] animLocation = unrealTake + "_Subscenes/project/" + "_" + unrealScene animation_asset = unreal.load_asset(animLocation) return animation_asset, animLocation take_recorder_panel = ( unreal.TakeRecorderBlueprintLibrary.get_take_recorder_panel() ) loca_1 = "/project/-02-11/project/" _, loca_2 = fetch_last_animation(take_recorder_panel) popUp.show_popup_message("recordings equal?", f"{loca_1} == {loca_2}\n{loca_1 == loca_2}")
# Copyright Epic Games, Inc. All Rights Reserved """ This script handles processing jobs for a specific sequence """ import unreal from getpass import getuser from .render_queue_jobs import render_jobs from .utils import ( movie_pipeline_queue, project_settings, get_asset_data ) def setup_sequence_parser(subparser): """ This method adds a custom execution function and args to a sequence subparser :param subparser: Subparser for processing custom sequences """ # We will use the level sequence and the map as our context for # other subsequence arguments. subparser.add_argument( "sequence", type=str, help="The level sequence that will be rendered." ) subparser.add_argument( "map", type=str, help="The map the level sequence will be loaded with for rendering.", ) # Get some information for the render queue subparser.add_argument( "mrq_preset", type=str, help="The MRQ preset used to render the current job.", ) # Function to process arguments subparser.set_defaults(func=_process_args) def render_current_sequence( sequence_name, sequence_map, mrq_preset, user=None, shots=None, is_remote=False, is_cmdline=False, remote_batch_name=None, remote_job_preset=None, executor_instance=None, output_dir_override=None, output_filename_override=None ): """ Renders a sequence with a map and mrq preset :param str sequence_name: Sequence to render :param str sequence_map: Map to load sequence :param str mrq_preset: MRQ preset for rendering sequence :param str user: Render user :param list shots: Shots to render :param bool is_remote: Flag to determine if the job should be executed remotely :param bool is_cmdline: Flag to determine if the render was executed via commandline :param str remote_batch_name: Remote render batch name :param str remote_job_preset: deadline job Preset Library :param executor_instance: Movie Pipeline executor Instance :param str output_dir_override: Movie Pipeline output directory override :param str output_filename_override: Movie Pipeline filename format override :return: MRQ executor """ # The queue subsystem behaves like a singleton so # clear all the jobs in the current queue. movie_pipeline_queue.delete_all_jobs() render_job = movie_pipeline_queue.allocate_new_job( unreal.SystemLibrary.conv_soft_class_path_to_soft_class_ref( project_settings.default_executor_job ) ) render_job.author = user or getuser() sequence_data_asset = get_asset_data(sequence_name, "LevelSequence") # Create a job in the queue unreal.log(f"Creating render job for `{sequence_data_asset.asset_name}`") render_job.job_name = sequence_data_asset.asset_name unreal.log( f"Setting the job sequence to `{sequence_data_asset.asset_name}`" ) render_job.sequence = sequence_data_asset.to_soft_object_path() map_data_asset = get_asset_data(sequence_map, "World") unreal.log(f"Setting the job map to `{map_data_asset.asset_name}`") render_job.map = map_data_asset.to_soft_object_path() mrq_preset_data_asset = get_asset_data( mrq_preset, "MoviePipelinePrimaryConfig" ) unreal.log( f"Setting the movie pipeline preset to `{mrq_preset_data_asset.asset_name}`" ) render_job.set_configuration(mrq_preset_data_asset.get_asset()) # MRQ added the ability to enable and disable jobs. Check to see is a job # is disabled and enable it. The assumption is we want to render this # particular job. # Note this try/except block is for backwards compatibility try: if not render_job.enabled: render_job.enabled = True except AttributeError: pass # If we have a shot list, iterate over the shots in the sequence # and disable anything that's not in the shot list. If no shot list is # provided render all the shots in the sequence if shots: for shot in render_job.shot_info: if shot.inner_name in shots or (shot.outer_name in shots): shot.enabled = True else: unreal.log_warning( f"Disabling shot `{shot.inner_name}` from current render job `{render_job.job_name}`" ) shot.enabled = False try: # Execute the render. This will execute the render based on whether # its remote or local executor = render_jobs( is_remote, remote_batch_name=remote_batch_name, remote_job_preset=remote_job_preset, is_cmdline=is_cmdline, executor_instance=executor_instance, output_dir_override=output_dir_override, output_filename_override=output_filename_override ) except Exception as err: unreal.log_error( f"An error occurred executing the render.\n\tError: {err}" ) raise return executor def _process_args(args): """ Function to process the arguments for the sequence subcommand :param args: Parsed Arguments from parser """ return render_current_sequence( args.sequence, args.map, args.mrq_preset, user=args.user, shots=args.shots, is_remote=args.remote, is_cmdline=args.cmdline, remote_batch_name=args.batch_name, remote_job_preset=args.deadline_job_preset, output_dir_override=args.output_override, output_filename_override=args.filename_override )
# This script shows how to setup dependencies between variants when using the Variant Manager Python API import unreal lvs = unreal.VariantManagerLibrary.create_level_variant_sets_asset("LVS", "/Game/") if lvs is None: print ("Failed to spawn either the LevelVariantSets asset or the LevelVariantSetsActor!") quit() var_set_colors = unreal.VariantSet() var_set_colors.set_display_text("Colors") var_set_letters = unreal.VariantSet() var_set_letters.set_display_text("Letters") var_set_fruits = unreal.VariantSet() var_set_fruits.set_display_text("Fruits") var_red = unreal.Variant() var_red.set_display_text("Red") var_green = unreal.Variant() var_green.set_display_text("Green") var_blue = unreal.Variant() var_blue.set_display_text("Blue") var_a = unreal.Variant() var_a.set_display_text("A") var_b = unreal.Variant() var_b.set_display_text("B") var_apple = unreal.Variant() var_apple.set_display_text("Apple") var_orange = unreal.Variant() var_orange.set_display_text("Orange") # Adds the objects to the correct parents lvs.add_variant_set(var_set_colors) lvs.add_variant_set(var_set_letters) lvs.add_variant_set(var_set_fruits) var_set_colors.add_variant(var_red) var_set_colors.add_variant(var_green) var_set_colors.add_variant(var_blue) var_set_letters.add_variant(var_a) var_set_letters.add_variant(var_b) var_set_fruits.add_variant(var_apple) var_set_fruits.add_variant(var_orange) # Let's make variant 'Red' also switch on variant 'A' before it is switched on dep1 = unreal.VariantDependency() dep1.set_editor_property('VariantSet', var_set_letters) dep1.set_editor_property('Variant', var_a) dep1_index = var_red.add_dependency(dep1) # Let's also make variant 'A' also switch on variant 'Orange' before it is switched on dep2 = unreal.VariantDependency() dep2.set_editor_property('VariantSet', var_set_fruits) dep2.set_editor_property('Variant', var_orange) var_a.add_dependency(dep2) # Because dependencies trigger first, this will switch on 'Orange', then 'A' and finally 'Red' var_red.switch_on() # Let's disable the first dependency # Note we need to set the struct back into the variant, as it's returned by value dep1.set_editor_property('bEnabled', False) var_red.set_dependency(dep1_index[0], dep1) # Now this will only trigger 'Red', because dep1 is disabled and doesn't propagate to variant 'A' var_red.switch_on ( )
import unreal selected_assets = unreal.EditorUtilityLibrary.get_selected_assets() for asset in selected_assets : # 파라미터 및 parameter_name = "EnableUDW" control_bool_val = False if isinstance(asset, unreal.MaterialInstanceConstant): found = unreal.MaterialEditingLibrary.set_material_instance_static_switch_parameter_value(asset, parameter_name, control_bool_val) #업데이트 해놔야 컨텐츠 브라우저에서 저장먹힘 이거 안하면 저장안됨 unreal.MaterialEditingLibrary.update_material_instance(asset) print( asset.get_name(), ">>", parameter_name, ">>>", control_bool_val ) else: pass
import unreal @unreal.uclass() class MCPManager(unreal.Object): unreal_python = unreal.uproperty(bool, meta={"Category": "MCP Servers", "DisplayName": "unreal_python"})
import unreal import tempfile import csv import os import json from scripts.common.utils import get_sheet_data # 이 줄 추가 from . import level_data # DT_LevelData 임포트를 위한 모듈 SHEET_ID = "19t28YoMTYX6jrA8tW5mXvsu7PMjUNco7VwQirzImmIE" GID = "810949862" TABLE_PATH = "/project/" def create_scene_spot_data(display_name, thumb_id, camera_name): """SceneSpotData 구조체 생성""" # 썸네일 경로 생성 thumbnail_path = f"/project/{thumb_id}/PhotoSpot1.PhotoSpot1" # 해당 썸네일이 존재하는지 확인 if not unreal.EditorAssetLibrary.does_asset_exist(thumbnail_path): # 썸네일이 없으면 기본 이미지 사용 thumbnail_path = "/project/.T_empty_logo_horizontal" return f'((DisplayName=NSLOCTEXT("", "{display_name}", "{display_name}"),'\ f'Thumbnail="{thumbnail_path}",'\ f'CameraName="{camera_name}",Tags=))' def create_crowd_data(): """CrowdData 구조체 생성""" return '((DisplayName="",DensityLevel=MildlyCrowded,CrowdLevelId=""),'\ '(DisplayName="",DensityLevel=Crowded,CrowdLevelId=""))' def create_light_environment(env_id, display_name, min_time, max_time): """LightEnvironment 구조체 생성""" return f'(DisplayName=NSLOCTEXT("", "{env_id}", "{display_name}"),'\ f'MinEffectiveTime={min_time:.6f},'\ f'MaxEffectiveTime={max_time:.6f},'\ f'EnvironmentLevelId="{env_id}")' def validate_row(row_dict): """필수 컬럼 검증""" required_fields = [ 'ID', # MapID 'DisplayName', 'MainLevelId', 'DefaultTimeOfTheDay', 'SceneLightEnvironment.EnvironmentLevelId[0]', 'SceneLightEnvironment.DisplayName[0]', 'SceneLightEnvironment.MinEffectiveTime[0]', 'SceneLightEnvironment.MaxEffectiveTime[0]', 'bIsEnabled', 'bIsExposedToLibrary' ] missing_fields = [] for field in required_fields: if field not in row_dict or not row_dict[field]: missing_fields.append(field) if missing_fields: print(f"행 {row_dict.get('ID', '알 수 없음')} 누락된 필드: {', '.join(missing_fields)}") return False return True def set_file_writable(file_path): """파일의 읽기 전용 속성을 해제""" if os.path.exists(file_path): try: import stat current_permissions = os.stat(file_path).st_mode os.chmod(file_path, current_permissions | stat.S_IWRITE) print(f"파일 쓰기 권한 설정됨: {file_path}") return True except Exception as e: print(f"파일 권한 변경 실패: {str(e)}") return False return True def checkout_and_make_writable(asset_path): """에셋을 소스 컨트롤에서 checkout하고 쓰기 가능하게 만듦""" try: # 에셋이 존재하는지 확인 if not unreal.EditorAssetLibrary.does_asset_exist(asset_path): print(f"에셋이 존재하지 않음: {asset_path}") return {'success': False, 'error': f"에셋이 존재하지 않습니다: {asset_path}"} # 에셋 로드 asset = unreal.EditorAssetLibrary.load_asset(asset_path) if not asset: print(f"에셋을 로드할 수 없음: {asset_path}") return {'success': False, 'error': f"에셋을 로드할 수 없습니다: {asset_path}"} # 소스 컨트롤 상태 확인 try: source_control = unreal.EditorUtilityLibrary.get_source_control_provider() if source_control and source_control.is_enabled(): state = source_control.get_state(asset_path) if state: other_user = state.get_other_user() if other_user: error_msg = f"{other_user}에 의해 에셋이 잠겨있습니다. {other_user}에게 문의해주세요." print(f"⚠️ {error_msg}") return {'success': False, 'error': error_msg} except Exception as e: print(f"소스 컨트롤 상태 확인 중 오류 발생: {str(e)}") # 에셋 체크아웃 시도 try: if not unreal.EditorAssetLibrary.checkout_loaded_asset(asset): print(f"⚠️ 에셋 체크아웃 실패: {asset_path}") return {'success': False, 'error': "에셋이 잠겨있습니다. 소스 컨트롤 상태를 확인해주세요."} except Exception as e: print(f"체크아웃 중 오류 발생: {str(e)}") return {'success': False, 'error': f"체크아웃 중 오류 발생: {str(e)}"} print(f"✅ 에셋이 체크아웃됨: {asset_path}") # 에셋의 실제 파일 경로 가져오기 package_path = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(asset) if not package_path: print(f"에셋 경로를 찾을 수 없음: {asset_path}") return {'success': False, 'error': f"에셋 경로를 찾을 수 없습니다: {asset_path}"} # 파일 쓰기 가능하게 만들기 if not set_file_writable(package_path): print(f"파일을 쓰기 가능하게 만들 수 없음: {package_path}") return {'success': False, 'error': f"파일을 쓰기 가능하게 만들 수 없습니다: {package_path}"} print(f"✅ 에셋이 쓰기 가능하게 설정됨: {asset_path}") return {'success': True} except Exception as e: print(f"에셋 설정 중 오류 발생: {str(e)}") return {'success': False, 'error': str(e)} def import_table(sheet_id=SHEET_ID, gid=GID): try: print(f"=== 씬 레벨 데이터 임포트 시작 ===") print("테이블 정보:") print(f"- Sheet ID: {sheet_id}") print(f"- GID: {gid}") print(f"- 테이블 경로: {TABLE_PATH}") data = get_sheet_data(sheet_id, gid) if not data: return {'success': False, 'error': '데이터를 가져올 수 없습니다.'} # 에셋 checkout checkout_result = checkout_and_make_writable(TABLE_PATH) if not checkout_result['success']: print(f"체크아웃 실패: {checkout_result['error']}") return checkout_result # 데이터 테이블 생성 또는 로드 data_table = unreal.EditorAssetLibrary.load_asset(TABLE_PATH) if not data_table: data_table = unreal.EditorAssetLibrary.make_new_data_table_asset(TABLE_PATH, unreal.DataTable) if not data_table: print(f"데이터 테이블 생성 실패: {TABLE_PATH}") return {'success': False, 'error': '데이터 테이블을 생성할 수 없습니다.'} # 데이터 처리 및 저장 if process_and_save_data(data_table, data): print(f"데이터 테이블 업데이트 성공 ({len(data)}행)") return {'success': True, 'count': len(data)} return {'success': False, 'error': '데이터 처리 중 오류가 발생했습니다.'} except Exception as e: print(f"실패: {str(e)}") import traceback traceback.print_exc() return {'success': False, 'error': str(e)} def process_and_save_data(data_table, data): try: # CSV 파일 생성 temp_dir = tempfile.gettempdir() temp_csv_path = os.path.join(temp_dir, "temp_scene_level_data.csv") fieldnames = ['ID', 'DisplayName', 'MainLevelId', 'CameraLevelId', 'PropLevelId', 'ZoneLevelId', 'SceneSpotDatas', 'DefaultCrowdDensityLevel', 'SceneCrowdDatas', 'DefaultTimeOfTheDay', 'SceneLightEnvironments', 'bIsEnabled', 'bIsExposedToLibrary'] with open(temp_csv_path, 'w', encoding='utf-8', newline='') as outfile: writer = csv.DictWriter(outfile, fieldnames=fieldnames) writer.writeheader() for row in data: scene_id = str(row.get('ID', '')).strip() if not scene_id: continue # SceneSpotDatas 생성 scene_spots = [] for i in range(3): # 최대 3개의 스팟 데이터 display_name = str(row.get(f'SceneSpotDatas_DisplayName[{i}]', '')).strip() thumb = str(row.get(f'SceneSpotDatas_Thumb[{i}]', '')).strip() camera = str(row.get(f'SceneSpotDatas_Camera[{i}]', '')).strip() if display_name or thumb or camera: thumbnail_path = f'/project/{scene_id}/{thumb}.{thumb}' entry = f'(DisplayName="{display_name}",Thumbnail="{thumbnail_path}",CameraName="{camera}")' scene_spots.append(entry) # SceneLightEnvironments 생성 light_envs = [] for i in range(3): # DAY, SUNSET, NIGHT env_id = str(row.get(f'SceneLightEnvironment.EnvironmentLevelId[{i}]', '')).strip() display_name = str(row.get(f'SceneLightEnvironment.DisplayName[{i}]', '')).strip() min_time = str(row.get(f'SceneLightEnvironment.MinEffectiveTime[{i}]', '0')).strip() max_time = str(row.get(f'SceneLightEnvironment.MaxEffectiveTime[{i}]', '0')).strip() if env_id and display_name: light_envs.append({ 'EnvironmentLevelId': env_id, 'DisplayName': display_name, 'MinEffectiveTime': min_time, 'MaxEffectiveTime': max_time }) new_row = { 'ID': scene_id, 'DisplayName': str(row.get('DisplayName', '')).strip(), 'MainLevelId': str(row.get('MainLevelId', '')).strip(), 'CameraLevelId': str(row.get('CameraLevelId', '')).strip(), 'PropLevelId': str(row.get('PropLevelId', '')).strip(), 'ZoneLevelId': str(row.get('ZoneLevelId', '')).strip(), 'SceneSpotDatas': f'({",".join(scene_spots)})', 'DefaultCrowdDensityLevel': str(row.get('DefaultCrowdDensityLevel', '')).strip(), 'SceneCrowdDatas': json.dumps([ {'DensityLevel': 'MildlyCrowded', 'LevelId': str(row.get('Mildly_Crowded', '')).strip()}, {'DensityLevel': 'Crowded', 'LevelId': str(row.get('Crowded', '')).strip()} ]), 'DefaultTimeOfTheDay': str(row.get('DefaultTimeOfTheDay', '')).strip(), 'SceneLightEnvironments': json.dumps(light_envs), 'bIsEnabled': str(row.get('bIsEnabled', 'true')).upper(), 'bIsExposedToLibrary': str(row.get('bIsExposedToLibrary', 'true')).upper() } writer.writerow(new_row) # 데이터 테이블 임포트 설정 struct_path = "/project/.CinevSceneLevelData" row_struct = unreal.load_object(None, struct_path) if not row_struct: print(f"구조체를 찾을 수 없습니다: {struct_path}") return False # CSV 임포트 설정 factory = unreal.CSVImportFactory() factory.automated_import_settings.import_row_struct = row_struct # 임포트 태스크 설정 task = unreal.AssetImportTask() task.filename = temp_csv_path task.destination_path = os.path.dirname(TABLE_PATH) task.destination_name = os.path.basename(TABLE_PATH).replace("/Game/", "") task.replace_existing = True task.automated = True task.save = True task.factory = factory # 데이터 테이블 임포트 실행 asset_tools = unreal.AssetToolsHelpers.get_asset_tools() asset_tools.import_asset_tasks([task]) # 임시 파일 삭제 try: os.remove(temp_csv_path) print(f"임시 파일 삭제됨: {temp_csv_path}") except Exception as e: print(f"임시 파일 삭제 실패: {e}") return True except Exception as e: print(f"데이터 처리 중 오류 발생: {str(e)}") return False def import_scene_level_data(sheet_id, gid, table_path): try: print(f"=== 씬 레벨 데이터 임포트 시작 ===") print("테이블 정보:") print(f"- Sheet ID: {sheet_id}") print(f"- GID: {gid}") print(f"- 테이블 경로: {table_path}") data = get_sheet_data(sheet_id, gid) if not data: return False # 에셋 checkout if not checkout_and_make_writable(table_path): return False # 데이터 테이블 생성 또는 로드 data_table = unreal.EditorAssetLibrary.load_asset(table_path) if not data_table: data_table = unreal.EditorAssetLibrary.make_new_data_table_asset(table_path, unreal.DataTable) if not data_table: print(f"데이터 테이블 생성 실패: {table_path}") return False # 데이터 처리 및 저장 if process_and_save_data(data_table, data): print(f"데이터 테이블 업데이트 성공 ({len(data)}행)") return True return False except Exception as e: print(f"씬 레벨 데이터 임포트 중 오류 발생: {str(e)}") return False
import unreal import pyblish.api class ValidateNoDependencies(pyblish.api.InstancePlugin): """Ensure that the uasset has no dependencies The uasset is checked for dependencies. If there are any, the instance cannot be published. """ order = pyblish.api.ValidatorOrder label = "Check no dependencies" families = ["uasset"] hosts = ["unreal"] optional = True def process(self, instance): ar = unreal.AssetRegistryHelpers.get_asset_registry() all_dependencies = [] for obj in instance[:]: asset = ar.get_asset_by_object_path(obj) dependencies = ar.get_dependencies( asset.package_name, unreal.AssetRegistryDependencyOptions( include_soft_package_references=False, include_hard_package_references=True, include_searchable_names=False, include_soft_management_references=False, include_hard_management_references=False )) if dependencies: for dep in dependencies: if str(dep).startswith("/Game/"): all_dependencies.append(str(dep)) if all_dependencies: raise RuntimeError( f"Dependencies found: {all_dependencies}")
import unreal actorLocation = unreal.Vector(0, 0, 0) pointLight = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.PointLight, actorLocation) pointLight.set_actor_label("key_light") # Function to find the light actor by label name. The label name is what you name the light in the editor def find_point_light_actor_by_label(label): actors = unreal.EditorLevelLibrary.get_all_level_actors() for actor in actors: if isinstance(actor, unreal.PointLight) and actor.get_actor_label() == label: return actor return None # Set the intensity of the point light def set_point_light_intensity(actor_label, intensity): point_light_actor = find_point_light_actor_by_label(actor_label) if point_light_actor: point_light_component = point_light_actor.light_component point_light_component.set_intensity(intensity) print(f"Point light intensity set to '{intensity}'") else: print(f"No PointLight actor found with the name '{actor_label}'") # Set the desired intensity value desired_intensity = 1000.0 point_light_actor_label = "key_light" set_point_light_intensity(point_light_actor_label, desired_intensity)
""" Blueprint manipulation operations for creating and modifying Blueprint classes. """ from typing import Any, Dict, List, Optional import unreal # Enhanced error handling framework from utils.error_handling import ( AssetPathRule, ProcessingError, RequiredRule, TypeRule, ValidationError, handle_unreal_errors, require_asset, safe_operation, validate_inputs, ) from utils.general import log_debug as log_info from utils.general import log_error, log_warning @validate_inputs( { "class_name": [RequiredRule(), TypeRule(str)], "parent_class": [RequiredRule(), TypeRule(str)], "target_folder": [RequiredRule(), TypeRule(str)], "components": [TypeRule(list, allow_none=True)], "variables": [TypeRule(list, allow_none=True)], } ) @handle_unreal_errors("create_blueprint") @safe_operation("blueprint") def create( class_name: str, parent_class: str = "Actor", target_folder: str = "/project/", components: Optional[List[Dict[str, Any]]] = None, variables: Optional[List[Dict[str, Any]]] = None, ) -> Dict[str, Any]: """ Create a new Blueprint class. Args: class_name: Name for the new Blueprint class parent_class: Parent class name or path target_folder: Destination folder for the Blueprint components: Optional list of components to add variables: Optional list of variables to add Returns: Dictionary with creation result """ # Ensure target folder exists if not unreal.EditorAssetLibrary.does_directory_exist(target_folder): unreal.EditorAssetLibrary.make_directory(target_folder) # Construct the full asset path asset_path = f"{target_folder}/{class_name}" # Check if Blueprint already exists if unreal.EditorAssetLibrary.does_asset_exist(asset_path): raise ProcessingError( f"Blueprint already exists at {asset_path}", operation="create_blueprint", details={"asset_path": asset_path}, ) # Resolve parent class parent_class_obj = None if "/" in parent_class: # It's a path to another Blueprint parent_asset = unreal.EditorAssetLibrary.load_asset(parent_class) if parent_asset and isinstance(parent_asset, unreal.Blueprint): parent_class_obj = parent_asset.generated_class() else: raise ProcessingError( f"Parent Blueprint not found: {parent_class}", operation="create_blueprint", details={"parent": parent_class}, ) else: # It's a native class name parent_class_mapping = { "Actor": unreal.Actor, "Pawn": unreal.Pawn, "Character": unreal.Character, "GameMode": unreal.GameModeBase, "PlayerController": unreal.PlayerController, "ActorComponent": unreal.ActorComponent, "SceneComponent": unreal.SceneComponent, } parent_class_obj = parent_class_mapping.get(parent_class, unreal.Actor) # Create the Blueprint asset asset_tools = unreal.AssetToolsHelpers.get_asset_tools() blueprint_factory = unreal.BlueprintFactory() blueprint_factory.set_editor_property("parent_class", parent_class_obj) # Create the Blueprint blueprint = asset_tools.create_asset( asset_name=class_name, package_path=target_folder, asset_class=unreal.Blueprint, factory=blueprint_factory ) if not blueprint: raise ProcessingError( "Failed to create Blueprint asset", operation="create_blueprint", details={"asset_path": asset_path} ) # Note: Direct modification of Blueprint classes via Python is limited # Add components if specified if components: log_warning( "Component addition to Blueprints is not yet implemented " "due to Unreal Python API limitations. Components were not added." ) for comp_def in components: comp_name = comp_def.get("name") comp_type = comp_def.get("type") if comp_name and comp_type: # Note: This only logs the intended components # Actual addition requires Blueprint editor subsystem log_info( f"Component {comp_name} ({comp_type}) requested but " f"not added - requires manual addition in Blueprint editor" ) # Add variables if specified if variables: log_warning( "Variable addition to Blueprints is not yet implemented " "due to Unreal Python API limitations. Variables were not added." ) for var_def in variables: var_name = var_def.get("name") var_type = var_def.get("type") if var_name and var_type: # Note: This only logs the intended variables # Actual addition requires Blueprint editor subsystem log_info( f"Variable {var_name} ({var_type}) requested but " f"not added - requires manual addition in Blueprint editor" ) # Compile the Blueprint unreal.EditorAssetLibrary.save_asset(asset_path) log_info(f"Created Blueprint: {asset_path}") result = {"success": True, "blueprintPath": asset_path} # Include warnings about limitations if components: result["componentsNotAdded"] = [ f"{c.get('name')} ({c.get('type')})" for c in components if c.get("name") and c.get("type") ] result["componentWarning"] = ( "Components were not added due to UE Python API limitations. " "Please add them manually in the Blueprint editor." ) if variables: result["variablesNotAdded"] = [ f"{v.get('name')}: {v.get('type')}" for v in variables if v.get("name") and v.get("type") ] result["variableWarning"] = ( "Variables were not added due to UE Python API limitations. " "Please add them manually in the Blueprint editor." ) return result @validate_inputs({"blueprint_path": [RequiredRule(), AssetPathRule()]}) @handle_unreal_errors("get_blueprint_info") @safe_operation("blueprint") def get_info(blueprint_path: str) -> Dict[str, Any]: """ Get detailed information about a Blueprint. Args: blueprint_path: Path to the Blueprint asset Returns: Dictionary with Blueprint information """ # Load and validate the Blueprint bp_asset = require_asset(blueprint_path) if not isinstance(bp_asset, unreal.Blueprint): raise ProcessingError( f"Not a Blueprint asset: {blueprint_path}", operation="get_blueprint_info", details={"asset_path": blueprint_path}, ) # Get basic information info = { "success": True, "blueprintPath": blueprint_path, "className": bp_asset.get_name(), } # Get parent class information parent_class = bp_asset.get_editor_property("parent_class") if parent_class: info["parentClass"] = parent_class.get_name() # Note: Getting detailed component and variable information # requires more advanced Blueprint introspection which has # limitations in the Python API return info @validate_inputs( { "path": [RequiredRule(), TypeRule(str)], "filter": [TypeRule(str, allow_none=True)], "limit": [TypeRule(int, allow_none=True)], } ) @handle_unreal_errors("list_blueprints") @safe_operation("blueprint") def list_blueprints(path: str = "/Game", filter: Optional[str] = None, limit: Optional[int] = 50) -> Dict[str, Any]: """ List Blueprint assets with optional filtering. Args: path: Path to search for Blueprints filter: Optional name filter (case-insensitive) limit: Maximum number of results Returns: Dictionary with list of Blueprints """ # Get all assets in the specified path all_assets = unreal.EditorAssetLibrary.list_assets(path, recursive=True, include_folder=False) blueprints = [] for asset_path in all_assets: # Load asset to check if it's a Blueprint asset = unreal.EditorAssetLibrary.load_asset(asset_path) if not asset or not isinstance(asset, unreal.Blueprint): continue # Apply name filter if specified asset_name = asset.get_name() if filter and filter.lower() not in asset_name.lower(): continue # Get basic Blueprint information blueprint_info = { "name": asset_name, "path": asset_path, } # Get parent class if available parent_class = asset.get_editor_property("parent_class") if parent_class: blueprint_info["parentClass"] = parent_class.get_name() # Get modification time if available asset_data = unreal.EditorAssetLibrary.find_asset_data(asset_path) if asset_data: # Note: Getting exact modification time is complex in UE Python API blueprint_info["lastModified"] = "Available in editor" blueprints.append(blueprint_info) # Apply limit if limit and len(blueprints) >= limit: break log_info(f"Found {len(blueprints)} Blueprints in {path}") return {"success": True, "blueprints": blueprints} @validate_inputs({"blueprint_path": [RequiredRule(), AssetPathRule()]}) @handle_unreal_errors("compile_blueprint") @safe_operation("blueprint") def compile(blueprint_path: str) -> Dict[str, Any]: """ Compile a Blueprint and report compilation status. Args: blueprint_path: Path to the Blueprint asset Returns: Dictionary with compilation result """ # Load and validate the Blueprint blueprint = require_asset(blueprint_path) if not isinstance(blueprint, unreal.Blueprint): raise ProcessingError( f"Not a Blueprint asset: {blueprint_path}", operation="compile_blueprint", details={"asset_path": blueprint_path}, ) # Compile the Blueprint (fail-fast; decorators handle UE errors) # Note: Direct compilation via Python has limitations blueprint.mark_package_dirty() # Force compilation by accessing the generated class generated_class = blueprint.generated_class() # Check compilation status (best-effort) compilation_success = generated_class is not None result = {"success": True, "compilationSuccess": compilation_success, "errors": [], "warnings": []} if compilation_success: log_info(f"Blueprint compiled successfully: {blueprint_path}") else: log_error(f"Blueprint compilation failed: {blueprint_path}") result["errors"].append("Blueprint compilation failed - check Blueprint editor for detailed errors") return result @validate_inputs( { "blueprint_paths": [RequiredRule(), TypeRule(list)], "output_path": [TypeRule(str, allow_none=True)], "include_components": [TypeRule(bool, allow_none=True)], "include_variables": [TypeRule(bool, allow_none=True)], "include_functions": [TypeRule(bool, allow_none=True)], "include_events": [TypeRule(bool, allow_none=True)], "include_dependencies": [TypeRule(bool, allow_none=True)], } ) @handle_unreal_errors("document_blueprints") @safe_operation("blueprint") def document( blueprint_paths: List[str], output_path: Optional[str] = None, include_components: bool = True, include_variables: bool = True, include_functions: bool = True, include_events: bool = True, include_dependencies: bool = False, ) -> Dict[str, Any]: """ Generate comprehensive markdown documentation for Blueprints. Args: blueprint_paths: List of Blueprint paths to document output_path: Optional output file path for documentation include_components: Include component hierarchy include_variables: Include variable descriptions include_functions: Include function signatures include_events: Include custom events include_dependencies: Include Blueprint dependencies Returns: Dictionary with documentation result """ documentation_parts = [] documented_blueprints = [] # Generate documentation header documentation_parts.append("# Blueprint System Documentation\n") documentation_parts.append(f"Generated on: {unreal.DateTime.now()}\n") documentation_parts.append(f"Total Blueprints: {len(blueprint_paths)}\n\n") for blueprint_path in blueprint_paths: # Validate each path early to fail fast if not isinstance(blueprint_path, str) or not blueprint_path.startswith("/"): raise ValidationError( f"Invalid blueprint path: {blueprint_path}", operation="generate_blueprint_docs", details={"path": str(blueprint_path)}, ) # Load and validate Blueprint blueprint = require_asset(blueprint_path) if not isinstance(blueprint, unreal.Blueprint): raise ProcessingError( f"Not a Blueprint asset: {blueprint_path}", operation="generate_blueprint_docs", details={"asset_path": blueprint_path}, ) blueprint_name = blueprint.get_name() log_info(f"Documenting Blueprint: {blueprint_name}") # Start Blueprint documentation section documentation_parts.append(f"## {blueprint_name}\n\n") documentation_parts.append(f"**Path**: `{blueprint_path}`\n\n") # Get basic information parent_class = blueprint.get_editor_property("parent_class") if parent_class: documentation_parts.append(f"**Parent Class**: {parent_class.get_name()}\n\n") # Blueprint summary for tracking bp_summary = { "name": blueprint_name, "path": blueprint_path, "componentsCount": 0, "variablesCount": 0, "functionsCount": 0, "eventsCount": 0, } # Add sections based on options if include_components: documentation_parts.append("### Components\n\n") documentation_parts.append( "*Component information requires Blueprint editor access for detailed inspection.*\n\n" ) if include_variables: documentation_parts.append("### Variables\n\n") documentation_parts.append( "*Variable information requires Blueprint editor access for detailed inspection.*\n\n" ) if include_functions: documentation_parts.append("### Functions\n\n") documentation_parts.append( "*Function information requires Blueprint editor access for detailed inspection.*\n\n" ) if include_events: documentation_parts.append("### Custom Events\n\n") documentation_parts.append( "*Event information requires Blueprint editor access for detailed inspection.*\n\n" ) if include_dependencies: documentation_parts.append("### Dependencies\n\n") documentation_parts.append( "*Dependency analysis requires Blueprint editor access for detailed inspection.*\n\n" ) # Add Blueprint to documented list documented_blueprints.append(bp_summary) documentation_parts.append("---\n\n") # Combine documentation full_documentation = "".join(documentation_parts) # Save to file if output path specified if output_path: import os os.makedirs(os.path.dirname(output_path), exist_ok=True) with open(output_path, "w", encoding="utf-8") as f: f.write(full_documentation) log_info(f"Documentation saved to: {output_path}") log_info(f"Generated documentation for {len(documented_blueprints)} Blueprints") result = {"success": True, "documentedBlueprints": documented_blueprints, "documentation": full_documentation} if output_path: result["outputPath"] = output_path return result
# py automise script by Minomi ## run with python 2.7 in UE4 #######################################import modules from here################################# from pyclbr import Class import unreal import re from typing import List #######################################import modules end####################################### #######################################functions from here####################################### def get_selected_asset_dir() -> str : ar_asset_lists = unreal.EditorUtilityLibrary.get_selected_assets() if len(ar_asset_lists) > 0 : str_selected_asset = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(ar_asset_lists[0]) path = str_selected_asset.rsplit('/', 1)[0] else : path = '' return path def get_anim_list (__path: str) -> List[str] : seq_list = unreal.EditorAssetLibrary.list_assets(__path, False, False) return seq_list def check_animseq_by_name_in_list (__anim_name: str, __list: list ) -> str : need_to_return :str = '' if len(__list) > 0 : for each in __list : result = re.search(__anim_name, each) if result != None : need_to_return = each break return need_to_return else : return need_to_return #Re Module로 리팩토링함. ##애니메이션을 못찾으면 끼워넣지 않아요! def set_bs_sample (__animation, __axis_x: float, __axis_y: float) -> object : # returns [BlendSample] unreal native type bs_sample = unreal.BlendSample() vec_sample = unreal.Vector(__axis_x, __axis_y, 0.0) #do not use 3D BlendSampleVector bs_sample.set_editor_property('animation', __animation) bs_sample.set_editor_property('sample_value', vec_sample) bs_sample.set_editor_property('rate_scale', 1.0) bs_sample.set_editor_property('snap_to_grid', True) return bs_sample def set_blendSample_to_bs (__blendspace, __blendsample) -> int : #returns [BlendSpace] unreal loaded asset __blendspace.set_editor_property('sample_data', __blendsample) return 0 def set_blendParameter (__min: float , __max: float) -> object : bs_parameter = unreal.BlendParameter() bs_parameter.set_editor_property('display_name', 'none') bs_parameter.set_editor_property('grid_num', 4) bs_parameter.set_editor_property('min', __min) bs_parameter.set_editor_property('max', __max) return bs_parameter def set_square_blendSpace (__blendspace, __blendparameter) -> None : __blendspace.set_editor_property('blend_parameters', [__blendparameter,__blendparameter,__blendparameter]) #######################################functions end####################################### #######################################class from here###################################### class wrapedBlendSpaceSetting: main_dir: str = '' bs_dir: str = '/project/' #blend space relative path post_fix: str = '' #edit this if variation pre_fix: str = '' #edit this if variation custom_input: str = pre_fix + '/Animation' + post_fix bs_names: list = [ "IdleRun_BS_Peaceful", "IdleRun_BS_Battle", "Down_BS", "Groggy_BS", "Airborne_BS", "LockOn_BS" ] seq_names: list = [ '_Idle01', '_Walk_L', '_BattleIdle01', '_Run_L', '_KnockDown_L', '_Groggy_L', '_Airborne_L', '_Caution_Cw', '_Caution_Fw', '_Caution_Bw', '_Caution_Lw', '_Caution_Rw' ] #######################################class end####################################### #######################################run from here####################################### wraped :Class = wrapedBlendSpaceSetting() wraped.main_dir = get_selected_asset_dir() seek_anim_path = wraped.main_dir + wraped.custom_input bs_path = wraped.main_dir + wraped.bs_dir anim_list = get_anim_list(seek_anim_path) name_list :list = [] for each in wraped.seq_names : anim_name = check_animseq_by_name_in_list( ( wraped.pre_fix + each ) , anim_list) name_list.append(anim_name) print(anim_name) found_list: list = [] for each in name_list : loaded_seq = unreal.EditorAssetLibrary.load_asset(each) found_list.append(loaded_seq) bs_sample_for_idle_peace = [ set_bs_sample(found_list[0], 0.0, 0.0), set_bs_sample(found_list[1], 100.0, 0.0) ] bs_sample_for_idle_battle = [ set_bs_sample(found_list[2], 0.0, 0.0), set_bs_sample(found_list[3], 0.0, 0.0) ] bs_sample_for_down = [set_bs_sample(found_list[4], 0.0, 0.0)] bs_sample_for_groggy = [set_bs_sample(found_list[5], 0.0, 0.0)] bs_sample_for_airborne = [set_bs_sample(found_list[6], 0.0, 0.0)] bs_sample_for_lock_on = [ set_bs_sample(found_list[7], 0.0, 0.0), set_bs_sample(found_list[8], 0.0, 1.0), set_bs_sample(found_list[9], 0.0, -1.0), set_bs_sample(found_list[10], 1.0, 0.0), set_bs_sample(found_list[11], -1.0, 0.0) ] bs_param_idle = set_blendParameter(0.0, 100.0) bs_param_lock_on = set_blendParameter(-1.0, 1.0) bs_idle_peaceful = unreal.EditorAssetLibrary.load_asset ( bs_path + '/' + wraped.bs_names[0] ) bs_idle_battle = unreal.EditorAssetLibrary.load_asset ( bs_path + '/' + wraped.bs_names[1] ) bs_idle_down = unreal.EditorAssetLibrary.load_asset ( bs_path + '/' + wraped.bs_names[2] ) bs_idle_groggy = unreal.EditorAssetLibrary.load_asset ( bs_path + '/' + wraped.bs_names[3] ) bs_idle_airborne = unreal.EditorAssetLibrary.load_asset ( bs_path + '/' + wraped.bs_names[4] ) bs_idle_lockon = unreal.EditorAssetLibrary.load_asset ( bs_path + '/' + wraped.bs_names[5] ) set_square_blendSpace( bs_idle_peaceful, bs_param_idle) set_square_blendSpace( bs_idle_battle, bs_param_idle) set_square_blendSpace( bs_idle_down, bs_param_idle) set_square_blendSpace( bs_idle_groggy, bs_param_idle) set_square_blendSpace( bs_idle_airborne, bs_param_idle) set_square_blendSpace( bs_idle_lockon, bs_param_lock_on) set_blendSample_to_bs( bs_idle_peaceful, bs_sample_for_idle_peace) set_blendSample_to_bs( bs_idle_battle, bs_sample_for_idle_battle) set_blendSample_to_bs( bs_idle_down, bs_sample_for_down) set_blendSample_to_bs( bs_idle_groggy, bs_sample_for_groggy) set_blendSample_to_bs( bs_idle_airborne, bs_sample_for_airborne) set_blendSample_to_bs( bs_idle_lockon, bs_sample_for_lock_on) #######################################run end here####################################### ## save execution from here ## unreal.EditorAssetLibrary.save_directory(bs_path, True, True) ## save execution End here ##
import unreal def get_selected_asset_dir() : ar_asset_lists = unreal.EditorUtilityLibrary.get_selected_assets() if len(ar_asset_lists) > 0 : str_selected_asset = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(ar_asset_lists[0]) path = str_selected_asset.rsplit('/', 1)[0] + '/' return path
import unreal """ Script adds prefixes to the selected assets """ def remove_prefix(asset: unreal.Object, prefixes): name = asset.get_name() separated = str(name).split('_') i = 0 if len(separated) == 1: return '_'.join(i for i in separated) while i < len(separated): if len(separated[i]) > 2 and str(separated[i] + '_') not in prefixes: break else: separated.pop(i) return '_'.join(i for i in separated) def generate_new_asset_name(asset: unreal.Object): prefixes = { unreal.MaterialInstance : "MI_", unreal.EditorUtilityWidgetBlueprint : "EUW_", unreal.Material : "M_", unreal.Texture : "T_", unreal.Blueprint : "BP_", unreal.StaticMesh : "SM_", unreal.MaterialFunction : "MF_", unreal.SkeletalMesh : "SK_", unreal.Skeleton : "SKEL_", unreal.AnimSequence : "A_", unreal.LevelSequence : "LS_", unreal.BlendSpace : "BS_", unreal.BlendSpace1D : "BS_", unreal.MorphTarget : "MT_", unreal.PhysicsAsset : "PHYS_", unreal.NiagaraSystem : "NS_", unreal.NiagaraEmitter : "NE_" } for i in prefixes: if isinstance(asset, i): prefix = prefixes[i] prefixlist = [prefixes[b] for b in prefixes] return prefix + remove_prefix(asset, prefixlist) return asset.get_name() def change_selected_assets_names(): selected_assets = unreal.EditorUtilityLibrary().get_selected_assets() for i in range(len(selected_assets)): asset: unreal.Object = selected_assets[i] old_name = asset.get_name() new_name = generate_new_asset_name(asset) if old_name == new_name: print(new_name + " does not changed") continue old_path = asset.get_path_name() asset_folder = unreal.Paths.get_path(old_path) new_path = asset_folder + "/" + new_name print(f"{old_name} -> {new_name}") rename_success = unreal.EditorAssetLibrary.rename_asset(old_path, new_path) if not rename_success: unreal.log_error("Could not rename" + old_path) def main(): change_selected_assets_names() if __name__ == "__main__": main()
import unreal def get_bone_transforms(skinned_mesh_component: unreal.SkinnedMeshComponent) -> dict: bone_transforms = {} for bone_index in range(skinned_mesh_component.get_num_bones()): bone_name = skinned_mesh_component.get_bone_name(bone_index) skeleton = skinned_mesh_component.skeletal_mesh.skeleton if not skeleton: continue anim_pose = skeleton.get_reference_pose() for bone_name in anim_pose.get_bone_names(): transform = anim_pose.get_bone_pose(bone_name, space=unreal.AnimPoseSpaces.WORLD) transform.translation bone_transforms[str(bone_name)] = { 'location': transform.translation.to_tuple(), 'rotation': transform.rotation.to_tuple(), 'scale': transform.scale3d.to_tuple() } return bone_transforms
import unreal import os import glob # Import additional ies files assets to tests other file types. asset_path_to_change = os.path.join('C:/temp/','IES_Types') # Listing all .ies files in folder # Folder where files are located files = glob.glob(asset_path_to_change+os.sep+'*.ies') # Create folder in UE light_directory_name = '/project/' assetSubsystem = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem) destination_path = assetSubsystem.make_directory(light_directory_name) # Import all files for f in files: uetask = unreal.AssetImportTask() uetask.filename = f uetask.destination_path = light_directory_name uetask.replace_existing = True uetask.automated = False uetask.save = False task = [uetask] unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks(task)
import unreal import re ar_asset_lists = [] ar_asset_lists = unreal.EditorUtilityLibrary.get_selected_assets() print (ar_asset_lists[0]) str_selected_asset = '' if len(ar_asset_lists) > 0 : str_selected_asset = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(ar_asset_lists[0]) #str_selected_asset = str(ar_asset_lists[0]) print(str_selected_asset) ar_numbers = re.findall("\d+", str_selected_asset) i_number = ar_numbers[0] print(ar_numbers) print(i_number)
import unreal reg_helper = unreal.AssetRegistryHelpers() asset_reg = reg_helper.get_asset_registry() asset_tool = unreal.AssetToolsHelpers.get_asset_tools() packages_to_check = unreal.load_package('/project/.Skel_Arlong01_L_rig') origin = unreal.SoftObjectPath('/project/.Skel_Arlong01_L_rig_Skeleton') target = unreal.SoftObjectPath('/project/.Skel_Arlong01_L_rig_Skeleton') asset_tool.rename_referencing_soft_object_paths([packages_to_check],{ origin:target }) path = "/project/" assets = asset_reg.get_assets_by_path(path,True) ar_filter = unreal.ARFilter(package_paths=["/project/"]) assets = asset_reg.use_filter_to_exclude_assets(assets,ar_filter) print(assets) asset = unreal.load_asset('/project/.Boodle01') data = reg_helper.create_asset_data(asset) assets = asset_reg.get_assets_by_package_name(data.package_name,True) assets = asset_reg.get_assets_by_package_name('/project/') print(assets) ar_filter = unreal.ARFilter(package_paths=['/project/']) assets = asset_reg.get_assets(ar_filter) print(assets)
import unreal from ueGear.controlrig.paths import CONTROL_RIG_FUNCTION_PATH from ueGear.controlrig.components import base_component, EPIC_control_01 from ueGear.controlrig.helpers import controls class Component(base_component.UEComponent): name = "chain" mgear_component = "EPIC_chain_01" def __init__(self): super().__init__() self.functions = {'construction_functions': ['construct_chain'], 'forward_functions': ['forward_chain'], 'backwards_functions': ['backwards_chain'], } self.cr_variables = {} # Control Rig Inputs self.cr_inputs = {'construction_functions': ['parent'], 'forward_functions': [], 'backwards_functions': [], } # Control Rig Outputs self.cr_output = {'construction_functions': ['root'], 'forward_functions': [], 'backwards_functions': [], } # mGear self.inputs = [] self.outputs = [] def create_functions(self, controller: unreal.RigVMController = None): if controller is None: return # calls the super method super().create_functions(controller) # Generate Function Nodes for evaluation_path in self.functions.keys(): # Skip the forward function creation if no joints are needed to be driven if evaluation_path == 'forward_functions' and self.metadata.joints is None: continue for cr_func in self.functions[evaluation_path]: new_node_name = f"{self.name}_{cr_func}" ue_cr_node = controller.get_graph().find_node_by_name(new_node_name) # Create Component if doesn't exist if ue_cr_node is None: ue_cr_ref_node = controller.add_external_function_reference_node(CONTROL_RIG_FUNCTION_PATH, cr_func, unreal.Vector2D(0.0, 0.0), node_name=new_node_name) # In Unreal, Ref Node inherits from Node ue_cr_node = ue_cr_ref_node else: # if exists, add it to the nodes self.nodes[evaluation_path].append(ue_cr_node) unreal.log_error(f" Cannot create function {new_node_name}, it already exists") continue self.nodes[evaluation_path].append(ue_cr_node) # Gets the Construction Function Node and sets the control name func_name = self.functions['construction_functions'][0] construct_func = base_component.get_construction_node(self, f"{self.name}_{func_name}") if construct_func is None: unreal.log_error(" Create Functions Error - Cannot find construct singleton node") def populate_bones(self, bones: list[unreal.RigBoneElement] = None, controller: unreal.RigVMController = None): """ populates the bone shoulder joint node """ if bones is None or len(bones) < 3: unreal.log_error(f"[Bone Populate] Failed no Bones found: Found {len(bones)} bones") return if controller is None: unreal.log_error("[Bone Populate] Failed no Controller found") return for bone in bones: bone_name = bone.key.name # Unique name for this skeleton node array array_node_name = f"{self.metadata.fullname}_RigUnit_ItemArray" # node doesn't exists, create the joint node if not controller.get_graph().find_node_by_name(array_node_name): self._init_master_joint_node(controller, array_node_name, bones) node = controller.get_graph().find_node_by_name(array_node_name) self.add_misc_function(node) def init_input_data(self, controller: unreal.RigVMController): self._connect_bones(controller) def _connect_bones(self, controller: unreal.RigVMController): """Connects the bone array list to the construction node""" bone_node_name = f"{self.metadata.fullname}_RigUnit_ItemArray" construction_node_name = self.nodes["construction_functions"][0].get_name() forward_node_name = self.nodes["forward_functions"][0].get_name() backwards_node_name = self.nodes["backwards_functions"][0].get_name() controller.add_link(f'{bone_node_name}.Items', f'{construction_node_name}.fk_bones') controller.add_link(f'{bone_node_name}.Items', f'{forward_node_name}.Array') controller.add_link(f'{bone_node_name}.Items', f'{backwards_node_name}.chain_joints') def populate_control_names(self, controller: unreal.RigVMController): # Connecting nodes needs to occur first, else the array node does not know the type and will not accept default # values construction_func_name = self.nodes["construction_functions"][0].get_name() default_values = "" for control_name in self.metadata.controls: default_values += f"{control_name}," # trims off the extr ',' default_values = default_values[:-1] # Populates and resizes the pin in one go controller.set_pin_default_value(f'{construction_func_name}.control_names', f"({default_values})", True, setup_undo_redo=True, merge_undo_action=True) # TODO: setup an init_controls method and move this method and the populate controls method into it def populate_control_transforms(self, controller: unreal.RigVMController = None): """Updates the transform data for the controls generated, with the data from the mgear json file. """ construction_func_name = self.nodes["construction_functions"][0].get_name() default_values = "" for i, control_name in enumerate(self.metadata.controls): control_transform = self.metadata.control_transforms[control_name] quat = control_transform.rotation pos = control_transform.translation string_entry = (f"(Rotation=(X={quat.x},Y={quat.y},Z={quat.z},W={quat.w}), " f"Translation=(X={pos.x},Y={pos.y},Z={pos.z}), " f"Scale3D=(X=1.000000,Y=1.000000,Z=1.000000)),") default_values += string_entry # trims off the extr ',' default_values = default_values[:-1] # Populates and resizes the pin in one go controller.set_pin_default_value( f"{construction_func_name}.control_transforms", f"({default_values})", True, setup_undo_redo=True, merge_undo_action=True) self.populate_control_names(controller) self.populate_control_scale(controller) self.populate_control_shape_offset(controller) self.populate_control_colour(controller) def populate_control_shape_offset(self, controller: unreal.RigVMController): """ As some controls have there pivot at the same position as the transform, but the control is actually moved away from that pivot point. We use the bounding box position as an offset for the control shape. """ construction_func_name = self.nodes["construction_functions"][0].get_name() default_values = "" for i, control_name in enumerate(self.metadata.controls): aabb = self.metadata.controls_aabb[control_name] bb_center = aabb[0] string_entry = f'(X={bb_center[0]}, Y={bb_center[1]}, Z={bb_center[2]}),' default_values += string_entry # trims off the extr ',' default_values = default_values[:-1] controller.set_pin_default_value( f'{construction_func_name}.control_offsets', f'({default_values})', True, setup_undo_redo=True, merge_undo_action=True) def populate_control_scale(self, controller: unreal.RigVMController): """ Generates a scale value per a control """ construction_func_name = self.nodes["construction_functions"][0].get_name() reduce_ratio = 4.0 """Magic number to try and get the maya control scale to be similar to that of unreal. As the mGear uses a square and ueGear uses a cirlce. """ default_values = "" # Calculates the unreal scale for the control and populates it into the array node. for i, control_name in enumerate(self.metadata.controls): aabb = self.metadata.controls_aabb[control_name] unreal_size = [round(element/reduce_ratio, 4) for element in aabb[1]] # todo: this is a test implementation, for a more robust validation, each axis should be checked. # rudementary way to check if the bounding box might be flat, if it is then # the first value if applied onto the axis if unreal_size[0] == unreal_size[1] and unreal_size[2] < 0.2: unreal_size[2] = unreal_size[0] elif unreal_size[1] == unreal_size[2] and unreal_size[0] < 0.2: unreal_size[0] = unreal_size[1] elif unreal_size[0] == unreal_size[2] and unreal_size[1] < 0.2: unreal_size[1] = unreal_size[0] default_values += f'(X={unreal_size[0]},Y={unreal_size[1]},Z={unreal_size[2]}),' # trims off the extr ',' default_values = default_values[:-1] # Populates and resizes the pin in one go controller.set_pin_default_value( f'{construction_func_name}.control_scale', f'({default_values})', True, setup_undo_redo=True, merge_undo_action=True) def populate_control_colour(self, controller: unreal.RigVMController): cr_func = self.functions["construction_functions"][0] construction_node = f"{self.name}_{cr_func}" default_values = "" for i, control_name in enumerate(self.metadata.controls): colour = self.metadata.controls_colour[control_name] string_entry = f"(R={colour[0]}, G={colour[1]}, B={colour[2]}, A=1.0)," default_values += string_entry # trims off the extr ',' default_values = default_values[:-1] # Populates and resizes the pin in one go controller.set_pin_default_value( f'{construction_node}.control_colours', f"({default_values})", True, setup_undo_redo=True, merge_undo_action=True) class ManualComponent(Component): name = "EPIC_chain_01" def __init__(self): super().__init__() self.functions = {'construction_functions': ['manual_construct_chain'], 'forward_functions': ['forward_chain'], 'backwards_functions': ['backwards_chain'] } self.is_manual = True # These are the roles that will be parented directly under the parent component. self.root_control_children = ["fk0"] self.hierarchy_schematic_roles = {} # Default to fall back onto self.default_shape = "Box_Thick" self.control_shape = {} def create_functions(self, controller: unreal.RigVMController): EPIC_control_01.ManualComponent.create_functions(self, controller) self.setup_dynamic_hierarchy_roles(fk_count=len(self.metadata.controls)) def setup_dynamic_hierarchy_roles(self, fk_count, end_control_role=None): """Manual controls have some dynamic control creation. This function sets up the control relationship for the dynamic control hierarchy.""" # Calculate the amount of fk's based on the division amount for i in range(fk_count): parent_role = f"fk{i}" child_index = i+1 child_role = f"fk{child_index}" # end of the fk chain, parent the end control if one specified if child_index >= fk_count: if end_control_role: self.hierarchy_schematic_roles[parent_role] = [end_control_role] continue self.hierarchy_schematic_roles[parent_role] = [child_role] def initialize_hierarchy(self, hierarchy_controller: unreal.RigHierarchyController): """Performs the hierarchical restructuring of the internal components controls""" # Parent control hierarchy using roles for parent_role in self.hierarchy_schematic_roles.keys(): child_roles = self.hierarchy_schematic_roles[parent_role] parent_ctrl = self.control_by_role[parent_role] for child_role in child_roles: child_ctrl = self.control_by_role[child_role] hierarchy_controller.set_parent(child_ctrl.rig_key, parent_ctrl.rig_key) def generate_manual_controls(self, hierarchy_controller: unreal.RigHierarchyController): """Creates all the manual controls for the Spine""" # Stores the controls by Name control_table = dict() for control_name in self.metadata.controls: new_control = controls.CR_Control(name=control_name) role = self.metadata.controls_role[control_name] # stored metadata values control_transform = self.metadata.control_transforms[control_name] control_colour = self.metadata.controls_colour[control_name] control_aabb = self.metadata.controls_aabb[control_name] control_offset = control_aabb[0] control_scale = [control_aabb[1][0] / 4.0, control_aabb[1][1] / 4.0, control_aabb[1][2] / 4.0] # Set the colour, required before build new_control.colour = control_colour if role not in self.control_shape.keys(): new_control.shape_name = self.default_shape else: new_control.shape_name = self.control_shape[role] # Generate the Control new_control.build(hierarchy_controller) # Sets the controls position, and offset translation and scale of the shape new_control.set_transform(quat_transform=control_transform) new_control.shape_transform_global(pos=control_offset, scale=control_scale, rotation=[90, 0, 0]) control_table[control_name] = new_control # Stores the control by role, for loopup purposes later self.control_by_role[role] = new_control self.initialize_hierarchy(hierarchy_controller) def populate_control_transforms(self, controller: unreal.RigVMController = None): construction_func_name = self.nodes["construction_functions"][0].get_name() controls = [] for role_key in self.control_by_role.keys(): control = self.control_by_role[role_key] controls.append(control) def update_input_plug(plug_name, control_list): """ Simple helper function making the plug population reusable for ik and fk """ control_metadata = [] for entry in control_list: if entry.rig_key.type == unreal.RigElementType.CONTROL: t = "Control" if entry.rig_key.type == unreal.RigElementType.NULL: t = "Null" n = entry.rig_key.name entry = f'(Type={t}, Name="{n}")' control_metadata.append(entry) concatinated_controls = ",".join(control_metadata) controller.set_pin_default_value( f'{construction_func_name}.{plug_name}', f"({concatinated_controls})", True, setup_undo_redo=True, merge_undo_action=True) update_input_plug("controls", controls)
from typing import List import unreal def list_assets() -> List[str]: assets = unreal.EditorAssetLibrary.list_assets("/Game", recursive=True) return assets def main(): assets = list_assets() print(assets) if __name__ == "__main__": main()