text
stringlengths 15
267k
|
|---|
import unreal
import json
from typing import Dict, Any, List, Tuple, Union
from utils import unreal_conversions as uc
from utils import logging as log
def handle_modify_object(command: Dict[str, Any]) -> Dict[str, Any]:
"""
Handle a modify_object command
Args:
command: The command dictionary containing:
- actor_name: Name of the actor to modify
- property_type: Type of property to modify (material, position, rotation, scale)
- value: Value to set for the property
Returns:
Response dictionary with success/failure status
"""
try:
# Extract parameters
actor_name = command.get("actor_name")
property_type = command.get("property_type")
value = command.get("value")
if not actor_name or not property_type or value is None:
log.log_error("Missing required parameters for modify_object")
return {"success": False, "error": "Missing required parameters"}
log.log_command("modify_object", f"Actor: {actor_name}, Property: {property_type}")
# Use the C++ utility class
gen_actor_utils = unreal.GenActorUtils
# Handle different property types
if property_type == "material":
# Set the material
material_path = value
success = gen_actor_utils.set_actor_material_by_path(actor_name, material_path)
if success:
log.log_result("modify_object", True, f"Material of {actor_name} set to {material_path}")
return {"success": True}
log.log_error(f"Failed to set material for {actor_name}")
return {"success": False, "error": f"Failed to set material for {actor_name}"}
elif property_type == "position":
# Set position
try:
vec = uc.to_unreal_vector(value)
success = gen_actor_utils.set_actor_position(actor_name, vec)
if success:
log.log_result("modify_object", True, f"Position of {actor_name} set to {vec}")
return {"success": True}
log.log_error(f"Failed to set position for {actor_name}")
return {"success": False, "error": f"Failed to set position for {actor_name}"}
except ValueError as e:
log.log_error(str(e))
return {"success": False, "error": str(e)}
elif property_type == "rotation":
# Set rotation
try:
rot = uc.to_unreal_rotator(value)
success = gen_actor_utils.set_actor_rotation(actor_name, rot)
if success:
log.log_result("modify_object", True, f"Rotation of {actor_name} set to {rot}")
return {"success": True}
log.log_error(f"Failed to set rotation for {actor_name}")
return {"success": False, "error": f"Failed to set rotation for {actor_name}"}
except ValueError as e:
log.log_error(str(e))
return {"success": False, "error": str(e)}
elif property_type == "scale":
# Set scale
try:
scale = uc.to_unreal_vector(value)
success = gen_actor_utils.set_actor_scale(actor_name, scale)
if success:
log.log_result("modify_object", True, f"Scale of {actor_name} set to {scale}")
return {"success": True}
log.log_error(f"Failed to set scale for {actor_name}")
return {"success": False, "error": f"Failed to set scale for {actor_name}"}
except ValueError as e:
log.log_error(str(e))
return {"success": False, "error": str(e)}
else:
log.log_error(f"Unknown property type: {property_type}")
return {"success": False, "error": f"Unknown property type: {property_type}"}
except Exception as e:
log.log_error(f"Error modifying object: {str(e)}", include_traceback=True)
return {"success": False, "error": str(e)}
def handle_edit_component_property(command: Dict[str, Any]) -> Dict[str, Any]:
"""
Handle a command to edit a component property in a Blueprint or scene actor.
Args:
command: The command dictionary containing:
- blueprint_path: Path to the Blueprint
- component_name: Name of the component
- property_name: Name of the property to edit
- value: New value as a string
- is_scene_actor: Boolean flag for scene actor (optional, default False)
- actor_name: Name of the scene actor (required if is_scene_actor is True)
Returns:
Dictionary with success/failure status, message, and optional suggestions
"""
try:
blueprint_path = command.get("blueprint_path", "")
component_name = command.get("component_name")
property_name = command.get("property_name")
value = command.get("value")
is_scene_actor = command.get("is_scene_actor", False)
actor_name = command.get("actor_name", "")
if not component_name or not property_name or value is None:
log.log_error("Missing required parameters for edit_component_property")
return {"success": False, "error": "Missing required parameters"}
if is_scene_actor and not actor_name:
log.log_error("Actor name required for scene actor editing")
return {"success": False, "error": "Actor name required for scene actor"}
# Log detailed information about what we're trying to do
log_msg = f"Blueprint: {blueprint_path}, Component: {component_name}, Property: {property_name}, Value: {value}"
if is_scene_actor:
log_msg += f", Actor: {actor_name}"
log.log_command("edit_component_property", log_msg)
# Call the C++ implementation
node_creator = unreal.GenObjectProperties
result = node_creator.edit_component_property(blueprint_path, component_name, property_name, value, is_scene_actor, actor_name)
# Parse the result - CHANGED: Convert JSON string to dict
try:
parsed_result = json.loads(result)
log.log_result("edit_component_property", parsed_result["success"],
parsed_result.get("message", parsed_result.get("error", "No message")))
# CHANGED: Return the parsed dict instead of the original JSON string
return parsed_result
except json.JSONDecodeError:
# If the result is not valid JSON, wrap it in a JSON object
log.log_warning(f"Invalid JSON result from C++: {result}")
return {"success": False, "error": f"Invalid response format: {result}"}
except Exception as e:
log.log_error(f"Error editing component property: {str(e)}", include_traceback=True)
return {"success": False, "error": str(e)}
def handle_add_component_with_events(command: Dict[str, Any]) -> Dict[str, Any]:
"""
Handle a command to add a component to a Blueprint with overlap events if applicable.
Args:
command: The command dictionary containing:
- blueprint_path: Path to the Blueprint
- component_name: Name of the new component
- component_class: Class of the component (e.g., "BoxComponent")
Returns:
Response dictionary with success/failure status, message, and event GUIDs
"""
try:
blueprint_path = command.get("blueprint_path")
component_name = command.get("component_name")
component_class = command.get("component_class")
if not blueprint_path or not component_name or not component_class:
log.log_error("Missing required parameters for add_component_with_events")
return {"success": False, "error": "Missing required parameters"}
log.log_command("add_component_with_events", f"Blueprint: {blueprint_path}, Component: {component_name}, Class: {component_class}")
node_creator = unreal.GenBlueprintUtils
result = node_creator.add_component_with_events(blueprint_path, component_name, component_class)
import json
parsed_result = json.loads(result)
log.log_result("add_component_with_events", parsed_result["success"], parsed_result.get("message", parsed_result.get("error", "No message")))
return parsed_result
except Exception as e:
log.log_error(f"Error adding component with events: {str(e)}", include_traceback=True)
return {"success": False, "error": str(e)}
def handle_create_game_mode(command: Dict[str, Any]) -> Dict[str, Any]:
try:
game_mode_path = command.get("game_mode_path")
pawn_blueprint_path = command.get("pawn_blueprint_path")
base_class = command.get("base_class", "GameModeBase")
if not game_mode_path or not pawn_blueprint_path:
return {"success": False, "error": "Missing game_mode_path or pawn_blueprint_path"}
node_creator = unreal.GenActorUtils
result = node_creator.create_game_mode_with_pawn(game_mode_path, pawn_blueprint_path, base_class)
return json.loads(result)
except Exception as e:
return {"success": False, "error": str(e)}
|
import unreal
def get_da_list(da:unreal.PrimaryDataAsset, property_name:str) -> list[unreal.Object]:
return unreal.PrimaryDataAsset.get_editor_property(da, property_name)
def get_da_item(da:unreal.PrimaryDataAsset, property_name:str) -> unreal.SkeletalMesh:
return unreal.PrimaryDataAsset.get_editor_property(da, property_name)
def set_da_list(blueprint_asset, property_name:str ,sm_materials):
key_name = property_name
property_info = {key_name: sm_materials}
blueprint_asset.set_editor_properties(property_info)
return blueprint_asset.set_editor_properties(property_info)
def get_sm_materials(selected_sm:unreal.SkeletalMesh) -> list[unreal.MaterialInstanceConstant]:
sm_materials = []
for material in selected_sm.materials:
mic:unreal.MaterialInstanceConstant = material.material_interface
sm_materials.append(mic)
return sm_materials
selected_data_asset: list[unreal.Object] = unreal.EditorUtilityLibrary.get_selected_assets()[0]
loaded_subsystem = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem)
if selected_data_asset.__class__ != unreal.PrimaryDataAsset:
print('Please select a data asset')
exit()
#set variables
da_path = selected_data_asset.get_path_name()
da_materials = get_da_list(selected_data_asset, "Materials")
da_outlines = get_da_list(selected_data_asset, "OutlineMaterials")
da_sm = get_da_item(selected_data_asset, "SkeletalMesh")
da_base_outline = get_da_item(selected_data_asset, "BasicOutlineMaterial")
da_clear = get_da_item(selected_data_asset, "ClearMaterial")
da_cha_name = str(get_da_item(selected_data_asset, "CharacterName"))
da_ca = get_da_item(selected_data_asset, "ChaosCloth")
#####################
#####################
ca_mats = da_ca.get_editor_property('Materials')
new_outlines = []
for mi in ca_mats:
new_outlines.append(da_base_outline)
set_da_list(selected_data_asset, "ChaosOutlines", new_outlines)
loaded_subsystem.save_asset(da_path)
|
# Copyright Epic Games, Inc. All Rights Reserved.
import unreal
import os
import sys
# Display source control state of specified file and return state object
def _sc_test_state(file_str):
unreal.log("Getting source control state fo/project/ {0}".format(file_str))
state = unreal.SourceControl.query_file_state(file_str)
# Is state valid?
if state.is_valid:
unreal.log("is_unknown: {0}".format(state.is_unknown))
unreal.log("is_source_controlled: {0}".format(state.is_source_controlled))
unreal.log("can_check_out: {0}".format(state.can_check_out))
unreal.log("is_checked_out: {0}".format(state.is_checked_out))
unreal.log("can_check_in: {0}".format(state.can_check_in))
unreal.log("is_checked_out_other: {0}".format(state.is_checked_out_other))
unreal.log("checked_out_other: {0}".format(state.checked_out_other))
unreal.log("is_current: {0}".format(state.is_current))
unreal.log("can_add: {0}".format(state.can_add))
unreal.log("is_added: {0}".format(state.is_added))
unreal.log("can_delete: {0}".format(state.can_delete))
unreal.log("is_deleted: {0}".format(state.is_deleted))
unreal.log("is_ignored: {0}".format(state.is_ignored))
unreal.log("can_edit: {0}".format(state.can_edit))
unreal.log("is_conflicted: {0}".format(state.is_conflicted))
unreal.log("can_revert: {0}".format(state.can_revert))
unreal.log("is_modified: {0}".format(state.is_modified))
else:
unreal.log("- state is invalid!")
return state
# Get the resolved file path from the specified file string
def _sc_get_file_from_state(file_str):
state = unreal.SourceControl.query_file_state(file_str)
unreal.log("File string: {0}".format(file_str))
# Is state valid?
if state.is_valid:
unreal.log("- converted path: {0}".format(state.filename))
return state.filename
else:
unreal.log("- state is invalid!")
return ""
# Test of resolving file string to fully qualified file path for use with
# source control.
def _sc_test_file_strings():
unreal.log("\nTesting source control file strings.")
# File strings used in source control commands can be:
# - export text path (often stored on clipboard)
file1 = _sc_get_file_from_state(r"Texture2D'/project/.S_Actor'")
# - asset
file2 = _sc_get_file_from_state(r"/project/.S_Actor")
# - long package name
file3 = _sc_get_file_from_state(r"/project/")
# - relative path
file4 = _sc_get_file_from_state(r"Content/project/.uasset")
# - fully qualified path (just use result of relative path)
file5 = _sc_get_file_from_state(file4)
# All the resolved file paths should be the same
same_paths = file1 == file2 == file3 == file4 == file5
unreal.log("The resolved file paths are all the same: {0}".format(same_paths))
# This tests a sampling of source control commands.
#
# Also has optional arguments:
# arg1 - source controlled file that is not yet checked out.
# arg2 - source controlled file that is checked out and modified
# arg3 - source controlled file that is checked out by another user
#
# Example:
# test_source_control.py Source\Developer\SourceControl\Private\SourceControlModule.cpp Source\Developer\SourceControl\Private\SourceControlHelpers.cpp Plugins\Experimental\PythonScriptPlugin\Source\PythonScriptPlugin\Private\PythonScriptPlugin.cpp
def main():
unreal.log("Source control tests started!")
if not unreal.SourceControl.is_enabled():
unreal.log("Source control is not currently enabled, please run this test in an environment where source control is enabled.")
return
#---------------------------------------
# Set file defaults - overriding with any supplied arguments
arg_num = len(sys.argv)
if arg_num == 1:
unreal.log(("Supply arguments for custom files to tes/project/"
" arg1 - source controlled file that is not yet checked out\n"
" arg2 - source controlled file that is checked out and modified\n"
" arg3 - source controlled file that is checked out by another user"))
# Source controlled file that is not yet checked out
file_in_sc = r"Source\Developer\SourceControl\Private\SourceControlSettings.cpp"
if arg_num > 1:
file_in_sc = sys.argv[1]
# Source controlled file that is checked out and modified
file_modified = ""
if arg_num > 2:
file_modified = sys.argv[2]
# Source controlled file that is checked out by another user
file_other = ""
if arg_num > 3:
file_other = sys.argv[3]
#---------------------------------------
unreal.log("\nDisplaying source control script commands")
help(unreal.SourceControl)
unreal.log("\nDisplaying source control file state members")
help(unreal.SourceControlState)
#---------------------------------------
# Source control tests
_sc_test_file_strings()
# Outside of source controlled directories
unreal.log("\nTesting state of file not in source control: \\NoSuchFile.txt")
state = _sc_test_state(r"\NoSuchFile.txt")
if state.is_source_controlled:
unreal.log_error("Expected '\\NoSuchFile.txt' to not be source controlled.")
# Test checking out, deleting, adding and reverting
if len(file_in_sc):
#---------------------------------------
unreal.log("\nTesting state of file during check out and revert: {0}".format(file_in_sc))
# Test pre check out
state = _sc_test_state(file_in_sc)
if not state.can_check_out:
unreal.log_error("Expected '{0}' to be able checked out.".format(file_in_sc))
# Test check out
unreal.SourceControl.check_out_or_add_file(file_in_sc)
state = _sc_test_state(file_in_sc)
if not state.is_checked_out:
unreal.log_error("Expected '{0}' to be checked out.".format(file_in_sc))
# Test revert
unreal.SourceControl.revert_file(file_in_sc)
state = _sc_test_state(file_in_sc)
if state.is_checked_out:
unreal.log_error("Expected '{0}' to not be checked out.".format(file_in_sc))
#---------------------------------------
unreal.log("\nTesting file mark for delete and revert: {0}".format(file_in_sc))
# Test pre delete
if not state.can_delete:
unreal.log_error("Expected '{0}' to be able to delete.".format(file_in_sc))
# Test delete
unreal.SourceControl.mark_file_for_delete(file_in_sc)
state = _sc_test_state(file_in_sc)
if not state.is_deleted:
unreal.log_error("Expected '{0}' to be marked for delete.".format(file_in_sc))
# Test revert
unreal.SourceControl.revert_file(file_in_sc)
state = _sc_test_state(file_in_sc)
if state.is_deleted:
unreal.log_error("Expected '{0}' to not be marked for delete.".format(file_in_sc))
#---------------------------------------
# File to mark for add and revert
# Make a file to add based on the resolved file_in_sc name stored in
# state so it uses a directory that is source controlled.
file_add = os.path.join(os.path.dirname(state.filename), "AddTest.txt")
unreal.log("\nTesting file mark for add and revert: {0}".format(file_add))
open(file_add, "w+")
# Test pre add
state = _sc_test_state(file_add)
if not state.can_add:
unreal.log_error("Expected '{0}' to be able to add.".format(file_add))
# Test add
unreal.SourceControl.mark_file_for_add(file_add)
state = _sc_test_state(file_add)
if not state.is_added:
unreal.log_error("Expected '{0}' to be added.".format(file_add))
if not state.is_source_controlled:
unreal.log_error("Expected '{0}' to be under source control.".format(file_add))
# Make sure that we aren't deleting the file on revert, as this matches the behavior of most providers.
# Currently only perforce provider enforces delete on revert, so it would be inconsistent to test this option at true for all providers
source_control_preferences = unreal.get_default_object(unreal.find_object(None, "/project/.SourceControlPreferences"))
should_delete_files_on_revert_orig_value = source_control_preferences.get_editor_property("bShouldDeleteNewFilesOnRevert")
source_control_preferences.set_editor_property("bShouldDeleteNewFilesOnRevert", False)
# Test revert
unreal.SourceControl.revert_file(file_add)
state = _sc_test_state(file_add)
if state.is_source_controlled:
unreal.log_error("Expected '{0}' to not be under source control.".format(file_add))
# Remove test add file
os.remove(file_add)
#restore original value to the config setting for delete on revert
source_control_preferences.set_editor_property("bShouldDeleteNewFilesOnRevert", should_delete_files_on_revert_orig_value)
#---------------------------------------
# Modified and checked out
if len(file_modified):
unreal.log("\nTesting file modified state: {0}".format(file_in_sc))
state = _sc_test_state(file_modified)
if not state.is_modified:
unreal.log_error("Expected {0} to be modified compared to checked in version and it is not.".format(file_modified))
#---------------------------------------
# Checked out by another
if len(file_other):
unreal.log("\nTesting file checked out by another user: {0}".format(file_in_sc))
state = _sc_test_state(file_other)
if not state.is_checked_out_other:
unreal.log_error("Expected {0} to be checked out by another user and it is not.".format(file_other))
unreal.log("Source control tests completed!")
if __name__ == "__main__":
main()
|
# -*- 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
|
#!/project/ python
# format_test.py - Tests different command formats for MCP Server
import socket
import json
import sys
import time
# Configuration
HOST = '127.0.0.1'
PORT = 13377
TIMEOUT = 5 # seconds
# Simple Python code to execute
PYTHON_CODE = """
import unreal
return "Hello from Python!"
"""
def send_command(command_dict):
"""Send a command to the MCP Server and return the response."""
try:
# Create a socket connection
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(TIMEOUT)
s.connect((HOST, PORT))
# Convert command to JSON and send
command_json = json.dumps(command_dict)
print(f"Sending command format: {command_json}")
s.sendall(command_json.encode('utf-8'))
# Receive response
response = b""
while True:
chunk = s.recv(4096)
if not chunk:
break
response += chunk
# Parse and return response
if response:
try:
return json.loads(response.decode('utf-8'))
except json.JSONDecodeError:
return {"status": "error", "message": "Invalid JSON response", "raw": response.decode('utf-8')}
else:
return {"status": "error", "message": "Empty response"}
except socket.timeout:
return {"status": "error", "message": "Connection timed out"}
except ConnectionRefusedError:
return {"status": "error", "message": "Connection refused. Is the MCP Server running?"}
except Exception as e:
return {"status": "error", "message": f"Error: {str(e)}"}
def test_format(format_name, command_dict):
"""Test a specific command format and print the result."""
print(f"\n=== Testing Format: {format_name} ===")
response = send_command(command_dict)
print(f"Response: {json.dumps(response, indent=2)}")
if response.get("status") == "success":
print(f"✅ SUCCESS: Format '{format_name}' works!")
return True
else:
print(f"❌ FAILED: Format '{format_name}' does not work.")
return False
def main():
print("=== MCP Server Command Format Test ===")
print(f"Connecting to {HOST}:{PORT}")
# Test different command formats
formats = [
("Format 1: Basic", {
"command": "execute_python",
"code": PYTHON_CODE
}),
("Format 2: Type field", {
"type": "execute_python",
"code": PYTHON_CODE
}),
("Format 3: Command in data", {
"command": "execute_python",
"data": {
"code": PYTHON_CODE
}
}),
("Format 4: Type in data", {
"type": "execute_python",
"data": {
"code": PYTHON_CODE
}
}),
("Format 5: Command and params", {
"command": "execute_python",
"params": {
"code": PYTHON_CODE
}
}),
("Format 6: Type and params", {
"type": "execute_python",
"params": {
"code": PYTHON_CODE
}
}),
("Format 7: Command and type", {
"command": "execute_python",
"type": "python",
"code": PYTHON_CODE
}),
("Format 8: Command, type, and data", {
"command": "execute_python",
"type": "python",
"data": {
"code": PYTHON_CODE
}
})
]
success_count = 0
for format_name, command_dict in formats:
if test_format(format_name, command_dict):
success_count += 1
time.sleep(1) # Brief pause between tests
print(f"\n=== Test Summary ===")
print(f"Tested {len(formats)} command formats")
print(f"Successful formats: {success_count}")
print(f"Failed formats: {len(formats) - success_count}")
if __name__ == "__main__":
main()
|
# coding: utf-8
import unreal
import argparse
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]
|
# Copyright Epic Games, Inc. All Rights Reserved.
# These examples showcase how to use scripting with movie render graph
import unreal
import MovieGraphCreateConfigExample as graph_helper
import MovieGraphEditorExampleHelpers
# USAGE:
# - Requires the "Python Editor Script Plugin" to be enabled in your project.
# In the main() function, you'll find examples demonstrating how to load and
# modify movie graphs, overwrite exposed variables and perform other
# operations related to the Movie Render Graph
#
# Make sure to change the "Assets to load" section to point to your own
# Movie Render Queue and Movie Graph Config Assets
'''
Python Globals to keep the UObjects alive through garbage collection.
Must be deleted by hand on completion.
'''
subsystem = None
executor = None
def render_queue(queue_to_load: unreal.MoviePipelineQueue=None,
graph_to_load: unreal.MovieGraphConfig=None):
"""
This example demonstrates how to:
- load a queue or use the current queue
- Set a graph Config as a Preset
- Add a simple executor started callback
- Add a simple executor finished callback
"""
# Get the subsystem to interact with the Movie Pipeline Queue
subsystem = unreal.get_editor_subsystem(unreal.MoviePipelineQueueSubsystem)
# Load the provided Queue Asset if provided, otherwise use the active Queue
if queue_to_load:
if subsystem.load_queue(queue_to_load, prompt_on_replacing_dirty_queue=False):
unreal.log("Loaded specified queue")
# Get a reference to the active Queue
pipeline_queue = subsystem.get_queue()
if not pipeline_queue.get_jobs():
unreal.log("There are no jobs in the Queue.")
return
# For each job we can start modifying the job parameters such as accessing
# the graph preset of the job, modifying values
for job in pipeline_queue.get_jobs():
#Make sure we are working with a job graph config for this example
if not job.get_graph_preset():
unreal.log("A Graph Config needs to be specified for this example)")
return
if graph_to_load:
job.set_graph_preset(graph_to_load)
# A collection of job operation examples can be found in
MovieGraphEditorExampleHelpers.advanced_job_operations(job)
# We are using the globals keyword to indicate that the executor belongs to the
# global scope to avoid it being garbage collected after the job is finished rendering
global executor
executor = unreal.MoviePipelinePIEExecutor(subsystem)
# Before a render starts, execute the callback on_individual_job_started_callback
executor.on_individual_job_started_delegate.add_callable_unique(
MovieGraphEditorExampleHelpers.on_job_started_callback
)
# When the render jobs are done, execute the callback on_queue_finished_callback
executor.on_executor_finished_delegate.add_callable_unique(
MovieGraphEditorExampleHelpers.on_queue_finished_callback
)
# Start Rendering, similar to pressing "Render" in the UI,
subsystem.render_queue_with_executor_instance(executor)
def allocate_render_job(config_to_load: unreal.MovieGraphConfig=None):
'''
Allocates new job and populates it's parameters before kicking off a render
'''
# Get The current Queue
subsytem = unreal.get_editor_subsystem(unreal.MoviePipelineQueueSubsystem)
pipeline_queue = subsytem.get_queue()
# Delete existing jobs to clear the current Queue
pipeline_queue.delete_all_jobs()
job = pipeline_queue.allocate_new_job(unreal.MoviePipelineExecutorJob)
# To override Job Parameters check
# MovieGraphEditorExampleHelpers.set_job_parameters(job)
if config_to_load:
job.set_graph_preset(config_to_load)
subsystem = unreal.get_editor_subsystem(unreal.MoviePipelineQueueSubsystem)
executor = unreal.MoviePipelinePIEExecutor(subsystem)
subsystem.render_queue_with_executor_instance(executor)
def render_queue_minimal():
'''This an MVP example on how to render a Queue which already has jobs allocated
A more exhaustive example covering overrides can be found in the function render_queue
'''
subsystem = unreal.get_editor_subsystem(unreal.MoviePipelineQueueSubsystem)
executor = unreal.MoviePipelinePIEExecutor(subsystem)
subsystem.render_queue_with_executor_instance(executor)
def main():
"""We are showcasing how to render a queue (render_queue) and also how to create
a job from scratch without initially creating a queue. (allocate_render_job)
Run these examples independently.
"""
# Creates A Graph Asset called "Example" in /project/
# that exposes the output resolution as a user variable
created_graph = graph_helper.CreateIntermediateConfig()
# Render a Queue with a saved Queue Asset, Add Executor Callbacks, you can pass
# a Movie Render Queue Asset or just make sure you have jobs in a Movie Render Queue
render_queue()
# This function creates a job in the Queue by allocating a new MoviePipelineJob,
# You can also pass in config_to_load to set a graph config and finally start's the render
allocate_render_job()
if __name__ == "__main__":
unreal.log("Check the main() function for examples")
|
# 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()
|
# coding:utf-8
# ue4 asset functions
import unreal
def build_import_task(filename, dest_path, options=None):
# unreal.AssetImportTask https://api.unrealengine.com/project/.html
task = unreal.AssetImportTask()
task.set_editor_property('automated', True)
task.set_editor_property('destination_name', '')
task.set_editor_property('destination_path', dest_path)
task.set_editor_property('filename', filename)
task.set_editor_property('replace_existing', True)
task.set_editor_property('save', True)
# for Fbx Mesh
task.set_editor_property('options', options)
return task
def do_import_tasks(tasks):
# unreal.AssetToolsHelpers https://api.unrealengine.com/project/.html
# unreal.AssetTools [Abstract Class? baseClass is unreal.Interface]
# https://api.unrealengine.com/project/.html
unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks(tasks)
for task in tasks:
for path in task.get_editor_property('imported_object_paths'):
unreal.log_warning('Imported: %s'%path)
def build_static_mesh_import_options():
options = unreal.FbxImportUI()
# unreal.FbxImportUI https://api.unrealengine.com/project/.html
options.set_editor_property('import_mesh', True)
options.set_editor_property('import_textures', False)
options.set_editor_property('import_materials', False)
options.set_editor_property('import_as_skeletal', False) # Static Mesh
# unreal.FbxMeshImportData https://api.unrealengine.com/project/.html
options.static_mesh_import_data.set_editor_property('import_translation', unreal.Vector(0.0, 0.0, 0.0))
options.static_mesh_import_data.set_editor_property('import_rotation', unreal.Rotator(0.0, 0.0, 0.0))
options.static_mesh_import_data.set_editor_property('import_uniform_scale', 1.0)
# unreal.FbxStaticMeshImportData https://api.unrealengine.com/project/.html
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 build_skeletal_mesh_import_options():
options = unreal.FbxImportUI()
# unreal.FbxImportUI https://api.unrealengine.com/project/.html
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 https://api.unrealengine.com/project/.html
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
# https://api.unrealengine.com/project/.html
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
# #################################################### Testing
def test_import_textures():
# import textures testing
import os
_dir = 'D:/download/'
_textures = ['T_Snow_N.psd', 'Cliffs0464_7_seamless_S.jpg']
tasks = []
for tex in _textures:
task = build_import_task(os.path.join(_dir, tex), '/project/')
tasks.append(task)
do_import_tasks(tasks)
def test_import_fbx():
# import as StaticMesh Or SkeletalMesh
static_mesh_fbx = r'D:/project/.fbx'
skeletal_mesh_fbx = r'D:/project/.fbx'
static_mesh_task = build_import_task(static_mesh_fbx, '/project/', build_static_mesh_import_options())
skeletal_mesh_task = build_import_task(skeletal_mesh_fbx, '/project/', build_skeletal_mesh_import_options())
do_import_tasks([static_mesh_task, skeletal_mesh_task])
def main():
pass
|
# -*- coding: utf-8 -*-
"""
"""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
__author__ = "timmyliang"
__email__ = "[email protected]"
__date__ = "2021-08-11 23:17:48"
import unreal
from functools import partial
from Qt import QtCore
from unreal import EditorStaticMeshLibrary as static_mesh_lib
red_lib = unreal.RedArtToolkitBPLibrary
render_lib = unreal.RenderingLibrary
level_lib = unreal.EditorLevelLibrary
sys_lib = unreal.SystemLibrary
static_mesh_lib = unreal.EditorStaticMeshLibrary
defer = QtCore.QTimer.singleShot
path = "/project/.BP_UVCapture"
bp = unreal.load_asset(path)
RT = unreal.load_asset("/project/.RT_UV")
# NOTE 记录和隐藏所有 Actor 的显示
vis_dict = {}
for actor in level_lib.get_all_level_actors():
vis = actor.is_temporarily_hidden_in_editor()
vis_dict[actor] = vis
actor.set_is_temporarily_hidden_in_editor(True)
# NOTE 蓝图生成到场景里面
uv_material = unreal.load_asset("/project/.M_UVCapture")
mesh_2 = unreal.load_asset(
"/project/.aaa_magellan002_body_d1"
)
# mesh_1 = unreal.load_asset("/project/.aaa")
mesh_1 = unreal.load_asset(
"/project/.Skel_Arlong01_L_rig"
)
meshes = [mesh_1, mesh_2]
def get_static_materials(mesh):
return [
mesh.get_material(i) for i in range(static_mesh_lib.get_number_materials(mesh))
]
def get_skeletal_materials(mesh):
return [
m.get_editor_property("material_interface")
for m in mesh.get_editor_property("materials")
]
def capture(mesh):
# NOTE 删除 capture
capture_actor = level_lib.spawn_actor_from_object(bp, unreal.Vector())
capture_comp = capture_actor.get_editor_property("capture")
if isinstance(mesh, unreal.StaticMesh):
static_comp = capture_actor.get_editor_property("static")
static_comp.set_editor_property("static_mesh", mesh)
static_comp = capture_actor.get_editor_property("static")
materials = get_static_materials(mesh)
static_comp.set_editor_property(
"override_materials", [uv_material] * len(materials)
)
elif isinstance(mesh, unreal.SkeletalMesh):
skeletal_comp = capture_actor.get_editor_property("skeletal")
skeletal_comp.set_editor_property("skeletal_mesh", mesh)
skeletal_comp = capture_actor.get_editor_property("skeletal")
materials = get_skeletal_materials(mesh)
skeletal_comp.set_editor_property(
"override_materials", [uv_material] * len(materials)
)
capture_comp.capture_scene()
defer(
500,
lambda: (
render_lib.render_target_create_static_texture2d_editor_only(RT, "UV_map"),
capture_actor.destroy_actor(),
),
)
def end_call(vis_dict):
# NOTE 删除蓝图 & 恢复场景的显示
for actor, vis in vis_dict.items():
actor.set_is_temporarily_hidden_in_editor(vis)
interval = 1000
for i, mesh in enumerate(meshes, 1):
defer(interval * i, partial(capture, mesh))
defer(interval * (i + 1), partial(end_call, vis_dict))
|
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)
|
import unreal
def process_modols_assets():
"""
Processes Modols assets, iterating through them and placing them in the level.
This function will contain the core logic for asset processing.
"""
unreal.log("Processing Modols assets...")
static_mesh_assets_info = []
try:
asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
modols_path = "/project/"
search_options = unreal.AssetRegistrySearchOptions()
search_options.package_paths = [modols_path]
search_options.recursive_paths = True
static_mesh_class_name = unreal.StaticMesh.static_class().get_name()
search_options.asset_class_names = [static_mesh_class_name]
asset_data_list = asset_registry.get_assets(search_options)
num_assets_found = len(asset_data_list)
unreal.log(f"Found {num_assets_found} static meshes in {modols_path}.")
if num_assets_found > 0:
for asset_data in asset_data_list:
asset_path = str(asset_data.package_name)
unreal.log(f" Found StaticMesh: {asset_path}")
static_mesh_assets_info.append({"path": asset_path, "asset_data": asset_data})
else:
unreal.log("No StaticMeshes found under {modols_path}") # Note: f-string was missing here
# Corrected: unreal.log(f"No StaticMeshes found under {modols_path}")
except Exception as e:
unreal.log_error(f"Error during asset processing: {e}")
return [] # Return empty list on error to signal failure
return static_mesh_assets_info
def create_outliner_folders(static_mesh_assets_info, base_path="/project/"):
"""
Creates a hierarchical folder structure in the World Outliner based on asset paths.
"""
unreal.log("Starting to create Outliner folders...")
created_folders = set()
clean_base_path = base_path.strip("/")
try:
for asset_info in static_mesh_assets_info:
try:
full_asset_path = str(asset_info["path"]).strip("/")
path_to_match = clean_base_path
if full_asset_path.startswith(path_to_match + "/"):
relative_path_with_asset_name = full_asset_path[len(path_to_match) + 1:]
path_components = relative_path_with_asset_name.split("/")
if len(path_components) > 1:
relative_folder_path = "/".join(path_components[:-1])
current_hierarchical_path = ""
for folder_component in relative_folder_path.split("/"):
if not current_hierarchical_path:
current_hierarchical_path = folder_component
else:
current_hierarchical_path = f"{current_hierarchical_path}/{folder_component}"
if current_hierarchical_path not in created_folders:
try:
# unreal.log(f"Attempting to create Outliner folder: {current_hierarchical_path}") # Less verbose
unreal.EditorLevelLibrary.create_folder_in_world(current_hierarchical_path)
created_folders.add(current_hierarchical_path)
unreal.log(f"Successfully created/ensured Outliner folder: {current_hierarchical_path}")
except Exception as e_create:
unreal.log_error(f"Failed to create Outliner folder '{current_hierarchical_path}': {e_create}")
except Exception as e_asset:
unreal.log_error(f"Error processing asset info for folder creation ('{asset_info.get('path', 'Unknown path')}'): {e_asset}")
# Continue to next asset_info if possible
except Exception as e_main_loop:
unreal.log_error(f"A critical error occurred in create_outliner_folders main loop: {e_main_loop}")
unreal.log("Finished creating Outliner folders.")
def place_static_meshes_in_level(static_mesh_assets_info, base_path="/project/"):
"""
Loads static mesh assets, spawns them into the level, and places them in corresponding Outliner folders.
"""
unreal.log("Starting to place static meshes in level...")
editor_level_lib = unreal.EditorLevelLibrary()
clean_base_path = base_path.strip("/")
actors_placed_count = 0
try:
for asset_info in static_mesh_assets_info:
asset_path = str(asset_info.get("path", "Unknown path")) # Use .get for safety
try:
# Load the Static Mesh Asset
static_mesh = None
try:
static_mesh = unreal.load_asset(asset_path)
except Exception as e_load:
unreal.log_warning(f"Exception while loading asset {asset_path}: {e_load}")
continue # Skip to next asset
if not static_mesh:
unreal.log_warning(f"Failed to load asset (returned None): {asset_path}")
continue
if not isinstance(static_mesh, unreal.StaticMesh):
unreal.log_warning(f"Asset at {asset_path} is not a StaticMesh. Type is '{type(static_mesh)}'. Skipping.")
continue
# Spawn Actor
spawned_actor = None
try:
actor_location = unreal.Vector(0.0, 0.0, 0.0)
actor_rotation = unreal.Rotator(0.0, 0.0, 0.0)
spawned_actor = editor_level_lib.spawn_actor_from_object(static_mesh, actor_location, actor_rotation)
except Exception as e_spawn:
unreal.log_warning(f"Exception while spawning actor for StaticMesh {asset_path}: {e_spawn}")
continue # Skip to next asset
if not spawned_actor:
unreal.log_warning(f"Failed to spawn actor (returned None) for StaticMesh: {asset_path}")
continue
unreal.log(f"Spawned actor '{spawned_actor.get_actor_label()}' for '{asset_path}'")
# Determine Target Outliner Folder Path
relative_folder_path = ""
full_asset_path_stripped = asset_path.strip("/")
if full_asset_path_stripped.startswith(clean_base_path + "/"):
relative_path_with_asset_name = full_asset_path_stripped[len(clean_base_path) + 1:]
path_components = relative_path_with_asset_name.split("/")
if len(path_components) > 1:
relative_folder_path = "/".join(path_components[:-1])
# Set Actor's Folder Path
try:
if relative_folder_path:
spawned_actor.set_folder_path(relative_folder_path)
unreal.log(f"Moved actor '{spawned_actor.get_actor_label()}' to Outliner folder: '{relative_folder_path}'")
else:
spawned_actor.set_folder_path("")
unreal.log(f"Actor '{spawned_actor.get_actor_label()}' placed at Outliner root.")
actors_placed_count += 1
except Exception as e_folder:
unreal.log_warning(f"Exception while setting folder path for actor '{spawned_actor.get_actor_label()}' (asset: {asset_path}): {e_folder}")
except Exception as e_asset_loop:
unreal.log_error(f"Error processing asset '{asset_path}' in place_static_meshes_in_level: {e_asset_loop}")
# Continue to next asset_info if possible
except Exception as e_main_loop:
unreal.log_error(f"A critical error occurred in place_static_meshes_in_level main loop: {e_main_loop}")
unreal.log(f"Finished placing static meshes in level. {actors_placed_count} actors placed.")
def run_asset_placer():
"""
Main function to run the Modols Asset Placer tool.
"""
unreal.log("Modols Asset Placer tool started.")
overall_success = False
try:
# TODO: Add UI elements here if a dedicated window is built.
# For now, the logic is executed directly.
static_mesh_assets_info = process_modols_assets()
if static_mesh_assets_info is None: # process_modols_assets signals error with None
unreal.log_error("Asset processing failed. Aborting.")
elif not static_mesh_assets_info: # Empty list, but no error during processing
unreal.log("No assets found to process. Skipping folder creation and actor placement.")
overall_success = True # Technically successful as there was nothing to do
else:
create_outliner_folders(static_mesh_assets_info, base_path="/project/")
place_static_meshes_in_level(static_mesh_assets_info, base_path="/project/")
overall_success = True # Assume success if functions complete without throwing to here
except Exception as e:
unreal.log_error(f"An unexpected error occurred during Modols Asset Placer execution: {e}")
# overall_success remains False
if overall_success:
unreal.log("Modols Asset Placer tool finished processing successfully.")
else:
unreal.log_error("Modols Asset Placer tool encountered errors. Please check the log for details.")
if __name__ == "__main__":
# This section is for testing the script directly if needed.
# In Unreal Engine, this script will likely be triggered by a UI element or another mechanism.
run_asset_placer()
|
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_01"
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_01"
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)
|
# coding=utf-8
import os
import re
from functools import reduce
import unreal
from UnrealUtils import (
editor_utility_subsystem,
editor_actor_subsystem
)
from EditorAssetUtils import open_assets_in_editor
from UnrealStructure import WidgetAMStructure
Category = 'Actor Manager Editor BP Function Library'
@unreal.uclass()
class AMEditorBPFLibrary(unreal.BlueprintFunctionLibrary):
@unreal.ufunction(static=True, params=[unreal.Actor], meta=dict(Category=Category))
def select_actor(actor):
"""
:type actor: unreal.Actor
:return:
"""
editor_actor_subsystem.set_selected_level_actors([actor])
# return actor.get_actor_label()
@unreal.ufunction(
static=True,
params=[unreal.Array(unreal.Actor), unreal.Set(str)],
ret=unreal.Array(unreal.Actor),
meta=dict(Category=Category))
def filter_actors_by_labels(actors, keywords):
"""
:type actor: list[unreal.Actor]
:return:
"""
if not keywords:
return actors
_filter = lambda k: [a for a in actors if re.search(k.lower(), a.get_actor_label().lower())]
filtered_actors = [_filter(k) for k in keywords if k.strip()]
if not filtered_actors:
return actors
filtered_actors = reduce(lambda a, b: a + b, filtered_actors)
return list(set(filtered_actors))
@unreal.ufunction(
static=True,
params=[unreal.Actor, str],
ret=str,
meta=dict(Category=Category))
def rename_actor_label(actor, new_label):
"""
:param actor:
:param new_label:
:return:
"""
old_label = actor.get_actor_label()
if not old_label == new_label:
actor.set_actor_label(new_label)
return new_label
@unreal.ufunction(
static=True,
params=[unreal.Array(unreal.Actor), unreal.Array(unreal.EditableTextBox)],
meta=dict(Category=Category))
def batch_rename_actors_label(actors, text_boxes):
"""
:type actor: list[unreal.Actor]
:type text_boxes: list[unreal.EditableTextBox]
:return:
"""
for index, actor in enumerate(actors):
new_label = ''
for tb in text_boxes:
text = str(tb.get_text())
if re.search('^#+$', text):
new_label += f'%0{len(text)}i' % (index + 1)
else:
new_label += text
if not new_label:
return
actor.set_actor_label(new_label)
@unreal.ufunction(
static=True,
params=[unreal.ComboBoxString, unreal.Array(unreal.Actor)],
ret=unreal.Array(str),
meta=dict(Category=Category))
def setup_combo_box_str_options(box, actors):
"""
:type box: unreal.ComboBoxString
:type actors: list[unreal.Actor]
:return:
"""
if not actors:
return []
mesh_components = actors[0].get_components_by_class(unreal.MeshComponent)
if not mesh_components:
return []
um = unreal.MaterialEditingLibrary
scalars = []
switches = []
vectors = []
results = []
for component in mesh_components:
mi_dynamic = component.get_materials()
for mi in mi_dynamic:
scalars.extend(um.get_scalar_parameter_names(mi))
switches.extend(um.get_static_switch_parameter_names(mi))
vectors.extend(um.get_vector_parameter_names(mi))
results.extend([f'<scalar> {a}' for a in scalars])
results.extend([f'<switch> {a}' for a in switches])
results.extend([f'<color> {a}' for a in vectors])
unreal.log(results)
box.clear_options()
for option in results:
box.add_option(option)
return results
|
import unreal
from Utilities.Utils import Singleton
import math
try:
import numpy as np
b_use_numpy = True
except:
b_use_numpy = False
class ImageCompare(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.left_texture_size = (128, 128)
self.right_texture_size = (128, 128)
self.dpi_scale = 1
self.ui_img_left = "ImageLeft"
self.ui_img_right = "ImageRight"
self.ui_img_right_bg = "ImageRightBG"
self.ui_comparison_widget = "ComparisonWidget"
self.ui_dpi_scaler = "Scaler"
self.ui_status_bar = "StatusBar"
self.ui_ignore_alpha = "AlphaCheckBox"
self.ui_scaler_combobox = "ScaleComboBox"
self.combobox_items = self.data.get_combo_box_items(self.ui_scaler_combobox)
self.update_status_bar()
def set_image_from_viewport(self, bLeft):
data, width_height = unreal.PythonBPLib.get_viewport_pixels_as_data()
w, h = width_height.x, width_height.y
channel_num = int(len(data) / w / h)
if b_use_numpy:
im = np.fromiter(data, dtype=np.uint8).reshape(w, h, channel_num)
self.data.set_image_data_from_memory(self.ui_img_left if bLeft else self.ui_img_right, im.ctypes.data, len(data)
, w, h, channel_num=channel_num, bgr=False
, tiling=unreal.SlateBrushTileType.HORIZONTAL if bLeft else unreal.SlateBrushTileType.NO_TILE)
else:
texture = unreal.PythonBPLib.get_viewport_pixels_as_texture()
self.data.set_image_data_from_texture2d(self.ui_img_left if bLeft else self.ui_img_right, texture
, tiling=unreal.SlateBrushTileType.HORIZONTAL if bLeft else unreal.SlateBrushTileType.NO_TILE)
if bLeft:
self.left_texture_size = (w, h)
else:
self.right_texture_size = (w, h)
self.update_dpi_by_texture_size()
self.fit_window_size()
def fit_window_size1(self):
size = unreal.ChameleonData.get_chameleon_desired_size(self.json_path)
def set_images_from_viewport(self):
unreal.AutomationLibrary.set_editor_viewport_view_mode(unreal.ViewModeIndex.VMI_LIT)
self.set_image_from_viewport(bLeft=True)
unreal.AutomationLibrary.set_editor_viewport_view_mode(unreal.ViewModeIndex.VMI_WIREFRAME)
self.set_image_from_viewport(bLeft=False)
unreal.AutomationLibrary.set_editor_viewport_view_mode(unreal.ViewModeIndex.VMI_LIT)
self.fit_window_size()
self.update_status_bar()
def update_dpi_by_texture_size(self):
max_size = max(self.left_texture_size[1], self.right_texture_size[1])
if max_size >= 64:
self.dpi_scale = 1 / math.ceil(max_size / 512)
else:
self.dpi_scale = 4 if max_size <= 16 else 2
print(f"Set dpi -> {self.dpi_scale }")
self.data.set_dpi_scale(self.ui_dpi_scaler, self.dpi_scale)
for index, value_str in enumerate(self.combobox_items):
if float(value_str) == self.dpi_scale:
self.data.set_combo_box_selected_item(self.ui_scaler_combobox, index)
break
def on_ui_change_scale(self, value_str):
self.dpi_scale = float(value_str)
self.data.set_dpi_scale(self.ui_dpi_scaler, self.dpi_scale)
self.fit_window_size()
def update_status_bar(self):
self.data.set_text(self.ui_status_bar, f"Left: {self.left_texture_size}, Right: {self.right_texture_size} ")
if self.left_texture_size != self.right_texture_size:
self.data.set_color_and_opacity(self.ui_status_bar, unreal.LinearColor(2, 0, 0, 1))
else:
self.data.set_color_and_opacity(self.ui_status_bar, unreal.LinearColor.WHITE)
def fit_window_size(self):
max_x = max(self.left_texture_size[0], self.right_texture_size[0])
max_y = max(self.left_texture_size[1], self.right_texture_size[1])
MIN_WIDTH = 400
MAX_HEIGHT = 900
self.data.set_chameleon_window_size(self.json_path
, unreal.Vector2D(max(MIN_WIDTH, max_x * self.dpi_scale + 18)
, min(MAX_HEIGHT, max_y * self.dpi_scale + 125))
)
def on_drop(self, bLeft, **kwargs):
for asset_path in kwargs["assets"]:
asset = unreal.load_asset(asset_path)
if isinstance(asset, unreal.Texture2D):
width = asset.blueprint_get_size_x()
height = asset.blueprint_get_size_y()
ignore_alpha = self.data.get_is_checked(self.ui_ignore_alpha)
if self.data.set_image_data_from_texture2d(self.ui_img_left if bLeft else self.ui_img_right, asset, ignore_alpha=ignore_alpha):
if bLeft:
self.left_texture_size = (width, height)
else:
self.right_texture_size = (width, height)
self.update_dpi_by_texture_size()
self.fit_window_size()
self.update_status_bar()
break
|
# AdvancedSkeleton To ControlRig
# Copyright (C) Animation Studios
# email: [email protected]
# exported using AdvancedSkeleton version:x.xx
import unreal
import re
engineVersion = unreal.SystemLibrary.get_engine_version()
asExportVersion = x.xx
asExportTemplate = '4x'
print ('AdvancedSkeleton To ControlRig (Unreal:'+engineVersion+') (AsExport:'+str(asExportVersion)+') (Template:'+asExportTemplate+')')
utilityBase = unreal.GlobalEditorUtilityBase.get_default_object()
selectedAssets = utilityBase.get_selected_assets()
if len(selectedAssets)<1:
raise Exception('Nothing selected, you must select a ControlRig')
selectedAsset = selectedAssets[0]
if selectedAsset.get_class().get_name() != 'ControlRigBlueprint':
raise Exception('Selected object is not a ControlRigBlueprint, you must select a ControlRigBlueprint')
blueprint = selectedAsset
RigGraphDisplaySettings = blueprint.get_editor_property('rig_graph_display_settings')
RigGraphDisplaySettings.set_editor_property('node_run_limit',256)
library = blueprint.get_local_function_library()
library_controller = blueprint.get_controller(library)
hierarchy = blueprint.hierarchy
hierarchy_controller = hierarchy.get_controller()
RigVMController = blueprint.get_controller() #UE5
PreviousArrayInfo = dict()
global ASCtrlNr
global PreviousEndPlug
global PreviousEndPlugInv
global PreviousYInv
global sp
global nonTransformFaceCtrlNr
PreviousYInv = 0
ASCtrlNr = 0
nonTransformFaceCtrlNr = -1
sp = '/project/.RigUnit_'
PreviousEndPlug = 'RigUnit_BeginExecution.ExecuteContext'
PreviousEndPlugInv = 'RigUnit_InverseExecution.ExecuteContext'
def asAddCtrl (name, parent, joint, type, arrayInfo, gizmoName, ws, size, offT, color):
global PreviousEndPlug
global PreviousEndPlugInv
global PreviousYInv
global PreviousArrayInfo
global ctrlBoxSize
global ASCtrlNr
global nonTransformFaceCtrlNr
endPlug = PreviousEndPlug
RigVMGraph = blueprint.model
numNodes = len(RigVMGraph.get_nodes())
y = ASCtrlNr*400
ASCtrlNr=ASCtrlNr+1
ASDrivenNr = int()
RootScale = unreal.Vector(x=1.0, y=1.0, z=1.0)
ParentRigBone = unreal.RigBone()
ParentRigBoneName = parent.replace("FK", "")
hasCon = True
x = joint.split("_")
if len(x)>1:
baseName = x[0]
side = '_'+x[1]
x = ParentRigBoneName.split("_")
if len(x)>1:
ParentRigBoneBaseName = x[0]
RigElementKeys = asGetRigElementKeys ()
for key in RigElementKeys:
if (key.name == 'Root_M'):
hierarchy.get_global_transform(key, initial = True)
if (key.name == ParentRigBoneName):
if (key.type == 1):#Bone
ParentRigBone = hierarchy.find_bone (key)
asAddController (name, parent, joint, type, gizmoName, ws, size, offT, color)
if name=='Main':
return
if name=='RootX_M':
#Item
Item = asAddNode (sp+'Item','Execute',node_name=name+'_Item')
RigVMController.set_node_position (Item, [-500, y])
RigVMController.set_pin_default_value(name+'_Item.Item.Type','Control')
RigVMController.set_pin_default_value(name+'_Item.Item.Name',name)
#CON
CON = asAddNode (sp+'ParentConstraint','Execute',node_name=name+'_CON')
RigVMController.set_node_position (CON, [100, y-90])
RigVMController.set_pin_default_value(name+'_CON.Child.Type','Bone')
RigVMController.set_pin_default_value(name+'_CON.Child.Name',joint)
RigVMController.add_link(name+'_Item.Item', name+'_CON.Parents.0.Item')
RigVMController.add_link(endPlug , name+'_CON.ExecuteContext')
endPlug = name+'_CON.ExecuteContext'
elif (not "inbetweenJoints" in arrayInfo) and (not "inbetweenJoints" in PreviousArrayInfo):
#GT
GT = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GT')
RigVMController.set_node_position (GT, [-500, y])
RigVMController.set_pin_default_value(name+'_GT.Item.Type','Control')
RigVMController.set_pin_default_value(name+'_GT.Item.Name',name)
#ST
ST = asAddNode (sp+'SetTransform','Execute',node_name=name+'_ST')
RigVMController.set_node_position (ST, [100, y])
RigVMController.set_pin_default_value(name+'_ST.Item.Type','Bone')
RigVMController.set_pin_default_value(name+'_ST.Item.Name',joint)
RigVMController.add_link(name+'_GT.Transform' , name+'_ST.Transform')
RigVMController.set_pin_default_value(name+'_ST.bPropagateToChildren','True')
RigVMController.add_link(endPlug , name+'_ST.ExecuteContext')
endPlug = name+'_ST.ExecuteContext'
#twistJoints
if ("twistJoints" in arrayInfo) and (not "twistJoints" in PreviousArrayInfo):
GT2 = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GT2')
RigVMController.set_node_position (GT2, [500, y+50])
RigVMController.set_pin_default_value(name+'_GT2.Item.Type','Control')
RigVMController.set_pin_default_value(name+'_GT2.Item.Name',name)
RigVMController.set_pin_default_value(name+'_GT2.Space','LocalSpace')
TWSW = asAddNode (sp+'MathQuaternionSwingTwist','Execute',node_name=name+'_TWSW')
RigVMController.set_node_position (TWSW, [850, y+90])
RigVMController.add_link(name+'_GT2.Transform.Rotation' , name+'_TWSW.Input')
INV = asAddNode (sp+'MathQuaternionInverse','Execute',node_name=name+'_INV')
RigVMController.set_node_position (INV, [850, y+220])
RigVMController.add_link(name+'_TWSW.Twist' , name+'_INV.Value')
OFF= asAddNode (sp+'OffsetTransformForItem','Execute',node_name=name+'_OFF')
RigVMController.set_node_position (OFF, [1050, y])
RigVMController.set_pin_default_value(name+'_OFF.Item.Type','Bone')
RigVMController.set_pin_default_value(name+'_OFF.Item.Name',joint)
RigVMController.add_link(name+'_INV.Result' , name+'_OFF.OffsetTransform.Rotation')
RigVMController.add_link(endPlug , name+'_OFF.ExecuteContext')
endPlug = name+'_OFF.ExecuteContext'
GT3 = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GT3')
RigVMController.set_node_position (GT3, [1400, y+50])
RigVMController.set_pin_default_value(name+'_GT3.Item.Type','Control')
RigVMController.set_pin_default_value(name+'_GT3.Item.Name',name)
ST2 = asAddNode (sp+'SetTranslation','Execute',node_name=name+'_ST2')
RigVMController.set_node_position (ST2, [1700, y])
RigVMController.set_pin_default_value(name+'_ST2.Item.Type','Bone')
RigVMController.set_pin_default_value(name+'_ST2.Item.Name',joint)
RigVMController.add_link(name+'_GT3.Transform.Translation' , name+'_ST2.Translation')
RigVMController.add_link(endPlug , name+'_ST2.ExecuteContext')
endPlug = name+'_ST2.ExecuteContext'
if "twistJoints" in PreviousArrayInfo:
twistJoints = int (PreviousArrayInfo["twistJoints"])
TwistArray = asAddNode (sp+'CollectionChainArray','Execute',node_name=name+'_TwistArray')
RigVMController.set_node_position (TwistArray , [500, y+50])
RigVMController.set_pin_default_value(name+'_TwistArray.FirstItem', '(Type=Bone,Name='+ParentRigBoneBaseName+'Part1'+side+')')
RigVMController.set_pin_default_value(name+'_TwistArray.LastItem', '(Type=Bone,Name='+ParentRigBoneBaseName+'Part'+str(twistJoints)+side+')')
TwistArrayIterator = RigVMController.add_array_node_from_object_path(unreal.RigVMOpCode.ARRAY_ITERATOR, 'FRigElementKey', '/project/.RigElementKey', unreal.Vector2D(0, 0), name+'_TwistArrayIterator')
RigVMController.set_node_position (TwistArrayIterator , [850, y])
RigVMController.add_link(name+'_TwistArray.Items' , name+'_TwistArrayIterator.Array')
RigVMController.add_link(endPlug , name+'_TwistArrayIterator.ExecuteContext')
endPlug = name+'_TwistArrayIterator.Completed'
GTRE = asAddNode (sp+'GetRelativeTransformForItem','Execute',node_name=name+'_GTRE')
RigVMController.set_node_position (GTRE , [1050, y+50])
RigVMController.set_pin_default_value(name+'_GTRE.Child', '(Type=Bone,Name='+joint+')')
RigVMController.set_pin_default_value(name+'_GTRE.Parent', '(Type=Bone,Name='+ParentRigBoneName+')')
TWSW = asAddNode (sp+'MathQuaternionSwingTwist','Execute',node_name=name+'_TWSW')
RigVMController.set_node_position (TWSW, [1350, y+50])
RigVMController.add_link(name+'_GTRE.RelativeTransform.Rotation' , name+'_TWSW.Input')
TOEU = asAddNode (sp+'MathQuaternionToEuler','Execute',node_name=name+'_TOEU')
RigVMController.set_node_position (TOEU, [1350, y+170])
RigVMController.add_link(name+'_TWSW.Twist' , name+'_TOEU.Value')
FREU = asAddNode (sp+'MathQuaternionFromEuler','Execute',node_name=name+'_FREU')
RigVMController.set_node_position (FREU, [1350, y+270])
RigVMController.add_link(name+'_TOEU.Result' , name+'_FREU.Euler')
QS = asAddNode (sp+'MathQuaternionScale','Execute',node_name=name+'_QS')
RigVMController.set_node_position (QS, [1550, y+50])
RigVMController.set_pin_default_value(name+'_QS.Scale', str(1.0/int (PreviousArrayInfo["twistJoints"])))
RigVMController.add_link(name+'_FREU.Result' , name+'_QS.Value')
SR = asAddNode (sp+'SetRotation','Execute',node_name=name+'_SR')
RigVMController.set_node_position (SR, [1700, y])
RigVMController.add_link(name+'_QS.Value' , name+'_SR.Rotation')
RigVMController.add_link(name+'_TwistArrayIterator.Element', name+'_SR.Item')
RigVMController.set_pin_default_value(name+'_SR.Space','LocalSpace')
RigVMController.set_pin_default_value(name+'_SR.bPropagateToChildren','False')
RigVMController.add_link(name+'_TwistArrayIterator.ExecuteContext' , name+'_SR.ExecuteContext')
#inbetweenJoints
if "inbetweenJoints" in arrayInfo:
inbetweenJoints = int (arrayInfo["inbetweenJoints"])
Chain = asAddNode (sp+'CollectionChainArray','Execute',node_name=name+'_Chain')
RigVMController.set_node_position (Chain, [500, y])
RigVMController.set_pin_default_value(name+'_Chain.FirstItem.Name',joint)
RigVMController.set_pin_default_value(name+'_Chain.LastItem.Name',baseName+'Part'+str(inbetweenJoints)+side)
#GTDistr
GTDistr = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTDistr')
RigVMController.set_node_position (GTDistr, [850, y])
RigVMController.set_pin_default_value(name+'_GTDistr.Item.Type','Control')
RigVMController.set_pin_default_value(name+'_GTDistr.Item.Name',name)
RigVMController.set_pin_default_value(name+'_GTDistr.Space','LocalSpace')
#Distr
Distr = asAddNode (sp+'DistributeRotationForItemArray','Execute',node_name=name+'_Distr')
RigVMController.set_node_position (Distr, [1200, y])
weight = (1.0 / inbetweenJoints)
RigVMController.set_pin_default_value(name+'_Distr.Weight',str(weight))
RigVMController.add_link(name+'_Chain.Items' , name+'_Distr.Items')
RigVMController.add_array_pin(name+'_Distr.Rotations')
RigVMController.add_link(name+'_GTDistr.Transform.Rotation' , name+'_Distr.Rotations.0.Rotation')
RigVMController.add_link(endPlug , name+'_Distr.ExecuteContext')
endPlug = name+'_Distr.ExecuteContext'
if "inbetweenJoints" in PreviousArrayInfo:
jointKey = asGetKeyFromName (joint)
jointTransform = hierarchy.get_global_transform(jointKey, initial = True)
NullKey = hierarchy_controller.add_null ('Null'+joint,asGetKeyFromName(parent),jointTransform)
#GTNull
GTNull = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTNull')
RigVMController.set_node_position (GTNull, [1600, y+50])
RigVMController.set_pin_default_value(name+'_GTNull.Item.Type','Bone')
RigVMController.set_pin_default_value(name+'_GTNull.Item.Name',joint)
#STNull
STNull = asAddNode (sp+'SetTransform','Execute',node_name=name+'_STNull')
RigVMController.set_node_position (STNull, [2000, y])
RigVMController.set_pin_default_value(name+'_STNull.Item.Type','Null')
RigVMController.set_pin_default_value(name+'_STNull.Item.Name','Null'+joint)
RigVMController.add_link(name+'_GTNull.Transform' , name+'_STNull.Transform')
RigVMController.set_pin_default_value(name+'_STNull.bPropagateToChildren','True')
RigVMController.add_link(endPlug , name+'_STNull.ExecuteContext')
endPlug = name+'_STNull.ExecuteContext'
hierarchy_controller.set_parent(asGetKeyFromName(name),asGetKeyFromName('Null'+joint))
hierarchy.set_control_offset_transform(asGetKeyFromName(name), unreal.Transform(),initial=True)
hierarchy.set_local_transform(asGetKeyFromName(name), unreal.Transform(),initial=True)
hierarchy.set_local_transform(asGetKeyFromName(name), unreal.Transform(),initial=False)
#GT2
GT2 = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GT2')
RigVMController.set_node_position (GT2, [2400, y])
RigVMController.set_pin_default_value(name+'_GT2.Item.Type','Control')
RigVMController.set_pin_default_value(name+'_GT2.Item.Name',name)
#ST2
ST2 = asAddNode (sp+'SetTransform','Execute',node_name=name+'_ST2')
RigVMController.set_node_position (ST2, [2700, y])
RigVMController.set_pin_default_value(name+'_ST2.Item.Type','Bone')
RigVMController.set_pin_default_value(name+'_ST2.Item.Name',joint)
RigVMController.add_link(name+'_GT2.Transform' , name+'_ST2.Transform')
RigVMController.set_pin_default_value(name+'_ST2.bPropagateToChildren','True')
RigVMController.add_link(endPlug , name+'_ST2.ExecuteContext')
endPlug = name+'_ST2.ExecuteContext'
if "global" in arrayInfo and float(arrayInfo["global"])==10:
Transform = hierarchy.get_global_transform(asGetKeyFromName(name), initial = True)
NullKey = hierarchy_controller.add_null ('Global'+name,asGetKeyFromName(parent),Transform)
hierarchy_controller.set_parent(asGetKeyFromName(name),asGetKeyFromName('Global'+name),maintain_global_transform=True)
hierarchy.set_control_offset_transform(asGetKeyFromName(name), unreal.Transform(), True, True)
hierarchy.set_local_transform(asGetKeyFromName(name), unreal.Transform(),initial=True)
hierarchy.set_local_transform(asGetKeyFromName(name), unreal.Transform(),initial=False)
#resolve where `PreviousEndPlug` is connected to, as that is the start for this Row, which is not always the _ST node
Pin = RigVMGraph.find_pin(PreviousEndPlug)
LinkePins = Pin.get_linked_target_pins()
PreviousEndPlugConnectedToPin = LinkePins[0].get_pin_path()
PNPGlobal = asAddNode (sp+'ProjectTransformToNewParent','Execute',node_name=name+'_PNPGlobal')
RigVMController.set_node_position (PNPGlobal, [-1200, y])
RigVMController.set_pin_default_value(name+'_PNPGlobal.Child.Type','Control')
RigVMController.set_pin_default_value(name+'_PNPGlobal.Child.Name',name)
RigVMController.set_pin_default_value(name+'_PNPGlobal.OldParent.Type','Control')
RigVMController.set_pin_default_value(name+'_PNPGlobal.OldParent.Name','Main')
RigVMController.set_pin_default_value(name+'_PNPGlobal.NewParent.Type','Control')
RigVMController.set_pin_default_value(name+'_PNPGlobal.NewParent.Name','Main')
#SRGlobal
SRGlobal = asAddNode (sp+'SetRotation','Execute',node_name=name+'_SRGlobal')
RigVMController.set_node_position (SRGlobal, [-850, y])
RigVMController.set_pin_default_value(name+'_SRGlobal.Item.Type','Null')
RigVMController.set_pin_default_value(name+'_SRGlobal.Item.Name','Global'+name)
RigVMController.set_pin_default_value(name+'_SRGlobal.bPropagateToChildren','True')
RigVMController.add_link(name+'_PNPGlobal.Transform.Rotation' , name+'_SRGlobal.Rotation')
RigVMController.add_link(PreviousEndPlug , name+'_SRGlobal.ExecuteContext')
endPlug = name+'_SRGlobal.ExecuteContext'
#STGlobal
STGlobal = asAddNode (sp+'SetTranslation','Execute',node_name=name+'_STGlobal')
RigVMController.set_node_position (STGlobal, [-850, y+250])
RigVMController.set_pin_default_value(name+'_STGlobal.Item.Type','Null')
RigVMController.set_pin_default_value(name+'_STGlobal.Item.Name','Global'+name)
RigVMController.set_pin_default_value(name+'_STGlobal.Space','LocalSpace')
RigVMController.set_pin_default_value(name+'_STGlobal.bPropagateToChildren','True')
Transform = hierarchy.get_local_transform(NullKey)
RigVMController.set_pin_default_value(name+'_STGlobal.Translation.X',str(Transform.translation.x))
RigVMController.set_pin_default_value(name+'_STGlobal.Translation.Y',str(Transform.translation.y))
RigVMController.set_pin_default_value(name+'_STGlobal.Translation.Z',str(Transform.translation.z))
RigVMController.add_link(name+'_SRGlobal.ExecuteContext' , name+'_STGlobal.ExecuteContext')
endPlug = name+'_STGlobal.ExecuteContext'
RigVMController.add_link(endPlug , PreviousEndPlugConnectedToPin)
endPlug = PreviousEndPlugConnectedToPin
if type=='IK':
asAddController ('Pole'+name, parent, joint, type, 'Sphere_Solid', ws, size/5.0, offT, color)
hierarchy.set_control_offset_transform(asGetKeyFromName('Pole'+name), unreal.Transform(location=[float(arrayInfo["ppX"])*RootScale.x,float(arrayInfo["ppZ"])*RootScale.y,float(arrayInfo["ppY"])*RootScale.z],scale=RootScale), True, True)
#IK(Basic IK)
IK = asAddNode (sp+'TwoBoneIKSimplePerItem','Execute',node_name=name+'_IK')
RigVMController.set_node_position (IK, [600, y-130])
RigVMController.set_pin_default_value(name+'_IK.ItemA.Name',arrayInfo["startJoint"])
RigVMController.set_pin_default_value(name+'_IK.ItemB.Name',arrayInfo["middleJoint"])
RigVMController.set_pin_default_value(name+'_IK.EffectorItem.Name',arrayInfo["endJoint"])
RigVMController.set_pin_default_value(name+'_IK.PrimaryAxis.X',arrayInfo["paX"])
RigVMController.set_pin_default_value(name+'_IK.PrimaryAxis.Y',arrayInfo["paY"])
RigVMController.set_pin_default_value(name+'_IK.PrimaryAxis.Z',arrayInfo["paZ"])
RigVMController.set_pin_default_value(name+'_IK.SecondaryAxis.X',arrayInfo["saX"])
RigVMController.set_pin_default_value(name+'_IK.SecondaryAxis.Y',arrayInfo["paY"])
RigVMController.set_pin_default_value(name+'_IK.SecondaryAxis.Z',arrayInfo["paZ"])
RigVMController.set_pin_default_value(name+'_IK.PoleVectorKind','Location')
RigVMController.set_pin_default_value(name+'_IK.PoleVectorSpace.Type','Control')
RigVMController.set_pin_default_value(name+'_IK.PoleVectorSpace.Name','Pole'+name)
RigVMController.set_pin_default_value(name+'_IK.bPropagateToChildren','True')
RigVMController.add_link(name+'_GT.Transform' , name+'_IK.Effector')
RigVMController.add_link(endPlug , name+'_IK.ExecuteContext')
endPlug = name+'_IK.ExecuteContext'
#GTPole
GTPole = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTPole')
RigVMController.set_node_position (GTPole, [1000, y])
RigVMController.set_pin_default_value(name+'_GTPole.Item.Type','Control')
RigVMController.set_pin_default_value(name+'_GTPole.Item.Name','Pole'+name)
#GTMidJoint
GTMidJoint = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTMidJoint')
RigVMController.set_node_position (GTMidJoint, [1000, y+200])
RigVMController.set_pin_default_value(name+'_GTMidJoint.Item.Type','Bone')
RigVMController.set_pin_default_value(name+'_GTMidJoint.Item.Name',arrayInfo["middleJoint"])
PoleLine = asAddNode (sp+'DebugLineItemSpace','Execute',node_name=name+'_PoleLine')
RigVMController.set_node_position (PoleLine, [1350, y])
RigVMController.add_link(name+'_GTPole.Transform.Translation' , name+'_PoleLine.A')
RigVMController.add_link(name+'_GTMidJoint.Transform.Translation' , name+'_PoleLine.B')
RigVMController.add_link(endPlug , name+'_PoleLine.ExecuteContext')
endPlug = name+'_PoleLine.ExecuteContext'
control_value = hierarchy.make_control_value_from_euler_transform(unreal.EulerTransform(scale=[1, 1, 1]))
control_settings = unreal.RigControlSettings()
control_settings.shape_enabled = False
hierarchy_controller.add_control (name+'LS','', control_settings,control_value)
hierarchy_controller.set_parent(asGetKeyFromName(name+'LS'),asGetKeyFromName(name),maintain_global_transform=False)
RigVMController.set_pin_default_value(name+'_GT.Item.Name',name+'LS')
for key in RigElementKeys:
if (key.name == arrayInfo["endJoint"]):
endJointKey = key
EndJointTransform = hierarchy.get_global_transform(endJointKey, initial = False)
Rotation = EndJointTransform.rotation.rotator()
Transform = unreal.Transform(location=[0,0,0],rotation=Rotation,scale=[1,1,1])
hierarchy.set_control_offset_transform(asGetKeyFromName(name+'LS'), Transform, True, True)
#Backwards solve nodes (IK)
PNPinvIK = asAddNode (sp+'ProjectTransformToNewParent','Execute',node_name=name+'_PNPinvIK')
RigVMController.set_node_position (PNPinvIK, [-2900, y])
RigVMController.set_pin_default_value(name+'_PNPinvIK.Child.Type','Control')
RigVMController.set_pin_default_value(name+'_PNPinvIK.Child.Name',name)
RigVMController.set_pin_default_value(name+'_PNPinvIK.OldParent.Type','Control')
RigVMController.set_pin_default_value(name+'_PNPinvIK.OldParent.Name',name+'LS')
RigVMController.set_pin_default_value(name+'_PNPinvIK.NewParent.Type','Bone')
RigVMController.set_pin_default_value(name+'_PNPinvIK.NewParent.Name',joint)
#STinvIK
STinvIK = asAddNode (sp+'SetTransform','Execute',node_name=name+'_STinvIK')
RigVMController.set_node_position (STinvIK, [-2500, y])
RigVMController.set_pin_default_value(name+'_STinvIK.Item.Type','Control')
RigVMController.set_pin_default_value(name+'_STinvIK.Item.Name',name)
RigVMController.set_pin_default_value(name+'_STinvIK.bPropagateToChildren','True')
RigVMController.add_link(name+'_PNPinvIK.Transform' , name+'_STinvIK.Transform')
RigVMController.add_link(PreviousEndPlugInv , name+'_STinvIK.ExecuteContext')
#GTinvPole
GTinvPole = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTinvPole')
RigVMController.set_node_position (GTinvPole, [-1700, y])
RigVMController.set_pin_default_value(name+'_GTinvPole.Item.Type','Bone')
RigVMController.set_pin_default_value(name+'_GTinvPole.Item.Name',arrayInfo["middleJoint"])
#STinvPole
STinvPole = asAddNode (sp+'SetTransform','Execute',node_name=name+'_STinvPole')
RigVMController.set_node_position (STinvPole, [-1300, y])
RigVMController.set_pin_default_value(name+'_STinvPole.Item.Type','Control')
RigVMController.set_pin_default_value(name+'_STinvPole.Item.Name','Pole'+name)
RigVMController.set_pin_default_value(name+'_STinvPole.bPropagateToChildren','True')
RigVMController.add_link(name+'_GTinvPole.Transform' , name+'_STinvPole.Transform')
RigVMController.add_link(name+'_STinvIK.ExecuteContext' , name+'_STinvPole.ExecuteContext')
endPlugInv = name+'_STinvPole.ExecuteContext'
PreviousEndPlugInv = endPlugInv
PreviousYInv = y
if "twistJoints" in arrayInfo or "inbetweenJoints" in arrayInfo:
PreviousArrayInfo = arrayInfo
else:
PreviousArrayInfo.clear()
#DrivingSystem
if type=='DrivingSystem' or type=='ctrlBox':
if type=='DrivingSystem':
RigVMController.set_pin_default_value(name+'_GT.Item.Type','Bone')
RigVMController.set_pin_default_value(name+'_GT.Item.Name',joint)
RigVMController.set_pin_default_value(name+'_ST.Item.Type','Control')
RigVMController.set_pin_default_value(name+'_ST.Item.Name',name)
if type=='ctrlBox' and name!='ctrlBox':
parentTransform = hierarchy.get_global_control_offset_transform(asGetKeyFromName(parent))
Transform = unreal.Transform(location=[offT[0]/ctrlBoxSize,offT[2]/ctrlBoxSize,offT[1]/ctrlBoxSize])
Transform.rotation = [0,0,0]
hierarchy.set_control_offset_transform(asGetKeyFromName(name), Transform, True, True)
if name=='ctrlBox':
#add a ws oriented ctrlBoxOffset
NullKey = hierarchy_controller.add_null ('ctrlBoxOffset',asGetKeyFromName(parent),unreal.Transform(),transform_in_global=True)
Transform = hierarchy.get_local_transform(NullKey)
Transform.translation = [0,0,0]
hierarchy.set_local_transform(NullKey, Transform,initial=True)
hierarchy.set_local_transform(NullKey, Transform,initial=False)
hierarchy_controller.set_parent(asGetKeyFromName(name),NullKey,maintain_global_transform=False)
ctrlBoxSize = float (arrayInfo["ctrlBoxSize"])
Scale = [0.6,1.5,1.0]
ctrlBoxScale = [ctrlBoxSize,ctrlBoxSize,ctrlBoxSize]
parentTransform = hierarchy.get_global_control_offset_transform(asGetKeyFromName(parent))
Transform2 = hierarchy.get_global_control_offset_transform(asGetKeyFromName(name)).make_relative(parentTransform)
Transform2.translation = [offT[0],offT[2],offT[1]]
Transform2.scale3d = [ctrlBoxSize,ctrlBoxSize,ctrlBoxSize]
hierarchy.set_control_offset_transform(asGetKeyFromName(name), Transform2, True, True)
Transform = unreal.Transform(location=[0,0,-1],rotation=[0,0,90],scale=Scale)
hierarchy.set_control_shape_transform(asGetKeyFromName(name), Transform, True, True)
return
nonTransformFaceCtrl = False
if type=='ctrlBox':
RigVMController.remove_node(RigVMGraph.find_node_by_name(name+'_GT'))
RigVMController.remove_node(RigVMGraph.find_node_by_name(name+'_ST'))
Transform = unreal.Transform(scale=[0.05,0.05,0.05])
hierarchy.set_control_shape_transform(asGetKeyFromName(name), Transform, True, True)
maxXform = unreal.Vector2D(1,1)
minXform = unreal.Vector2D(-1,-1)
if name=='ctrlMouth_M':
maxXform = [1,0]
if re.search("^ctrlCheek_", name) or re.search("^ctrlNose_", name):
minXform = [-1,0]
RigElementKeys = asGetRigElementKeys ()
for key in RigElementKeys:
if (key.name == name):
RigControlKey = key
hierarchy.set_control_value(asGetKeyFromName(name),unreal.RigHierarchy.make_control_value_from_vector2d(maxXform), unreal.RigControlValueType.MAXIMUM)
hierarchy.set_control_value(asGetKeyFromName(name),unreal.RigHierarchy.make_control_value_from_vector2d(minXform), unreal.RigControlValueType.MINIMUM)
endPlug = PreviousEndPlug
control_settings = unreal.RigControlSettings()
control_value = hierarchy.make_control_value_from_euler_transform(unreal.EulerTransform(scale=[1, 1, 1]))
AttrGrpkey = hierarchy_controller.add_control (name+"_Attributes",'',control_settings,control_value)
if type=='ctrlBox':
hierarchy_controller.set_parent(asGetKeyFromName(name+"_Attributes"),asGetKeyFromName(parent),maintain_global_transform=False)
else:
hierarchy_controller.set_parent(asGetKeyFromName(name+"_Attributes"),asGetKeyFromName(name),maintain_global_transform=False)
hierarchy.set_control_shape_transform(asGetKeyFromName(name+"_Attributes"), unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[0,0,0]), True)
Transform = hierarchy.get_global_control_offset_transform(asGetKeyFromName(name), initial = True).copy()
parentTransform = hierarchy.get_global_transform(asGetKeyFromName(parent), initial = True)
Transform = Transform.make_relative(parentTransform)
if type=='ctrlBox':
Transform.translation.x = -5.0
Transform.translation.z += 0.8
if re.search("_L", name) or re.search("_M", name):
Transform.translation.x = 4.0
if nonTransformFaceCtrl:
Transform.translation.z = -5.5-(nonTransformFaceCtrlNr*2) # stack rows of sliders downwards
else:
numAttrs = 0
for Attr in arrayInfo.keys():
if not re.search("-set", Attr):
numAttrs=numAttrs+1
Transform = unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[1,1,1])
Transform.translation.x = offT[0]
Transform.translation.y = numAttrs*0.5*(size/4.0)*-0.5
Transform.translation.z = size/8.0
if re.search("_L", name):
Transform.translation.z *= -1
Transform.scale3d=[size/4.0,size/4.0,size/4.0]
hierarchy.set_control_offset_transform(asGetKeyFromName(name+"_Attributes"), Transform, True, True)
Attrs = arrayInfo.keys()
attrNr = 0
for Attr in Attrs:
if re.search("-set", Attr):
if re.search("-setLimits", Attr):
DictDrivens = arrayInfo.get(Attr)
min = float(list(DictDrivens.keys())[0])
max = float(list(DictDrivens.values())[0])
RigElementKeys = asGetRigElementKeys ()
for key in RigElementKeys:
if key.name == name+"_"+Attr.replace("-setLimits", ""):
hierarchy.set_control_value(key, unreal.RigHierarchy.make_control_value_from_float(min), unreal.RigControlValueType.MINIMUM)
hierarchy.set_control_value(key, unreal.RigHierarchy.make_control_value_from_float(max), unreal.RigControlValueType.MAXIMUM)
continue
transformAttrDriver = True
if not re.search("translate", Attr) or re.search("rotate", Attr) or re.search("scale", Attr):
control_settings = unreal.RigControlSettings()
control_settings.control_type = unreal.RigControlType.FLOAT
control_settings.shape_color = unreal.LinearColor(r=1.0, g=0.0, b=0.0, a=1.0)
control_settings.limit_enabled = [unreal.RigControlLimitEnabled(True, True)]
if nonTransformFaceCtrl or re.search("_M", name):
control_settings.primary_axis = unreal.RigControlAxis.Z
else:
control_settings.primary_axis = unreal.RigControlAxis.X
key = hierarchy_controller.add_control (name+"_"+Attr,asGetKeyFromName(name+"_Attributes"),control_settings,control_value)
hierarchy.set_control_value(key,unreal.RigHierarchy.make_control_value_from_float(1), unreal.RigControlValueType.MAXIMUM)
hierarchy.set_control_shape_transform(asGetKeyFromName(name+"_"+Attr), unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[0.035,0.035,0.035]), True, True)
Transform = unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[1,1,1])
Transform.translation = [0,attrNr*0.5,0]
if type=='ctrlBox':
Transform.translation = [0,0,attrNr*-0.5]
if nonTransformFaceCtrl or re.search("_M", name):
Transform.translation = [attrNr,0,0]
attrNr = attrNr+1
hierarchy.set_control_offset_transform(asGetKeyFromName(name+"_"+Attr), Transform, True, True)
transformAttrDriver = False
DictDrivens = arrayInfo.get(Attr)
KeysDrivens = DictDrivens.keys()
for Driven in KeysDrivens:
Value = float(DictDrivens.get(Driven))
x2 = ASDrivenNr*1200
dNr = str(ASDrivenNr)
ASDrivenNr = ASDrivenNr+1
x = Driven.split(".")
obj = x[0]
attr = '_'+x[1]
axis = attr[-1]
valueMult = 1
if re.search("rotate", attr):
if axis == 'X' or axis=='Z':
valueMult = -1
if re.search("translate", attr):
if axis=='Y':
valueMult = -1
multiplier = Value*valueMult
asFaceBSDriven = False
if re.search("asFaceBS[.]", Driven):#asFaceBS
asFaceBSDriven = True
if not (asFaceBSDriven):
RigElementKeys = asGetRigElementKeys ()
for key in RigElementKeys:
if key.name == obj:
objKey = key
if not asObjExists ('Offset'+obj):
objParentKey = hierarchy.get_parents(objKey)[0]
OffsetKey = hierarchy_controller.add_null ('Offset'+obj,objKey,unreal.Transform(),transform_in_global=False)
hierarchy_controller.set_parent(OffsetKey,objParentKey)
hierarchy_controller.set_parent(objKey,OffsetKey)
parentTo = 'Offset'+obj
for x in range(1,9):
sdk = 'SDK'+obj+"_"+str(x)
if not asObjExists (sdk):
break
if x>1:
parentTo = 'SDK'+obj+"_"+str(x-1)
SDKKey = hierarchy_controller.add_null (sdk,asGetKeyFromName(parentTo),unreal.Transform(),transform_in_global=False)
hierarchy_controller.set_parent(objKey,SDKKey)
#GTDriver
if transformAttrDriver:
GTDriver = asAddNode (sp+'GetControlVector2D','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_GTDriver')
RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_GTDriver.Control',name)
gtPlug = name+"_"+obj+"_"+attr+dNr+'_GTDriver.Vector.'+Attr[-1]#Attr[-1] is DriverAxis
else:
GTDriver = asAddNode (sp+'GetControlFloat','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_GTDriver')
RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_GTDriver.Control',name+"_"+Attr)
gtPlug = name+"_"+obj+"_"+attr+dNr+'_GTDriver.FloatValue'
RigVMController.set_node_position (GTDriver, [500+x2, y])
#MFM
MFM = asAddNode (sp+'MathFloatMul','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_MFM')
RigVMController.set_node_position (MFM, [900+x2, y])
RigVMController.add_link(gtPlug , name+"_"+obj+"_"+attr+dNr+'_MFM.A')
RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_MFM.B',str(multiplier))
if asFaceBSDriven:
#Clamp
Clamp = asAddNode (sp+'MathFloatClamp','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_Clamp')
RigVMController.set_node_position (Clamp, [900+x2, y+100])
RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_Clamp.Maximum','5.0')
RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_MFM.Result' , name+"_"+obj+"_"+attr+dNr+'_Clamp.Value')
#STDriven
STDriven = asAddNode (sp+'SetCurveValue','Execute',node_name=name+"_"+Attr+"_"+attr+'_STDriven')
RigVMController.set_node_position (STDriven, [1100+x2, y])
RigVMController.set_pin_default_value(name+"_"+Attr+"_"+attr+'_STDriven.Curve',Driven.split(".")[1])
RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_Clamp.Result' , name+"_"+Attr+"_"+attr+'_STDriven.Value')
RigVMController.add_link(endPlug , name+"_"+Attr+"_"+attr+'_STDriven.ExecuteContext')
endPlug =name+"_"+Attr+"_"+attr+'_STDriven.ExecuteContext'
else:
#STDriven
STDriven = asAddNode (sp+'SetTransform','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_STDriven')
RigVMController.set_node_position (STDriven, [1300+x2, y])
RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_STDriven.Item.Type','Null')
RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_STDriven.Item.Name',sdk)
RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_STDriven.Space','LocalSpace')
RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_STDriven.bPropagateToChildren','True')
RigVMController.add_link(endPlug , name+"_"+obj+"_"+attr+dNr+'_STDriven.ExecuteContext')
endPlug = name+"_"+obj+"_"+attr+dNr+'_STDriven.ExecuteContext'
#TFSRT
TFSRT = asAddNode (sp+'MathTransformFromSRT','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_TFSRT')
RigVMController.set_node_position (TFSRT, [900+x2, y+150])
if re.search("translate", attr):
RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_MFM.Result' , name+"_"+obj+"_"+attr+dNr+'_TFSRT.Location.'+axis)
if re.search("rotate", attr):
RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_MFM.Result' , name+"_"+obj+"_"+attr+dNr+'_TFSRT.Rotation.'+axis)
if re.search("scale", attr):
#scale just add 1, not accurate but simplified workaround
MFA = asAddNode (sp+'MathFloatAdd','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_MFA')
RigVMController.set_node_position (MFA, [1100+x2, y])
RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_MFM.Result' , name+"_"+obj+"_"+attr+dNr+'_MFA.A')
RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_MFA.B','1')
RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_MFA.Result' , name+"_"+obj+"_"+attr+dNr+'_TFSRT.Scale.'+axis)
RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_TFSRT.Transform', name+"_"+obj+"_"+attr+dNr+'_STDriven.Transform')
#face
if re.search("Teeth_M", name):
RigControl.set_editor_property('gizmo_enabled',False)
hierarchy_controller.set_control (RigControl)
if name=="Jaw_M":
RigControl.set_editor_property('gizmo_name','HalfCircle_Thick')
RigControl.set_editor_property('gizmo_name','HalfCircle_Thick')
Transform = RigControl.get_editor_property('gizmo_transform')
Transform.rotation=[0,0,180]
RigControl.set_editor_property('gizmo_transform', Transform)
hierarchy_controller.set_control (RigControl)
PreviousEndPlug = endPlug
def asObjExists (obj):
RigElementKeys = asGetRigElementKeys ()
LocObject = None
for key in RigElementKeys:
if key.name == obj:
return True
return False
def asAddController (name, parent, joint, type, gizmoName, ws, size, offT, color):
parentKey = asGetKeyFromName(parent)
if gizmoName=='Gizmo':
gizmoName='Default'
control_settings = unreal.RigControlSettings()
if type=='ctrlBox':
control_settings.control_type = unreal.RigControlType.VECTOR2D
control_settings.primary_axis = unreal.RigControlAxis.Y
control_settings.limit_enabled = [unreal.RigControlLimitEnabled(True, True), unreal.RigControlLimitEnabled(True, True)]
else:
control_settings.control_type = unreal.RigControlType.EULER_TRANSFORM
if name=='ctrlEmotions_M' or name=='ctrlPhonemes_M' or name=='ctrlARKit_M' or name=='ctrlBoxRobloxHead_M':
control_settings.shape_enabled = False
control_settings.shape_name = gizmoName
control_settings.shape_color = unreal.LinearColor(color[0], color[1], color[2], 1.0)
control_value = hierarchy.make_control_value_from_euler_transform(unreal.EulerTransform(scale=[1, 1, 1]))
key = hierarchy_controller.add_control (name,'', control_settings,control_value)
jointKey = asGetKeyFromName (joint)
jointTransform = hierarchy.get_global_transform(jointKey, initial = True)
if ws == 1:
jointTransform.rotation = [0,0,0]
parentTransform = unreal.Transform()
if parent!='':
parentTransform = hierarchy.get_global_transform(asGetKeyFromName(parent), initial = True)
OffsetTransform = jointTransform.make_relative(parentTransform)
if parent!='':
hierarchy_controller.set_parent(asGetKeyFromName(name),asGetKeyFromName(parent),maintain_global_transform=False)
hierarchy.set_control_offset_transform(key, OffsetTransform, True, True)
GizmoLocation = [offT[0],offT[2],offT[1]]
GizmoRotation = [0,0,0]
if ws == 0:
GizmoRotation = [90,0,0]
GizmoLocation = [offT[0],offT[1]*-1,offT[2]]
if type=="DrivingSystem":
GizmoRotation = [0,0,0]
if type=="ctrlBox":
GizmoRotation = [0,0,90]
if re.search("^Eye_.*", name) or re.search("^Iris_.*", name) or re.search("^Pupil_.*", name):
GizmoRotation = [0,90,0]
hierarchy.set_control_visibility(key,False)
x = re.search("^Pole.*", name)
if x:
GizmoLocation = [0,0,0]
s = 0.1*size
Scale = [s,s,s]
if type=='FK' and ws == 0:
Scale[2]*=2.5
hierarchy.set_control_shape_transform(key, unreal.Transform(location=GizmoLocation,rotation=GizmoRotation,scale=Scale), True)
def asAddNode (script_struct_path, method_name, node_name):
#RigVMController.
#add_struct_node_from_struct_path UE4
#add_unit_node_from_struct_path UE5
try:
node = RigVMController.add_struct_node_from_struct_path(script_struct_path,method_name,node_name=node_name) #UE4
except:
node = RigVMController.add_unit_node_from_struct_path(script_struct_path,method_name,node_name=node_name) #UE5
return node
def asGetRigElementKeys ():
try:
RigElementKeys = hierarchy_controller.get_elements() #UE4
except:
RigElementKeys = hierarchy.get_all_keys() #UE5
return RigElementKeys
def asGetKeyFromName (name):
all_keys = hierarchy.get_all_keys(traverse = True)
for key in all_keys:
if key.name == name:
return key
return ''
def asBackwardsSolveNodes ():
global PreviousYInv
global PreviousEndPlugInv
PNP = asAddNode (sp+'ProjectTransformToNewParent','Execute',node_name='Root_M_PNP')
RigVMController.set_node_position (PNP, [-1500, PreviousYInv+400-90])
RigVMController.set_pin_default_value('Root_M_PNP.Child.Type','Control')
RigVMController.set_pin_default_value('Root_M_PNP.Child.Name','RootX_M')
RigVMController.set_pin_default_value('Root_M_PNP.OldParent.Type','Bone')
RigVMController.set_pin_default_value('Root_M_PNP.OldParent.Name','Root_M')
RigVMController.set_pin_default_value('Root_M_PNP.NewParent.Type','Bone')
RigVMController.set_pin_default_value('Root_M_PNP.NewParent.Name','Root_M')
STInv = asAddNode (sp+'SetTransform','Execute',node_name='Root_M_STInv')
RigVMController.set_node_position (STInv, [-1200, PreviousYInv+400-90])
RigVMController.set_pin_default_value('Root_M_STInv.Item.Type','Control')
RigVMController.set_pin_default_value('Root_M_STInv.Item.Name','RootX_M')
RigVMController.add_link('Root_M_PNP.Transform' , 'Root_M_STInv.Transform')
RigVMController.add_link(PreviousEndPlugInv , 'Root_M_STInv.ExecuteContext')
CCinv = asAddNode (sp+'CollectionChildren','Execute',node_name='CCinv')
RigVMController.set_node_position (CCinv, [-2600, PreviousYInv+1000])
RigVMController.set_pin_default_value('CCinv.Parent.Type','Bone')
RigVMController.set_pin_default_value('CCinv.Parent.Name','Root_M')
RigVMController.set_pin_default_value('CCinv.bRecursive','True')
RigVMController.set_pin_default_value('CCinv.TypeToSearch','Bone')
CLinv = asAddNode (sp+'CollectionLoop','Execute',node_name='CLinv')
RigVMController.set_node_position (CLinv, [-2150, PreviousYInv+1000])
RigVMController.add_link('Root_M_STInv.ExecuteContext' , 'CLinv.ExecuteContext')
RigVMController.add_link('CCinv.Collection' , 'CLinv.Collection')
PreviousEndPlugInv = 'CLinv.Completed'
NCinv = asAddNode (sp+'NameConcat','Execute',node_name='NCinv')
RigVMController.set_node_position (NCinv, [-1900, PreviousYInv+900])
RigVMController.set_pin_default_value('NCinv.A','FK')
RigVMController.add_link('CLinv.Item.Name' , 'NCinv.B')
GTinv = asAddNode (sp+'GetTransform','Execute',node_name='GTinv')
RigVMController.set_node_position (GTinv, [-1900, PreviousYInv+1000])
RigVMController.add_link('CLinv.Item.Name' , 'GTinv.Item.Name')
IEinv = asAddNode (sp+'ItemExists','Execute',node_name='IEinv')
RigVMController.set_node_position (IEinv, [-1700, PreviousYInv+700])
RigVMController.set_pin_default_value('IEinv.Item.Type','Control')
RigVMController.add_link('NCinv.Result' , 'IEinv.Item.Name')
BRinv = RigVMController.add_branch_node(node_name='BRinv')
RigVMController.set_node_position (BRinv, [-1650, PreviousYInv+850])
RigVMController.add_link('IEinv.Exists' , 'BRinv.Condition')
RigVMController.add_link('CLinv.ExecuteContext' , 'BRinv.ExecuteContext')
STinv = asAddNode (sp+'SetTransform','Execute',node_name='STinv')
RigVMController.set_node_position (STinv, [-1500, PreviousYInv+1000])
RigVMController.set_pin_default_value('STinv.Item.Type','Control')
RigVMController.add_link('NCinv.Result' , 'STinv.Item.Name')
RigVMController.add_link('GTinv.Transform' , 'STinv.Transform')
RigVMController.add_link('BRinv.True' , 'STinv.ExecuteContext')
def main ():
global PreviousEndPlugInv
RigElementKeys = asGetRigElementKeys ()
RigVMGraph = blueprint.model
#Clear out existing rig-setup
nodes = RigVMGraph.get_nodes()
for node in nodes:
RigVMController.remove_node(node)
#Clear out existing controllers
for key in RigElementKeys:
if key.name == 'MotionSystem':
hierarchy_controller.remove_element(key)
elif not (key.type==1 or key.type==8): #BONE
try:
hierarchy_controller.remove_element(key)
except:
pass
#UE5 does not include deleting children, so we will try to clean-up
controls = hierarchy.get_controls()
for key in controls:
hierarchy_controller.remove_element(key)
nulls = hierarchy.get_nulls()
for key in nulls:
hierarchy_controller.remove_element(key)
bones = hierarchy.get_bones()
for key in bones:
x = re.search("UnTwist", str(key.name))
if x:
hierarchy_controller.remove_element(key)
BeginExecutionNode = asAddNode (sp+'BeginExecution','Execute',node_name='RigUnit_BeginExecution')
RigVMController.set_node_position (BeginExecutionNode, [-300, -100])
InverseExecutionNode = asAddNode (sp+'InverseExecution','Execute',node_name='RigUnit_InverseExecution')
RigVMController.set_node_position (InverseExecutionNode, [-1900, -100])
MotionSystemKey = hierarchy_controller.add_null ('MotionSystem','',unreal.Transform())
MainSystemKey = hierarchy_controller.add_null ('MainSystem',MotionSystemKey,unreal.Transform())
DrivingSystemKey = hierarchy_controller.add_null ('DrivingSystem',MotionSystemKey ,unreal.Transform())
#//-- ASControllers Starts Here --//
#//-- ASControllers Ends Here --//
asBackwardsSolveNodes()
print ("ControlRig created")
if __name__ == "__main__":
main()
|
import unreal
import urllib.request
import json
import os
import stat
def check_unreal_environment():
"""언리얼 환경에서 실행 중인지 확인"""
try:
engine_version = unreal.SystemLibrary.get_engine_version()
print(f"언리얼 엔진 버전: {engine_version}")
return True
except Exception as e:
print(f"오류: 이 스크립트는 언리얼 에디터 내에서 실행해야 합니다. {str(e)}")
return False
def get_sheet_data(sheet_id, gid):
"""구글 시트에서 데이터 가져오기"""
try:
# 새로운 URL 사용
base_url = "https://script.google.com/project/-ncYNasEA/exec"
url = f"{base_url}?sheetId={sheet_id}&gid={gid}"
print(f"요청 URL: {url}")
response = urllib.request.urlopen(url)
data = response.read().decode('utf-8')
json_data = json.loads(data)
if isinstance(json_data, list):
print(f"데이터 {len(json_data)}개 로드됨")
if len(json_data) > 0:
print(f"첫 번째 행 필드: {list(json_data[0].keys())}")
return json_data
except Exception as e:
print(f"데이터 가져오기 오류: {str(e)}")
return None
def set_file_writable(file_path):
"""파일을 쓰기 가능한 상태로 변경"""
try:
# 현재 파일 권한 가져오기
current_permissions = os.stat(file_path).st_mode
# 쓰기 권한 추가
new_permissions = current_permissions | stat.S_IWRITE
# 권한 변경
os.chmod(file_path, new_permissions)
return True
except Exception as e:
print(f"파일 권한 변경 중 에러 발생: {str(e)}")
return False
|
"""
this startup code is used to add a script editor button to the unreal tool bar.
ignore this file when using this script editor widget outside Unreal
"""
import os
import sys
import unreal
MODULE_PATH = os.path.dirname(os.path.abspath(__file__))
UPPER_PATH = os.path.join(MODULE_PATH, '../../tools')
sys.path.append(UPPER_PATH)
def create_script_editor_button():
"""
Start up script to add script editor button to tool bar
"""
section_name = 'Plugins'
se_command = (
'from unrealScriptEditor import main;'
'global editor;'
'editor = main.show()'
)
menus = unreal.ToolMenus.get()
level_menu_bar = menus.find_menu('LevelEditor.LevelEditorToolBar.PlayToolBar')
level_menu_bar.add_section(section_name=section_name, label=section_name)
entry = unreal.ToolMenuEntry(type=unreal.MultiBlockType.TOOL_BAR_BUTTON)
entry.set_label('Script Editor')
entry.set_tool_tip('Unreal Python Script Editor')
entry.set_icon('EditorStyle', 'DebugConsole.Icon')
entry.set_string_command(
type=unreal.ToolMenuStringCommandType.PYTHON,
custom_type=unreal.Name(''),
string=se_command
)
level_menu_bar.add_menu_entry(section_name, entry)
menus.refresh_all_widgets()
if __name__ == "__main__":
create_script_editor_button()
|
# -*- coding: utf-8 -*-
"""
自动重启引擎
"""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
__author__ = "timmyliang"
__email__ = "[email protected]"
__date__ = "2020-09-18 15:53:10"
import sys
import subprocess
import unreal
from ue_util import error_log, toast
editor_util = unreal.EditorLoadingAndSavingUtils()
sys_lib = unreal.SystemLibrary()
paths = unreal.Paths()
@error_log
def main():
# NOTE 保存对象
check = editor_util.save_dirty_packages_with_dialog(True, True)
if not check:
toast(u"保存失败")
return
uproject = paths.get_project_file_path()
editor = sys.executable
# NOTE 启动当前引擎
subprocess.Popen([editor, uproject, "-skipcompile"], shell=True)
# NOTE 退出引擎
sys_lib.quit_editor()
if __name__ == "__main__":
main()
|
"""
This script describes how the metadata from USD prims can be collected and manipulated on
the Unreal side, after fully importing a stage or opening one with a stage actor. Just
remember to set the desired metadata options on the stage actor itself if using one, as
it will not collect metadata by default (e.g. `stage_actor.set_collect_metadata(True)`).
In general the metadata will be collected into UsdAssetUserData objects, that will be added
to the generated assets (and components, if the import option is set).
All asset types that we generate (with the exeption of UPhysicsAssets) can contain
UsdAssetUserData objects and will receive USD metadata from their source prims when being
generated.
The metadata values will always be stringified and stored within the UsdAssetUserData as
strings, as there is no real way of storing anything close to a "dynamic type" or variant
type (like VtValues) with UPROPERTIES. Keep in mind that unreal.UsdConversionLibrary contains
functions that can help converting these values to and from strings into Unreal types (the
very last step of this script shows an example of this). These functions can be used from
Python or Editor Utility Blueprints.
"""
import os
import unreal
DESTINATION_CONTENT_PATH = r"/project/"
this_directory = os.path.dirname(os.path.realpath(__file__))
full_file_path = os.path.join(this_directory, "metadata_cube.usda")
# Setup import options
options = unreal.UsdStageImportOptions()
options.import_actors = True
options.import_geometry = True
options.import_materials = True
options.metadata_options.collect_metadata = True
options.metadata_options.collect_from_entire_subtrees = True # Collapsed assets will contain metadata from collapsed children
options.metadata_options.collect_on_components = True # Spawned components will have Asset User Data too
options.metadata_options.blocked_prefix_filters = ["customData:int"] # All metadata entries starting with "customData:int" will be blocked
options.metadata_options.invert_filters = False # When this is false, the prefix filters select stuff to block, and allows everything else.
# When this is true, the prefix filters select stuff to allow, and block everything else
# Import scene
task = unreal.AssetImportTask()
task.set_editor_property('filename', full_file_path)
task.set_editor_property('destination_path', DESTINATION_CONTENT_PATH)
task.set_editor_property('automated', True)
task.set_editor_property('options', options)
task.set_editor_property('replace_existing', True)
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
asset_tools.import_asset_tasks([task])
asset_paths = task.get_editor_property("imported_object_paths")
success = asset_paths and len(asset_paths) > 0
if not success:
exit()
# Find our imported static mesh
asset_paths = unreal.EditorAssetLibrary.list_assets(DESTINATION_CONTENT_PATH)
for asset_path in asset_paths:
asset = unreal.load_asset(asset_path)
if isinstance(asset, unreal.StaticMesh):
static_mesh = asset
break
# Get the USD asset user data from the static mesh
aud = unreal.UsdConversionLibrary.get_usd_asset_user_data(static_mesh)
# Iterate through all the collected metadata
for stage_identifier, metadata in aud.stage_identifier_to_metadata.items():
for prim_path, prim_metadata in metadata.prim_path_to_metadata.items():
for key, value in prim_metadata.metadata.items():
print(f"{stage_identifier=} {prim_path=}, {key=}, {value=}")
# Get whatever USD generated for the stage identifier
stage_identifier = list(aud.stage_identifier_to_metadata.keys())[0]
# You can omit the stage identifier and prim path if the asset user data contains exactly one entry for either
has_int_value = unreal.UsdConversionLibrary.has_metadata_field(aud, "customData:intValue")
assert(not has_int_value) # We filtered entries starting with "customData:int", so we won't get the "intValue" entry
# Get a particular metadata value directly without iterating through the structs (there are additional functions within UsdConversionLibrary)
metadata_value = unreal.UsdConversionLibrary.get_metadata_field(aud, "customData:nestedMap:someColor", stage_identifier, "/Cube")
print(metadata_value.stringified_value) # Prints "(1, 0.5, 0.3)". Note that stringified_value is always just a string, however
print(metadata_value.type_name) # Prints "float3"
# Can use the library's utility functions to unstringify stringified_value directly into UE types
vector = unreal.UsdConversionLibrary.unstringify_as_float3(metadata_value.stringified_value)
assert(isinstance(vector, unreal.Vector))
print(vector) # Prints "<Struct 'Vector' (0x0000026B026371A0) {x: 1.000000, y: 0.500000, z: 0.300000}>"
|
# 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()
|
import unreal
from Lib import __lib_topaz__ as topaz
import importlib
importlib.reload(topaz)
actors = topaz.get_selected_level_actors()
for actor in actors :
components = actor.get_components_by_class(unreal.StaticMeshComponent)
for component in components :
asset = component.static_mesh
topaz.disable_ray_tracing(asset)
print(str(asset) + ' : ray tracing disabled')
#disalbe Ray Trace in LevelInstance powered by topaz
|
# 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)
|
import unreal_uiutils
import unreal_utils
import unreal
def extend_editor_example():
# declare menu entry
me_reloadbutton = unreal_uiutils.create_python_tool_menu_entry(
name="ReloadScriptsBtn",
label="Reload Script",
command_string="import importlib; import unreal_startup; importlib.reload(unreal_startup); unreal_startup.reload()",
)
me_quitbutton = unreal_uiutils.create_python_tool_menu_entry(
name="RestartUnrealBtn",
label="Restart Unreal",
command_string="import unreal_utils; unreal_utils.restart_editor()",
)
me_renameassetbutton = unreal_uiutils.create_python_tool_menu_entry(
name="RenameAssetBtn",
label="Rename Assets",
command_string="unreal.get_editor_subsystem(unreal.EditorUtilitySubsystem).spawn_and_register_tab(unreal.load_asset('/project/.EUW_JK_RenameTool'))",
)
# This create a button on toolboard
tb_reloadbutton = unreal_uiutils.create_toolbar_button(
name="ReloadBtn",
label="PyReload",
command_string="import importlib; import unreal_startup; importlib.reload(unreal_startup); unreal_startup.reload()",
)
# This create a drop down button on toolboard
# tb_combobutton = unreal_uiutils.create_toolbar_combo_button(
# "comboBtn", "python.tools"
# )
#TODO: Find out where it is possible to register a new context menu for combo button
# create submenu in 'File' Menu and register menu entry created above
# pythonsubmenu = unreal_uiutils.extend_mainmenu_item(
# "File", "PythonTools", "PythonTools", "Python Tools"
# )
# pythonsubmenu.add_section("python.file.menu", "Python Tools")
# pythonsubmenu.add_menu_entry("python.file.menu", me_reloadbutton)
# pythonsubmenu.add_menu_entry("python.file.menu", me_quitbutton)
# Create Standalone Menu and register menu entry created above
new_mainmenu = unreal_uiutils.extend_mainmenu("JKTools", "JKTools")
utils_section = new_mainmenu.add_section("utilities", "Utilities Tools")
new_mainmenu.add_menu_entry("utilities", me_reloadbutton)
new_mainmenu.add_menu_entry("utilities", me_quitbutton)
asset_tools = new_mainmenu.add_section("assettools", "Asset Tools")
new_mainmenu.add_menu_entry("assettools", me_renameassetbutton)
# Extend Asset Context Menu
sub_asset_context_menu = unreal_uiutils.extend_toolmenu(unreal_uiutils.get_asset_context_menu(), "JKAssetContextMenu", "JK Asset Actions")
sub_asset_context_menu.add_section("jk.assetmenu", "Tools")
sub_asset_context_menu.add_menu_entry("python.assetmenu", me_renameassetbutton)
# Extend Actor Context Menu
# actor_context_menu = unreal_uiutils.get_actor_context_menu()
# actor_context_menu.add_section("jk.actoractions", "Tools")
# sub_actor_context_menu = actor_context_menu.add_sub_menu(actor_context_menu.menu_name, "jk.actoractions", "JKActorContextMenu", "JK Actor Actions")
# sub_actor_context_menu.add_section("jk.actormenu", "Tools")
# action_sampleactorprint = unreal_uiutils.create_python_tool_menu_entry(
# name="SampleActorTool",
# label="Print Selected Actor",
# command_string='print(LevelLibrary.get_selected_level_actors())',
# )
# sub_actor_context_menu.add_menu_entry("jk.actormenu", action_sampleactorprint)
# actor_context_menu.add_menu_entry("python.actoractions", action_sampleactorprint)
# AssetRegistryPostLoad.register_callback(extend_editor)
def extend_editor():
# declare menu entry
me_reloadbutton = unreal_uiutils.create_python_tool_menu_entry(
name="ReloadScriptsBtn",
label="重载脚本",
command_string="import importlib; import unreal_startup; importlib.reload(unreal_startup); unreal_startup.reload()",
)
#创建独立菜单并注册上面创建的菜单项
new_mainmenu = unreal_uiutils.extend_mainmenu("LcLTools", "LcL Tools")
utils_section = new_mainmenu.add_section("reload", "Reload Tools")
new_mainmenu.add_menu_entry("reload", me_reloadbutton)
# =========================================工具栏 按钮======================================================
# This create a button on toolboard
unreal_uiutils.create_toolbar_button(
name="RestartUnrealBtn",
label="RestartUE",
tool_tip="重启UE编辑器",
icons = ["EditorStyle", "Cascade.RestartInLevel.Small"],
command_string="import unreal_utils; unreal_utils.restart_editor()",
)
unreal_uiutils.create_toolbar_button(
name="ShowActor",
label="Show",
tool_tip="显示选中的Actor",
icons = ["EditorStyle", "GenericViewButton"],
command_string="from UserInterfaces import quick_hide; quick_hide.show_select_actor()",
)
unreal_uiutils.create_toolbar_button(
name="HideActor",
label="Hide",
tool_tip="隐藏选中的Actor",
icons = ["EditorStyle", "Kismet.VariableList.HideForInstance"],
command_string="from UserInterfaces import quick_hide; quick_hide.hide_select_actor()",
)
# 菜单
# me_test = unreal_uiutils.create_python_tool_menu_entry(
# name="TestBtn",
# label="Test",
# command_string="from UserInterfaces import quick_hide; quick_hide.hide_select_actor()",
# )
# new_mainmenu.add_menu_entry("utilities", me_test)
extend_editor()
|
def update_meta_human_face(asset_path: str, dna_file_path: str, head_material_name: str, face_control_rig_asset_path: str, face_anim_bp_asset_path: str, blueprint_asset_path: str, unreal_level_sequence_asset_path: str, copy_assets: bool, material_slot_to_instance_mapping: dict): # type: ignore
import unreal
from pathlib import Path
from meta_human_dna_utilities.ingest import import_dna_file
from meta_human_dna_utilities.skeletal_mesh import set_head_mesh_settings, get_head_mesh_assets
from meta_human_dna_utilities.blueprint import create_actor_blueprint, add_face_component_to_blueprint
from meta_human_dna_utilities.level_sequence import add_asset_to_level_sequence, create_level_sequence
# post_fix = f"_{asset_path.split('/')[-1]}"
post_fix = f""
skeletal_mesh = unreal.load_asset(asset_path)
dna_file_path: Path = Path(dna_file_path)
# load the head mesh assets
face_control_rig_asset, face_anim_bp_asset, material_instances = get_head_mesh_assets(
content_folder=asset_path.rsplit('/', 1)[0],
skeletal_mesh=skeletal_mesh,
face_control_rig_asset_path=face_control_rig_asset_path,
face_anim_bp_asset_path=face_anim_bp_asset_path,
material_slot_to_instance_mapping=material_slot_to_instance_mapping,
copy_assets=copy_assets,
post_fix=post_fix
)
# set the head mesh settings
skeletal_mesh = set_head_mesh_settings(
skeletal_mesh=skeletal_mesh,
head_material_name=head_material_name,
face_control_rig_asset=face_control_rig_asset, # type: ignore
face_anim_bp_asset=face_anim_bp_asset, # type: ignore
material_instances=material_instances,
texture_disk_folder=dna_file_path.parent / 'Maps',
texture_content_folder=F"{asset_path.rsplit('/', 1)[0]}/Textures"
)
# then import the dna file onto the head mesh
import_dna_file(
file_path=dna_file_path,
skeletal_mesh_asset_path=asset_path
)
if not blueprint_asset_path:
blueprint_asset_path = f'{asset_path}_BP'
# create the blueprint asset
blueprint = create_actor_blueprint(blueprint_asset_path)
# add the face component to the blueprint
add_face_component_to_blueprint(
blueprint=blueprint,
skeletal_mesh=skeletal_mesh
)
# if a level sequence path is provided
if unreal_level_sequence_asset_path:
level_sequence = unreal.load_asset(unreal_level_sequence_asset_path)
# if the level sequence does not exist, create it
if not level_sequence:
content_folder = '/' + '/'.join([i for i in unreal_level_sequence_asset_path.split('/')[:-1] if i])
level_sequence_name = unreal_level_sequence_asset_path.split('/')[-1]
create_level_sequence(
content_folder=content_folder,
name=level_sequence_name
)
# add the asset to the level
add_asset_to_level_sequence(
asset=blueprint,
level_sequence=level_sequence,
label=blueprint.get_name()
)
# recompile the control rig asset
face_control_rig_asset.recompile_vm() # type: ignore
def get_body_bone_transforms(blueprint_asset_path: str) -> dict:
import unreal
from meta_human_dna_utilities.blueprint import get_body_skinned_mesh_component
from meta_human_dna_utilities.skeleton import get_bone_transforms
blueprint = unreal.load_asset(blueprint_asset_path)
if blueprint:
skeletal_mesh = get_body_skinned_mesh_component(blueprint=blueprint)
return get_bone_transforms(skeletal_mesh)
return {}
|
import unreal
def load_assets(folder_path, does_hard_load):
asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
assets = asset_registry.get_assets_by_path(folder_path, recursive=True)
error_message: str
if assets is not None:
static_meshes = []
for asset_data in assets:
asset_data_class: unreal.Class = asset_data.get_class()
if not asset_data_class:
continue
class_name = asset_data_class.get_name()
is_static_mesh = class_name == 'StaticMesh'
if is_static_mesh:
if does_hard_load:
print(f"Found asset: {asset_data.package_name}")
static_meshes.append(asset_data)
error_message = f"{folder_path}의 스태틱 매시 {len(static_meshes)}개"
return error_message
else:
error_message = f"{folder_path}에서 에셋을 찾을 수 없습니다"
return error_message
folder_pathes = ["/project/", "/project/"]
error_messages = []
does_hard_load: bool
for folder_path in folder_pathes:
result = load_assets(folder_path, does_hard_load)
print(result)
error_messages.append(unreal.Name(result))
|
# coding: utf-8
import unreal
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-vrm")
parser.add_argument("-rig")
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();
## meta 取得
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
##
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)
### 全ての骨
modelBoneListAll = []
modelBoneNameList = []
for e in reversed(h_mod.get_elements()):
if (e.type != unreal.RigElementType.BONE):
h_mod.remove_element(e)
name_to_control = {"dummy_for_table" : None}
gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.2, 0.2, 0.2])
for e in h_mod.get_elements():
print(e.name)
if (e.type != unreal.RigElementType.BONE):
continue
bone = h_mod.get_bone(e)
parentName = "{}".format(bone.get_editor_property('parent_name'))
#print("parent==")
#print(parentName)
cur_parentName = parentName + "_c"
name_s = "{}".format(e.name) + "_s"
name_c = "{}".format(e.name) + "_c"
space = h_mod.add_space(name_s, parent_name=cur_parentName, space_type=unreal.RigSpaceType.CONTROL)
control = h_mod.add_control(name_c,
space_name=space.name,
gizmo_color=[0.1, 0.1, 1.0, 1.0],
)
h_mod.set_initial_global_transform(space, h_mod.get_global_transform(e))
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)
name_to_control[name_c] = cc
c = None
try:
i = list(name_to_control.keys()).index(cur_parentName)
except:
i = -1
if (i >= 0):
c = name_to_control[cur_parentName]
if (cc != None):
if ("{}".format(e.name) in meta.humanoid_bone_table.values() ):
cc.set_editor_property('gizmo_color', unreal.LinearColor(0.1, 0.1, 1.0, 1.0))
h_mod.set_control(cc)
else:
cc.set_editor_property('gizmo_color', unreal.LinearColor(1.0, 0.1, 0.1, 1.0))
h_mod.set_control(cc)
c = rig.controller
g = c.get_graph()
n = g.get_nodes()
# 配列ノード追加
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=Control' in pin.get_default_value():
collectionItem_forControl = node
if 'Type=Bone' in pin.get_default_value():
collectionItem_forBone = 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())
if (collectionItem_forBone != None):
items_forBone = collectionItem_forBone.find_pin('Items')
c.clear_array_pin(items_forBone.get_pin_path())
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)
for e in h_mod.get_elements():
print(e.name)
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)
|
# -*- coding: utf-8 -*-
import unreal
from Utilities.Utils import Singleton
class MinimalExample(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.ui_output = "InfoOutput"
self.click_count = 0
def on_button_click(self):
self.click_count += 1
self.data.set_text(self.ui_output, "Clicked {} time(s)".format(self.click_count))
|
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 26 09:26:32 2024
@author: WillQuantique
"""
import random as rd
import unreal
def create_sequence_from_selection(sequence_name, length_frames = 1, package_path = '/project/', target_camera = unreal.Object):
'''
Args:
sequence_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
'''
print("launching")
# Create the sequence asset in the desired location
sequence = unreal.AssetToolsHelpers.get_asset_tools().create_asset(
sequence_name,
package_path,
unreal.LevelSequence,
unreal.LevelSequenceFactoryNew())
print("sequence created from selection")
# 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_master_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)
# bind the camera
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
print("camerajob done")
unreal.log("Trex" + str(sequence))
return sequence
def setup_camera_actor(location=unreal.Vector(0, 0, 0), rotation=unreal.Rotator(0, 0, 0), focus = 132.0):
# adapted from https://github.com/project/.py
"""
Parameters
----------
location : Unreal vector for camera location
DESCRIPTION. The default is unreal.Vector(0, 0, 0).
rotation : Unreal rotator for camera rotation
DESCRIPTION. The default is unreal.Rotator(0, 0, 0).
focus : float, for focus distance
DESCRIPTION. The default is 132.0.
Returns
-------
camera_actor : Unreal actor
The camera set with given rotation, position and focal distance
"""
# Spawn a Camera Actor in the World
world = unreal.EditorLevelLibrary.get_editor_world()
camera_actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.CineCameraActor, location, rotation)
# set focal distance
# create an instance of camera settings and pass it properties of interest
settings = unreal.CameraFocusSettings()
settings.manual_focus_distance = focus
settings.focus_method = unreal.CameraFocusMethod.MANUAL
# pass the settings to the camera
ccc = camera_actor.get_cine_camera_component()
ccc.set_editor_property("focus_settings", settings)
return camera_actor
asset_name="sequence"+str(rd.randint(0,99999999))+str(rd.randint(0,99999999))+str(rd.randint(0,99999999))+str(rd.randint(0,99999999))
loc = unreal.Vector(260,280,150)
rot = unreal.Rotator(0,0,-90)
foc = 150.0
camera = setup_camera_actor(loc,rot,foc)
sequence = create_sequence_from_selection(asset_name,
length_frames = 1,
package_path = '/project/',
target_camera = camera)
# Load the Pose Asset and the Skeletal Mesh of the Metahuman
pose_asset_path = "/project/-03_Joy"
metahuman_skeletal_mesh_path = "/project/"
ctrl_rig_path = "/project/"
"""
rig_asset = unreal.EditorAssetLibrary.load_asset(ctrl_rig_path)
unreal.log(rig_asset)
rig = rig_asset.create_control_rig()
unreal.log(rig)
"""
#rig_class = rig.get_control_rig_class()
editor_actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
all_actors = editor_actor_subsystem.get_all_level_actors()
# for that one actor with FA007 in the name
for actor in all_actors:
if "FA007" in actor.get_name():
metahuman_actor_name = actor.get_name()
break
pose_asset = unreal.EditorAssetLibrary.load_asset(pose_asset_path)
#pose_rig = pose_asset.create_control_rig()
# Attempt to find the Metahuman actor in the scene
metahuman_actor = next((actor for actor in all_actors if actor.get_name() == metahuman_actor_name), None)
if not metahuman_actor:
print("Failed to find the Metahuman actor named:", metahuman_actor_name)
#unreal.log(sequence)
mh_binding = sequence.add_possessable(metahuman_actor)
levelSequence = unreal.LevelSequenceEditorBlueprintLibrary.get_current_level_sequence()
# Get face rigs
faceRigs = []
rigProxies = unreal.ControlRigSequencerLibrary.get_control_rigs(levelSequence)
for rigProxy in rigProxies:
rig = rigProxy.control_rig
if rig.get_name() == 'Face_ControlBoard_CtrlRig':
print("Face found")
faceRigs.append(rig)
"""
for pose in pose_asset.pose.copy_of_controls:
if pose.name == "CTRL_L_mouth_dimple":
unreal.log(pose.name)
unreal.log(pose.control_type)
unreal.log(pose.local_transform)
unreal.log(pose.global_transform )
unreal.log(pose.offset_transform)
unreal.log(pose.parent_key)
unreal.log(pose.parent_transform)
"""
pose = pose_asset.pose.copy_of_controls[0]
loc_trans = unreal.Transform
loc_trans.rotation = pose.local_transform.rotation
unreal.ControlRigSequencerLibrary.set_local_control_rig_transform(sequence, faceRigs[0], pose.name,unreal.FrameNumber(0), loc_trans)
# Find the Metahuman actor in the scene
for pose in pose_asset.pose.copy_of_controls:
unreal.log(pose.name)
unreal.log(pose.local_transform.rotation)
unreal.ControlRigSequencerLibrary.set_local_control_rig_transform(sequence, faceRigs[0], pose.name,unreal.FrameNumber(0), pose.local_transform)
if not pose_asset:
print("Failed to load the Pose Asset from path:", pose_asset_path)
# finally create the rig track
#rig_track = unreal.ControlRigSequencerLibrary.find_or_create_control_rig_track(world,sequence, rig_class, mh_binding)
controls = pose_asset.get_control_names()
for control in controls:
rig.select_control(control)
if rig.current_control_selection():
unreal.log(rig.current_control_selection())
pose_asset.paste_pose(rig)
#unreal.log(unreal.ControlRigSequencerLibrary().get_local_control_rig_float(sequence, rig, controls[0], unreal.FrameNumber(1),time_unit=unreal.SequenceTimeUnit.DISPLAY_RATE))
|
from webbrowser import get
from pkg_resources import normalize_path
import unreal
from pathlib import Path
from CommonFunctions import get_asset_dir
# selected_assets = unreal.EditorUtilityLibrary.get_selected_assets()
# selected_folders = unreal.EditorUtilityLibrary.get_selected_folder_paths()
string_lib = unreal.StringLibrary()
editor_lib = unreal.EditorUtilityLibrary
def get_selected_dir():
selected_assets = editor_lib .get_selected_assets()
selected_folders_path = editor_lib .get_selected_folder_paths()
if len(selected_assets) != 0:
asset = selected_assets[0]
asset_dir_path = get_asset_dir(asset)
elif len(selected_folders_path) != 0:
folder_path = selected_folders_path[0]
asset_dir_path = string_lib.split(folder_path,"/All")[1]
else:
asset_dir_path = editor_lib .get_current_content_browser_path()
return asset_dir_path
print(get_selected_dir())
# dir_name = unreal.Paths.normalize_directory_name
# relative_path = unreal.Paths.make_path_relative_to
# get_dir = unreal.Paths.get_path
# string_lib = unreal.StringLibrary()
# def get_asset_path(asset):
# """资产完整路径,剔除资产本身文件名"""
# asset_path_name = asset.get_path_name()
# asset_dir = str(Path(asset_path_name).parent)
# asset_dirx = dir_name(asset_dir)
# print(asset_path_name)
# print(asset_dir)
# print(asset_dirx)
# print("getdir:" + get_dir(asset_path_name))
# gg=get_asset_dir(selected_asset[0])
# print(gg)
# mesh_dir_input = "/Meshes/"
# print("aa" + dir_name(mesh_dir_input))
# unreal python select a folder and get the path of the folder
|
import sys
import unreal
import os
# Get the Unreal project directory
project_dir = unreal.SystemLibrary.get_project_directory()
# Build the path to your tools folder relative to the project directory
tools_path = os.path.join(project_dir, "Python")
# Add to sys.path if not already present
if tools_path not in sys.path:
sys.path.append(tools_path)
import custom_import_unreal
unreal.log(f"Tools Path: {tools_path}")
|
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 26 09:43:45 2024
@author: WillQuantique
"""
import unreal
# Access the Editor Actor Utilities Subsystem
editor_actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
# Get all actors in the scene
all_actors = editor_actor_subsystem.get_all_level_actors()
# Assuming Metahumans have a unique naming or tagging convention, you could filter by name or tag
# For this example, the script lists all actors without specific filtering
for actor in all_actors:
print(actor.get_name())
|
import unreal
import os
import time
import uuid
import shutil
from pathlib import Path
"""
纹理通道迁移工具 (Texture Channel Transfer Tool)
版本: 1.0
功能说明:
本脚本用于将一组M(Mask)纹理的蓝色通道(B)自动迁移到对应D(Diffuse/Albedo)纹理的Alpha通道(A)中。
主要用于批量处理材质纹理,简化美术工作流程,优化纹理通道的使用。
具体功能:
1. 自动识别同一目录下的配对M和D纹理(基于命名规则: 基础名称+"_m"和"_d")
2. 将M纹理中的B通道提取并替换到D纹理的Alpha通道
3. 保留原始D纹理的所有重要设置(压缩方式、MipMap设置、寻址模式等)
4. 维护所有对D纹理的引用关系(如材质中的引用),确保修改后引用不丢失
使用方法:
1. 在内容浏览器中选择包含M和D纹理对的目标文件夹
2. 运行此脚本
3. 脚本将自动处理选中文件夹中的所有匹配纹理对
注意事项:
- 需要PIL库支持(如未安装,请在UE的Python环境中运行: pip install pillow)
- 脚本会临时将纹理导出到项目Temp目录中进行处理,完成后会自动清理
- 处理过程不会修改原始M纹理,仅修改D纹理的Alpha通道
"""
def process_textures():
# 获取当前在内容浏览器中选择的文件夹
selected_folders = unreal.EditorUtilityLibrary.get_selected_folder_paths()
if not selected_folders or len(selected_folders) == 0:
unreal.log_warning("请先在内容浏览器中选择一个文件夹,然后再运行此脚本")
return
selected_path = selected_folders[0]
selected_path = selected_path.replace("/All", "")
unreal.log_warning(f"处理目录: {selected_path}")
# 获取所有Texture2D资产
assets = unreal.PythonBPLib.get_assets_data_by_class(
paths_folders=[selected_path],
class_names=["Texture2D"],
)
unreal.log_warning(f"在目录 {selected_path} 中找到 {len(assets)} 个纹理资产")
# 将获取的资产整理到字典中
texture_assets = {}
for asset in assets:
asset_name = str(asset.asset_name)
package_path = str(asset.package_path)
package_name = str(asset.package_name)
texture_assets[asset_name] = (package_path, package_name)
# unreal.log(f"资产: {asset_name}, 路径: {package_name}")
# 建立_m和_d纹理的映射关系
m_textures = {}
d_textures = {}
for texture_name, (package_path, package_name) in texture_assets.items():
if "_m" in texture_name:
base_name = texture_name.split("_m")[0]
m_textures[base_name] = (texture_name, package_path, package_name)
elif "_d" in texture_name:
base_name = texture_name.split("_d")[0]
d_textures[base_name] = (texture_name, package_path, package_name)
unreal.log_warning(f"找到 {len(m_textures)} 个_m纹理和 {len(d_textures)} 个_d纹理")
# 创建临时目录 - 使用UE项目临时目录而不是系统临时目录
project_dir = unreal.Paths.project_dir()
temp_base_dir = os.path.join(project_dir, "Temp")
temp_dir = os.path.join(temp_base_dir, f"TextureProcess_{uuid.uuid4().hex}")
# 确保目录存在
try:
os.makedirs(temp_dir, exist_ok=True)
unreal.log(f"创建临时目录: {temp_dir}")
except Exception as e:
unreal.log_error(f"无法创建临时目录: {e}")
return
# 检查并处理纹理对
processed_count = 0
# 准备批量导出
texture_pairs = []
for base_name in m_textures:
if base_name in d_textures:
m_texture_name, m_package_path, m_package_name = m_textures[base_name]
d_texture_name, d_package_path, d_package_name = d_textures[base_name]
# unreal.log(f"准备处理纹理对: {base_name}")
# unreal.log(f"M纹理: {m_texture_name}, 路径: {m_package_name}")
# unreal.log(f"D纹理: {d_texture_name}, 路径: {d_package_name}")
# 记录纹理对,便于后续处理
texture_pairs.append((
base_name,
m_texture_name, m_package_path, m_package_name,
d_texture_name, d_package_path, d_package_name
))
try:
# 获取AssetTools实例
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
# 创建两个导出目录
m_export_dir = os.path.join(temp_dir, "m_textures")
d_export_dir = os.path.join(temp_dir, "d_textures")
os.makedirs(m_export_dir, exist_ok=True)
os.makedirs(d_export_dir, exist_ok=True)
# 处理每一对纹理
for (base_name, m_texture_name, m_package_path, m_package_name,
d_texture_name, d_package_path, d_package_name) in texture_pairs:
try:
unreal.log(f"处理纹理对: {base_name}")
# 获取原始D纹理资产以保存其设置
d_asset = unreal.EditorAssetLibrary.load_asset(d_package_name)
if not d_asset:
unreal.log_error(f"无法加载D纹理资产: {d_package_name}")
continue
# 保存原始D纹理的所有重要设置
d_texture_settings = {
# 基本设置组
"compression_settings": d_asset.get_editor_property("compression_settings"),
"srgb": d_asset.get_editor_property("srgb"),
"filter": d_asset.get_editor_property("filter"),
"mip_gen_settings": d_asset.get_editor_property("mip_gen_settings"),
# 纹理寻址设置
"address_x": d_asset.get_editor_property("address_x") if hasattr(d_asset, "address_x") else None,
"address_y": d_asset.get_editor_property("address_y") if hasattr(d_asset, "address_y") else None,
# LOD和流送设置
"lod_bias": d_asset.get_editor_property("lod_bias") if hasattr(d_asset, "lod_bias") else None,
"lod_group": d_asset.get_editor_property("lod_group") if hasattr(d_asset, "lod_group") else None,
"never_stream": d_asset.get_editor_property("never_stream") if hasattr(d_asset, "never_stream") else None,
# 压缩和质量设置
"compression_quality": d_asset.get_editor_property("compression_quality") if hasattr(d_asset, "compression_quality") else None,
"compression_no_alpha": d_asset.get_editor_property("compression_no_alpha") if hasattr(d_asset, "compression_no_alpha") else None,
"defer_compression": d_asset.get_editor_property("defer_compression") if hasattr(d_asset, "defer_compression") else None,
"lossy_compression_amount": d_asset.get_editor_property("lossy_compression_amount") if hasattr(d_asset, "lossy_compression_amount") else None,
# Mip和缩放设置
"power_of_two_mode": d_asset.get_editor_property("power_of_two_mode") if hasattr(d_asset, "power_of_two_mode") else None,
"max_texture_size": d_asset.get_editor_property("max_texture_size") if hasattr(d_asset, "max_texture_size") else None,
"downscale": d_asset.get_editor_property("downscale") if hasattr(d_asset, "downscale") else None,
# 颜色和通道设置
"flip_green_channel": d_asset.get_editor_property("flip_green_channel") if hasattr(d_asset, "flip_green_channel") else None,
"use_legacy_gamma": d_asset.get_editor_property("use_legacy_gamma") if hasattr(d_asset, "use_legacy_gamma") else None,
"chroma_key_texture": d_asset.get_editor_property("chroma_key_texture") if hasattr(d_asset, "chroma_key_texture") else None,
# 虚拟纹理设置
"virtual_texture_streaming": d_asset.get_editor_property("virtual_texture_streaming") if hasattr(d_asset, "virtual_texture_streaming") else None,
}
# 提取包路径的最后部分作为资产名称
m_asset_filename = os.path.basename(m_package_name)
d_asset_filename = os.path.basename(d_package_name)
# 导出M纹理和D纹理
asset_tools.export_assets([m_package_name], m_export_dir)
asset_tools.export_assets([d_package_name], d_export_dir)
# 等待文件确实被写入磁盘
time.sleep(0.5)
# 寻找M纹理和D纹理的导出文件
m_export_path = None
d_export_path = None
# 递归寻找导出的文件
for root, dirs, files in os.walk(m_export_dir):
for file in files:
if m_asset_filename in file:
m_export_path = os.path.join(root, file)
break
if m_export_path:
break
for root, dirs, files in os.walk(d_export_dir):
for file in files:
if d_asset_filename in file:
d_export_path = os.path.join(root, file)
break
if d_export_path:
break
if m_export_path is None or d_export_path is None:
unreal.log_error(f"无法找到导出的纹理文件: M={m_export_path}, D={d_export_path}")
continue
# unreal.log(f"找到M纹理文件: {m_export_path}")
# unreal.log(f"找到D纹理文件: {d_export_path}")
# 调用Python图像处理库来修改纹理
try:
from PIL import Image
# 打开两个图像(增加重试机制)
retry_count = 0
m_img = None
d_img = None
while retry_count < 5:
try:
m_img = Image.open(m_export_path)
d_img = Image.open(d_export_path)
break
except Exception as e:
retry_count += 1
unreal.log_warning(f"尝试打开图像时遇到错误,重试 {retry_count}/5: {str(e)}")
time.sleep(1)
if m_img is None or d_img is None:
unreal.log_error("无法打开导出的图像文件")
continue
# 检查图像模式并转换为RGBA
m_img = m_img.convert("RGBA")
d_img = d_img.convert("RGBA")
# 记录尺寸,用于调试
m_size = m_img.size
d_size = d_img.size
# 检查尺寸是否匹配,如果不匹配则调整M纹理大小
if m_size != d_size:
# unreal.log_warning(f"纹理尺寸不匹配! M: {m_size}, D: {d_size},正在调整M纹理尺寸...")
m_img = m_img.resize(d_size, Image.Resampling.LANCZOS)
# 拆分通道
m_r, m_g, m_b, m_a = m_img.split()
d_r, d_g, d_b, d_a = d_img.split()
# 再次检查通道尺寸是否匹配
if m_b.size != d_r.size:
# unreal.log_warning(f"通道尺寸仍不匹配! M蓝通道: {m_b.size}, D红通道: {d_r.size},正在调整通道尺寸...")
m_b = m_b.resize(d_r.size, Image.Resampling.LANCZOS)
# 检查B通道是否所有像素都是白色
import numpy as np
m_b_array = np.array(m_b)
if np.all(m_b_array == 255):
unreal.log_warning(f"---跳过复制通道:{base_name} 的B通道所有像素都是255(白色)")
continue
unreal.log_warning(f"===正在处理纹理对: {base_name} (M: {m_texture_name}, D: {d_texture_name})")
# 将M纹理的B通道用作D纹理的A通道
new_dimg = Image.merge("RGBA", (d_r, d_g, d_b, m_b))
# 直接覆盖原始D纹理文件
# 先保存到一个临时文件
temp_output_path = os.path.splitext(d_export_path)[0] + "_temp.tga"
new_dimg.save(temp_output_path, format="TGA")
# 确认文件已经写入磁盘
retry_count = 0
while not os.path.exists(temp_output_path) and retry_count < 5:
time.sleep(0.5)
retry_count += 1
if not os.path.exists(temp_output_path):
unreal.log_error(f"无法保存修改后的纹理: {temp_output_path}")
continue
# 删除原始D纹理文件,然后将临时文件重命名为原始文件名
try:
if os.path.exists(d_export_path):
os.remove(d_export_path)
os.rename(temp_output_path, d_export_path)
# unreal.log_warning(f"成功覆盖原始D纹理文件: {d_export_path}")
except Exception as e:
unreal.log_error(f"覆盖原始文件时出错: {str(e)}")
continue
# 导入纹理
imported_asset = unreal.AssetImportTask()
imported_asset.filename = d_export_path
imported_asset.destination_path = d_package_path
imported_asset.destination_name = d_asset_filename
imported_asset.replace_existing = True
imported_asset.save = True
imported_asset.automated = True
asset_tools.import_asset_tasks([imported_asset])
# 获取新导入的资产
new_dasset = unreal.EditorAssetLibrary.load_asset(d_package_name)
if not new_dasset:
unreal.log_error(f"导入后无法加载D纹理资产: {d_package_name}")
continue
# 应用原始设置到新纹理
# unreal.log(f"应用原始纹理设置到新导入的纹理")
# 应用所有保存的设置到新纹理
for prop_name, prop_value in d_texture_settings.items():
if prop_value is not None:
try:
new_dasset.set_editor_property(prop_name, prop_value)
except Exception as e:
unreal.log_warning(f"无法设置属性 {prop_name}: {str(e)}")
# 保存资产
unreal.EditorAssetLibrary.save_loaded_asset(new_dasset)
unreal.log(f"成功将修改后的纹理导入回引擎,覆盖了: {d_package_name}")
unreal.log(f"保留了原始纹理的所有重要设置")
processed_count += 1
except ImportError as ie:
unreal.log_error(f"缺少PIL库: {str(ie)}")
unreal.log_error("请先在UE的Python环境中安装PIL: pip install pillow")
except Exception as e:
unreal.log_error(f"处理图像时发生错误: {str(e)}")
import traceback
unreal.log_error(traceback.format_exc())
except Exception as e:
unreal.log_error(f"处理贴图 {base_name} 时发生错误: {str(e)}")
import traceback
unreal.log_error(traceback.format_exc())
except Exception as e:
unreal.log_error(f"导出资产时发生错误: {str(e)}")
import traceback
unreal.log_error(traceback.format_exc())
# 清理临时文件
try:
shutil.rmtree(temp_dir, ignore_errors=True)
unreal.log(f"已尝试清理临时目录: {temp_dir}")
except Exception as e:
unreal.log_warning(f"清理临时文件时发生错误: {e}")
unreal.log(f"处理完成! 共处理了 {processed_count} 对纹理。")
# 直接执行函数
process_textures()
|
import unreal
def get_selected_content_browser_assets():
editor_utility = unreal.EditorUtilityLibrary()
selected_assets = editor_utility.get_selected_assets()
return selected_assets
def log_asset_types(assets):
for asset in assets:
unreal.log(f"Asset Name: {asset.get_name()} is a {type(asset)}")
def find_material_in_assets(assets):
for asset in assets:
if type(asset) is unreal.Material:
return asset
return None
def find_textures2D_in_assets(assets):
textures = []
for asset in assets:
if type(asset) is unreal.Texture2D:
textures.append(asset)
return textures
def get_random_color():
return unreal.LinearColor(unreal.MathLibrary.rand_range(0, 1), unreal.MathLibrary.rand_range(0, 1), unreal.MathLibrary.rand_range(0, 1))
def get_random_bright_color():
return unreal.LinearColor(unreal.MathLibrary.rand_range(0.5, 1), unreal.MathLibrary.rand_range(0.5, 1), unreal.MathLibrary.rand_range(0.5, 1))
def create_material_instance(parent_material, asset_path, new_asset_name):
# Create the child material
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
material_factory = unreal.MaterialInstanceConstantFactoryNew()
new_asset = asset_tools.create_asset(new_asset_name, asset_path, None, material_factory)
# Assign its parent
unreal.MaterialEditingLibrary.set_material_instance_parent(new_asset, parent_material)
return new_asset
def create_material_instances_for_texture(parent_material, instance_name, texture, color):
unreal.log(f"Creating material instance for texture: {texture.get_name()}")
material_asset_path = unreal.Paths.get_path(texture.get_path_name())
material_instance = create_material_instance(parent_material, material_asset_path, instance_name)
# Assign the texture
unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value(material_instance, "MainTex", texture)
# Assign a random color
unreal.MaterialEditingLibrary.set_material_instance_vector_parameter_value(material_instance, "Color", color)
# Save the asset
unreal.EditorAssetLibrary.save_asset(material_instance.get_path_name(), only_if_is_dirty=True)
return material_instance
def create_material_instances_for_each_texture(material, textures):
material_instances = []
for texture in textures:
material_name = f"{material.get_name()}_{texture.get_name()}"
material_instance = create_material_instances_for_texture(material, material_name, texture, get_random_bright_color())
material_instances.append(material_instance)
return material_instances
def create_material_instances_variations(parent_material, textures):
material_instances = []
for texture in textures:
variation_count = 10
for i in range(variation_count):
material_name = f"{parent_material.get_name()}_{texture.get_name()}_{i}"
material_instance = create_material_instances_for_texture(parent_material, material_name, texture, get_random_color())
material_instances.append(material_instance)
return material_instances
def run():
unreal.log("Running create material instances script")
selected_assets = get_selected_content_browser_assets()
log_asset_types(selected_assets)
material = find_material_in_assets(selected_assets)
textures = find_textures2D_in_assets(selected_assets)
if not material:
unreal.log_error("No material selected")
return
if not textures:
unreal.log_error("No textures selected")
return
unreal.log(f"Selected material: {material.get_name()}")
unreal.log(f"{len(textures)} textures selected")
material_instances = create_material_instances_variations(material, textures)
# # Open the editor for these new material instance
# asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
# asset_tools.open_editor_for_assets((material_instances))
run()
|
import unreal
# 삭제할 블루프린트 액터의 경로
blueprint_path = '/project/.BP_RefBall'
# 삭제할 액터 클래스의 레퍼런스 얻기
actor_class_ref = unreal.EditorAssetLibrary.load_blueprint_class(blueprint_path)
# 레벨의 모든 액터를 가져오기
actors = unreal.EditorLevelLibrary.get_all_level_actors()
# 액터들을 반복 처리하며, 특정 액터 찾기
for actor in actors:
# 액터의 클래스를 가져옴
actor_class = actor.get_class()
# 액터의 클래스와 삭제할 블루프린트의 클래스가 일치하는지 확인
if actor_class == actor_class_ref:
# 액터 파괴
unreal.EditorLevelLibrary.destroy_actor(actor)
print("All BP_RefBall actors destroyed.")
|
# 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 ##
|
# 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)
|
import unreal
# 현재 레벨에 있는 모든 액터 가져오기
actors = unreal.EditorLevelLibrary.get_all_level_actors()
for actor in actors:
print(f"Actor found: {actor.get_name()}")
|
# 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
|
# -*- coding: utf-8 -*-
"""
Documentation:
"""
import unreal
import socket
import traceback
from threading import Thread
from queue import Queue
class Timer():
handle = None
def __init__(self, fn, delay=0.0, repeat=False):
self.fn = fn
self.delay = delay
self.repeat = repeat
self.passed = 0.0
self.handle = unreal.register_slate_post_tick_callback(self.tick)
def stop(self):
self.fn = None
if not self.handle:
return
unreal.unregister_slate_post_tick_callback(self.handle)
self.handle = None
def tick(self, delta_time):
if not self.fn:
self.stop()
return
self.passed += delta_time
if self.passed < self.delay:
return
try:
self.fn()
except:
print(traceback.format_exc())
if self.repeat:
self.passed = 0.0
else:
self.stop()
class UnrealSocket():
Instance = []
def __init__(self, host='172.0.0.1', port=55100):
self.__class__.Instance.append(self)
self.host = host
self.port = port
self.live = False
self.queue = Queue()
def start(self):
if self.live:
raise RuntimeError
self.live = True
try:
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.bind((self.host, self.port))
self._socket.listen(1)
except Exception as e:
print(f'Socket error: {(self.host, self.port)}', e)
print(traceback.format_exc())
return
self._thread = Thread(target=self.receive)
self._thread.start()
self._timer = Timer(self.execute, delay=0.3, repeat=True, )
def stop(self):
self.live = False
self._timer.stop()
self._socket.close()
def receive(self):
while self.live:
conn, address = self._socket.accept()
while self.live:
data = conn.recv(4096)
if data:
self.queue.put(data)
# exec(data.decode())
else:
break
def execute(self):
syslib = unreal.SystemLibrary()
if not self.live:
return self._timer.stop()
if not self.queue.qsize():
return
data = self.queue.get_nowait()
cmd = data.decode()
# syslib.print_string(None, string=cmd, print_to_screen=True, print_to_log=True,
# text_color=[255.0, 255.0, 0.0, 255.0], duration=2.0)
syslib.execute_console_command(None, cmd)
def __del__(self):
self.live = False
self._timer.stop()
self._socket.shutdown(socket.SHUT_RDWR)
self._socket.close()
def listen(host="127.0.0.1", port=55100):
prev = getattr(unreal, "udp_2_cmd_listener", None)
if prev:
prev.__del__()
unreal.udp_2_cmd_listener = UnrealSocket(host, port)
unreal.udp_2_cmd_listener.start()
if __name__ == '__main__':
listen()
print(__name__)
|
# coding: utf-8
import unreal
import argparse
print("VRM4U python begin")
print (__file__)
parser = argparse.ArgumentParser()
parser.add_argument("-vrm")
parser.add_argument("-rig")
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();
## meta 取得
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
##
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)
### 全ての骨
modelBoneListAll = []
modelBoneNameList = []
for e in reversed(h_mod.get_elements()):
if (e.type != unreal.RigElementType.BONE):
h_mod.remove_element(e)
name_to_control = {"dummy_for_table" : None}
gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.2, 0.2, 0.2])
for e in h_mod.get_elements():
print(e.name)
if (e.type != unreal.RigElementType.BONE):
continue
bone = h_mod.get_bone(e)
parentName = "{}".format(bone.get_editor_property('parent_name'))
#print("parent==")
#print(parentName)
cur_parentName = parentName + "_c"
name_s = "{}".format(e.name) + "_s"
name_c = "{}".format(e.name) + "_c"
space = h_mod.add_space(name_s, parent_name=cur_parentName, space_type=unreal.RigSpaceType.CONTROL)
control = h_mod.add_control(name_c,
space_name=space.name,
gizmo_color=[0.1, 0.1, 1.0, 1.0],
)
h_mod.set_initial_global_transform(space, h_mod.get_global_transform(e))
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)
name_to_control[name_c] = cc
c = None
try:
i = list(name_to_control.keys()).index(cur_parentName)
except:
i = -1
if (i >= 0):
c = name_to_control[cur_parentName]
if (cc != None):
if ("{}".format(e.name) in meta.humanoid_bone_table.values() ):
cc.set_editor_property('gizmo_color', unreal.LinearColor(0.1, 0.1, 1.0, 1.0))
h_mod.set_control(cc)
else:
cc.set_editor_property('gizmo_color', unreal.LinearColor(1.0, 0.1, 0.1, 1.0))
h_mod.set_control(cc)
c = rig.controller
g = c.get_graph()
n = g.get_nodes()
# 配列ノード追加
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=Control' in pin.get_default_value():
collectionItem_forControl = node
if 'Type=Bone' in pin.get_default_value():
collectionItem_forBone = 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())
if (collectionItem_forBone != None):
items_forBone = collectionItem_forBone.find_pin('Items')
c.clear_array_pin(items_forBone.get_pin_path())
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)
for e in h_mod.get_elements():
print(e.name)
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)
|
import unreal
from logger.base import Logger
class UnrealLogger(Logger):
def debug(self, msg: str):
unreal.log(msg)
def info(self, msg: str):
unreal.log(msg)
def warning(self, msg: str):
unreal.log_warning(msg)
def error(self, msg: str):
unreal.log_error(msg)
def critical(self, msg: str):
unreal.log_error(f"[CRITICAL] {msg}")
|
import unreal
def get_mesh_type_string(actor):
"""Returns the PRIMITIVE_* string based on the actor's static mesh."""
static_mesh_component = actor.get_component_by_class(unreal.StaticMeshComponent)
if not static_mesh_component:
return "PRIMITIVE_NONE"
static_mesh = static_mesh_component.static_mesh
if not static_mesh:
return "PRIMITIVE_NONE"
mesh_name = static_mesh.get_name()
if "Cube" in mesh_name:
return "PRIMITIVE_CUBE"
elif "Plane" in mesh_name:
return "PRIMITIVE_PLANE"
elif "Sphere" in mesh_name:
return "PRIMITIVE_SPHERE"
elif "Cylinder" in mesh_name:
return "PRIMITIVE_CYLINDER"
# ❗ ADDED: Return PRIMITIVE_CAPSULE if the mesh is a capsule
elif "Capsule" in mesh_name:
return "PRIMITIVE_CAPSULE"
else:
return "PRIMITIVE_UNKNOWN"
def save_scene_to_level_file(file_path, actors_to_save):
"""Writes a list of actors to a .level file with correct formatting and transformations."""
with open(file_path, 'w') as file:
for actor in actors_to_save:
file.write("[GameObject]\n")
file.write(f"Name: {actor.get_actor_label()}\n")
file.write("ParentName: None\n")
location = actor.get_actor_location()
file.write(f"Position: {location.y / 100.0} {location.z / 100.0} {location.x / 100.0}\n")
rotation_rotator = actor.get_actor_rotation()
rotation_quat = rotation_rotator.quaternion()
file.write(f"Rotation: {rotation_quat.y} {rotation_quat.z} {rotation_quat.x} {rotation_quat.w}\n")
scale = actor.get_actor_scale3d()
mesh_type = get_mesh_type_string(actor)
# Note: No scale correction is applied for capsules, assuming a 1:1 mapping.
if mesh_type == "PRIMITIVE_PLANE":
scale /= 10.0
elif mesh_type == "PRIMITIVE_CYLINDER":
scale.z /= 2.0
elif mesh_type == "PRIMITIVE_CAPSULE":
scale /= 2.0
file.write(f"Scale: {scale.y} {scale.z} {scale.x}\n")
file.write(f"MeshType: {mesh_type}\n")
static_mesh_component = actor.get_component_by_class(unreal.StaticMeshComponent)
# FIXED: This is the correct method to check the physics state.
has_rigidbody = static_mesh_component.is_simulating_physics() if static_mesh_component else False
file.write(f"HasRigidbody: {str(has_rigidbody).lower()}\n\n")
unreal.log(f"Scene successfully saved to {file_path}")
# --- Main Execution ---
folder_name = "ImportedFromLevel"
all_level_actors = unreal.EditorLevelLibrary.get_all_level_actors()
actors_to_save = [actor for actor in all_level_actors if actor.get_folder_path() == folder_name]
if actors_to_save:
output_file_path = "E:/project/ Stuff/DLSU Stuff/project/.level"
save_scene_to_level_file(output_file_path, actors_to_save)
unreal.log(f"Found and saved {len(actors_to_save)} actors from folder '{folder_name}'.")
else:
unreal.log_warning(f"No actors found in the folder '{folder_name}'. Nothing to save.")
|
import unreal
import time
def set_comp_mobility(Comp, Cull):
# unreal.log("setCompMobility() : " + Comp.static_mesh.get_name())
current_actor = unreal.EditorLevelLibrary.get_selected_level_actors()[0]
comps = current_actor.get_components_by_class(unreal.InstancedStaticMeshComponent)
for c in comps:
if c.static_mesh.get_name() == Comp.static_mesh.get_name():
c.set_cull_distances(Cull[0], Cull[1])
c.set_collision_profile_name("NoCollision")
c.set_editor_property('mobility', unreal.ComponentMobility.STATIC)
def set_decal_properties(Comp, Cull, inVirtualTexture=None, sort=90):
# unreal.log("setDecalProperties() : " + Comp.static_mesh.get_name())
current_actor = unreal.EditorLevelLibrary.get_selected_level_actors()[0]
comps = current_actor.get_components_by_class(unreal.InstancedStaticMeshComponent)
for c in comps:
if c.static_mesh.get_name() == Comp.static_mesh.get_name():
c.set_editor_property('mobility', unreal.ComponentMobility.STATIC)
current_actor = unreal.EditorLevelLibrary.get_selected_level_actors()[0]
comps = current_actor.get_components_by_class(unreal.InstancedStaticMeshComponent)
for c in comps:
if c.static_mesh.get_name() == Comp.static_mesh.get_name():
c.set_editor_property('translucency_sort_priority', sort)
current_actor = unreal.EditorLevelLibrary.get_selected_level_actors()[0]
comps = current_actor.get_components_by_class(unreal.InstancedStaticMeshComponent)
for c in comps:
if c.static_mesh.get_name() == Comp.static_mesh.get_name():
c.set_collision_profile_name("NoCollision")
c.set_cull_distances(Cull[0], Cull[1])
c.set_editor_property('runtime_virtual_textures', inVirtualTexture)
# Comp.set_cull_distances(505.0, 1100.0)
# set tag
def get_the_foliage(content):
result = []
for col in content:
if col != "":
col_elems = col[2:-2]
col_list = col_elems.split('),(')
for lis in col_list:
result.append(lis.split('\"\',bound')[0].split('.')[-1])
return result
def get_decal_name_and_sort(datatable):
roadSysDecalsTable = datatable
if datatable is None:
roadSysDecalsTable = unreal.EditorAssetLibrary.load_asset('/project/')
if isinstance(roadSysDecalsTable, unreal.DataTable):
decalMeshColumns = unreal.DataTableFunctionLibrary.get_data_table_column_as_string(roadSysDecalsTable, "DecalMesh")
sortColumns = unreal.DataTableFunctionLibrary.get_data_table_column_as_string(roadSysDecalsTable, "Sort")
FoliageColumns = unreal.DataTableFunctionLibrary.get_data_table_column_as_string(roadSysDecalsTable, "GenFoliage")
return [col.split('.')[-1][:-1] for col in decalMeshColumns], [int(sort) for sort in sortColumns], get_the_foliage(FoliageColumns)
def processing(start, end):
unreal.log("blueprint processing!")
Cull = (start, end)
# get targets
actors = unreal.EditorLevelLibrary.get_selected_level_actors()
bp = actors[0] if len(actors) > 0 else None
assets = unreal.EditorUtilityLibrary.get_selected_assets()
dt = None
if len(assets) > 0:
if isinstance(assets[0], unreal.DataTable):
dt = assets[0]
# get dt decal info and sort
decalFilter, decalSort, foliageFilter = get_decal_name_and_sort(dt)
# get virtual texture
virtualTextureVolumes = unreal.GameplayStatics.get_all_actors_of_class(unreal.EditorLevelLibrary.get_editor_world(),
unreal.RuntimeVirtualTextureVolume)
virtualTexture = [vt.virtual_texture_component.virtual_texture for vt in virtualTextureVolumes]
# processing main
if bp is not None :
if "xPCG_roadsys" in bp.get_actor_label() or 'xPCG_Roadsys' in bp.get_actor_label() :
instance_comps = bp.get_components_by_class(unreal.InstancedStaticMeshComponent)
count = 0
target = len(instance_comps)
success = True
if instance_comps:
with unreal.ScopedSlowTask(target, 'Processing Blueprint ...') as slow_task:
slow_task.make_dialog(True)
for comp in instance_comps:
if slow_task.should_cancel():
break
decal_mesh_name = comp.static_mesh.get_name()
if decal_mesh_name in decalFilter:
index = decalFilter.index(decal_mesh_name)
decal_sort = decalSort[index] if index >= 0 else 0
set_decal_properties(comp, Cull, virtualTexture, decal_sort)
elif decal_mesh_name in foliageFilter:
set_comp_mobility(comp, Cull)
else:
unreal.log_warning(" There is not a " + decal_mesh_name + " in the data table !!!")
success = False
count += 1
success_status = " successfully !" if success else "failed !"
message = "Processing " + decal_mesh_name + success_status + " " + str(count) + '/' + str(target)
slow_task.enter_progress_frame(1, message)
if not success:
time.sleep(1.0)
# Main
# instart, inend from blueprint
processing(instart, inend)
|
from application.shared.result import Result
from domain.entity.asset_data import StaticMeshAssetData
from infrastructure.utils.unreal_extensions import UnrealEditorAssetLibrary, UnrealEditorStaticMeshLibrary
import unreal
class StaticMeshService():
def __init__(self, _editorAssetLibrary: UnrealEditorAssetLibrary, _editorStaticMeshLibrary: UnrealEditorStaticMeshLibrary):
self.editorAssetLibrary = _editorAssetLibrary
self.editorStaticMeshLibrary = _editorStaticMeshLibrary
def mesh_has_no_lods(self, asset) -> Result:
staticMesheData = StaticMeshAssetData(self.editorAssetLibrary.find_asset_data(asset))
result = Result()
if staticMesheData.is_static_mesh():
_staticMeshAsset = unreal.StaticMesh.cast(staticMesheData.asset)
lod_count = self.editorStaticMeshLibrary.get_lod_count(_staticMeshAsset)
if lod_count <= 1:
result.message = (" %s ------------> At Path: %s \n" % (staticMesheData.assetName, staticMesheData.assetPathName))
return result
def mesh_with_no_collision(self, asset) -> Result:
staticMesheData = StaticMeshAssetData(self.editorAssetLibrary.find_asset_data(asset))
result = Result()
if staticMesheData.is_static_mesh():
_staticMeshAsset = unreal.StaticMesh.cast(staticMesheData.asset)
_TotalNumCollisionElements = self.editorStaticMeshLibrary.get_simple_collision_count(_staticMeshAsset) + self.editorStaticMeshLibrary.get_convex_collision_count(_staticMeshAsset)
if _TotalNumCollisionElements <= 0:
result.message = (" %s ------------> At Path: %s \n" % (staticMesheData.assetName, staticMesheData.assetPathName))
return result
def mesh_num_of_materials(self, asset, numOfMatsToCheckFor) -> Result:
staticMesheData = StaticMeshAssetData(self.editorAssetLibrary.find_asset_data(asset))
result = Result()
if staticMesheData.is_static_mesh():
_staticMeshAsset = unreal.StaticMesh.cast(staticMesheData.asset)
_howManyMaterials = self.editorStaticMeshLibrary.get_number_materials(_staticMeshAsset)
if _howManyMaterials >= numOfMatsToCheckFor:
result.message = (" %s ------------> At Path: %s \n" % (staticMesheData.assetName, staticMesheData.assetPathName))
return result
def mesh_has_multiple_uv_channels(self, asset, numOfChannelsToCheckFor) -> Result:
staticMesheData = StaticMeshAssetData(self.editorAssetLibrary.find_asset_data(asset))
result = Result()
if staticMesheData.is_static_mesh():
_staticMeshAsset = unreal.StaticMesh.cast(staticMesheData.asset)
_howManyUV_channels = self.editorStaticMeshLibrary.get_num_uv_channels(_staticMeshAsset, 0)
if _howManyUV_channels >= numOfChannelsToCheckFor:
result.message = (" %s ------------> At Path: %s \n" % (staticMesheData.assetName, staticMesheData.assetPathName))
return result
|
import re
from dataclasses import dataclass
from typing import Set
import unreal
from Common import get_component_by_class
@dataclass
class MaterialDesc:
pattern: re.Pattern
material: unreal.PhysicalMaterial
@staticmethod
def load_phys_material(name: str) -> unreal.PhysicalMaterial:
base_phys_material_dir = "/project/"
path = f"{base_phys_material_dir}/{name}"
phys_material = unreal.EditorAssetLibrary.load_asset(path)
if phys_material is None:
raise ValueError(f"Can't load asset: {path}")
# noinspection PyTypeChecker
return phys_material
@classmethod
def load(cls, pattern: str, name: str):
return cls(re.compile(pattern), MaterialDesc.load_phys_material(name))
materials = [
MaterialDesc.load(r"\w*concrete\w*", "PM_Concrete"),
MaterialDesc.load(r"\w*plaster\w*", "PM_Concrete"),
MaterialDesc.load(r"\w*glass\w*", "PM_Glass"),
MaterialDesc.load(r"\w*metal\w*", "PM_Metal"),
MaterialDesc.load(r"\w*_tin_\w*", "PM_Metal"),
MaterialDesc.load(r"\w*dirt\w*", "PM_Mud"),
MaterialDesc.load(r"\w*wood\w*", "PM_Wood"),
MaterialDesc.load(r"\w*tree\w*", "PM_Wood"),
MaterialDesc.load(r"\w*crate\w*", "PM_Wood"),
MaterialDesc.load(r"\w*brick\w*", "PM_Rock"),
MaterialDesc.load(r"\w*stone\w*", "PM_Rock"),
MaterialDesc.load(r"\w*de_dust\w*wall\w*", "PM_Rock"),
MaterialDesc.load(r"\w*de_mirage\w*wall\w*", "PM_Rock"),
MaterialDesc.load(r"\w*de_dust_sign\w*", "PM_Metal"),
MaterialDesc.load(r"\w*train_wheels\w*", "PM_Metal"),
MaterialDesc.load(r"\w*rug\w*", "PM_Mud"),
MaterialDesc.load(r"\w*window\w*", "PM_Wood"), # can be false-positive fixes
MaterialDesc.load(r"\w*cinderblock\w*", "PM_Rock"),
MaterialDesc.load(r"\w*tilewall\w*", "PM_Rock"),
]
prefixes = {"worldspawn_", "func_brush_", "func_detail_", "prop_static_"}
def is_skip_material(material: unreal.Material):
material_name = material.get_name()
return "tools_toolsblack" in material_name or \
"tools_toolsnodraw" in material_name or \
material.get_editor_property("blend_mode") == unreal.BlendMode.BLEND_TRANSLUCENT or \
material.get_editor_property("phys_material") is not None
def setup_phys_material_ex(actor: unreal.Actor, material: unreal.Material):
if is_skip_material(material):
return False
material_name = material.get_name()
for desc in materials:
if desc.pattern.match(material_name):
print(f"Setup phys material '{desc.material.get_name()}' "
f"for actor='{actor.get_name()}' "
f"material='{material.get_name()}'")
material.set_editor_property("phys_material", desc.material)
return True
raise ValueError("Can't setup material")
def setup_phys_material_actor(
actor: unreal.Actor,
changed_materials: Set[unreal.MaterialInterface],
without_material: Set[unreal.MaterialInterface]
):
try:
component = get_component_by_class(actor, unreal.StaticMeshComponent)
except KeyError:
return
# print(f"Analyze {component.static_mesh.get_name()}")
for index in range(component.get_num_materials()):
material = component.get_material(index)
assert isinstance(material, unreal.Material), \
f"Material required, not a material interface for {material.get_name()}"
try:
if setup_phys_material_ex(actor, material):
# unreal.MaterialEditingLibrary.recompile_material(material)
changed_materials.add(material)
except ValueError:
without_material.add(material)
def fix_physical_materials():
changed_materials = set()
without_material = set()
for actor in unreal.EditorLevelLibrary.get_all_level_actors():
actor_name: str = actor.get_name()
if any(prefix for prefix in prefixes if actor_name.startswith(prefix)):
setup_phys_material_actor(actor, changed_materials, without_material)
if changed_materials:
print("<============================================================>")
print("Changed materials:")
for material in changed_materials:
print(f" {material.get_name()}")
if without_material:
print("<============================================================>")
print("Material without physical materials:")
for material in without_material:
print(f" {material.get_name()}")
unreal.EditorAssetLibrary.save_loaded_assets(changed_materials, only_if_is_dirty=False)
if __name__ == '__main__':
fix_physical_materials()
|
"""
UEMCP Asset Operations - All asset and content browser operations
Enhanced with improved error handling framework to eliminate try/catch boilerplate.
"""
import os
from typing import Any, Dict, List, Optional
import unreal
from utils import asset_exists, log_error
# Enhanced error handling framework
from utils.error_handling import (
AssetPathRule,
FileExistsRule,
RequiredRule,
TypeRule,
ValidationError,
handle_unreal_errors,
require_asset,
safe_operation,
validate_inputs,
)
class AssetOperations:
"""Handles all asset-related operations."""
# Tolerance for pivot type detection (in Unreal units)
PIVOT_TOLERANCE = 0.1
# Texture compression settings mapping
COMPRESSION_MAP = {
"TC_Default": unreal.TextureCompressionSettings.TC_DEFAULT,
"TC_Normalmap": unreal.TextureCompressionSettings.TC_NORMALMAP,
"TC_Masks": unreal.TextureCompressionSettings.TC_MASKS,
"TC_Grayscale": unreal.TextureCompressionSettings.TC_GRAYSCALE,
}
def _detect_pivot_type(self, origin, box_extent):
"""Detect the pivot type based on origin position relative to bounds.
Args:
origin: The origin point of the asset
box_extent: The box extent (half-size) of the asset
Returns:
str: The detected pivot type ('center', 'bottom-center', or 'corner-bottom')
"""
tolerance = self.PIVOT_TOLERANCE
# Check if pivot is at bottom-center
if abs(origin.z + box_extent.z) < tolerance:
# Check if also at corner
if abs(origin.x + box_extent.x) < tolerance and abs(origin.y + box_extent.y) < tolerance:
return "corner-bottom"
else:
return "bottom-center"
# Default to center
return "center"
def _has_simple_collision(self, body_setup):
"""Check if a body setup has simple collision geometry.
Args:
body_setup: The body setup to check
Returns:
bool: True if simple collision exists, False otherwise
"""
if not body_setup or not hasattr(body_setup, "aggregate_geom"):
return False
aggregate_geom = body_setup.aggregate_geom
return (
len(aggregate_geom.box_elems) > 0
or len(aggregate_geom.sphere_elems) > 0
or len(aggregate_geom.convex_elems) > 0
)
@validate_inputs(
{"path": [RequiredRule(), TypeRule(str)], "assetType": [TypeRule((str, type(None)))], "limit": [TypeRule(int)]}
)
@handle_unreal_errors("list_assets")
@safe_operation("asset")
def list_assets(self, path: str = "/Game", assetType: Optional[str] = None, limit: int = 20):
"""List assets in a given path.
Args:
path: Content browser path to search
assetType: Optional filter by asset type
limit: Maximum number of assets to return
Returns:
dict: Result with asset list
"""
asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
assets = asset_registry.get_assets_by_path(path, recursive=True)
# Filter by asset type if specified
if assetType:
filtered_assets = []
for asset in assets:
asset_type_name = (
str(asset.asset_class_path.asset_name)
if hasattr(asset.asset_class_path, "asset_name")
else str(asset.asset_class_path)
)
if asset_type_name == assetType:
filtered_assets.append(asset)
assets = filtered_assets
# Build asset list with limit
asset_list = []
for i, asset in enumerate(assets):
if i >= limit:
break
asset_type_name = (
str(asset.asset_class_path.asset_name)
if hasattr(asset.asset_class_path, "asset_name")
else str(asset.asset_class_path)
)
asset_list.append({"name": str(asset.asset_name), "type": asset_type_name, "path": str(asset.package_name)})
return {"assets": asset_list, "totalCount": len(assets), "path": path}
@validate_inputs({"assetPath": [RequiredRule(), AssetPathRule()]})
@handle_unreal_errors("get_asset_info")
@safe_operation("asset")
def get_asset_info(self, assetPath: str) -> Dict[str, Any]:
"""Get detailed information about an asset.
Args:
assetPath: Path to the asset
Returns:
dict: Asset information
"""
# Load the asset using error handling framework
asset = require_asset(assetPath)
info = {"assetPath": assetPath, "assetType": asset.get_class().get_name()}
# Get bounds for static meshes
if isinstance(asset, unreal.StaticMesh):
self._add_static_mesh_info(info, asset)
# Get info for blueprints
elif isinstance(asset, unreal.Blueprint):
self._add_blueprint_info(info, asset, assetPath)
# Get info for materials
elif isinstance(asset, unreal.Material) or isinstance(asset, unreal.MaterialInstance):
self._add_material_info(info, asset)
# Get info for textures
elif isinstance(asset, unreal.Texture2D):
self._add_texture_info(info, asset)
return info
def _add_static_mesh_info(self, info: dict, asset: unreal.StaticMesh):
"""Add static mesh information to the info dict.
Args:
info: Dictionary to populate
asset: Static mesh asset
"""
bounds = asset.get_bounds()
box_extent = bounds.box_extent
origin = bounds.origin
# Calculate bounds
min_bounds = unreal.Vector(origin.x - box_extent.x, origin.y - box_extent.y, origin.z - box_extent.z)
max_bounds = unreal.Vector(origin.x + box_extent.x, origin.y + box_extent.y, origin.z + box_extent.z)
# Add basic mesh info
info.update(
{
"bounds": self._format_bounds(origin, box_extent, min_bounds, max_bounds),
"pivot": {
"type": self._detect_pivot_type(origin, box_extent),
"offset": {"x": float(origin.x), "y": float(origin.y), "z": float(origin.z)},
},
"numVertices": asset.get_num_vertices(0),
"numTriangles": asset.get_num_triangles(0),
"numMaterials": asset.get_num_sections(0),
"numLODs": asset.get_num_lods(),
}
)
# Add collision info
info["collision"] = self._get_collision_info(asset)
# Add sockets info
info["sockets"] = self._get_socket_info(asset)
# Add material slots
info["materialSlots"] = self._get_material_slots(asset)
def _format_bounds(self, origin, box_extent, min_bounds, max_bounds):
"""Format bounds information.
Args:
origin: Origin vector
box_extent: Box extent vector
min_bounds: Minimum bounds vector
max_bounds: Maximum bounds vector
Returns:
dict: Formatted bounds
"""
return {
"extent": {"x": float(box_extent.x), "y": float(box_extent.y), "z": float(box_extent.z)},
"origin": {"x": float(origin.x), "y": float(origin.y), "z": float(origin.z)},
"size": {"x": float(box_extent.x * 2), "y": float(box_extent.y * 2), "z": float(box_extent.z * 2)},
"min": {"x": float(min_bounds.x), "y": float(min_bounds.y), "z": float(min_bounds.z)},
"max": {"x": float(max_bounds.x), "y": float(max_bounds.y), "z": float(max_bounds.z)},
}
def _get_collision_info(self, asset):
"""Get collision information from a static mesh.
Args:
asset: Static mesh asset
Returns:
dict: Collision information
"""
collision_info = {"hasCollision": False, "numCollisionPrimitives": 0}
# Get collision primitive count
if hasattr(asset, "get_num_collision_primitives"):
num_primitives = asset.get_num_collision_primitives()
if num_primitives is not None:
collision_info["hasCollision"] = num_primitives > 0
collision_info["numCollisionPrimitives"] = num_primitives
# Get body setup details
body_setup = asset.get_editor_property("body_setup")
if body_setup:
if hasattr(body_setup, "collision_trace_flag"):
collision_info["collisionComplexity"] = str(body_setup.collision_trace_flag)
else:
collision_info["collisionComplexity"] = "Unknown"
collision_info["hasSimpleCollision"] = self._has_simple_collision(body_setup)
return collision_info
def _get_socket_info(self, asset):
"""Get socket information from a static mesh.
Args:
asset: Static mesh asset
Returns:
list: Socket information
"""
sockets = []
if hasattr(asset, "sockets"):
mesh_sockets = getattr(asset, "sockets", None)
if mesh_sockets:
for socket in mesh_sockets:
# Validate socket has required attributes
if (
hasattr(socket, "socket_name")
and hasattr(socket, "relative_location")
and hasattr(socket, "relative_rotation")
and hasattr(socket, "relative_scale")
):
sockets.append(
{
"name": str(socket.socket_name),
"location": {
"x": float(socket.relative_location.x),
"y": float(socket.relative_location.y),
"z": float(socket.relative_location.z),
},
"rotation": {
"roll": float(socket.relative_rotation.roll),
"pitch": float(socket.relative_rotation.pitch),
"yaw": float(socket.relative_rotation.yaw),
},
"scale": {
"x": float(socket.relative_scale.x),
"y": float(socket.relative_scale.y),
"z": float(socket.relative_scale.z),
},
}
)
return sockets
def _get_material_slots(self, asset):
"""Get material slot information from a static mesh.
Args:
asset: Static mesh asset
Returns:
list: Material slot information
"""
material_slots = []
static_materials = self._get_static_materials(asset)
if static_materials:
for i, mat_slot in enumerate(static_materials):
if mat_slot: # Validate slot exists
slot_info = {"slotIndex": i, "slotName": f"Slot_{i}"}
# Get slot name
if hasattr(mat_slot, "material_slot_name") and mat_slot.material_slot_name:
slot_info["slotName"] = str(mat_slot.material_slot_name)
# Get material path
material_path = self._get_material_path(mat_slot)
if material_path:
slot_info["materialPath"] = material_path
material_slots.append(slot_info)
return material_slots
def _get_static_materials(self, asset):
"""Get static materials from a mesh asset.
Args:
asset: Static mesh asset
Returns:
list: Static materials
"""
if hasattr(asset, "static_materials"):
return asset.static_materials
elif hasattr(asset, "get_static_mesh_materials"):
return asset.get_static_mesh_materials()
else:
# Fallback to section materials
materials = []
num_sections = asset.get_num_sections(0)
for i in range(num_sections):
mat = asset.get_material(i)
if mat:
materials.append({"material_interface": mat})
return materials
def _get_material_path(self, mat_slot):
"""Get material path from a material slot.
Args:
mat_slot: Material slot object
Returns:
str or None: Material path
"""
if hasattr(mat_slot, "material_interface") and mat_slot.material_interface:
return str(mat_slot.material_interface.get_path_name())
elif isinstance(mat_slot, dict) and "material_interface" in mat_slot:
if mat_slot["material_interface"]:
return str(mat_slot["material_interface"].get_path_name())
return None
def _add_blueprint_info(self, info: dict, asset: unreal.Blueprint, assetPath: str):
"""Add blueprint information to the info dict.
Args:
info: Dictionary to populate
asset: Blueprint asset
assetPath: Path to the asset
"""
info["blueprintType"] = "Blueprint"
info["blueprintClass"] = str(asset.generated_class().get_name()) if asset.generated_class() else None
# Get blueprint default object information
if hasattr(asset, "generated_class") and asset.generated_class():
default_object = asset.generated_class().get_default_object()
if default_object:
# Get bounds
if hasattr(default_object, "get_actor_bounds"):
bounds_result = default_object.get_actor_bounds(False)
if bounds_result and len(bounds_result) >= 2:
origin, extent = bounds_result[0], bounds_result[1]
info["bounds"] = {
"extent": {"x": float(extent.x), "y": float(extent.y), "z": float(extent.z)},
"origin": {"x": float(origin.x), "y": float(origin.y), "z": float(origin.z)},
"size": {"x": float(extent.x * 2), "y": float(extent.y * 2), "z": float(extent.z * 2)},
}
# Get components
if hasattr(default_object, "get_components"):
components = self._get_blueprint_components(default_object)
if components:
info["components"] = components
def _get_blueprint_components(self, default_object):
"""Get component information from a blueprint default object.
Args:
default_object: Blueprint default object
Returns:
list: Component information
"""
component_info = []
components = default_object.get_components()
for comp in components:
comp_data = {"name": comp.get_name(), "class": comp.get_class().get_name()}
if hasattr(comp, "static_mesh") and comp.static_mesh:
comp_data["meshPath"] = str(comp.static_mesh.get_path_name())
component_info.append(comp_data)
return component_info
def _add_material_info(self, info: dict, asset):
"""Add material information to the info dict.
Args:
info: Dictionary to populate
asset: Material asset
"""
info["materialType"] = asset.get_class().get_name()
# Could add material parameters, textures, etc.
def _add_texture_info(self, info: dict, asset: unreal.Texture2D):
"""Add texture information to the info dict.
Args:
info: Dictionary to populate
asset: Texture2D asset
"""
info.update(
{
"width": asset.blueprint_get_size_x(),
"height": asset.blueprint_get_size_y(),
"format": str(asset.get_pixel_format()),
}
)
@validate_inputs({"paths": [RequiredRule(), TypeRule(list)]})
@handle_unreal_errors("validate_asset_paths")
@safe_operation("asset")
def validate_asset_paths(self, paths: List[str]):
"""Validate multiple asset paths exist.
Args:
paths: List of asset paths to validate
Returns:
dict: Validation results for each path
"""
results = {}
for path in paths:
results[path] = asset_exists(path)
return {
"results": results,
"validCount": sum(1 for v in results.values() if v),
"invalidCount": sum(1 for v in results.values() if not v),
}
@validate_inputs(
{
"assetType": [RequiredRule(), TypeRule(str)],
"searchPath": [RequiredRule(), TypeRule(str)],
"limit": [TypeRule(int)],
}
)
@handle_unreal_errors("find_assets_by_type")
@safe_operation("asset")
def find_assets_by_type(self, assetType: str, searchPath: str = "/Game", limit: int = 50):
"""Find all assets of a specific type.
Args:
assetType: Type of asset to find (e.g., 'StaticMesh', 'Material')
searchPath: Path to search in
limit: Maximum results
Returns:
dict: List of matching assets
"""
asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
# Build filter
filter = unreal.ARFilter()
filter.package_paths = [searchPath]
filter.recursive_paths = True
if assetType == "StaticMesh":
filter.class_names = ["StaticMesh"]
elif assetType == "Material":
filter.class_names = ["Material", "MaterialInstance"]
elif assetType == "Blueprint":
filter.class_names = ["Blueprint"]
elif assetType == "Texture":
filter.class_names = ["Texture2D"]
else:
# Generic class filter
filter.class_names = [assetType]
# Get assets
assets = asset_registry.get_assets(filter)
# Build result list
asset_list = []
for i, asset in enumerate(assets):
if i >= limit:
break
asset_list.append(
{
"name": str(asset.asset_name),
"path": str(asset.package_name),
"type": (
str(asset.asset_class_path.asset_name)
if hasattr(asset.asset_class_path, "asset_name")
else str(asset.asset_class_path)
),
}
)
return {
"assets": asset_list,
"totalCount": len(assets),
"assetType": assetType,
"searchPath": searchPath,
}
@validate_inputs(
{
"sourcePath": [RequiredRule(), TypeRule(str), FileExistsRule()],
"targetFolder": [RequiredRule(), TypeRule(str)],
"assetType": [TypeRule(str)],
"batchImport": [TypeRule(bool)],
"importSettings": [TypeRule(dict, allow_none=True)],
}
)
@handle_unreal_errors("import_assets")
@safe_operation("asset")
def import_assets(
self,
sourcePath: str,
targetFolder: str = "/project/",
importSettings: dict = None,
assetType: str = "auto",
batchImport: bool = False,
) -> dict:
"""Import assets from FAB marketplace or file system into UE project.
Args:
sourcePath: Path to source asset file or folder
targetFolder: Destination folder in UE project
importSettings: Import configuration settings
assetType: Type of asset to import ('auto', 'staticMesh', 'material', 'texture', 'blueprint')
batchImport: Import entire folder with all compatible assets
Returns:
dict: Import results with statistics and asset information
"""
import time
start_time = time.time()
# Prepare import settings
settings = self._prepare_import_settings(importSettings)
# Ensure target folder exists in content browser
self._ensure_content_folder_exists(targetFolder)
# Collect files to import
files_to_import = self._collect_import_files(sourcePath, assetType, batchImport)
if not files_to_import:
raise ValidationError("No compatible files found for import")
# Process imports
import_results = self._process_imports(files_to_import, targetFolder, settings, assetType)
# Build final result
processing_time = (time.time() - start_time) * 1000 # Convert to milliseconds
return self._build_import_result(import_results, targetFolder, files_to_import, processing_time)
def _prepare_import_settings(self, importSettings):
"""Prepare import settings by merging with defaults.
Args:
importSettings: User-provided import settings
Returns:
dict: Complete import settings
"""
default_settings = {
"generateCollision": True,
"generateLODs": False,
"importMaterials": True,
"importTextures": True,
"combineMeshes": False,
"createMaterialInstances": False,
"sRGB": True,
"compressionSettings": "TC_Default",
"autoGenerateLODs": False,
"lodLevels": 3,
"overwriteExisting": False,
"preserveHierarchy": True,
}
settings = default_settings.copy()
if importSettings:
settings.update(importSettings)
return settings
def _process_imports(self, files_to_import, targetFolder, settings, assetType):
"""Process the import of multiple files.
Args:
files_to_import: List of files to import
targetFolder: Target content folder
settings: Import settings
assetType: Asset type
Returns:
dict: Categorized import results
"""
imported_assets = []
failed_assets = []
skipped_assets = []
total_size = 0
for file_path in files_to_import:
# Import single asset - errors are handled internally
result = self._import_single_asset(file_path, targetFolder, settings, assetType)
if result["status"] == "success":
imported_assets.append(result)
if result.get("size"):
total_size += result["size"]
elif result["status"] == "failed":
failed_assets.append(result)
elif result["status"] == "skipped":
skipped_assets.append(result)
return {
"imported": imported_assets,
"failed": failed_assets,
"skipped": skipped_assets,
"totalSize": total_size,
}
def _build_import_result(self, import_results, targetFolder, files_to_import, processing_time):
"""Build the final import result dictionary.
Args:
import_results: Categorized import results
targetFolder: Target content folder
files_to_import: List of files that were processed
processing_time: Time taken in milliseconds
Returns:
dict: Final formatted result
"""
return {
"success": True,
"importedAssets": import_results["imported"],
"failedAssets": import_results["failed"],
"skippedAssets": import_results["skipped"],
"statistics": {
"totalProcessed": len(files_to_import),
"successCount": len(import_results["imported"]),
"failedCount": len(import_results["failed"]),
"skippedCount": len(import_results["skipped"]),
"totalSize": import_results["totalSize"] if import_results["totalSize"] > 0 else None,
},
"targetFolder": targetFolder,
"processingTime": processing_time,
}
def _ensure_content_folder_exists(self, folder_path: str):
"""Ensure a content browser folder exists.
Args:
folder_path: Content browser path (e.g., '/project/')
"""
# Convert to content browser path format
if not folder_path.startswith("/Game"):
folder_path = f'/Game/{folder_path.lstrip("/")}'
# Note: UE will auto-create folders when we import assets
# No additional action needed
def _collect_import_files(self, source_path: str, asset_type: str, batch_import: bool) -> list:
"""Collect files to import based on source path and settings.
Args:
source_path: Source file or folder path
asset_type: Type filter for assets
batch_import: Whether to import entire folder
Returns:
list: List of file paths to import
"""
import os
# Supported file extensions by type
SUPPORTED_EXTENSIONS = {
"staticMesh": [".fbx", ".obj", ".dae", ".3ds", ".ase", ".ply"],
"material": [".mat"], # UE material files
"texture": [".png", ".jpg", ".jpeg", ".tga", ".bmp", ".tiff", ".exr", ".hdr"],
"blueprint": [".uasset"], # Blueprint files
"auto": [
".fbx",
".obj",
".dae",
".3ds",
".ase",
".ply",
".png",
".jpg",
".jpeg",
".tga",
".bmp",
".tiff",
".exr",
".hdr",
".uasset",
],
}
extensions = SUPPORTED_EXTENSIONS.get(asset_type, SUPPORTED_EXTENSIONS["auto"])
files_to_import = []
if os.path.isfile(source_path):
# Single file import
if any(source_path.lower().endswith(ext) for ext in extensions):
files_to_import.append(source_path)
elif os.path.isdir(source_path) and batch_import:
# Batch import from folder
for root, _dirs, files in os.walk(source_path):
for file in files:
if any(file.lower().endswith(ext) for ext in extensions):
files_to_import.append(os.path.join(root, file))
elif os.path.isdir(source_path):
# Single folder - only direct files
for file in os.listdir(source_path):
file_path = os.path.join(source_path, file)
if os.path.isfile(file_path) and any(file.lower().endswith(ext) for ext in extensions):
files_to_import.append(file_path)
return files_to_import
def _import_single_asset(self, file_path: str, target_folder: str, settings: dict, asset_type: str) -> dict:
"""Import a single asset file.
Args:
file_path: Path to source file
target_folder: Target content browser folder
settings: Import settings
asset_type: Asset type hint
Returns:
dict: Import result for this asset
"""
from pathlib import Path
# Validate file path exists
if not os.path.exists(file_path):
return {
"originalPath": file_path,
"targetPath": "",
"assetType": "unknown",
"status": "failed",
"error": f"Source file does not exist: {file_path}",
}
file_name = Path(file_path).stem
file_ext = Path(file_path).suffix.lower()
# Determine target path
target_path = f"{target_folder}/{file_name}"
# Check if asset already exists and handle accordingly
if not settings.get("overwriteExisting", False):
if asset_exists(target_path):
return {
"originalPath": file_path,
"targetPath": target_path,
"assetType": self._detect_asset_type_from_extension(file_ext),
"status": "skipped",
"error": "Asset already exists",
}
# Setup import task based on file type
import_task = self._create_import_task(file_path, target_folder, settings, file_ext)
if not import_task:
return {
"originalPath": file_path,
"targetPath": target_path,
"assetType": self._detect_asset_type_from_extension(file_ext),
"status": "failed",
"error": "Unsupported file type or failed to create import task",
}
# Execute import
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
imported_assets = asset_tools.import_asset_tasks([import_task])
if imported_assets and len(imported_assets) > 0:
imported_asset = imported_assets[0]
# Get asset information
asset_info = self._get_imported_asset_info(imported_asset, file_path)
return {
"originalPath": file_path,
"targetPath": imported_asset.get_path_name(),
"assetType": imported_asset.get_class().get_name(),
"status": "success",
"size": asset_info.get("size", 0),
"vertexCount": asset_info.get("vertexCount"),
"materialCount": asset_info.get("materialCount"),
}
else:
return {
"originalPath": file_path,
"targetPath": target_path,
"assetType": self._detect_asset_type_from_extension(file_ext),
"status": "failed",
"error": "Import task completed but no assets were created",
}
def _detect_asset_type_from_extension(self, file_ext: str) -> str:
"""Detect asset type from file extension.
Args:
file_ext: File extension (with dot)
Returns:
str: Asset type
"""
ext = file_ext.lower()
if ext in [".fbx", ".obj", ".dae", ".3ds", ".ase", ".ply"]:
return "StaticMesh"
elif ext in [".png", ".jpg", ".jpeg", ".tga", ".bmp", ".tiff", ".exr", ".hdr"]:
return "Texture2D"
elif ext in [".mat"]:
return "Material"
elif ext in [".uasset"]:
return "Blueprint"
else:
return "Unknown"
def _create_import_task(
self, file_path: str, target_folder: str, settings: dict, file_ext: str
) -> unreal.AssetImportTask:
"""Create an import task for the given file.
Args:
file_path: Source file path
target_folder: Target content folder
settings: Import settings
file_ext: File extension
Returns:
AssetImportTask or None if unsupported
"""
# Validate file path exists before creating task
if not os.path.exists(file_path):
log_error(f"Cannot create import task - file does not exist: {file_path}")
return None
task = self._create_base_import_task(file_path, target_folder, settings)
if not task:
log_error(f"Failed to create base import task for: {file_path}")
return None
# Configure options based on file type
if file_ext in [".fbx", ".obj", ".dae", ".3ds", ".ase", ".ply"]:
self._configure_mesh_import(task, settings)
elif file_ext in [".png", ".jpg", ".jpeg", ".tga", ".bmp", ".tiff", ".exr", ".hdr"]:
self._configure_texture_import(task, settings)
return task
def _create_base_import_task(self, file_path: str, target_folder: str, settings: dict) -> unreal.AssetImportTask:
"""Create a base import task with common settings.
Args:
file_path: Source file path
target_folder: Target content folder
settings: Import settings
Returns:
AssetImportTask with base configuration
"""
task = unreal.AssetImportTask()
task.filename = file_path
task.destination_path = target_folder
task.replace_existing = settings.get("overwriteExisting", False)
task.automated = True
task.save = True
return task
def _configure_mesh_import(self, task: unreal.AssetImportTask, settings: dict):
"""Configure import task for mesh files.
Args:
task: Import task to configure
settings: Import settings
"""
options = unreal.FbxImportUI()
# Mesh settings
options.import_mesh = True
options.import_materials = settings.get("importMaterials", True)
options.import_textures = settings.get("importTextures", True)
options.import_as_skeletal = False
# Static mesh specific settings
mesh_options = options.static_mesh_import_data
mesh_options.combine_meshes = settings.get("combineMeshes", False)
mesh_options.generate_lightmap_u_vs = True
mesh_options.auto_generate_collision = settings.get("generateCollision", True)
# LOD settings
if settings.get("generateLODs", False):
mesh_options.auto_generate_collision = True
task.options = options
def _configure_texture_import(self, task: unreal.AssetImportTask, settings: dict):
"""Configure import task for texture files.
Args:
task: Import task to configure
settings: Import settings
"""
factory = unreal.TextureFactory()
factory.s_rgb = settings.get("sRGB", True)
# Set compression based on settings
compression = settings.get("compressionSettings", "TC_Default")
if compression in self.COMPRESSION_MAP:
factory.compression_settings = self.COMPRESSION_MAP[compression]
task.factory = factory
def _get_imported_asset_info(self, asset, original_file_path: str) -> dict:
"""Get information about an imported asset.
Args:
asset: The imported asset
original_file_path: Original source file path
Returns:
dict: Asset information
"""
import os
info = {}
# Get file size if original file exists
if os.path.exists(original_file_path):
info["size"] = os.path.getsize(original_file_path)
# Get mesh-specific info with validation
if isinstance(asset, unreal.StaticMesh):
# Check if the asset has any LODs before accessing LOD 0
if asset.get_num_lods() > 0:
info["vertexCount"] = asset.get_num_vertices(0)
info["materialCount"] = asset.get_num_sections(0)
else:
info["vertexCount"] = 0
info["materialCount"] = 0
return info
|
# -*- coding: utf-8 -*-
import unreal
import sys
import pydoc
import inspect
import os
import json
from enum import IntFlag
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
def has_instance(cls):
return cls in cls._instances
def get_instance(cls):
if cls in cls._instances:
return cls._instances[cls]
return None
def cast(object_to_cast, object_class):
try:
return object_class.cast(object_to_cast)
except:
return None
# short cut for print dir
def d(obj, subString=''):
subString = subString.lower()
for x in dir(obj):
if subString == '' or subString in x.lower():
print(x)
def l(obj, subString='', bPrint = True):
'''
输出物体详细信息:函数、属性,editorProperty等,并以log形式输出
:param obj: Object实例或者类
:param subString: 过滤用字符串
:return: 无
'''
def _simplifyDoc(content):
bracketS, bracketE = content.find('('), content.find(')')
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]
param = content[bracketS + 1: bracketE].strip()
return funcDoc, param
def _getEditorProperties(content, obj):
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('`` ')
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 = line[typeS: typeE]
rws = line[rwS: rwE]
descript = line[rwE + 2:]
allInfoFound = True
result.append((name, type, rws, descript))
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
if obj == None:
unreal.log_warning("obj == None")
return None
if inspect.ismodule(obj):
return None
ignoreList = ['__delattr__', '__getattribute__', '__hash__', '__init__', '__setattr__']
propertiesNames = []
builtinCallableNames = []
otherCallableNames = []
for x in dir(obj):
if subString == '' or subString in x.lower():
attr = getattr(obj, x)
if callable(attr):
if inspect.isbuiltin(attr): # or inspect.isfunction(attr) or inspect.ismethod(attr):
builtinCallableNames.append(x)
else:
# Not Built-in
otherCallableNames.append(x)
else:
# Properties
propertiesNames.append(x)
# 1 otherCallables
otherCallables = []
for name in otherCallableNames:
descriptionStr = ""
if name == "__doc__":
resultStr = "ignored.." #doc太长,不输出
else:
resultStr = "{}".format(getattr(obj, name))
otherCallables.append([name, (), descriptionStr, resultStr])
# 2 builtinCallables
builtinCallables = []
for name in builtinCallableNames:
attr = getattr(obj, name)
descriptionStr = ""
resultStr = ""
bHasParameter = False
if hasattr(attr, '__doc__'):
docForDisplay, paramStr = _simplifyDoc(attr.__doc__)
if paramStr == '':
# Method with No params
descriptionStr = docForDisplay[docForDisplay.find(')') + 1:]
if '-> None' not in docForDisplay:
resultStr = "{}".format(attr.__call__())
else:
resultStr = 'skip call'
else:
# 有参函数
descriptionStr = paramStr
bHasParameter = True
resultStr = ""
else:
pass
builtinCallables.append([name, (bHasParameter,), descriptionStr, resultStr])
# 3 properties
editorPropertiesInfos = []
editorPropertiesNames = []
if hasattr(obj, '__doc__') and isinstance(obj, unreal.Object):
editorPropertiesInfos = _getEditorProperties(obj.__doc__, obj)
for name, _, _, _ in editorPropertiesInfos:
editorPropertiesNames.append(name)
properties = []
for name in propertiesNames:
descriptionStr = ""
if name == "__doc__":
resultStr = "ignored.." #doc太长,不输出
else:
try:
resultStr = "{}".format(getattr(obj, name))
except:
resultStr = ""
isAlsoEditorProperty = name in editorPropertiesNames #是否同时是EditorProprty同时也是property
properties.append([name, (isAlsoEditorProperty,), descriptionStr, resultStr])
# 4 editorProperties
editorProperties = []
propertyAlsoEditorPropertyCount = 0
for info in editorPropertiesInfos:
name, type, rw, descriptionStr = info
if subString == '' or subString in name.lower(): #过滤掉不需要的
try:
value = eval('obj.get_editor_property("{}")'.format(name))
except:
value = ""
descriptionStr = "[{}]".format(rw)
resultStr = "{}".format(value)
isAlsoProperty = name in propertiesNames
if isAlsoProperty:
propertyAlsoEditorPropertyCount += 1
editorProperties.append( [name, (isAlsoProperty,), descriptionStr, resultStr])
strs = []
strs.append("Detail: {}".format(obj))
formatWidth = 70
for info in otherCallables:
name, flags, descriptionStr, resultStr = info
# line = "\t{} {}{}{}".format(name, descriptionStr, " " *(formatWidth -1 - len(name) - len(descriptionStr)), resultStr)
line = "\t{} {}".format(name, descriptionStr)
line += "{}{}".format(" " * (formatWidth-len(line)+1-4), resultStr)
strs.append(line)
for info in builtinCallables:
name, flags, descriptionStr, resultStr = info
if flags[0]: # 有参函数
# line = "\t{}({}) {} {}".format(name, descriptionStr, " " * (formatWidth - 5 - len(name) - len(descriptionStr)), resultStr)
line = "\t{}({})".format(name, descriptionStr)
line += "{}{}".format(" " * (formatWidth-len(line)+1-4), resultStr)
else:
# line = "\t{}() {} |{}| {}".format(name, descriptionStr, "-" * (formatWidth - 7 - len(name) - len(descriptionStr)), resultStr)
line = "\t{}() {}".format(name, descriptionStr)
line += "|{}| {}".format("-" * (formatWidth-len(line)+1-4-3), resultStr)
strs.append(line)
for info in properties:
name, flags, descriptionStr, resultStr = info
sign = "**" if flags[0] else ""
# line = "\t\t{} {} {}{}{}".format(name, sign, descriptionStr, " " * (formatWidth - 6 - len(name) -len(sign) - len(descriptionStr)), resultStr)
line = "\t\t{} {} {}".format(name, sign, descriptionStr)
line += "{}{}".format(" " * (formatWidth-len(line)+2-8), resultStr)
strs.append(line)
strs.append("Special Editor Properties:")
for info in editorProperties:
name, flags, descriptionStr, resultStr = info
if flags[0]:
pass # 已经输出过跳过
else:
sign = "*"
# line = "\t\t{0} {1} {3}{4} {2}".format(name, sign, descriptionStr, " " * (formatWidth - 3 - len(name) -len(sign) ), resultStr) #descriptionStr 中是[rw]放到最后显示
line = "\t\t{} {}".format(name, sign)
line += "{}{} {}".format(" " * (formatWidth-len(line)+2-8), resultStr, descriptionStr) # descriptionStr 中是[rw]放到最后显示
strs.append(line)
if bPrint:
for l in strs:
print(l)
print("'*':Editor Property, '**':Editor Property also object attribute.")
print("{}: matched, builtinCallable: {} otherCallables: {} prop: {} EditorProps: {} both: {}".format(obj
, len(builtinCallables), len(otherCallables), len(properties), len(editorProperties), propertyAlsoEditorPropertyCount))
return otherCallables, builtinCallables, properties, editorProperties
# short cut for print type
def t(obj):
print(type(obj))
# unreal type to Python dict
def ToJson(v):
tp = type(v)
if tp == unreal.Transform:
result = {'translation': ToJson(v.translation), 'rotation': ToJson(v.rotation), 'scale3d': ToJson(v.scale3d)}
return result
elif tp == unreal.Vector:
return {'x': v.x, 'y': v.y, 'z': v.z}
elif tp == unreal.Quat:
return {'x': v.x, 'y': v.y, 'z': v.z, 'w': v.w}
else:
print("Error type: " + str(tp) + " not implemented.")
return None
def get_selected_comps():
return unreal.PythonBPLib.get_selected_components()
def get_selected_comp():
comps = unreal.PythonBPLib.get_selected_components()
return comps[0] if len(comps) > 0 else None
def get_selected_asset():
selected = unreal.PythonBPLib.get_selected_assets_paths()
if selected:
return unreal.load_asset(unreal.PythonBPLib.get_selected_assets_paths()[0])
else:
return None
def get_selected_assets():
assets = []
for path in unreal.PythonBPLib.get_selected_assets_paths():
asset = unreal.load_asset(path)
if (asset != None):
assets.append(asset)
return assets
def get_selected_actors():
return unreal.get_editor_subsystem(unreal.EditorActorSubsystem).get_selected_level_actors()
def get_selected_actor():
actors = unreal.get_editor_subsystem(unreal.EditorActorSubsystem).get_selected_level_actors()
return actors[0] if len(actors) > 0 else None
def set_preview_es31():
unreal.PythonBPLib.set_preview_platform("GLSL_ES3_1_ANDROID", "ES3_1")
def set_preview_sm5():
unreal.PythonBPLib.set_preview_platform("", "SM5")
# todo: create export tools for create help/dir to file
def export_dir(filepath, cls):
f = open(filepath, 'w')
sys.stdout = f
for x in sorted(dir(cls)):
print(x)
sys.stdout = sys.__stdout__
f.close()
def export_help(filepath, cls):
f = open(filepath, 'w')
sys.stdout = f
pydoc.help(cls)
sys.stdout = sys.__stdout__
f.close()
# 修改site.py 文件中的Encoding
def set_default_encoding(encodingStr):
pythonPath = os.path.dirname(sys.path[0])
if not os.path.exists(pythonPath):
unreal.PythonBPLib.message_dialog("can't find python folder: {}".format(pythonPath), "Warning")
return
sitePyPath = pythonPath + "/project/.py"
if not os.path.exists(sitePyPath):
unreal.PythonBPLib.message_dialog("can't find site.py: {}".format(sitePyPath), "Warning")
return
#简单查找字符串替换
with open(sitePyPath, "r") as f:
lines = f.readlines()
startLine = -1
endLine = -1
for i in range(len(lines)):
if startLine == -1 and lines[i][:len('def setencoding():')] == 'def setencoding():':
startLine = i
continue
if endLine == -1 and startLine > -1 and lines[i].startswith('def '):
endLine = i
print("startLine: {} endLine: {}".format(startLine, endLine))
changedLineCount = 0
if -1 < startLine and startLine < endLine:
linePosWithIf = []
for i in range(startLine + 1, endLine):
if lines[i].lstrip().startswith('if '):
linePosWithIf.append(i)
print(lines[i])
if len(linePosWithIf) != 4:
unreal.PythonBPLib.message_dialog("Find pos failed: {}".format(sitePyPath), "Warning")
print(linePosWithIf)
return
lines[linePosWithIf[2]] = lines[linePosWithIf[2]].replace("if 0", "if 1") # 简单修改第三个if所在行的内容
changedLineCount += 1
for i in range(linePosWithIf[2] + 1, linePosWithIf[3]):
line = lines[i]
if "encoding=" in line.replace(" ", ""):
s = line.find('"')
e = line.find('"', s+1)
if s > 0 and e > s:
lines[i] = line[:s+1] + encodingStr + line[e:]
changedLineCount += 1
break
if changedLineCount == 2:
with open(sitePyPath, 'w') as f:
f.writelines(lines)
unreal.PythonBPLib.notification("Success: {}".format(sitePyPath), 0)
currentEncoding = sys.getdefaultencoding()
if currentEncoding == encodingStr:
unreal.PythonBPLib.notification("已将default encoding设置为{}".format(currentEncoding), 0)
else:
unreal.PythonBPLib.message_dialog("已将default encoding设置为{},需要重启编辑器以便生效".format(encodingStr), "Warning")
else:
unreal.PythonBPLib.message_dialog("Find content failed: {}".format(sitePyPath), "Warning")
def get_actors_at_location(location, error_tolerance):
allActors = unreal.get_editor_subsystem(unreal.EditorActorSubsystem).get_selected_level_actors()
result = [_actor for _actor in allActors if _actor.get_actor_location().is_near_equal(location, error_tolerance)]
return result
def select_actors_at_location(location, error_tolerance, actorTypes=None):
actors = get_actors_at_location(location, error_tolerance)
if len(actors) > 1:
print("Total {} actor(s) with the same locations.".format(len(actors)))
if actorTypes is not None:
actors = [actor for actor in actors if type(actor) in actorTypes]
unreal.get_editor_subsystem(unreal.EditorActorSubsystem).set_selected_level_actors(actors)
return actors
else:
print("None actor with the same locations.")
return []
def select_actors_with_same_location(actor, error_tolerance):
if actor is not None:
actors = select_actors_at_location(actor.get_actor_location(), error_tolerance, [unreal.StaticMeshActor, unreal.SkeletalMeshActor])
return actors
else:
print("actor is None.")
return []
def get_chameleon_tool_instance(json_name):
found_count = 0
result = None
for var in globals():
if hasattr(var, "jsonPath") and hasattr(var, "data"):
if isinstance(var.data, unreal.ChameleonData):
if var.jsonPath.endswith(json_name):
found_count += 1
result = var
if found_count == 1:
return result
if found_count > 1:
unreal.log_warning(f"Found Multi-ToolsInstance by name: {json_name}, count: {found_count}")
return None
#
# Flags describing an object instance
#
class EObjectFlags(IntFlag):
# Do not add new flags unless they truly belong here. There are alternatives.
# if you change any the bit of any of the RF_Load flags, then you will need legacy serialization
RF_NoFlags = 0x00000000, #< No flags, used to avoid a cast
# This first group of flags mostly has to do with what kind of object it is. Other than transient, these are the persistent object flags.
# The garbage collector also tends to look at these.
RF_Public =0x00000001, #< Object is visible outside its package.
RF_Standalone =0x00000002, #< Keep object around for editing even if unreferenced.
RF_MarkAsNative =0x00000004, #< Object (UField) will be marked as native on construction (DO NOT USE THIS FLAG in HasAnyFlags() etc)
RF_Transactional =0x00000008, #< Object is transactional.
RF_ClassDefaultObject =0x00000010, #< This object is its class's default object
RF_ArchetypeObject =0x00000020, #< This object is a template for another object - treat like a class default object
RF_Transient =0x00000040, #< Don't save object.
# This group of flags is primarily concerned with garbage collection.
RF_MarkAsRootSet =0x00000080, #< Object will be marked as root set on construction and not be garbage collected, even if unreferenced (DO NOT USE THIS FLAG in HasAnyFlags() etc)
RF_TagGarbageTemp =0x00000100, #< This is a temp user flag for various utilities that need to use the garbage collector. The garbage collector itself does not interpret it.
# The group of flags tracks the stages of the lifetime of a uobject
RF_NeedInitialization =0x00000200, #< This object has not completed its initialization process. Cleared when ~FObjectInitializer completes
RF_NeedLoad =0x00000400, #< During load, indicates object needs loading.
RF_KeepForCooker =0x00000800, #< Keep this object during garbage collection because it's still being used by the cooker
RF_NeedPostLoad =0x00001000, #< Object needs to be postloaded.
RF_NeedPostLoadSubobjects =0x00002000, #< During load, indicates that the object still needs to instance subobjects and fixup serialized component references
RF_NewerVersionExists =0x00004000, #< Object has been consigned to oblivion due to its owner package being reloaded, and a newer version currently exists
RF_BeginDestroyed =0x00008000, #< BeginDestroy has been called on the object.
RF_FinishDestroyed =0x00010000, #< FinishDestroy has been called on the object.
# Misc. Flags
RF_BeingRegenerated =0x00020000, #< Flagged on UObjects that are used to create UClasses (e.g. Blueprints) while they are regenerating their UClass on load (See FLinkerLoad::CreateExport()), as well as UClass objects in the midst of being created
RF_DefaultSubObject =0x00040000, #< Flagged on subobjects that are defaults
RF_WasLoaded =0x00080000, #< Flagged on UObjects that were loaded
RF_TextExportTransient =0x00100000, #< Do not export object to text form (e.g. copy/paste). Generally used for sub-objects that can be regenerated from data in their parent object.
RF_LoadCompleted =0x00200000, #< Object has been completely serialized by linkerload at least once. DO NOT USE THIS FLAG, It should be replaced with RF_WasLoaded.
RF_InheritableComponentTemplate = 0x00400000, #< Archetype of the object can be in its super class
RF_DuplicateTransient =0x00800000, #< Object should not be included in any type of duplication (copy/paste, binary duplication, etc.)
RF_StrongRefOnFrame =0x01000000, #< References to this object from persistent function frame are handled as strong ones.
RF_NonPIEDuplicateTransient =0x02000000, #< Object should not be included for duplication unless it's being duplicated for a PIE session
RF_Dynamic =0x04000000, #< Field Only. Dynamic field. UE_DEPRECATED(5.0, "RF_Dynamic should no longer be used. It is no longer being set by engine code.") - doesn't get constructed during static initialization, can be constructed multiple times # @todo: BP2CPP_remove
RF_WillBeLoaded =0x08000000, #< This object was constructed during load and will be loaded shortly
RF_HasExternalPackage =0x10000000, #< This object has an external package assigned and should look it up when getting the outermost package
# RF_Garbage and RF_PendingKill are mirrored in EInternalObjectFlags because checking the internal flags is much faster for the Garbage Collector
# while checking the object flags is much faster outside of it where the Object pointer is already available and most likely cached.
# RF_PendingKill is mirrored in EInternalObjectFlags because checking the internal flags is much faster for the Garbage Collector
# while checking the object flags is much faster outside of it where the Object pointer is already available and most likely cached.
RF_PendingKill = 0x20000000, #< Objects that are pending destruction (invalid for gameplay but valid objects). UE_DEPRECATED(5.0, "RF_PendingKill should not be used directly. Make sure references to objects are released using one of the existing engine callbacks or use weak object pointers.") This flag is mirrored in EInternalObjectFlags as PendingKill for performance
RF_Garbage =0x40000000, #< Garbage from logical point of view and should not be referenced. UE_DEPRECATED(5.0, "RF_Garbage should not be used directly. Use MarkAsGarbage and ClearGarbage instead.") This flag is mirrored in EInternalObjectFlags as Garbage for performance
RF_AllocatedInSharedPage =0x80000000, #< Allocated from a ref-counted page shared with other UObjects
class EMaterialValueType(IntFlag):
MCT_Float1 = 1,
MCT_Float2 = 2,
MCT_Float3 = 4,
MCT_Float4 = 8,
MCT_Texture2D = 1 << 4,
MCT_TextureCube = 1 << 5,
MCT_Texture2DArray = 1 << 6,
MCT_TextureCubeArray = 1 << 7,
MCT_VolumeTexture = 1 << 8,
MCT_StaticBool = 1 << 9,
MCT_Unknown = 1 << 10,
MCT_MaterialAttributes = 1 << 11,
MCT_TextureExternal = 1 << 12,
MCT_TextureVirtual = 1 << 13,
MCT_VTPageTableResult = 1 << 14,
MCT_ShadingModel = 1 << 15,
MCT_Strata = 1 << 16,
MCT_LWCScalar = 1 << 17,
MCT_LWCVector2 = 1 << 18,
MCT_LWCVector3 = 1 << 19,
MCT_LWCVector4 = 1 << 20,
MCT_Execution = 1 << 21,
MCT_VoidStatement = 1 << 22,
def guess_instance_name(json_file_path):
try:
with open(json_file_path, 'r', encoding='utf-8') as f:
py_cmd = json.load(f).get("InitPyCmd", "")
print(next(line[:line.find('=')].strip() for line in py_cmd.split(";") if "%jsonpath" in line.lower()))
except (FileNotFoundError, KeyError) as e:
print(f"guess_instance_name failed: {e}")
|
from cgl.plugins.preflight.preflight_check import PreflightCheck
# there is typically a alchemy.py, and utils.py file in the plugins directory.
# look here for pre-built, useful functions
# from cgl.plugins.unreal import alchemy as alc
import unreal
class Levelselected(PreflightCheck):
def getName(self):
pass
def run(self):
"""
script to be executed when the preflight is run.
If the preflight is successful:
self.pass_check('Message about a passed Check')
if the preflight fails:
self.fail_check('Message about a failed check')
:return:
"""
selected_assets = unreal.EditorUtilityLibrary.get_selected_assets()
if len(selected_assets) > 0:
if selected_assets[0].get_class().get_name() == "World":
self.pass_check('Check Passed')
else:
self.fail_check("Error: Selected Asset Must Be Level")
else:
self.fail_check("Error: No Asset Selected")
|
# unreal 5.6
import os
import warnings
import unreal
asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
static_mesh_editor_subsystem = unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem)
def export_usd_mesh(static_mesh, output_file):
task = unreal.AssetExportTask()
task.object = static_mesh
task.filename = output_file
task.replace_identical = True
task.prompt = False
task.automated = True
task.options = unreal.StaticMeshExporterUSDOptions()
task.options.stage_options = unreal.UsdStageOptions()
task.options.stage_options.up_axis = unreal.UsdUpAxis.Y_AXIS
task.options.stage_options.meters_per_unit = 1
task.options.mesh_asset_options = unreal.UsdMeshAssetOptions()
task.options.mesh_asset_options.use_payload = False
task.options.mesh_asset_options.bake_materials = True
task.options.mesh_asset_options.lowest_mesh_lod = 0
task.options.mesh_asset_options.material_baking_options = unreal.UsdMaterialBakingOptions()
task.options.mesh_asset_options.material_baking_options.constant_color_as_single_value = True
task.options.mesh_asset_options.material_baking_options.default_texture_size = unreal.IntPoint(64, 64)
task.options.mesh_asset_options.material_baking_options.textures_dir = unreal.DirectoryPath(os.path.join(os.path.dirname(output_file), "Textures"))
unreal.Exporter.run_asset_export_task(task)
def export_usd_material(material_instance, output_file, only_textures = False):
iterations = 10
for i in range(iterations): # Run export task multiple times to fix texture quality. This issue probably related to Texture Streaming.
task = unreal.AssetExportTask()
task.object = material_instance
task.filename = output_file
task.replace_identical = True
task.prompt = False
task.automated = True
task.options = unreal.MaterialExporterUSDOptions()
task.options.material_baking_options = unreal.UsdMaterialBakingOptions()
task.options.material_baking_options.constant_color_as_single_value = True
task.options.material_baking_options.default_texture_size = unreal.IntPoint(4096, 4096)
task.options.material_baking_options.textures_dir = unreal.DirectoryPath(os.path.join(os.path.dirname(output_file), "Textures"))
if i != (iterations - 1): # write textures only at last iteration
task.options.material_baking_options.textures_dir.path = os.path.join(task.options.material_baking_options.textures_dir.path, os.devnull)
unreal.Exporter.run_asset_export_task(task)
if only_textures:
os.remove(output_file)
def export_png(texture_2d, output_file):
texture_exporter = unreal.TextureExporterPNG()
task = unreal.AssetExportTask()
task.object = texture_2d
task.filename = output_file
task.exporter = texture_exporter
task.automated = True
task.prompt = False
task.replace_identical = True
unreal.Exporter.run_asset_export_task(task)
def get_subpath(object_path):
return os.path.relpath(os.path.dirname(object_path), '/Game')
def convert_material_path_to_filename(input_path, parameter_name):
names_map = {
"BaseColor": "BaseColor",
"Albedo": "BaseColor",
"Roughness": "Roughness",
"Normal": "Normal",
}
name_key = str(parameter_name)
if name_key not in names_map:
return None
name = names_map[name_key]
result = input_path[1:] # remove first character
result = ".".join(result.split(".")[:1]) # remove last
result = result.replace("/", "_")
result += f"_{name}"
return result
def export_material_textures(asset_object, object_path, output_path):
for texture_parameter_value in asset_object.texture_parameter_values:
texture_filename = convert_material_path_to_filename(asset_object.get_path_name(), texture_parameter_value.parameter_info.name)
if texture_filename is None:
continue
texture_2d = texture_parameter_value.parameter_value;
output_file = os.path.join(output_path, get_subpath(object_path), "Textures", f"{texture_filename}.png")
export_png(texture_2d, output_file)
def disable_nanite(static_mesh):
"""
used to export original mesh as USD https://forums.unrealengine.com/project/-method-of-exporting-level-meshes-and-nanite/project/
will cause memory leak for each call
"""
nanite_settings = static_mesh.get_editor_property("nanite_settings")
if (nanite_settings.enabled):
print(f"Disabling nanite for {static_mesh}")
nanite_settings.enabled = False
static_mesh_editor_subsystem.set_nanite_settings(static_mesh, nanite_settings)
def undo_changes():
dirty_content_packages = unreal.EditorLoadingAndSavingUtils.get_dirty_content_packages()
unreal.EditorLoadingAndSavingUtils.reload_packages(dirty_content_packages, interaction_mode=unreal.ReloadPackagesInteractionMode.ASSUME_POSITIVE)
def cread_dirs(output_file):
output_dir = os.path.dirname(output_file)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
def export_object(object_path, output_path):
asset_info = asset_registry.get_asset_by_object_path(object_path)
asset_object = asset_info.get_asset()
if type(asset_object) is unreal.StaticMesh:
print(f"Exporting StaticMesh {object_path}")
disable_nanite(asset_object)
output_file = os.path.join(output_path, get_subpath(object_path), f"{asset_info.asset_name}.usd")
cread_dirs(output_file)
export_usd_mesh(asset_object, output_file)
material = asset_object.get_material(0)
output_file = os.path.join(output_path, get_subpath(object_path), f"{asset_info.asset_name}_Material.usd")
export_usd_material(material, output_file, True)
export_material_textures(material, object_path, output_path)
print(f"Exported to {output_file}")
def get_sort_key_material(object_path):
asset_info = asset_registry.get_asset_by_object_path(object_path)
asset_object = asset_info.get_asset()
return 1 if type(asset_object) is unreal.MaterialInstanceConstant else 0
def main():
print("------ Start Exporting ------")
output_path = os.environ.get('OUTPUT_PATH', "F:/project/")
path = os.environ.get('ASSETS_PATH', unreal.EditorUtilityLibrary.get_current_content_browser_path())
if path is None or output_path is None:
print("Empty paths. Aborting")
return
else:
print("Exporting from path: " + path)
asset_data_list = unreal.EditorAssetLibrary.list_assets(path, recursive=True)
asset_data_list.sort(get_sort_key_material)
for object_path in asset_data_list:
export_object(object_path, output_path)
print("------ Done Exporting ------")
main()
|
# -*- coding: utf-8 -*-
import unreal
from Utilities.Utils import Singleton
class MinimalExample(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.ui_output = "InfoOutput"
self.click_count = 0
def on_button_click(self):
self.click_count += 1
self.data.set_text(self.ui_output, "Clicked {} time(s)".format(self.click_count))
|
# 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
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)
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)))
# 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'))
else:
items_forControl.append(node.find_pin('Items'))
print(values_forCurve)
# reset controller
for e in reversed(hierarchy.get_controls()):
if (hierarchy.get_parents(e)[0].name == 'MorphControlRoot_s'):
#if (str(e.name).rstrip('_c') in morphList):
# continue
print('delete')
#print(str(e.name))
h_con.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)
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())
control = hierarchy.find_control(k)
except:
k = h_con.add_control(name_c, space, settings, unreal.RigControlValue())
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())
control = hierarchy.find_control(k)
except:
k = h_con.add_control(name_c, space, settings, unreal.RigControlValue())
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
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)
|
# Copyright Epic Games, Inc. All Rights Reserved
"""
This script handles processing jobs and shots in the current loaded queue
"""
import unreal
from .utils import (
movie_pipeline_queue,
execute_render,
setup_remote_render_jobs,
update_render_output
)
def setup_render_parser(subparser):
"""
This method adds a custom execution function and args to a render subparser
:param subparser: Subparser for processing custom sequences
"""
# Function to process arguments
subparser.set_defaults(func=_process_args)
def render_jobs(
is_remote=False,
is_cmdline=False,
executor_instance=None,
remote_batch_name=None,
remote_job_preset=None,
output_dir_override=None,
output_filename_override=None
):
"""
This renders the current state of the queue
:param bool is_remote: Is this a remote render
:param bool is_cmdline: Is this a commandline render
:param executor_instance: Movie Pipeline Executor instance
:param str remote_batch_name: Batch name for remote renders
:param str remote_job_preset: Remote render job preset
:param str output_dir_override: Movie Pipeline output directory override
:param str output_filename_override: Movie Pipeline filename format override
:return: MRQ executor
"""
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!!")
# Update the job
for job in movie_pipeline_queue.get_jobs():
# If we have output job overrides and filename overrides, update it on
# the job
if output_dir_override or output_filename_override:
update_render_output(
job,
output_dir=output_dir_override,
output_filename=output_filename_override
)
# Get the job output settings
output_setting = job.get_configuration().find_setting_by_class(
unreal.MoviePipelineOutputSetting
)
# Allow flushing flies to disk per shot.
# Required for the OnIndividualShotFinishedCallback to get called.
output_setting.flush_disk_writes_per_shot = True
if is_remote:
setup_remote_render_jobs(
remote_batch_name,
remote_job_preset,
movie_pipeline_queue.get_jobs(),
)
try:
# Execute the render.
# This will execute the render based on whether its remote or local
executor = execute_render(
is_remote,
executor_instance=executor_instance,
is_cmdline=is_cmdline,
)
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_jobs(
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
)
|
import unreal
@unreal.uenum()
class MyPythonEnum(unreal.EnumBase):
FIRST = unreal.uvalue(0)
SECOND = unreal.uvalue(1)
FOURTH = unreal.uvalue(3)
@unreal.ustruct()
class PythonUnrealStruct(unreal.StructBase):
some_string = unreal.uproperty(str)
some_number = unreal.uproperty(float)
array_of_string = unreal.uproperty(unreal.Array(str))
@unreal.uclass()
class PythonTestClass(unreal.BlueprintFunctionLibrary):
@unreal.ufunction(static = True, params = [int], ret = PythonUnrealStruct)
def MyPythonFunction(integer_argument1):
struct = PythonUnrealStruct()
struct.some_string = "5"
struct.some_number = integer_argument1 + 1
struct.array_of_string = ["a", "b", "c"]
return struct
@unreal.ufunction(static = True, params = [str], ret = bool)
def MyPythonFunction2(string_argument1):
print(string_argument1)
return True
|
# /project/
# @CBgameDev Optimisation Script - Log No LODs On Skeletal Meshes
# /project/
import unreal
import os
EditAssetLib = unreal.EditorAssetLibrary()
SkelMeshLib = unreal.EditorSkeletalMeshLibrary()
workingPath = "/Game/" # Using the root directory
notepadFilePath = os.path.dirname(__file__) + "//PythonOptimiseLog.txt"
allAssets = EditAssetLib.list_assets(workingPath, True, False)
selectedAssetsPath = workingPath
LogStringsArray = []
numOfOptimisations = 0
with unreal.ScopedSlowTask(len(allAssets), selectedAssetsPath) as ST:
ST.make_dialog(True)
for asset in allAssets:
_assetData = EditAssetLib.find_asset_data(asset)
_assetName = _assetData.get_asset().get_name()
_assetPathName = _assetData.get_asset().get_path_name()
_assetClassName = _assetData.get_asset().get_class().get_name()
# unreal.log(_assetClassName)
if _assetClassName == "SkeletalMesh":
_SkeletalMeshAsset = unreal.SkeletalMesh.cast(EditAssetLib.load_asset(asset))
# unreal.log(SkelMeshLib.get_lod_count(_SkeletalMeshAsset))
# unreal.log(_SkeletalMeshAsset)
if SkelMeshLib.get_lod_count(_SkeletalMeshAsset) <= 1:
LogStringsArray.append(" %s ------------> At Path: %s \n" % (_assetName, _assetPathName))
# unreal.log("Asset Name: %s Path: %s \n" % (_assetName, _assetPathName))
numOfOptimisations += 1
if ST.should_cancel():
break
ST.enter_progress_frame(1, asset)
# Write results into a log file
# /project/
TitleOfOptimisation = "Log No LODs On Skeletal Meshes"
DescOfOptimisation = "Searches the entire project for skeletal mesh assets that do not have any LODs setup"
SummaryMessageIntro = "-- Skeletal Mesh Assets Which Do Not Have any LODs Setup --"
if unreal.Paths.file_exists(notepadFilePath): # Check if txt file already exists
os.remove(notepadFilePath) # if does remove it
# Create new txt file and run intro text
file = open(notepadFilePath, "a+") # we should only do this if have a count?
file.write("OPTIMISING SCRIPT by @CBgameDev \n")
file.write("==================================================================================================== \n")
file.write(" SCRIPT NAME: %s \n" % TitleOfOptimisation)
file.write(" DESCRIPTION: %s \n" % DescOfOptimisation)
file.write("==================================================================================================== \n \n")
if numOfOptimisations <= 0:
file.write(" -- NONE FOUND -- \n \n")
else:
for i in range(len(LogStringsArray)):
file.write(LogStringsArray[i])
# Run summary text
file.write("\n")
file.write("======================================================================================================= \n")
file.write(" SUMMARY: \n")
file.write(" %s \n" % SummaryMessageIntro)
file.write(" Found: %s \n \n" % numOfOptimisations)
file.write("======================================================================================================= \n")
file.write(" Logged to %s \n" % notepadFilePath)
file.write("======================================================================================================= \n")
file.close()
os.startfile(notepadFilePath) # Trigger the notepad file to open
|
import unreal
projectPath = unreal.Paths.project_dir()
content_path = unreal.Paths.project_content_dir()
path_split = projectPath.split('/')
wip_folder_name = path_split[len(path_split)-3] + '_WIP'
path_split[len(path_split)-3] = wip_folder_name
wip_path = '/'.join(path_split)
wip_folder = wip_path
source_folder = content_path
texture_folder = wip_path + 'Game/'
desired_size = 2024
print('WIP Folder:', wip_folder)
print('Source Folder:', source_folder)
print('Texture Folder:', texture_folder)
print('Desired Size:', desired_size)
|
import unreal
import torch
from unreal import EditorLevelLibrary
editor_subsystem = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem)
# Use the new method to get the editor world
editor_world = editor_subsystem.get_editor_world()
# Now you can continue with your operations using editor_world
print(editor_world)
print("halli hallå")
|
"""Test file so I can run quick code snippet inside unreal
> Use py /project/ in the cmd inside unreal.
"""
import os
import opentimelineio as otio
#import path_utils
import unreal
def export_sequencer_data_as_otio():
"""Export out of unreal folder"""
# Get the output folder for the out usd data
out_dir = '/project/'
print(os.path.exists(out_dir))
if not os.path.exists(out_dir):
os.makedirs(out_dir)
timeline = otio.schema.Timeline(name="MyTimeline")
track = otio.schema.Track()
timeline.tracks.append(track)
out_path = out_dir + "my_timeline.otio"
unreal.log("yay")
unreal.log(out_dir)
print(timeline)
if os.path.exists(out_dir):
print("path exists!")
otio.adapters.write_to_file(timeline, out_path)
else:
unreal.log_error("Can't write OTIO files, {} dir does not exists".format(out_dir))
export_sequencer_data_as_otio()
|
# 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()
|
import unreal
from Utilities.Utils import Singleton
class ModalWindowExample(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)
|
# 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 an HDA and then
set 2 inputs: a geometry input (a cube) 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_wrapper = None
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 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
geo_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPIGeoInput)
# Set the input objects/assets for this input
geo_object = get_geo_asset()
if not geo_input.set_input_objects((geo_object, )):
# If any errors occurred, get the last error message
print('Error on geo_input: {0}'.format(geo_input.get_last_error_message()))
# copy the input data to the HDA as node input 0
in_wrapper.set_input_at_index(0, geo_input)
# We can now discard the API input object
geo_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(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)
# Error handling/message example: try to set geo_object on curve input
if not curve_input.set_input_objects((geo_object, )):
print('Error (example) while setting \'{0}\' on curve input: {1}'.format(
geo_object.get_name(), curve_input.get_last_error_message()
))
# 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
# Check for errors on the wrapper
last_error = in_wrapper.get_last_error_message()
if last_error:
print('Error on wrapper during input configuration: {0}'.format(last_error))
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 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_wrapper
# instantiate an asset with auto-cook enabled
_g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform())
# Configure inputs on_post_instantiation, after instantiation, but before first cook
_g_wrapper.on_post_instantiation_delegate.add_callable(configure_inputs)
# Print the input state after the cook and output creation.
_g_wrapper.on_post_processing_delegate.add_callable(print_inputs)
if __name__ == '__main__':
run()
|
import unreal
import socket
import traceback
from threading import Thread
from queue import Queue
syslib = unreal.SystemLibrary()
class MyTimer:
_hndl = None
def __init__(self, *w, **kw):
if w:self.start(*w, **kw)
def start(self, foo, delay=0.0, repeat=False):
self.stop()
assert callable(foo)
self._foo = foo
self._delay = max(delay, 0.0)
self._repeat = repeat
self._passed = 0.0
self._hndl = unreal.register_slate_post_tick_callback(self._tick)
def stop(self):
self._foo = None
if not self._hndl: return
unreal.unregister_slate_post_tick_callback(self._hndl)
self._hndl = None
def _tick(self, delta_time):
if not self._foo: return self.stop()
self._passed += delta_time
if self._passed < self._delay: return
try: self._foo()
except: traceback.print_exc()
if self._repeat:
self._passed = 0.0
else:
self.stop()
class UDP2CMD:
def __init__(self):
self.port = 1234
self._live = False
self.from_sublime_queue = Queue()
def start(self):
args = unreal.SystemLibrary.get_command_line()
tokens, switches, params = unreal.SystemLibrary.parse_command_line(args)
if "tellunreal_listen_port" in params:
print("tellunreal_listen_port:%r"%params["tellunreal_listen_port"])
self.port = int(params["tellunreal_listen_port"])
print("External Command Line object is initialized")
if self._live: raise RuntimeError
self._live = True
self.listen_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.listen_socket.bind(("localhost", self.port))
self.listen_thread = Thread(target = self._thr_listen)
self.listen_thread.start()
self._main_timer = MyTimer(self.onTimer, 0.3, repeat=True)
def stop(self):
print("STOP UDP2CMD %r"%self)
self._live = False
self._main_timer.stop()
self.listen_socket.close()
def _thr_listen(self):
while self._live:
try:
data, address = self.listen_socket.recvfrom(10000)
except OSError as err:
print("UDP2CMD _thr_listen recvfrom ERR:%s"%err)
break
if data:
self.from_sublime_queue.put(data)
print("UDP2CMD STOP thread %r"%self)
def onTimer(self):
if not self._live:
return self._main_timer.stop()
if not self.from_sublime_queue.qsize(): return
data = self.from_sublime_queue.get_nowait()
print("UDP2CMD data:%r"%data)
cmd = data.decode()
syslib.print_string(None, string=cmd, print_to_screen=True, print_to_log=True,
text_color=[255.0, 0.0, 0.0, 255.0], duration=2.0)
syslib.execute_console_command(None, cmd)
prev = getattr(unreal, "udp_2_cmd_listener", None )
if prev:
prev.stop()
unreal.udp_2_cmd_listener = UDP2CMD()
unreal.udp_2_cmd_listener.start()
|
import unreal
class GallaryWidgetFactory:
export = True
def create(self) -> unreal.Widget:
...
def with_content(self):
return "Example"
|
# -*- coding: utf-8 -*-
"""Loader for Static Mesh alembics."""
from ayon_core.pipeline import AYON_CONTAINER_ID
from ayon_unreal.api import plugin
from ayon_unreal.api.pipeline import (
create_container,
imprint,
format_asset_directory,
UNREAL_VERSION,
get_dir_from_existing_asset
)
from ayon_core.settings import get_current_project_settings
from ayon_core.lib import EnumDef, BoolDef
import unreal # noqa
class StaticMeshAlembicLoader(plugin.Loader):
"""Load Unreal StaticMesh from Alembic"""
product_types = {"model", "staticMesh"}
label = "Import Alembic Static Mesh"
representations = {"abc"}
icon = "cube"
color = "orange"
abc_conversion_preset = "maya"
loaded_asset_dir = "{folder[path]}/{product[name]}_{version[version]}"
loaded_asset_name = "{folder[name]}_{product[name]}_{version[version]}_{representation[name]}" # noqa
show_dialog = False
@classmethod
def apply_settings(cls, project_settings):
super(StaticMeshAlembicLoader, cls).apply_settings(project_settings)
# Apply import settings
unreal_settings = project_settings["unreal"]["import_settings"]
cls.abc_conversion_preset = unreal_settings["abc_conversion_preset"]
cls.loaded_asset_dir = unreal_settings["loaded_asset_dir"]
cls.loaded_asset_name = unreal_settings["loaded_asset_name"]
cls.show_dialog = unreal_settings["show_dialog"]
@classmethod
def get_options(cls, contexts):
return [
EnumDef(
"abc_conversion_preset",
label="Alembic Conversion Preset",
items={
"3dsmax": "3dsmax",
"maya": "maya",
"custom": "custom"
},
default=cls.abc_conversion_preset
),
EnumDef(
"abc_material_settings",
label="Alembic Material Settings",
items={
"no_material": "Do not apply materials",
"create_materials": "Create matarials by face sets",
"find_materials": "Search matching materials by face sets",
},
default="no_materials"
),
BoolDef(
"merge_meshes",
label="Merge Meshes",
default=True
)
]
@staticmethod
def get_task(filename, asset_dir, asset_name, replace, loaded_options):
task = unreal.AssetImportTask()
options = unreal.AbcImportSettings()
sm_settings = unreal.AbcStaticMeshSettings()
mat_settings = unreal.AbcMaterialSettings()
conversion_settings = unreal.AbcConversionSettings()
task.set_editor_property('filename', filename)
task.set_editor_property('destination_path', asset_dir)
task.set_editor_property('destination_name', asset_name)
task.set_editor_property('replace_existing', replace)
task.set_editor_property(
'automated', not loaded_options.get("show_dialog"))
task.set_editor_property('save', True)
# set import options here
# Unreal 4.24 ignores the settings. It works with Unreal 4.26
options.set_editor_property(
'import_type', unreal.AlembicImportType.STATIC_MESH)
sm_settings.set_editor_property(
'merge_meshes', loaded_options.get("merge_meshes", True))
if loaded_options.get("abc_material_settings") == "create_materials":
mat_settings.set_editor_property("create_materials", True)
mat_settings.set_editor_property("find_materials", False)
elif loaded_options.get("abc_material_settings") == "find_materials":
mat_settings.set_editor_property("create_materials", False)
mat_settings.set_editor_property("find_materials", True)
else:
mat_settings.set_editor_property("create_materials", False)
mat_settings.set_editor_property("find_materials", False)
if not loaded_options.get("default_conversion"):
conversion_settings = None
abc_conversion_preset = loaded_options.get("abc_conversion_preset")
if abc_conversion_preset == "maya":
if UNREAL_VERSION.major >= 5 and UNREAL_VERSION.minor >= 4:
conversion_settings = unreal.AbcConversionSettings(
preset=unreal.AbcConversionPreset.MAYA)
else:
conversion_settings = unreal.AbcConversionSettings(
preset=unreal.AbcConversionPreset.CUSTOM,
flip_u=False, flip_v=True,
rotation=[90.0, 0.0, 0.0],
scale=[1.0, -1.0, 1.0])
elif abc_conversion_preset == "3dsmax":
if UNREAL_VERSION.major >= 5:
conversion_settings = unreal.AbcConversionSettings(
preset=unreal.AbcConversionPreset.MAX)
else:
conversion_settings = unreal.AbcConversionSettings(
preset=unreal.AbcConversionPreset.CUSTOM,
flip_u=False, flip_v=True,
rotation=[0.0, 0.0, 0.0],
scale=[1.0, -1.0, 1.0])
else:
data = get_current_project_settings()
preset = (
data["unreal"]["import_settings"]["custom"]
)
conversion_settings = unreal.AbcConversionSettings(
preset=unreal.AbcConversionPreset.CUSTOM,
flip_u=preset["flip_u"],
flip_v=preset["flip_v"],
rotation=[
preset["rot_x"],
preset["rot_y"],
preset["rot_z"]
],
scale=[
preset["scl_x"],
preset["scl_y"],
preset["scl_z"]
]
)
options.conversion_settings = conversion_settings
options.static_mesh_settings = sm_settings
options.material_settings = mat_settings
task.options = options
return task
def import_and_containerize(
self, filepath, asset_dir, asset_name,
container_name, loaded_options
):
"""
Import the asset and create a container for it.
Handle asset loading based on settings.
"""
task = None
# If the asset does not exist, create a new one
if not unreal.EditorAssetLibrary.does_asset_exist(
f"{asset_dir}/{asset_name}"
):
task = self.get_task(
filepath, asset_dir, asset_name, False, loaded_options
)
unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks([task])
if not unreal.EditorAssetLibrary.does_asset_exist(
f"{asset_dir}/{container_name}"
):
# Create Asset Container
create_container(container=container_name, path=asset_dir)
return asset_dir
def imprint(
self,
folder_path,
asset_dir,
container_name,
asset_name,
representation,
product_type,
project_name,
layout
):
data = {
"schema": "ayon:container-2.0",
"id": AYON_CONTAINER_ID,
"folder_path": folder_path,
"namespace": asset_dir,
"container_name": container_name,
"asset_name": asset_name,
"loader": str(self.__class__.__name__),
"representation": representation["id"],
"parent": representation["versionId"],
"product_type": product_type,
# TODO these should be probably removed
"asset": folder_path,
"family": product_type,
"project_name": project_name,
"layout": layout
}
imprint(f"{asset_dir}/{container_name}", data)
def load(self, context, name, namespace, options):
"""Load and containerise representation into Content Browser.
Args:
context (dict): application context
name (str): Product name
namespace (str): in Unreal this is basically path to container.
This is not passed here, so namespace is set
by `containerise()` because only then we know
real path.
data (dict): Those would be data to be imprinted.
Returns:
list(str): list of container content
"""
# Create directory for asset and Ayon container
folder_path = context["folder"]["path"]
suffix = "_CON"
path = self.filepath_from_context(context)
asset_root, asset_name = format_asset_directory(
context, self.loaded_asset_dir, self.loaded_asset_name
)
tools = unreal.AssetToolsHelpers().get_asset_tools()
asset_dir, container_name = tools.create_unique_asset_name(
asset_root, suffix="")
container_name += suffix
should_use_layout = options.get("layout", False)
# Get existing asset dir if possible, otherwise import & containerize
if should_use_layout and (
existing_asset_dir := get_dir_from_existing_asset(
asset_dir, asset_name)
):
asset_dir = existing_asset_dir
else:
loaded_options = {
"default_conversion": options.get(
"default_conversion", False),
"abc_conversion_preset": options.get(
"abc_conversion_preset", self.abc_conversion_preset),
"abc_material_settings": options.get(
"abc_material_settings", "no_material"),
"merge_meshes": options.get("merge_meshes", True),
"show_dialog": options.get("show_dialog", self.show_dialog),
}
asset_dir = self.import_and_containerize(
path, asset_dir, asset_name,
container_name, loaded_options
)
product_type = context["product"]["productType"]
self.imprint(
folder_path,
asset_dir,
container_name,
asset_name,
context["representation"],
product_type,
context["project"]["name"],
should_use_layout
)
asset_content = unreal.EditorAssetLibrary.list_assets(
asset_dir, recursive=True, include_folder=False
)
for a in asset_content:
unreal.EditorAssetLibrary.save_asset(a)
return asset_content
def update(self, container, context):
folder_path = context["folder"]["path"]
product_type = context["product"]["productType"]
repre_entity = context["representation"]
# Create directory for asset and Ayon container
suffix = "_CON"
path = self.filepath_from_context(context)
asset_root, asset_name = format_asset_directory(
context, self.loaded_asset_dir, self.loaded_asset_name
)
tools = unreal.AssetToolsHelpers().get_asset_tools()
asset_dir, container_name = tools.create_unique_asset_name(
asset_root, suffix="")
container_name += suffix
should_use_layout = container.get("layout", False)
# Get existing asset dir if possible, otherwise import & containerize
if should_use_layout and (
existing_asset_dir := get_dir_from_existing_asset(
asset_dir, asset_name)
):
asset_dir = existing_asset_dir
else:
loaded_options = {
"default_conversion": False,
"abc_conversion_preset": self.abc_conversion_preset
}
asset_dir = self.import_and_containerize(
path, asset_dir, asset_name,
container_name, loaded_options
)
self.imprint(
folder_path,
asset_dir,
container_name,
asset_name,
repre_entity,
product_type,
context["project"]["name"],
should_use_layout
)
asset_content = unreal.EditorAssetLibrary.list_assets(
asset_dir, recursive=True, include_folder=False
)
for a in asset_content:
unreal.EditorAssetLibrary.save_asset(a)
def remove(self, container):
path = container["namespace"]
if unreal.EditorAssetLibrary.does_directory_exist(path):
unreal.EditorAssetLibrary.delete_directory(path)
|
# unreal.SystemLibrary
# https://api.unrealengine.com/project/.html
import unreal
import random
# active_viewport_only: bool : If True, will only affect the active viewport
# actor: obj unreal.Actor : The actor you want to snap to
def focusViewportOnActor(active_viewport_only=True, actor=None):
command = 'CAMERA ALIGN'
if active_viewport_only:
command += ' ACTIVEVIEWPORTONLY'
if actor:
command += ' NAME=' + actor.get_name()
executeConsoleCommand(command)
# Cpp ########################################################################################################################################################################################
# Note: This is the real Python function but it does not work in editor : unreal.SystemLibrary.execute_console_command(unreal.EditorLevelLibrary.get_editor_world(), 'stat unit')
# console_command: str : The console command
def executeConsoleCommand(console_command=''):
unreal.CppLib.execute_console_command(console_command)
# return: int : The index of the active viewport
def getActiveViewportIndex():
return unreal.CppLib.get_active_viewport_index()
# viewport_index: int : The index of the viewport you want to affect
# location: obj unreal.Vector : The viewport location
# rotation: obj unreal.Rotator : The viewport rotation
def setViewportLocationAndRotation(viewport_index=1, location=unreal.Vector(), rotation=unreal.Rotator()):
unreal.CppLib.set_viewport_location_and_rotation(viewport_index, location, rotation)
# viewport_index: int : The index of the viewport you want to affect
# actor: obj unreal.Actor : The actor you want to snap to
def snapViewportToActor(viewport_index=1, actor=None):
setViewportLocationAndRotation(viewport_index, actor.get_actor_location(), actor.get_actor_rotation())
|
# HEADER :
# File : folder_mat.py
# Create : 2024/project/
# Author : LiDanyang
# Branch : develop
# Descript : 替换迁移材质引用
# UPDATE: 2024/project/ 16:24 -> 完成所有材质修改,包含所有工位/AO下SM的材质实例的迁移,以及材质实例的父级材质的迁移
# 我发现如果当前路径下static mesh 的 同名文件夹时,使用list_assets获取文件夹中的所有asset的路径时,会优先获取static mesh
# 所以我先删除AO,之后重新生成
# 1. 选中一堆文件夹,先将选中文件夹下面所有static mesh的材质迁移到指定文件夹下
# 2. 之后再将选中文件夹下面所有材质实例的父级材质迁移到指定文件夹下
import unreal
def get_assets_name_list(folder_path, asset_type):
assets_list = []
assets_name_list = []
assets_path = unreal.EditorAssetLibrary().list_assets(folder_path, recursive=True, include_folder=False)
for asset_path in assets_path:
asset = unreal.EditorAssetLibrary.load_asset(asset_path.split('.')[0])
if asset and isinstance(asset, asset_type):
assets_list.append(asset)
if assets_list:
assets_name_list = [asset.get_name() for asset in assets_list]
else:
assets_name_list = []
return assets_name_list
# TODO:目标材质文件夹,材质迁移的位置
# 上飞厂材质文件夹
mat_folder_path = r'/project/'
mat_parent_folder_path = r'/project/'
# 供应商材质文件夹
# mat_folder_path = r'/project/'
# mat_parent_folder_path = r'/project/'
# 测试材质文件夹
# mat_folder_path = r'/project/'
# mat_parent_folder_path = r'/project/'
# # 1. 选中一堆文件夹,先将选中文件夹下面所有static mesh的材质迁移到指定文件夹下
# selected_folder_paths = unreal.EditorUtilityLibrary.get_selected_folder_paths()
#
# for active_folder_path in selected_folder_paths:
# assets_path = unreal.EditorAssetLibrary().list_assets(active_folder_path, recursive=True, include_folder=False)
#
# # 迁移材质
# for asset_path in assets_path: # 文件夹下面每一个asset的path
# # load asset into memory
# asset = unreal.EditorAssetLibrary.load_asset(asset_path)
#
# if asset and isinstance(asset, unreal.StaticMesh):
# static_materials = asset.static_materials # 获取当前资产使用到的所有材质[list]
#
# # for item in static_materials:
# # print(item.material_slot_name) # 2960641
# # print(item.material_interface) # <Object '/project/-1/project/.color_d2d2ffff' (0x0000053D20686200) Class 'MaterialInstanceConstant'>
# # print(item.material_interface.get_path_name()) # /project/-1/project/.color_d2d2ffff
# # print(item.material_interface.get_name()) # color_d2d2ffff
# # print(item.material_interface.get_class()) # <Object '/project/.MaterialInstanceConstant' (0x0000053C6B7B2800) Class 'Class'>
# # print(item.material_interface.get_class().get_name()) # MaterialInstanceConstant
# # print(item.material_interface.get_class().get_path_name()) # /project/.MaterialInstanceConstant
# mat_instance_name_list = get_assets_name_list(mat_folder_path,unreal.MaterialInstance)
#
# for i in range(len(static_materials)):
# current_name = static_materials[i].material_interface.get_name()
# current_path_name = static_materials[i].material_interface.get_path_name()
# current_slot_name = static_materials[i].material_slot_name
# if current_name in mat_instance_name_list:
# unreal.log(f"Already in Taget Folder : {asset.get_name()} : {current_slot_name} : {current_name}")
# else:
# unreal.log(f"Not in Taget Folder : {asset.get_name()} : {current_slot_name} : {current_name}")
# # BUG: 会报错,因为此时 mat_instance_name_list 没有更新
# duplicate_material = unreal.EditorAssetLibrary.duplicate_asset(current_path_name, mat_folder_path + current_name)
# unreal.log(f"{duplicate_material} is duplicated to {mat_folder_path + current_name}")
#
# new_material = unreal.EditorAssetLibrary.load_asset(mat_folder_path + current_name)
# asset.set_material(i, new_material)
# unreal.SystemLibrary.collect_garbage()
# unreal.EditorAssetSubsystem().save_directory('/Game/',only_if_is_dirty=True,recursive=True)
# 2. 之后再将选中文件夹下面所有材质实例的父级材质迁移到指定文件夹下
# 当前文件夹下所有的材质实例 asset path
mat_instance_path_list = unreal.EditorAssetLibrary.list_assets(mat_folder_path, recursive=True, include_folder=False) # /project/.color_f3feb1ff
mat_instace_name_list = get_assets_name_list(mat_folder_path, unreal.MaterialInstance) # color_0000ffff
mat_parent_path_list = unreal.EditorAssetLibrary.list_assets(mat_parent_folder_path, recursive=True, include_folder=False)
for item in mat_instance_path_list:
mat_parent_name_list = get_assets_name_list(mat_parent_folder_path , unreal.Material) # M_DatasmithCAD,M_DatasmithCADTransparent
mat = unreal.EditorAssetLibrary.load_asset(item.split('.')[0]) # mat_instance
assetData_matIns = unreal.EditorAssetLibrary.find_asset_data(mat.get_path_name()).get_asset()
# print(mat.get_name())
# print(mat.get_path_name())
if isinstance(mat, unreal.MaterialInstance):
mat_parent = mat.parent
if isinstance(mat_parent, unreal.Material): # M_DatasmithCAD,M_DatasmithCADTransparent
if mat_parent.get_name() not in mat_parent_name_list:
# 如果父材质不在目标文件夹中,则复制
duplicate_material = unreal.EditorAssetLibrary().duplicate_asset(mat_parent.get_path_name(), mat_parent_folder_path + str(mat_parent.get_name()))
assetData_matParent = unreal.EditorAssetLibrary.find_asset_data(duplicate_material.get_path_name())
_MatInstance = assetData_matParent.get_asset()
# _MatInstance = unreal.MaterialInstance.cast(assetData_matParent.get_asset())
unreal.MaterialEditingLibrary().set_material_instance_parent(assetData_matIns, _MatInstance)
else:
unreal.log(f"Already in {mat_parent_folder_path} : {mat_parent.get_name()}")
existing_material = unreal.EditorAssetLibrary.load_asset(mat_parent_folder_path + str(mat_parent.get_name()))
assetData_matParent = unreal.EditorAssetLibrary.find_asset_data(existing_material.get_path_name())
# _MatInstance = unreal.MaterialInstance.cast(assetData_matParent.get_asset())
_MatInstance = assetData_matParent.get_asset()
unreal.MaterialEditingLibrary().set_material_instance_parent(assetData_matIns, _MatInstance)
else:
unreal.log_warning(f"{mat.get_name()} has no parent material.")
unreal.get_editor_subsystem(unreal.EditorAssetSubsystem).save_directory(mat_folder_path , only_if_is_dirty=False , recursive=True)
|
# -*- coding: utf-8 -*-
import os
import json
import math
import unreal
from unreal import EditorLevelLibrary as ell
from unreal import EditorAssetLibrary as eal
import ayon_api
from ayon_core.pipeline import publish
class ExtractLayout(publish.Extractor):
"""Extract a layout."""
label = "Extract Layout"
hosts = ["unreal"]
families = ["layout"]
optional = True
def process(self, instance):
# Define extract output file path
staging_dir = self.staging_dir(instance)
# Perform extraction
self.log.info("Performing extraction..")
# Check if the loaded level is the same of the instance
current_level = ell.get_editor_world().get_path_name()
assert current_level == instance.data.get("level"), \
"Wrong level loaded"
json_data = []
project_name = instance.context.data["projectName"]
for member in instance[:]:
actor = ell.get_actor_reference(member)
mesh = None
# Check type the type of mesh
if actor.get_class().get_name() == 'SkeletalMeshActor':
mesh = actor.skeletal_mesh_component.skeletal_mesh
elif actor.get_class().get_name() == 'StaticMeshActor':
mesh = actor.static_mesh_component.static_mesh
if mesh:
# Search the reference to the Asset Container for the object
path = unreal.Paths.get_path(mesh.get_path_name())
filter = unreal.ARFilter(
class_names=["AyonAssetContainer"], package_paths=[path])
ar = unreal.AssetRegistryHelpers.get_asset_registry()
try:
asset_container = ar.get_assets(filter)[0].get_asset()
except IndexError:
self.log.error("AssetContainer not found.")
return
parent_id = eal.get_metadata_tag(asset_container, "parent")
family = eal.get_metadata_tag(asset_container, "family")
self.log.info("Parent: {}".format(parent_id))
blend = ayon_api.get_representation_by_name(
project_name, "blend", parent_id, fields={"id"}
)
blend_id = blend["id"]
json_element = {}
json_element["reference"] = str(blend_id)
json_element["family"] = family
json_element["product_type"] = family
json_element["instance_name"] = actor.get_name()
json_element["asset_name"] = mesh.get_name()
import_data = mesh.get_editor_property("asset_import_data")
json_element["file_path"] = import_data.get_first_filename()
transform = actor.get_actor_transform()
json_element["transform"] = {
"translation": {
"x": -transform.translation.x,
"y": transform.translation.y,
"z": transform.translation.z
},
"rotation": {
"x": math.radians(transform.rotation.euler().x),
"y": math.radians(transform.rotation.euler().y),
"z": math.radians(180.0 - transform.rotation.euler().z)
},
"scale": {
"x": transform.scale3d.x,
"y": transform.scale3d.y,
"z": transform.scale3d.z
}
}
json_data.append(json_element)
json_filename = "{}.json".format(instance.name)
json_path = os.path.join(staging_dir, json_filename)
with open(json_path, "w+") as file:
json.dump(json_data, fp=file, indent=2)
if "representations" not in instance.data:
instance.data["representations"] = []
json_representation = {
'name': 'json',
'ext': 'json',
'files': json_filename,
"stagingDir": staging_dir,
}
instance.data["representations"].append(json_representation)
|
import unreal
from ueGear.controlrig.paths import CONTROL_RIG_FUNCTION_PATH
import ueGear.controlrig.manager as ueMan
from ueGear.controlrig.components import base_component, EPIC_control_01
from ueGear.controlrig.helpers import controls
# TODO:
# [ ] Multiple joints can be generated by the component
# [ ] The start of each bone should have its own fk control.
# [ ] The end joint should be driven the "head" fk control
class Component(base_component.UEComponent):
name = "neck"
mgear_component = "EPIC_neck_02"
def __init__(self):
super().__init__()
self.functions = {'construction_functions': ['construct_neck'],
'forward_functions': ['forward_neck'],
'backwards_functions': ['backwards_neck'],
}
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
# Skip the backwards function creation if no joints are needed to be driven
if evaluation_path == 'backwards_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_joints')
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}.fk_joints')
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')
pins_exist = ueMan.array_node_has_pins(array_name, controller)
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.
"""
pin_index = 0
# Calculates the unreal scale for the control and populates it into the array node.
for control_name in 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 the spine, 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] < 1.0:
unreal_size[2] = unreal_size[0]
if not pins_exist:
existing_pin_count = len(array_node.get_pins()[0].get_sub_pins())
if existing_pin_count < len(self.metadata.controls_aabb):
controller.insert_array_pin(f'{array_name}.Values',
-1,
'')
controller.set_pin_default_value(f'{array_name}.Values.{pin_index}',
f'(X={unreal_size[0]},Y={unreal_size[1]},Z={unreal_size[2]})',
False)
pin_index += 1
def populate_control_names(self, controller: unreal.RigVMController):
import ueGear.controlrig.manager as ueMan
names_node = ueMan.create_array_node(f"{self.metadata.fullname}_control_names", controller)
node_names = controller.get_graph().find_node_by_name(names_node)
self.add_misc_function(node_names)
# 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()
controller.add_link(f'{names_node}.Array',
f'{construction_func_name}.fk_names')
# Checks the pins
name_pins_exist = ueMan.array_node_has_pins(names_node, controller)
pin_index = 0
for control_name in self.metadata.controls:
if not name_pins_exist:
found_node = controller.get_graph().find_node_by_name(names_node)
existing_pin_count = len(found_node.get_pins()[0].get_sub_pins())
if existing_pin_count < len(self.metadata.controls):
controller.insert_array_pin(f'{names_node}.Values',
-1,
'')
controller.set_pin_default_value(f'{names_node}.Values.{pin_index}',
control_name,
False)
pin_index += 1
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.
"""
import ueGear.controlrig.manager as ueMan
trans_node = ueMan.create_array_node(f"{self.metadata.fullname}_control_transforms", controller)
node_trans = controller.get_graph().find_node_by_name(trans_node)
self.add_misc_function(node_trans)
# 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()
controller.add_link(f'{trans_node}.Array',
f'{construction_func_name}.control_transforms')
# Checks the pins
trans_pins_exist = ueMan.array_node_has_pins(trans_node, controller)
pin_index = 0
for control_name in self.metadata.controls:
control_transform = self.metadata.control_transforms[control_name]
if not trans_pins_exist:
found_node = controller.get_graph().find_node_by_name(trans_node)
existing_pin_count = len(found_node.get_pins()[0].get_sub_pins())
if existing_pin_count < len(self.metadata.controls):
controller.insert_array_pin(f'{trans_node}.Values',
-1,
'')
quat = control_transform.rotation
pos = control_transform.translation
controller.set_pin_default_value(f"{trans_node}.Values.{pin_index}",
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))",
True)
pin_index += 1
# TODO: setup an init_controls method and move this method and the populate controls method into it
self.populate_control_names(controller)
self.populate_control_scale(controller)
self.populate_control_shape_offset(controller)
self.populate_control_colour(controller)
def populate_control_colour(self, controller):
cr_func = self.functions["construction_functions"][0]
construction_node = f"{self.name}_{cr_func}"
for i, control_name in enumerate(self.metadata.controls):
colour = self.metadata.controls_colour[control_name]
controller.insert_array_pin(f'{construction_node}.control_colours', -1, '')
controller.set_pin_default_value(f'{construction_node}.control_colours.{i}.R', f"{colour[0]}", False)
controller.set_pin_default_value(f'{construction_node}.control_colours.{i}.G', f"{colour[1]}", False)
controller.set_pin_default_value(f'{construction_node}.control_colours.{i}.B', f"{colour[2]}", False)
controller.set_pin_default_value(f'{construction_node}.control_colours.{i}.A', "1", False)
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')
pins_exist = ueMan.array_node_has_pins(array_name, controller)
pin_index = 0
for control_name in self.metadata.controls:
aabb = self.metadata.controls_aabb[control_name]
bb_center = aabb[0]
if not pins_exist:
existing_pin_count = len(array_node.get_pins()[0].get_sub_pins())
if existing_pin_count < len(self.metadata.controls_aabb):
controller.insert_array_pin(f'{array_name}.Values',
-1,
'')
controller.set_pin_default_value(f'{array_name}.Values.{pin_index}',
f'(X={bb_center[0]},Y={bb_center[1]},Z={bb_center[2]})',
False)
pin_index += 1
class ManualComponent(Component):
name = "EPIC_neck_02"
def __init__(self):
super().__init__()
self.functions = {'construction_functions': ['manual_construct_neck'],
'forward_functions': ['forward_neck'],
'backwards_functions': ['backwards_neck'],
}
self.is_manual = True
# These are the roles that will be parented directly under the parent component.
self.root_control_children = ["ik", "fk0"]
self.hierarchy_schematic_roles = {}
# Default to fall back onto
self.default_shape = "Box_Thick"
self.control_shape = {
"ik": "Box_Thick",
"head": "Box_Thick"
}
# ignores building the controls with the specific role
self.skip_roles = ["ik"]
def create_functions(self, controller: unreal.RigVMController):
EPIC_control_01.ManualComponent.create_functions(self, controller)
self.setup_dynamic_hierarchy_roles(self.metadata.settings['division'], end_control_role="head")
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]
# Skip a control that contains a role that has any of the keywords to skip
if any([skip in role for skip in self.skip_roles]):
continue
# 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()
fk_controls = []
ik_controls = []
for role_key in self.control_by_role.keys():
# Generates the list of fk controls
if 'fk' in role_key or "head" 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)
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("ik_controls", ik_controls)
update_input_plug("fk_controls", fk_controls)
|
# code in init_unreal.py wil run on startup if the plugin is enabled
import unreal
section_name = "Plugins"
se_command = 'print("Test")'
label = "LcL-Tools2"
tooltip = "my tooltip"
@unreal.uclass()
class Test(unreal.ToolMenuEntryScript):
def __init__(self):
super().__init__()
self.data: unreal.ToolMenuEntryScriptData
self.data.name = "TestEntry"
self.data.label = "TestEntryLabel"
self.data.section = "TestSection"
self.data.tool_tip = "This is a test entry"
@unreal.ufunction(override=True)
def execute(self, context):
# 当菜单项被点击时执行此函数
unreal.log("LcL-Tools 菜单项被点击了!")
def create_script_editor_button():
"""Add a tool button to the tool bar"""
section_name = "Plugins"
label = "LcL-Tools"
tooltip = "my tooltip"
menus = unreal.ToolMenus.get()
level_menu_bar = menus.find_menu("LevelEditor.LevelEditorToolBar.PlayToolBar")
level_menu_bar.add_section(section_name=section_name, label=section_name)
entry = unreal.ToolMenuEntry(type=unreal.MultiBlockType.TOOL_BAR_BUTTON)
entry.set_label(label)
entry.set_tool_tip(tooltip)
entry.set_icon("EditorStyle", "DebugConsole.Icon")
level_menu_bar.add_menu_entry(section_name, entry)
menus.refresh_all_widgets()
def main():
menus = unreal.ToolMenus.get()
main_menu = menus.find_menu("LevelEditor.MainMenu")
# 创建脚本对象
script_obj = Test()
# 创建菜单项并设置脚本对象
entry = unreal.ToolMenuEntry(
type=unreal.MultiBlockType.MENU_ENTRY,
script_object=script_obj,
)
script_menu = main_menu.add_sub_menu(
main_menu.get_name(), "SectionTest2", "NameTest2", "Test2"
)
script_menu.add_menu_entry("Scripts", entry)
menus.refresh_all_widgets()
main()
|
# 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
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)
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'))
if (str(c.get_pin_default_value(node.find_pin('Items').get_pin_path())).find('_ALL_Angry_c') >= 0):
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))
h_con.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, 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())
control = hierarchy.find_control(k)
except:
k = h_con.add_control(name_c, space, settings, unreal.RigControlValue())
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())
control = hierarchy.find_control(k)
except:
k = h_con.add_control(name_c, space, settings, unreal.RigControlValue())
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
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, setup_undo_redo=False)
# 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, setup_undo_redo=False)
|
import unreal
info = dir(unreal)
for i in info:
unreal.log("unreal" + str(i))
|
import unreal
from Utilities.Utils import Singleton
import math
try:
import numpy as np
b_use_numpy = True
except:
b_use_numpy = False
class ImageCompare(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.left_texture_size = (128, 128)
self.right_texture_size = (128, 128)
self.dpi_scale = 1
self.ui_img_left = "ImageLeft"
self.ui_img_right = "ImageRight"
self.ui_img_right_bg = "ImageRightBG"
self.ui_comparison_widget = "ComparisonWidget"
self.ui_dpi_scaler = "Scaler"
self.ui_status_bar = "StatusBar"
self.ui_ignore_alpha = "AlphaCheckBox"
self.ui_scaler_combobox = "ScaleComboBox"
self.combobox_items = self.data.get_combo_box_items(self.ui_scaler_combobox)
self.update_status_bar()
def set_image_from_viewport(self, bLeft):
data, width_height = unreal.PythonBPLib.get_viewport_pixels_as_data()
w, h = width_height.x, width_height.y
channel_num = int(len(data) / w / h)
if b_use_numpy:
im = np.fromiter(data, dtype=np.uint8).reshape(w, h, channel_num)
self.data.set_image_data_from_memory(self.ui_img_left if bLeft else self.ui_img_right, im.ctypes.data, len(data)
, w, h, channel_num=channel_num, bgr=False
, tiling=unreal.SlateBrushTileType.HORIZONTAL if bLeft else unreal.SlateBrushTileType.NO_TILE)
else:
texture = unreal.PythonBPLib.get_viewport_pixels_as_texture()
self.data.set_image_data_from_texture2d(self.ui_img_left if bLeft else self.ui_img_right, texture
, tiling=unreal.SlateBrushTileType.HORIZONTAL if bLeft else unreal.SlateBrushTileType.NO_TILE)
if bLeft:
self.left_texture_size = (w, h)
else:
self.right_texture_size = (w, h)
self.update_dpi_by_texture_size()
self.fit_window_size()
def fit_window_size1(self):
size = unreal.ChameleonData.get_chameleon_desired_size(self.json_path)
def set_images_from_viewport(self):
unreal.AutomationLibrary.set_editor_viewport_view_mode(unreal.ViewModeIndex.VMI_LIT)
self.set_image_from_viewport(bLeft=True)
unreal.AutomationLibrary.set_editor_viewport_view_mode(unreal.ViewModeIndex.VMI_WIREFRAME)
self.set_image_from_viewport(bLeft=False)
unreal.AutomationLibrary.set_editor_viewport_view_mode(unreal.ViewModeIndex.VMI_LIT)
self.fit_window_size()
self.update_status_bar()
def update_dpi_by_texture_size(self):
max_size = max(self.left_texture_size[1], self.right_texture_size[1])
if max_size >= 64:
self.dpi_scale = 1 / math.ceil(max_size / 512)
else:
self.dpi_scale = 4 if max_size <= 16 else 2
print(f"Set dpi -> {self.dpi_scale }")
self.data.set_dpi_scale(self.ui_dpi_scaler, self.dpi_scale)
for index, value_str in enumerate(self.combobox_items):
if float(value_str) == self.dpi_scale:
self.data.set_combo_box_selected_item(self.ui_scaler_combobox, index)
break
def on_ui_change_scale(self, value_str):
self.dpi_scale = float(value_str)
self.data.set_dpi_scale(self.ui_dpi_scaler, self.dpi_scale)
self.fit_window_size()
def update_status_bar(self):
self.data.set_text(self.ui_status_bar, f"Left: {self.left_texture_size}, Right: {self.right_texture_size} ")
if self.left_texture_size != self.right_texture_size:
self.data.set_color_and_opacity(self.ui_status_bar, unreal.LinearColor(2, 0, 0, 1))
else:
self.data.set_color_and_opacity(self.ui_status_bar, unreal.LinearColor.WHITE)
def fit_window_size(self):
max_x = max(self.left_texture_size[0], self.right_texture_size[0])
max_y = max(self.left_texture_size[1], self.right_texture_size[1])
MIN_WIDTH = 400
MAX_HEIGHT = 900
self.data.set_chameleon_window_size(self.json_path
, unreal.Vector2D(max(MIN_WIDTH, max_x * self.dpi_scale + 18)
, min(MAX_HEIGHT, max_y * self.dpi_scale + 125))
)
def on_drop(self, bLeft, **kwargs):
for asset_path in kwargs["assets"]:
asset = unreal.load_asset(asset_path)
if isinstance(asset, unreal.Texture2D):
width = asset.blueprint_get_size_x()
height = asset.blueprint_get_size_y()
ignore_alpha = self.data.get_is_checked(self.ui_ignore_alpha)
if self.data.set_image_data_from_texture2d(self.ui_img_left if bLeft else self.ui_img_right, asset, ignore_alpha=ignore_alpha):
if bLeft:
self.left_texture_size = (width, height)
else:
self.right_texture_size = (width, height)
self.update_dpi_by_texture_size()
self.fit_window_size()
self.update_status_bar()
break
|
import unreal
# instances of unreal classes
editor_asset_lib = unreal.EditorAssetLibrary()
string_lib = unreal.StringLibrary()
# get all assets in source dir
source_dir = "/Game/"
include_subfolders = True
set_textures = 0
assets = editor_asset_lib.list_assets(source_dir, recursive = include_subfolders)
color_patterns = ["_ORM", "_OcclusionRoughnessMetallic","_Metallic","_Roughness","_Mask"]
for asset in assets:
# for every asset check it against all the patterns
for pattern in color_patterns:
if string_lib.contains(asset, pattern):
# load the asset, tunr off sRGB and set compression settings to TC_Mask
asset_obj = editor_asset_lib.load_asset(asset)
asset_obj.set_editor_property("sRGB",False)
asset_obj.set_editor_property("CompressionSettings", unreal.TextureCompressionSettings.TC_MASKS)
unreal.log("Setting TC_Masks and turning off sRGB for asset {}".format(asset))
set_textures += 1
break
unreal.log("Linear color for matching textures set for {} asset".format(set_textures))
|
# 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()
|
import unreal
import os
# instances of unreal classes
editor_util = unreal.EditorUtilityLibrary()
editor_asset_lib = unreal.EditorAssetLibrary()
# get the selected assets
selected_assets = editor_util.get_selected_assets()
num_assets = len(selected_assets)
removed = 0
# instantly delete assets or move to Trash folder
instant_delete = True
trash_folder = os.path.join(os.sep, "Game", "Trash")
to_be_deleted = []
for asset in selected_assets:
# get the full path to the to be duplicated asset
asset_name = asset.get_fname()
asset_path = editor_asset_lib.get_path_name_for_loaded_asset(asset)
# get a list of references for this asset
asset_references = editor_asset_lib.find_package_referencers_for_asset(asset_path)
if len(asset_references) == 0:
to_be_deleted.append(asset)
for asset in to_be_deleted:
asset_name = asset.get_fname()
# instantly delete the assets
if instant_delete:
deleted = editor_asset_lib.delete_loaded_asset(asset)
if not deleted:
unreal.log_warning("Asset {} could not be deleted".format(asset_name))
continue
removed += 1
# move the assets to the trash folder
else:
new_path = os.path.join(trash_folder, str(asset_name))
moved = editor_asset_lib.rename_loaded_asset(asset, new_path)
if not moved:
unreal.log_warning("Asset {} could not be moved to Trash".format(asset_name))
continue
removed += 1
output_test = "removed" if instant_delete else "moved to Trash folder"
unreal.log("{} of {} to be deleted assets, of {} selected, removed".format(removed, len(to_be_deleted), num_assets))
|
"""Spawn actors on the map based on map export data produced by MapExport.py. Should be used with internal UE API"""
import os.path
import unreal
import json
import re
# Change me!
map_data_filepath = "C:/project/ Projects/project/" \
"MapData/project/.json"
EXCLUDE_ENGINE_ASSETS = True
level_library = unreal.EditorLevelLibrary
editor_asset_library = unreal.EditorAssetLibrary
# relative_offset = unreal.Vector(-167598.703125, -1021464.375, +96750.0)
relative_offset_loc = unreal.Vector(0, 0, 0)
with open("C:/project/ Projects/project/"
"MapData/project/.json", "r") as f:
path_replacing_map = json.load(f)
with open(map_data_filepath, "rb") as f:
data = json.load(f)
for element in data:
path, transform = element["path"], element["transform"]
path = re.search(r"\w+\s(?P<path>[\/\w]+).\w+", path).group("path")
path = path_replacing_map.get(path, path)
print(path)
if path.startswith("/") and editor_asset_library.does_asset_exist(path):
if path.startswith("/Engine/") and EXCLUDE_ENGINE_ASSETS:
continue
asset = editor_asset_library.find_asset_data(path).get_asset()
actor = level_library.spawn_actor_from_object(asset, transform["loc"])
actor.set_actor_rotation(
unreal.Rotator(pitch=transform["rot"][0], roll=transform["rot"][1], yaw=transform["rot"][2]), True)
actor.set_actor_scale3d(transform["scale"])
current_location = actor.get_actor_location()
actor.set_actor_location(current_location + relative_offset_loc, False, False)
else:
print(f"Error: Asset {path} doesn't exist")
|
#!/project/ python3
"""
Script to update the character blueprint with all 8 animations
"""
import unreal
def log_message(message):
"""Print and log message"""
print(message)
unreal.log(message)
def update_character_blueprint_with_all_animations():
"""Update character blueprint to be consistent with C++ changes"""
log_message("=== UPDATING CHARACTER BLUEPRINT WITH ALL 8 ANIMATIONS ===")
try:
# Load character blueprint
bp_path = "/project/"
bp = unreal.EditorAssetLibrary.load_asset(bp_path)
if not bp:
log_message("✗ Could not load character blueprint")
return False
log_message("✓ Loaded character blueprint")
# Load all 8 animations
animations = {
"Idle": "/project/",
"Move": "/project/",
"AttackUpwards": "/project/",
"AttackDownwards": "/project/",
"AttackSideways": "/project/",
"AttackUpwards2": "/project/",
"AttackDownwards2": "/project/",
"AttackSideways2": "/project/"
}
loaded_animations = {}
for name, path in animations.items():
if unreal.EditorAssetLibrary.does_asset_exist(path):
anim = unreal.EditorAssetLibrary.load_asset(path)
if anim and isinstance(anim, unreal.PaperFlipbook):
loaded_animations[name] = anim
log_message(f"✓ Loaded {name} animation")
else:
log_message(f"✗ {name} is not a valid PaperFlipbook")
else:
log_message(f"✗ {name} animation does not exist at {path}")
if len(loaded_animations) != 8:
log_message(f"✗ Only loaded {len(loaded_animations)}/8 animations")
return False
# Get the blueprint's default object
bp_class = bp.generated_class()
if not bp_class:
log_message("✗ Blueprint has no generated class")
return False
default_obj = bp_class.get_default_object()
if not default_obj:
log_message("✗ Blueprint has no default object")
return False
# Set the default animation to Idle on the sprite component
if hasattr(default_obj, 'sprite'):
sprite_comp = default_obj.sprite
if sprite_comp and 'Idle' in loaded_animations:
sprite_comp.set_flipbook(loaded_animations['Idle'])
log_message("✓ Set Idle animation as default on sprite component")
else:
log_message("✗ Could not access sprite component")
else:
log_message("✗ Character has no sprite attribute")
# Save the blueprint
unreal.EditorAssetLibrary.save_asset(bp_path)
log_message("✓ Saved character blueprint")
# Compile the blueprint
unreal.KismetSystemLibrary.compile_blueprint(bp)
log_message("✓ Compiled character blueprint")
return True
except Exception as e:
log_message(f"✗ Error updating character blueprint: {str(e)}")
return False
def verify_all_animations_exist():
"""Verify all 8 required animations exist"""
log_message("\n=== VERIFYING ALL 8 ANIMATIONS EXIST ===")
animations = [
"/project/",
"/project/",
"/project/",
"/project/",
"/project/",
"/project/",
"/project/",
"/project/"
]
all_exist = True
for anim_path in animations:
if unreal.EditorAssetLibrary.does_asset_exist(anim_path):
anim = unreal.EditorAssetLibrary.load_asset(anim_path)
if anim and isinstance(anim, unreal.PaperFlipbook):
frames = anim.get_num_frames()
log_message(f"✓ {anim_path.split('/')[-1]}: {frames} frames")
else:
log_message(f"✗ {anim_path}: Not a valid PaperFlipbook")
all_exist = False
else:
log_message(f"✗ {anim_path}: Does not exist")
all_exist = False
return all_exist
def create_test_input_mappings():
"""Document the input mappings for testing"""
log_message("\n=== INPUT MAPPINGS FOR TESTING ===")
log_message("Movement:")
log_message(" W/project/ - Move character")
log_message(" Space - Jump")
log_message("")
log_message("Primary Attacks:")
log_message(" Up Arrow - Attack Up")
log_message(" Down Arrow - Attack Down")
log_message(" Left Arrow - Attack Left")
log_message(" Right Arrow - Attack Right")
log_message(" Left Mouse - General Attack")
log_message("")
log_message("Secondary Attacks (with Shift):")
log_message(" Shift + Up Arrow - Attack Up 2")
log_message(" Shift + Down Arrow - Attack Down 2")
log_message(" Shift + Left Arrow - Attack Left 2")
log_message(" Shift + Right Arrow - Attack Right 2")
def main():
"""Main function"""
log_message("=" * 80)
log_message("CHARACTER BLUEPRINT UPDATE FOR ALL 8 ANIMATIONS")
log_message("=" * 80)
# Check 1: Verify all animations exist
animations_exist = verify_all_animations_exist()
# Check 2: Update character blueprint
blueprint_updated = update_character_blueprint_with_all_animations()
# Check 3: Document input mappings
create_test_input_mappings()
# Summary
log_message("\n" + "=" * 80)
log_message("UPDATE SUMMARY:")
log_message(f"✓ All 8 animations exist: {'YES' if animations_exist else 'NO'}")
log_message(f"✓ Character blueprint updated: {'YES' if blueprint_updated else 'NO'}")
if animations_exist and blueprint_updated:
log_message("\n🎉 CHARACTER BLUEPRINT SUCCESSFULLY UPDATED!")
log_message("✅ Character now supports all 8 animations!")
log_message("")
log_message("TESTING INSTRUCTIONS:")
log_message("1. Launch the editor and open TestLevel")
log_message("2. Click Play to enter PIE mode")
log_message("3. Test movement with WASD keys")
log_message("4. Test primary attacks with arrow keys")
log_message("5. Test secondary attacks with Shift + arrow keys")
log_message("6. Verify all animations play correctly")
else:
log_message("\n❌ BLUEPRINT UPDATE FAILED!")
log_message("Check the errors above for details.")
log_message("=" * 80)
if __name__ == "__main__":
main()
|
# Copyright Epic Games, Inc. All Rights Reserved.
import os
import re
import unreal
import tempfile
import flow.cmd
import unrealcmd
import prettyprinter
#-------------------------------------------------------------------------------
def _fuzzy_find_code(prompt):
import fzf
import subprocess as sp
rg_args = (
"rg",
"--files",
"--path-separator=/",
"--no-ignore",
"-g*.cpp", "-g*.Build.cs",
"--ignore-file=" + os.path.abspath(__file__ + "/../../dirs.rgignore"),
)
rg = sp.Popen(rg_args, stdout=sp.PIPE, stderr=sp.DEVNULL, stdin=sp.DEVNULL)
ret = None
for reply in fzf.run(None, prompt=prompt, ext_stdin=rg.stdout):
ret = reply
break
rg.stdout.close()
rg.terminate()
return ret
#-------------------------------------------------------------------------------
class _Builder(object):
def __init__(self, ue_context):
self._args = []
self._ue_context = ue_context
self._targets = ()
self._projected = False
self.set_platform(unreal.Platform.get_host())
self.set_variant("development")
def set_targets(self, *targets): self._targets = targets
def set_platform(self, platform): self._platform = platform
def set_variant(self, variant): self._variant = variant
def set_projected(self, value=True):self._projected = value
def add_args(self, *args):
self._args += list(args)
def read_actions(self):
platform = self._platform
variant = self._variant
targets = (x.get_name() for x in self._targets)
args = self._args
projected = any(x.is_project_target() for x in self._targets)
if self._projected or projected:
if project := self._ue_context.get_project():
args = ("-Project=" + str(project.get_path()), *args)
ubt = self._ue_context.get_engine().get_ubt()
yield from ubt.read_actions(*targets, platform, variant, *args)
#-------------------------------------------------------------------------------
class _PrettyPrinter(prettyprinter.Printer):
def __init__(self, logger):
self._source_re = re.compile(r"^(\s+\[[0-9/]+\]\s+|)([^ ]+\.[a-z]+)")
self._error_re = re.compile("([Ee]rror:|ERROR|Exception: |error LNK|error C)")
self._warning_re = re.compile("(warning C|[Ww]arning: |note:)")
self._progress_re = re.compile(r"^\s*@progress\s+('([^']+)'|\w+)(\s+(\d+))?")
self._for_target_re = re.compile(r"^\*\* For ([^\s]+) \*\*")
self._percent = 0
self._for_target = ""
self._section = None
self._logger = logger
self._error_file = tempfile.TemporaryFile(mode="w+t")
def print_error_summary(self):
import textwrap
import shutil
msg_width = shutil.get_terminal_size(fallback=(9999,0))[0]
error_file = self._error_file
error_file.seek(0);
files = {}
for line in error_file:
m = re.search(r"\s*(.+\.[a-z]+)[(:](\d+)[,:)0-9]+\s*(.+)$", line[1:])
if not m:
continue
line_no = int(m.group(2), 0)
lines = files.setdefault(m.group(1), {})
msgs = lines.setdefault(line_no, set())
msgs.add((line[0] != "W", m.group(3)))
if not files:
return
print()
print(flow.cmd.text.light_yellow("Errors and warnings:"))
print()
msg_width -= 6
for file_path, lines in files.items():
print(flow.cmd.text.white(file_path))
for line in sorted(lines.keys()):
msgs = lines[line]
print(
" Line",
flow.cmd.text.white(line),
flow.cmd.text.grey("/ " + os.path.basename(file_path))
)
for is_error, msg in msgs:
decorator = flow.cmd.text.light_red if is_error else flow.cmd.text.light_yellow
with decorator:
for msg_line in textwrap.wrap(msg, width=msg_width):
print(" ", msg_line)
def _print(self, line):
if " Creating library " in line:
return
progress = self._progress_re.search(line)
if progress:
next_section = progress.group(2)
if next_section:
self._percent = min(int(progress.group(3)), 100)
if next_section != self._section:
self._section = next_section
self._logger.print_info(self._section)
return
if self._error_re.search(line):
line = line.lstrip()
print("E", line, sep="", file=self._error_file)
print(flow.cmd.text.light_red(line))
return
if self._warning_re.search(line):
line = line.lstrip()
if "note:" not in line:
print("W", line, sep="", file=self._error_file)
print(flow.cmd.text.light_yellow(line))
return
for_target = self._for_target_re.search(line)
if for_target:
for_target = for_target.group(1)
self._for_target = for_target[:5]
return
out = ""
if self._section != None:
out = flow.cmd.text.grey("%3d%%" % self._percent) + " "
source = self._source_re.search(line)
if source:
spos, epos = source.span(2)
if self._for_target:
out += flow.cmd.text.grey(self._for_target)
out += " "
out += line[:spos]
out += flow.cmd.text.white(line[spos:epos])
out += line[epos:]
else:
out += line
print(out)
#-------------------------------------------------------------------------------
class _BuildCmd(unrealcmd.Cmd):
""" The 'fileormod' argument allows the build to be constrained to a specific
module or source file to. It accepts one of the following forms as input;
CoreTest - builds the target's "CoreTest" module
CoreTest/SourceFile.cpp - compiles CoreTest/Private/**/SourceFile.cpp
path/project/.cpp - absolute or relative single file to compile
- - fuzzy find the file/modules to build (single dash)
"""
_variant = unrealcmd.Arg("development", "The build variant to have the build build")
fileormod = unrealcmd.Arg("", "Constrain build to a single file or module")
ubtargs = unrealcmd.Arg([str], "Arguments to pass to UnrealBuildTool")
clean = unrealcmd.Opt(False, "Cleans the current build")
nouht = unrealcmd.Opt(False, "Skips building UnrealHeaderTool")
noxge = unrealcmd.Opt(False, "Disables IncrediBuild")
analyze = unrealcmd.Opt(("", "visualcpp"), "Run static analysis (add =pvsstudio for PVS)")
projected = unrealcmd.Opt(False, "Add the -Project= argument when running UnrealBuildTool")
complete_analyze = ("visualcpp", "pvsstudio")
#complete_ubtargs = ...see end of file
def complete_fileormod(self, prefix):
search_roots = (
"Source/Runtime/*",
"Source/Developer/*",
"Source/Editor/*",
)
ue_context = self.get_unreal_context()
if prefix:
from pathlib import Path
for root in search_roots:
for suffix in ("./Private/", "./Internal/"):
haystack = root[:-1] + prefix + suffix
yield from (x.name for x in ue_context.glob(haystack + "**/*.cpp"))
else:
seen = set()
for root in search_roots:
for item in (x for x in ue_context.glob(root) if x.is_dir()):
if item.name not in seen:
seen.add(item.name)
yield item.name
yield item.name + "/"
def _add_file_or_module(self, builder):
file_or_module = self.args.fileormod
self._constrained_build = bool(file_or_module)
if not file_or_module:
return
if file_or_module == "-":
print("Select .cpp/.Build.cs...", end="")
file_or_module = _fuzzy_find_code(".build [...] ")
if not file_or_module:
raise SystemExit
if file_or_module.endswith(".Build.cs"):
file_or_module = os.path.basename(file_or_module)[:-9]
ue_context = self.get_unreal_context()
all_modules = True
if project := ue_context.get_project():
project_path_str = str(project.get_dir())
all_modules = any(x in project_path_str for x in ("EngineTest", "Samples"))
if all_modules:
builder.add_args("-AllModules")
# If there's no ./\ in the argument then it is deemed to be a module
if not any((x in ".\\/") for x in file_or_module):
builder.add_args("-Module=" + file_or_module)
return
# We're expecting a file
if os.path.isfile(file_or_module):
file_or_module = os.path.abspath(file_or_module)
# (...N.B. an elif follows)
# Perhaps this is in module/file shorthand?
elif shorthand := file_or_module.split("/"):
rglob_pattern = "/".join(shorthand[1:])
search_roots = (
"Source/Runtime/",
"Source/Developer/",
"Source/Editor/",
)
for root in search_roots:
for item in ue_context.glob(root + shorthand[0]):
if file := next(item.rglob(rglob_pattern), None):
file_or_module = str(file.resolve())
break
builder.add_args("-SingleFile=" + file_or_module)
builder.add_args("-SkipDeploy")
def is_constrained_build(self):
return getattr(self, "_constrained_build", False)
def get_builder(self):
ue_context = self.get_unreal_context()
builder = _Builder(ue_context)
if self.args.clean: builder.add_args("-Clean")
if self.args.nouht: builder.add_args("-NoBuildUHT")
if self.args.noxge: builder.add_args("-NoXGE")
if self.args.analyze: builder.add_args("-StaticAnalyzer=" + self.args.analyze)
if self.args.ubtargs: builder.add_args(*self.args.ubtargs)
if self.args.projected: builder.set_projected() # forces -Project=
builder.add_args("-Progress")
# Handle shortcut to compile a specific module or individual file.
self._add_file_or_module(builder)
return builder
def run_build(self, builder):
try: exec_context = self._exec_context
except AttributeError: self._exec_context = self.get_exec_context()
exec_context = self._exec_context
# Inform the user of the current build configuration
self.print_info("Build configuration")
ue_context = self.get_unreal_context()
ubt = ue_context.get_engine().get_ubt()
for config in (x for x in ubt.read_configurations() if x.exists()):
level = config.get_level()
try:
for category, name, value in config.read_values():
name = flow.cmd.text.white(name)
print(category, ".", name, " = ", value, " (", level.name.title(), ")", sep="")
except IOError as e:
self.print_warning(f"Failed loading '{config.get_path()}'")
self.print_warning(str(e))
continue
self.print_info("Running UnrealBuildTool")
printer = _PrettyPrinter(self)
try:
for cmd, args in builder.read_actions():
cmd = exec_context.create_runnable(cmd, *args)
printer.run(cmd)
if ret := cmd.get_return_code():
break
else:
return
except KeyboardInterrupt:
raise KeyboardInterrupt("Waiting for UBT...")
finally:
printer.print_error_summary()
return ret
#-------------------------------------------------------------------------------
class Build(_BuildCmd, unrealcmd.MultiPlatformCmd):
""" Direct access to running UBT """
target = unrealcmd.Arg(str, "Name of the target to build")
platform = unrealcmd.Arg("", "Platform to build (default = host)")
variant = _BuildCmd._variant
def complete_target(self, prefix):
ue_context = self.get_unreal_context()
ubt_manifests = list(ue_context.glob("Intermediate/project/*RulesManifest.json"))
if not ubt_manifests:
yield from (x.name[:-10] for x in ue_context.glob("Source/*.Target.cs"))
yield from (x.name[:-10] for x in ue_context.glob("Source/Programs/*/*.Target.cs"))
for item in ubt_manifests:
with item.open("rt") as inp:
for line in inp:
if ".Target.cs" not in line:
continue
slash = line.rfind("\\")
if -1 == (slash := slash if slash != -1 else line.rfind("/")):
continue
line = line[slash + 1:]
if -1 == (dot := line.find(".")):
continue
yield line[:dot]
@unrealcmd.Cmd.summarise
def main(self):
self.use_all_platforms()
ue_context = self.get_unreal_context()
targets = self.args.target.split()
targets = map(ue_context.get_target_by_name, targets)
builder = self.get_builder()
builder.set_targets(*targets)
builder.set_variant(self.args.variant)
if self.args.platform:
try: platform = self.get_platform(self.args.platform).get_name()
except ValueError: platform = self.args.platform
builder.set_platform(platform)
return self.run_build(builder)
#-------------------------------------------------------------------------------
def _add_clean_cmd(cmd_class):
# Create a class for a CleanX command
class _Clean(object):
def main(self):
self.args.clean = True
return super().main()
clean_name = "Clean" + cmd_class.__name__
clean_class = type(clean_name, (_Clean, cmd_class), {})
globals()[clean_name] = clean_class
# Rather crudely change the first work from Build to Clean
doc = cmd_class.__doc__.lstrip()
if doc.startswith("Builds"):
new_cmd_class = type(cmd_class.__name__, (cmd_class,), {})
new_cmd_class.__doc__ = doc
cmd_class.__doc__ = None
cmd_class = new_cmd_class
doc = "Cleans" + doc[6:]
clean_class.__doc__ = doc
return cmd_class
#-------------------------------------------------------------------------------
@_add_clean_cmd
class Editor(_BuildCmd, unrealcmd.MultiPlatformCmd):
""" Builds the editor. By default the current host platform is targeted. This
can be overridden using the '--platform' option to cross-compile the editor."""
variant = _BuildCmd._variant
noscw = unrealcmd.Opt(False, "Skip building ShaderCompileWorker")
nopak = unrealcmd.Opt(False, "Do not build UnrealPak")
nointworker = unrealcmd.Opt(False, "Exclude the implicit InterchangeWorker dependency")
platform = unrealcmd.Opt("", "Platform to build the editor for")
@unrealcmd.Cmd.summarise
def main(self):
self.use_all_platforms()
builder = self.get_builder()
builder.set_variant(self.args.variant)
if self.args.platform:
platform = self.get_platform(self.args.platform).get_name()
builder.set_platform(platform)
ue_context = self.get_unreal_context()
editor_target = ue_context.get_target_by_type(unreal.TargetType.EDITOR)
targets = (editor_target,)
editor_only = self.is_constrained_build() # i.e. single file or module
editor_only |= bool(self.args.analyze)
editor_only |= self.args.variant != "development"
if not editor_only:
targets_to_add = []
if not self.args.noscw:
targets_to_add.append("ShaderCompileWorker")
if not self.args.nopak:
targets_to_add.append("UnrealPak")
if not self.args.nointworker:
targets_to_add.append("InterchangeWorker")
for name in targets_to_add:
prog_target = ue_context.get_target_by_name(name)
if prog_target.get_type() == unreal.TargetType.PROGRAM:
targets = (*targets, prog_target)
builder.set_targets(*targets)
return self.run_build(builder)
#-------------------------------------------------------------------------------
@_add_clean_cmd
class Program(_BuildCmd, unrealcmd.MultiPlatformCmd):
""" Builds a program for the current host platform (unless the --platform
argument is provided) """
program = unrealcmd.Arg(str, "Target name of the program to build")
variant = _BuildCmd._variant
platform = unrealcmd.Opt("", "Platform to build the program for")
def complete_program(self, prefix):
ue_context = self.get_unreal_context()
for depth in ("*", "*/*"):
for target_cs in ue_context.glob(f"Source/Programs/{depth}/*.Target.cs"):
yield target_cs.name[:-10]
@unrealcmd.Cmd.summarise
def main(self):
ue_context = self.get_unreal_context()
target = ue_context.get_target_by_name(self.args.program)
builder = self.get_builder()
builder.set_targets(target)
builder.set_variant(self.args.variant)
self.use_all_platforms()
if self.args.platform:
platform = self.get_platform(self.args.platform).get_name()
builder.set_platform(platform)
return self.run_build(builder)
#-------------------------------------------------------------------------------
@_add_clean_cmd
class Server(_BuildCmd, unrealcmd.MultiPlatformCmd):
""" Builds the server target for the host platform """
platform = unrealcmd.Arg("", "Platform to build the server for")
variant = _BuildCmd._variant
complete_platform = ("win64", "linux")
@unrealcmd.Cmd.summarise
def main(self):
# Set up the platform, defaulting to the host if none was given.
platform = self.args.platform
if not platform:
platform = unreal.Platform.get_host()
self.use_platform(self.args.platform)
ue_context = self.get_unreal_context()
target = ue_context.get_target_by_type(unreal.TargetType.SERVER)
builder = self.get_builder()
builder.set_targets(target)
builder.set_variant(self.args.variant)
if self.args.platform:
platform = self.get_platform(self.args.platform).get_name()
builder.set_platform(platform)
return self.run_build(builder)
#-------------------------------------------------------------------------------
class _Runtime(_BuildCmd, unrealcmd.MultiPlatformCmd):
platform = unrealcmd.Arg("", "Build the runtime for this platform")
variant = _BuildCmd._variant
@unrealcmd.Cmd.summarise
def _main_impl(self, target):
platform = self.args.platform
if not platform:
platform = unreal.Platform.get_host().lower()
self.use_platform(platform)
platform = self.get_platform(platform).get_name()
builder = self.get_builder()
builder.set_platform(platform)
builder.set_targets(target)
builder.set_variant(self.args.variant)
return self.run_build(builder)
#-------------------------------------------------------------------------------
@_add_clean_cmd
class Client(_Runtime):
""" Builds the client runtime """
def main(self):
ue_context = self.get_unreal_context()
target = ue_context.get_target_by_type(unreal.TargetType.CLIENT)
return super()._main_impl(target)
#-------------------------------------------------------------------------------
@_add_clean_cmd
class Game(_Runtime):
""" Builds the game runtime target binary executable """
def main(self):
ue_context = self.get_unreal_context()
target = ue_context.get_target_by_type(unreal.TargetType.GAME)
return super()._main_impl(target)
#-------------------------------------------------------------------------------
_BuildCmd.complete_ubtargs = (
"-2015", "-2017", "-2019", "-AllModules", "-alwaysgeneratedsym",
"-Architectures", "-build-as-framework", "-BuildPlugin", "-BuildVersion",
"-BundleVersion", "-Clean", "-CLion", "-CMakefile", "-CodeliteFiles",
"-CompileAsDll", "-CompileChaos", "-CompilerArguments", "-CompilerVersion",
"-CppStd", "-CreateStub", "-Define:", "-DependencyList", "-Deploy",
"-DisableAdaptiveUnity", "-DisablePlugin", "-DisableUnity", "-distribution",
"-dSYM", "-EdditProjectFiles", "-EnableASan", "-EnableMSan",
"-EnablePlugin", "-EnableTSan", "-EnableUBSan",
"-FailIfGeneratedCodeChanges", "-FastMonoCalls", "-FastPDB", "-FlushMac",
"-ForceDebugInfo", "-ForceHeaderGeneration", "-ForceHotReload",
"-ForceUnity", "-Formal", "-FromMsBuild", "-generatedsymbundle",
"-generatedsymfile", "-GPUArchitectures", "-IgnoreJunk",
"-ImportCertificate", "-ImportCertificatePassword", "-ImportProvision",
"-IncrementalLinking", "-Input", "-IWYU", "-KDevelopfile",
"-LinkerArguments", "-LiveCoding", "-LiveCodingLimit",
"-LiveCodingManifest", "-LiveCodingModules", "-Log", "-LTCG", "-Makefile",
"-Manifest", "-MapFile", "-MaxParallelActions", "-Modular", "-Module",
"-Monolithic", "-NoBuildUHT", "-NoCompileChaos", "-NoDebugInfo", "-NoDSYM",
"-NoEngineChanges", "-NoFASTBuild", "-NoFastMonoCalls", "-NoHotReload",
"-NoHotReloadFromIDE", "-NoIncrementalLinking", "-NoLink",
"-NoManifestChanges", "-NoMutex", "-NoPCH", "-NoPDB", "-NoSharedPCH",
"-NoUBTMakefiles", "-NoUseChaos", "-NoXGE", "-ObjSrcMap", "-Output",
"-OverrideBuildEnvironment", "-PGOOptimize", "-PGOProfile", "-Plugin",
"-Precompile", "-Preprocess", "-PrintDebugInfo", "-Progress",
"-ProjectDefine:", "-ProjectFileFormat", "-ProjectFiles",
"-PublicSymbolsByDefault", "-QMakefile", "-Quiet", "-RemoteIni", "-Rider",
"-rtti", "-ShadowVariableErrors", "-SharedBuildEnvironment",
"-ShowIncludes", "-SingleFile", "-SkipBuild", "-skipcrashlytics",
"-SkipDeploy", "-SkipPreBuildTargets", "-SkipRulesCompile",
"-StaticAnalyzer", "-StressTestUnity", "-Strict", "-stripsymbols",
"-ThinLTO", "-Timestamps", "-Timing", "-ToolChain", "-Tracing",
"-UniqueBuildEnvironment", "-UseChaos", "-UsePrecompiled", "-Verbose",
"-VeryVerbose", "-VSCode", "-VSMac", "-WaitMutex", "-WarningsAsErrors",
"-WriteOutdatedActions", "-XCodeProjectFiles", "-XGEExport",
)
|
# 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
class ProcessHDA(object):
""" An object that wraps async processing of an HDA (instantiating,
cooking/project/ an HDA), with functions that are called at the
various stages of the process, that can be overridden by subclasses for
custom funtionality:
- on_failure()
- on_complete(): upon successful completion (could be PostInstantiation
if auto cook is disabled, PostProcessing if auto bake is disabled, or
after PostAutoBake if auto bake is enabled.
- on_pre_instantiation(): before the HDA is instantiated, a good place
to set parameter values before the first cook.
- on_post_instantiation(): after the HDA is instantiated, a good place
to set/configure inputs before the first cook.
- on_post_auto_cook(): right after a cook
- on_pre_process(): after a cook but before output objects have been
created/processed
- on_post_processing(): after output objects have been created
- on_post_auto_bake(): after outputs have been baked
Instantiate the processor via the constructor and then call the activate()
function to start the asynchronous process.
"""
def __init__(
self,
houdini_asset,
instantiate_at=unreal.Transform(),
parameters=None,
node_inputs=None,
parameter_inputs=None,
world_context_object=None,
spawn_in_level_override=None,
enable_auto_cook=True,
enable_auto_bake=False,
bake_directory_path="",
bake_method=unreal.HoudiniEngineBakeOption.TO_ACTOR,
remove_output_after_bake=False,
recenter_baked_actors=False,
replace_previous_bake=False,
delete_instantiated_asset_on_completion_or_failure=False):
""" Instantiates an HDA in the specified world/level. Sets parameters
and inputs supplied in InParameters, InNodeInputs and parameter_inputs.
If bInEnableAutoCook is true, cooks the HDA. If bInEnableAutoBake is
true, bakes the cooked outputs according to the supplied baking
parameters.
This all happens asynchronously, with the various output pins firing at
the various points in the process:
- PreInstantiation: before the HDA is instantiated, a good place
to set parameter values before the first cook (parameter values
from ``parameters`` are automatically applied at this point)
- PostInstantiation: after the HDA is instantiated, a good place
to set/configure inputs before the first cook (inputs from
``node_inputs`` and ``parameter_inputs`` are automatically applied
at this point)
- PostAutoCook: right after a cook
- PreProcess: after a cook but before output objects have been
created/processed
- PostProcessing: after output objects have been created
- PostAutoBake: after outputs have been baked
- Completed: upon successful completion (could be PostInstantiation
if auto cook is disabled, PostProcessing if auto bake is disabled,
or after PostAutoBake if auto bake is enabled).
- Failed: If the process failed at any point.
Args:
houdini_asset (HoudiniAsset): The HDA to instantiate.
instantiate_at (Transform): The Transform to instantiate the HDA with.
parameters (Map(Name, HoudiniParameterTuple)): The parameters to set before cooking the instantiated HDA.
node_inputs (Map(int32, HoudiniPublicAPIInput)): The node inputs to set before cooking the instantiated HDA.
parameter_inputs (Map(Name, HoudiniPublicAPIInput)): The parameter-based inputs to set before cooking the instantiated HDA.
world_context_object (Object): A world context object for identifying the world to spawn in, if spawn_in_level_override is null.
spawn_in_level_override (Level): If not nullptr, then the HoudiniAssetActor is spawned in that level. If both spawn_in_level_override and world_context_object are null, then the actor is spawned in the current editor context world's current level.
enable_auto_cook (bool): If true (the default) the HDA will cook automatically after instantiation and after parameter, transform and input changes.
enable_auto_bake (bool): If true, the HDA output is automatically baked after a cook. Defaults to false.
bake_directory_path (str): The directory to bake to if the bake path is not set via attributes on the HDA output.
bake_method (HoudiniEngineBakeOption): The bake target (to actor vs blueprint). @see HoudiniEngineBakeOption.
remove_output_after_bake (bool): If true, HDA temporary outputs are removed after a bake. Defaults to false.
recenter_baked_actors (bool): Recenter the baked actors to their bounding box center. Defaults to false.
replace_previous_bake (bool): If true, on every bake replace the previous bake's output (assets + actors) with the new bake's output. Defaults to false.
delete_instantiated_asset_on_completion_or_failure (bool): If true, deletes the instantiated asset actor on completion or failure. Defaults to false.
"""
super(ProcessHDA, self).__init__()
self._houdini_asset = houdini_asset
self._instantiate_at = instantiate_at
self._parameters = parameters
self._node_inputs = node_inputs
self._parameter_inputs = parameter_inputs
self._world_context_object = world_context_object
self._spawn_in_level_override = spawn_in_level_override
self._enable_auto_cook = enable_auto_cook
self._enable_auto_bake = enable_auto_bake
self._bake_directory_path = bake_directory_path
self._bake_method = bake_method
self._remove_output_after_bake = remove_output_after_bake
self._recenter_baked_actors = recenter_baked_actors
self._replace_previous_bake = replace_previous_bake
self._delete_instantiated_asset_on_completion_or_failure = delete_instantiated_asset_on_completion_or_failure
self._asset_wrapper = None
self._cook_success = False
self._bake_success = False
@property
def asset_wrapper(self):
""" The asset wrapper for the instantiated HDA processed by this node. """
return self._asset_wrapper
@property
def cook_success(self):
""" True if the last cook was successful. """
return self._cook_success
@property
def bake_success(self):
""" True if the last bake was successful. """
return self._bake_success
@property
def houdini_asset(self):
""" The HDA to instantiate. """
return self._houdini_asset
@property
def instantiate_at(self):
""" The transform the instantiate the asset with. """
return self._instantiate_at
@property
def parameters(self):
""" The parameters to set on on_pre_instantiation """
return self._parameters
@property
def node_inputs(self):
""" The node inputs to set on on_post_instantiation """
return self._node_inputs
@property
def parameter_inputs(self):
""" The object path parameter inputs to set on on_post_instantiation """
return self._parameter_inputs
@property
def world_context_object(self):
""" The world context object: spawn in this world if spawn_in_level_override is not set. """
return self._world_context_object
@property
def spawn_in_level_override(self):
""" The level to spawn in. If both this and world_context_object is not set, spawn in the editor context's level. """
return self._spawn_in_level_override
@property
def enable_auto_cook(self):
""" Whether to set the instantiated asset to auto cook. """
return self._enable_auto_cook
@property
def enable_auto_bake(self):
""" Whether to set the instantiated asset to auto bake after a cook. """
return self._enable_auto_bake
@property
def bake_directory_path(self):
""" Set the fallback bake directory, for if output attributes do not specify it. """
return self._bake_directory_path
@property
def bake_method(self):
""" The bake method/target: for example, to actors vs to blueprints. """
return self._bake_method
@property
def remove_output_after_bake(self):
""" Remove temporary HDA output after a bake. """
return self._remove_output_after_bake
@property
def recenter_baked_actors(self):
""" Recenter the baked actors at their bounding box center. """
return self._recenter_baked_actors
@property
def replace_previous_bake(self):
""" Replace previous bake output on each bake. For the purposes of this
node, this would mostly apply to .uassets and not actors.
"""
return self._replace_previous_bake
@property
def delete_instantiated_asset_on_completion_or_failure(self):
""" Whether or not to delete the instantiated asset after Complete is called. """
return self._delete_instantiated_asset_on_completion_or_failure
def activate(self):
""" Activate the process. This will:
- instantiate houdini_asset and wrap it as asset_wrapper
- call on_failure() for any immediate failures
- otherwise bind to delegates from asset_wrapper so that the
various self.on_*() functions are called as appropriate
Returns immediately (does not block until cooking/processing is
complete).
Returns:
(bool): False if activation failed.
"""
# Get the API instance
houdini_api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
if not houdini_api:
# Handle failures: this will unbind delegates and call on_failure()
self._handle_on_failure()
return False
# Create an empty API asset wrapper
self._asset_wrapper = unreal.HoudiniPublicAPIAssetWrapper.create_empty_wrapper(houdini_api)
if not self._asset_wrapper:
# Handle failures: this will unbind delegates and call on_failure()
self._handle_on_failure()
return False
# Bind to the wrapper's delegates for instantiation, cooking, baking
# etc events
self._asset_wrapper.on_pre_instantiation_delegate.add_callable(
self._handle_on_pre_instantiation)
self._asset_wrapper.on_post_instantiation_delegate.add_callable(
self._handle_on_post_instantiation)
self._asset_wrapper.on_post_cook_delegate.add_callable(
self._handle_on_post_auto_cook)
self._asset_wrapper.on_pre_process_state_exited_delegate.add_callable(
self._handle_on_pre_process)
self._asset_wrapper.on_post_processing_delegate.add_callable(
self._handle_on_post_processing)
self._asset_wrapper.on_post_bake_delegate.add_callable(
self._handle_on_post_auto_bake)
# Begin the instantiation process of houdini_asset and wrap it with
# self.asset_wrapper
if not houdini_api.instantiate_asset_with_existing_wrapper(
self.asset_wrapper,
self.houdini_asset,
self.instantiate_at,
self.world_context_object,
self.spawn_in_level_override,
self.enable_auto_cook,
self.enable_auto_bake,
self.bake_directory_path,
self.bake_method,
self.remove_output_after_bake,
self.recenter_baked_actors,
self.replace_previous_bake):
# Handle failures: this will unbind delegates and call on_failure()
self._handle_on_failure()
return False
return True
def _unbind_delegates(self):
""" Unbinds from self.asset_wrapper's delegates (if valid). """
if not self._asset_wrapper:
return
self._asset_wrapper.on_pre_instantiation_delegate.add_callable(
self._handle_on_pre_instantiation)
self._asset_wrapper.on_post_instantiation_delegate.add_callable(
self._handle_on_post_instantiation)
self._asset_wrapper.on_post_cook_delegate.add_callable(
self._handle_on_post_auto_cook)
self._asset_wrapper.on_pre_process_state_exited_delegate.add_callable(
self._handle_on_pre_process)
self._asset_wrapper.on_post_processing_delegate.add_callable(
self._handle_on_post_processing)
self._asset_wrapper.on_post_bake_delegate.add_callable(
self._handle_on_post_auto_bake)
def _check_wrapper(self, wrapper):
""" Checks that wrapper matches self.asset_wrapper. Logs a warning if
it does not.
Args:
wrapper (HoudiniPublicAPIAssetWrapper): the wrapper to check
against self.asset_wrapper
Returns:
(bool): True if the wrappers match.
"""
if wrapper != self._asset_wrapper:
unreal.log_warning(
'[UHoudiniPublicAPIProcessHDANode] Received delegate event '
'from unexpected asset wrapper ({0} vs {1})!'.format(
self._asset_wrapper.get_name() if self._asset_wrapper else '',
wrapper.get_name() if wrapper else ''
)
)
return False
return True
def _handle_on_failure(self):
""" Handle any failures during the lifecycle of the process. Calls
self.on_failure() and then unbinds from self.asset_wrapper and
optionally deletes the instantiated asset.
"""
self.on_failure()
self._unbind_delegates()
if self.delete_instantiated_asset_on_completion_or_failure and self.asset_wrapper:
self.asset_wrapper.delete_instantiated_asset()
def _handle_on_complete(self):
""" Handles completion of the process. This can happen at one of
three stages:
- After on_post_instantiate(), if enable_auto_cook is False.
- After on_post_auto_cook(), if enable_auto_cook is True but
enable_auto_bake is False.
- After on_post_auto_bake(), if both enable_auto_cook and
enable_auto_bake are True.
Calls self.on_complete() and then unbinds from self.asset_wrapper's
delegates and optionally deletes the instantiated asset.
"""
self.on_complete()
self._unbind_delegates()
if self.delete_instantiated_asset_on_completion_or_failure and self.asset_wrapper:
self.asset_wrapper.delete_instantiated_asset()
def _handle_on_pre_instantiation(self, wrapper):
""" Called during pre_instantiation. Sets ``parameters`` on the HDA
and calls self.on_pre_instantiation().
"""
if not self._check_wrapper(wrapper):
return
# Set any parameters specified for the HDA
if self.asset_wrapper and self.parameters:
self.asset_wrapper.set_parameter_tuples(self.parameters)
self.on_pre_instantiation()
def _handle_on_post_instantiation(self, wrapper):
""" Called during post_instantiation. Sets inputs (``node_inputs`` and
``parameter_inputs``) on the HDA and calls self.on_post_instantiation().
Completes execution if enable_auto_cook is False.
"""
if not self._check_wrapper(wrapper):
return
# Set any inputs specified when the node was created
if self.asset_wrapper:
if self.node_inputs:
self.asset_wrapper.set_inputs_at_indices(self.node_inputs)
if self.parameter_inputs:
self.asset_wrapper.set_input_parameters(self.parameter_inputs)
self.on_post_instantiation()
# If not set to auto cook, complete execution now
if not self.enable_auto_cook:
self._handle_on_complete()
def _handle_on_post_auto_cook(self, wrapper, cook_success):
""" Called during post_cook. Sets self.cook_success and calls
self.on_post_auto_cook().
Args:
cook_success (bool): True if the cook was successful.
"""
if not self._check_wrapper(wrapper):
return
self._cook_success = cook_success
self.on_post_auto_cook(cook_success)
def _handle_on_pre_process(self, wrapper):
""" Called during pre_process. Calls self.on_pre_process().
"""
if not self._check_wrapper(wrapper):
return
self.on_pre_process()
def _handle_on_post_processing(self, wrapper):
""" Called during post_processing. Calls self.on_post_processing().
Completes execution if enable_auto_bake is False.
"""
if not self._check_wrapper(wrapper):
return
self.on_post_processing()
# If not set to auto bake, complete execution now
if not self.enable_auto_bake:
self._handle_on_complete()
def _handle_on_post_auto_bake(self, wrapper, bake_success):
""" Called during post_bake. Sets self.bake_success and calls
self.on_post_auto_bake().
Args:
bake_success (bool): True if the bake was successful.
"""
if not self._check_wrapper(wrapper):
return
self._bake_success = bake_success
self.on_post_auto_bake(bake_success)
self._handle_on_complete()
def on_failure(self):
""" Called if the process fails to instantiate or fails to start
a cook.
Subclasses can override this function implement custom functionality.
"""
pass
def on_complete(self):
""" Called if the process completes instantiation, cook and/or baking,
depending on enable_auto_cook and enable_auto_bake.
Subclasses can override this function implement custom functionality.
"""
pass
def on_pre_instantiation(self):
""" Called during pre_instantiation.
Subclasses can override this function implement custom functionality.
"""
pass
def on_post_instantiation(self):
""" Called during post_instantiation.
Subclasses can override this function implement custom functionality.
"""
pass
def on_post_auto_cook(self, cook_success):
""" Called during post_cook.
Subclasses can override this function implement custom functionality.
Args:
cook_success (bool): True if the cook was successful.
"""
pass
def on_pre_process(self):
""" Called during pre_process.
Subclasses can override this function implement custom functionality.
"""
pass
def on_post_processing(self):
""" Called during post_processing.
Subclasses can override this function implement custom functionality.
"""
pass
def on_post_auto_bake(self, bake_success):
""" Called during post_bake.
Subclasses can override this function implement custom functionality.
Args:
bake_success (bool): True if the bake was successful.
"""
pass
|
# SPDX-FileCopyrightText: 2018-2025 Xavier Loux (BleuRaven)
#
# SPDX-License-Identifier: GPL-3.0-or-later
# ----------------------------------------------
# Blender For UnrealEngine
# https://github.com/project/-For-UnrealEngine-Addons
# ----------------------------------------------
from pathlib import Path
from typing import Dict, Any, List, Tuple
import unreal
from . import bpl
from . import import_module_utils
from . import import_module_unreal_utils
from . import sequencer_utils
def ready_for_sequence_import():
if not import_module_unreal_utils.editor_scripting_utilities_active():
message = 'WARNING: Editor Scripting Utilities Plugin should be activated.' + "\n"
message += 'Edit > Plugin > Scripting > Editor Scripting Utilities.'
import_module_unreal_utils.show_warning_message("Editor Scripting Utilities not activated.", message)
return False
if not import_module_unreal_utils.sequencer_scripting_active():
message = 'WARNING: Sequencer Scripting Plugin should be activated.' + "\n"
message += 'Edit > Plugin > Scripting > Sequencer Scripting.'
import_module_unreal_utils.show_warning_message("Sequencer Scripting not activated.", message)
return False
return True
def create_sequencer(sequence_data: Dict[str, Any], show_finished_popup: bool = True):
is_spawnable_camera = sequence_data['spawnable_camera']
sequencer_frame_start = sequence_data['sequencer_frame_start']
sequencer_frame_end = sequence_data['sequencer_frame_end']+1
render_resolution_x = sequence_data['render_resolution_x']
render_resolution_y = sequence_data['render_resolution_y']
sequencer_frame_rate_denominator = sequence_data['sequencer_frame_rate_denominator']
sequencer_frame_rate_numerator = sequence_data['sequencer_frame_rate_numerator']
secure_crop = sequence_data['secure_crop'] # add end crop for avoid section overlay
imported_cameras: List[Tuple[str, unreal.MovieSceneObjectBindingID]] = [] # (CameraName, CameraGuid)
seq = sequencer_utils.create_new_sequence()
print("Sequencer reference created", seq)
# Process import
bpl.advprint.print_simple_title("Import started !")
# Set frame rate
myFFrameRate = sequencer_utils.get_sequencer_framerate(
denominator = sequencer_frame_rate_denominator,
numerator = sequencer_frame_rate_numerator
)
seq.set_display_rate(myFFrameRate)
# Set playback range
seq.set_playback_end_seconds((sequencer_frame_end-secure_crop)/float(sequencer_frame_rate_numerator))
seq.set_playback_start_seconds(sequencer_frame_start/float(sequencer_frame_rate_numerator)) # set_playback_end_seconds
if import_module_unreal_utils.get_unreal_version() > (5,2,0):
camera_cut_track = seq.add_track(unreal.MovieSceneCameraCutTrack)
else:
camera_cut_track = seq.add_master_track(unreal.MovieSceneCameraCutTrack)
camera_cut_track.set_editor_property('display_name', 'Imported Camera Cuts')
if import_module_unreal_utils.get_unreal_version() >= (4,26,0):
camera_cut_track.set_color_tint(unreal.Color(b=200, g=0, r=0, a=0))
else:
pass
for x, camera_data in enumerate(sequence_data["cameras"]):
# import camera
print("Start camera import " + str(x+1) + "/" + str(len(sequence_data["cameras"])) + " :" + camera_data["asset_name"])
# Import camera tracks transform
imported_cameras.append(import_camera_asset(seq, camera_data, is_spawnable_camera))
# Import camera cut section
for section in sequence_data['marker_sections']:
camera_cut_section = camera_cut_track.add_section()
if section["has_camera"] is not None:
for camera in imported_cameras:
if camera[0] == section["camera_name"]:
camera_binding_id = unreal.MovieSceneObjectBindingID()
if import_module_unreal_utils.get_unreal_version() >= (5,3,0):
camera_binding_id = seq.get_binding_id(camera[1])
elif import_module_unreal_utils.get_unreal_version() >= (4,27,0):
camera_binding_id = seq.get_portable_binding_id(seq, camera[1])
elif import_module_unreal_utils.get_unreal_version() >= (4,26,0):
camera_binding_id = seq.make_binding_id(camera[1], unreal.MovieSceneObjectBindingSpace.LOCAL)
else:
camera_binding_id = seq.make_binding_id(camera[1])
camera_cut_section.set_camera_binding_id(camera_binding_id)
camera_cut_section.set_end_frame_seconds((section["end_time"]-secure_crop)/float(sequencer_frame_rate_numerator))
camera_cut_section.set_start_frame_seconds(section["start_time"]/float(sequencer_frame_rate_numerator))
# Import result
bpl.advprint.print_simple_title("Imports completed !")
ImportedCameraStr = []
for cam in imported_cameras:
ImportedCameraStr.append(cam[0])
print(ImportedCameraStr)
bpl.advprint.print_separator()
# Select and open seq in content browser
if import_module_unreal_utils.get_unreal_version() >= (5,0,0):
pass #TO DO make crate the engine
#unreal.AssetEditorSubsystem.open_editor_for_assets(unreal.AssetEditorSubsystem(), [unreal.load_asset(seq.get_path_name())])
elif import_module_unreal_utils.get_unreal_version() >= (4,26,0):
unreal.AssetEditorSubsystem.open_editor_for_assets(unreal.AssetEditorSubsystem(), [unreal.load_asset(seq.get_path_name())])
else:
unreal.AssetToolsHelpers.get_asset_tools().open_editor_for_assets([unreal.load_asset(seq.get_path_name())])
unreal.EditorAssetLibrary.sync_browser_to_objects([seq.get_path_name()])
return 'Sequencer created with success !'
def import_camera_asset(seq: unreal.LevelSequence, camera_data: Dict[str, Any], is_spawnable_camera: bool) -> Tuple[str, unreal.MovieSceneObjectBindingID]:
def found_additional_data() -> Dict[str, Any]:
files: List[Dict[str, Any]] = camera_data["files"]
for file in files:
if file["content_type"] == "ADDITIONAL_DATA":
return import_module_utils.json_load_file(Path(file["file_path"]))
return {}
camera_additional_data = found_additional_data()
camera_name: str = camera_additional_data["camera_name"]
camera_target_class_ref: str = camera_additional_data["camera_actor"]
camera_target_class = unreal.load_class(None, camera_target_class_ref)
if camera_target_class is None:
message = f'WARNING: The camera class {camera_target_class_ref} was not found!' + "\n"
message += 'Verify that the class exists or that you have activated the necessary plugins.'
import_module_unreal_utils.show_warning_message("Failed to find camera class.", message)
camera_target_class = unreal.CineCameraActor
camera_binding, camera_component_binding = sequencer_utils.Sequencer_add_new_camera(seq, camera_target_class, camera_name, is_spawnable_camera)
sequencer_utils.update_sequencer_camera_tracks(seq, camera_binding, camera_component_binding, camera_additional_data)
return (camera_name, camera_binding)
|
##########################################################################################
# these code is test against UE 5.0. It doesn't guarantee to be functional in other versions
##########################################################################################
import os
import unreal
from importlib import reload
import UnrealUtils
reload(UnrealUtils)
from UnrealUtils import (
get_package_from_path,
asset_tools,
get_asset_by_path,
editor_level_subsystem,
get_bp_class_by_path,
editor_subsystem
)
def get_cb_selection():
"""
get asset selection list from content browser selection
:return:
"""
assets = unreal.EditorUtilityLibrary.get_selected_assets()
for a in assets:
unreal.log(a)
return assets
#######################################################################
# alternative
# utility_base = unreal.GlobalEditorUtilityBase.get_default_object()
# return utility_base.get_selected_assets()
#######################################################################
def show_assets_in_cb(paths=None):
"""
:param paths: Asset paths
:return:
"""
if paths is None:
paths = []
elif type(paths) is str:
paths = [paths]
elif type(paths) is list:
pass
else:
raise Exception(f'Unknown value {paths} in parameter paths')
unreal.EditorAssetLibrary.sync_browser_to_objects(asset_paths=paths)
def show_current_level_in_cb():
"""
show current level in content browser
:return:
"""
level_path = editor_level_subsystem.get_current_level().get_path_name()
show_assets_in_cb([level_path])
return level_path
def open_assets_in_editor(paths=None):
"""
:param paths: Asset paths
:return:
"""
if paths is None:
paths = []
elif type(paths) is str:
paths = [paths]
elif type(paths) in [list, tuple, set]:
pass
else:
raise Exception(f'Unknown value {paths} in parameter paths')
loaded_assets = [get_asset_by_path(x) for x in paths]
asset_tools.open_editor_for_assets(assets=loaded_assets)
def asset_exists(path=''):
"""
example py EditorAssetUtils.py --asset_exists (/project/.T_GridChecker_A)
:param path: Asset path
:return: True if the asset exists
"""
return unreal.EditorAssetLibrary.does_asset_exist(asset_path=path)
def get_material_instance_constant_parameter(mi_asset_path, parameter_name):
"""
example:
py EditorAssetUtils.py --get_material_instance_constant_parameter (/project/.M_Solid_Red,BaseColor)
:param mi_asset_path: the path to material instance asset
:param parameter_name: name of parameter to get value from
:return:
"""
mi_asset = get_asset_by_path(mi_asset_path)
#######################################################################
# get all parameters first and use it for looking up
#######################################################################
scalars = unreal.MaterialEditingLibrary.get_scalar_parameter_names(mi_asset)
switches = unreal.MaterialEditingLibrary.get_static_switch_parameter_names(mi_asset)
textures = unreal.MaterialEditingLibrary.get_texture_parameter_names(mi_asset)
vectors = unreal.MaterialEditingLibrary.get_vector_parameter_names(mi_asset)
#######################################################################
# try to get the correct type of parameter. If not valid type found raise exception
#######################################################################
if parameter_name in scalars:
getter = unreal.MaterialEditingLibrary.get_material_instance_scalar_parameter_value
elif parameter_name in switches:
getter = unreal.MaterialEditingLibrary.get_material_instance_static_switch_parameter_value
elif parameter_name in textures: # unreal.Texture
getter = unreal.MaterialEditingLibrary.get_material_instance_texture_parameter_value
elif parameter_name in vectors:
getter = unreal.MaterialEditingLibrary.get_material_instance_vector_parameter_value
else:
raise Exception(f'Unsupported type of parameter name {parameter_name}')
parameter_value = getter(instance=mi_asset, parameter_name=parameter_name)
# unreal.log(f'{mi_asset_path}.{parameter_name} is {parameter_value}')
return parameter_value
def build_skm_import_options(skeleton_path=None):
"""
:param skeleton_path: Skeleton asset path of the skeleton that will be used to bind the mesh
:return: Import option object. The basic import options for importing a skeletal mesh
"""
options = unreal.FbxImportUI()
# unreal.FbxImportUI
options.import_mesh = True
options.import_as_skeletal = True
options.mesh_type_to_import = unreal.FBXImportType.FBXIT_SKELETAL_MESH
options.import_textures = False
options.import_materials = False
options.create_physics_asset = False
if skeleton_path is None:
options.skeleton = skeleton_path
else:
options.skeleton = unreal.load_asset(skeleton_path)
# unreal.FbxMeshImportData
import_data = options.skeletal_mesh_import_data
import_data.import_translation = unreal.Vector(0.0, 0.0, 0.0)
import_data.import_rotation = unreal.Rotator(0.0, 0.0, 0.0)
import_data.import_uniform_scale = 1.0
#######################################################################
# unreal.FbxSkeletalMeshImportData
# Calling the FbxSkeletalMeshImportData properties with . doesn't work in UE5.0
# TODO: try the following code again in UE 5.1+ and see if it is fixed
# import_data.import_morph_targets = True
# import_data.update_skeleton_reference_pose = False
#######################################################################
import_data.set_editor_property('import_morph_targets', True)
import_data.set_editor_property('update_skeleton_reference_pose', False)
return options
def example_import_skm_asset():
source = r"/project/.fbx"
directory = '/project/'
option = build_skm_import_options(skeleton_path='/project/.human_rig_Skeleton')
task = build_import_task(source, directory, dest_name='New_Human', options=option)
asset_paths = execute_import_tasks([task])
show_assets_in_cb(asset_paths)
def example_import_csv_asset():
source = r"/project/.csv"
directory = '/project/'
struct_path = '/project/.Struct_Example'
datatable_task = build_import_task(source, directory)
factory = unreal.CSVImportFactory()
factory.automated_import_settings.import_row_struct = get_asset_by_path(struct_path)
datatable_task.factory = factory
asset_paths = execute_import_tasks([datatable_task])
show_assets_in_cb(asset_paths)
def build_anim_import_options(skeleton_path=None):
"""
:param skeleton_path: Skeleton asset path of the skeleton that will be used to bind the animation
:return: Import option object. The basic import options for importing an animation
"""
options = unreal.FbxImportUI()
# unreal.FbxImportUI
options.import_animations = True
options.mesh_type_to_import = unreal.FBXImportType.FBXIT_ANIMATION
if skeleton_path is None:
options.skeleton = skeleton_path
else:
options.skeleton = unreal.load_asset(skeleton_path)
# unreal.FbxMeshImportData
import_data.import_translation = unreal.Vector(0.0, 0.0, 0.0)
import_data.import_rotation = unreal.Rotator(0.0, 0.0, 0.0)
import_data.import_uniform_scale = 1.0
#######################################################################
# unreal.FbxAnimSequenceImportData
# Calling the FbxAnimSequenceImportData properties with . doesn't work in UE5.0
# TODO: try the following code again in UE 5.1+ and see if it is fixed
# import_data.animation_length = unreal.FBXAnimationLengthImportType.FBXALIT_EXPORTED_TIME
# import_data.remove_redundant_keys = False
#######################################################################
import_data = options.anim_sequence_import_data
import_data.set_editor_property(
'animation_length',
unreal.FBXAnimationLengthImportType.FBXALIT_EXPORTED_TIME
)
import_data.set_editor_property('remove_redundant_keys', False)
return options
def regenerate_skeletal_mesh_lods(skeletal_mesh_path, num_of_lods=4):
"""
regenerate lods for given skeletal mesh
:param skeletal_mesh_path: skeletal mesh path
:param num_of_lods:
:return:
"""
asset = get_asset_by_path(skeletal_mesh_path)
result = asset.regenerate_lod(num_of_lods)
if not result:
unreal.log_warning(f'Unable to generate lods for {skeletal_mesh_path}')
def create_directory(path=''):
"""
:param path: Directory path
:return: True if the operation succeeds
"""
return unreal.EditorAssetLibrary.make_directory(directory_path=path)
def duplicate_directory(from_dir='', to_dir=''):
"""
:param from_dir: Directory path to duplicate
:param to_dir: Duplicated directory path
:return: True if the operation succeeds
"""
return unreal.EditorAssetLibrary.duplicate_directory(
source_directory_path=from_dir,
destination_directory_path=to_dir
)
####################################################################################################
# def create_generic_asset_example():
# base_path = '/project/'
# generic_assets = [
# [base_path + 'sequence', unreal.LevelSequence, unreal.LevelSequenceFactoryNew()],
# [base_path + 'material', unreal.Material, unreal.MaterialFactoryNew()], # for parent material
# [base_path + 'world', unreal.World, unreal.WorldFactory()],
# [base_path + 'particle_system', unreal.ParticleSystem, unreal.ParticleSystemFactoryNew()],
# [base_path + 'paper_flipbook', unreal.PaperFlipbook, unreal.PaperFlipbookFactory()],
# [base_path + 'data_struct', unreal.UserDefinedStruct, unreal.StructureFactory()]
# ]
# for asset in generic_assets:
# print create_generic_asset(asset[0], asset[1], asset[2])
####################################################################################################
def create_generic_asset(asset_path='', asset_class=None, asset_factory=None, unique_name=True):
"""
:param asset_path: Path of asset to create
:param asset_class: The asset class
:param asset_factory: The associated factory of the class.
:param unique_name: If True, will add a number at the end of the asset name until unique
:return: The created asset
"""
if unique_name:
asset_path, asset_name = asset_tools.create_unique_asset_name(
base_package_name=asset_path, suffix=''
)
if asset_exists(asset_path):
result = unreal.load_asset(asset_path)
else:
_path_ = os.path.dirname(asset_path)
_name_ = os.path.basename(asset_path)
result = asset_tools.create_asset(
asset_name=_name_, package_path=_path_,
asset_class=asset_class,
factory=asset_factory
)
show_assets_in_cb([asset_path])
return result
def example_create_datatable_asset(asset_path='', data_struct=''):
"""
example_create_datatable_asset('/project/', '/project/')
:param asset_path:
:param data_struct:
:return:
"""
row_struct = create_generic_asset(data_struct, unreal.UserDefinedStruct, unreal.StructureFactory())
datatable_factory = unreal.DataTableFactory()
datatable_factory.struct = row_struct
create_generic_asset(asset_path, unreal.DataTable, datatable_factory)
def create_material_instance_constant(parent_material_path, mi_asset_name=None):
"""
create a material instance in the same directory of parent material
:param mi_asset_name: the material instance name
:param parent_material_path: the parent material path
:return:
"""
parent_material = get_asset_by_path(parent_material_path)
#######################################################################
# if no name is given it will use the parent name + inst
#######################################################################
if not mi_asset_name:
parent_material_basename = os.path.basename(parent_material_path)
parent_material_basename = parent_material_basename.split('.')[0]
mi_asset_name = parent_material_basename + '_inst'
mi_asset_directory = os.path.dirname(parent_material_path)
mi_asset_path = '/'.join([mi_asset_directory, mi_asset_name])
mi_asset = create_generic_asset(
asset_path=mi_asset_path,
asset_class=unreal.MaterialInstanceConstant,
asset_factory=unreal.MaterialInstanceConstantFactoryNew()
)
unreal.MaterialEditingLibrary.set_material_instance_parent(mi_asset, parent_material)
#######################################################################
# optional auto saving
# unreal.EditorAssetLibrary.save_asset(mi_asset_path)
#######################################################################
return mi_asset_path
def example_create_material_instances():
import random
for i in range(10):
mi_asset_path = create_material_instance_constant(
'/project/.M_Solid',
f'M_Solid_colored_{i}'
)
set_material_instance_constant_parameter(
mi_asset_path,
'BaseColor',
(random.random(), random.random(), random.random())
)
def duplicate_asset(from_path='', to_path=''):
"""
example:
duplicate_asset(
'/project/.T_GridChecker_A',
'/project/')
:param from_path: Asset path to duplicate
:param to_path: Duplicated asset path
:return: True if the operation succeeds
"""
return unreal.EditorAssetLibrary.duplicate_asset(
source_asset_path=from_path,
destination_asset_path=to_path
)
def rename_asset(from_path='', to_path=''):
"""
example:
rename_asset('/project/.T_Grid', '/project/')
:param from_path: Asset path to rename
:param to_path: Renamed asset path
:return: True if the operation succeeds
"""
return unreal.EditorAssetLibrary.rename_asset(
source_asset_path=from_path,
destination_asset_path=to_path
)
def delete_asset(path=''):
"""
example:
delete_asset('/project/.T_Grid1')
:param path: Asset path
:return: True if the operation succeeds
"""
if not path:
return
elif asset_exists(path):
return unreal.EditorAssetLibrary.delete_asset(asset_path_to_delete=path)
def duplicate_asset_dialog(from_path='', to_path='', show_dialog=True):
"""
example:
duplicate_asset_dialog(
'/project/.T_GridChecker_A',
'/project/'
)
This function will also work on assets of the type level. (But might be really slow if the level is huge)
:param from_path: Asset path to duplicate
:param to_path: Duplicate asset path
:param show_dialog: True if you want to show the confirm pop-up
:return: True if the operation succeeds
"""
splitted_path = to_path.rsplit('/', 1)
asset_path = splitted_path[0]
asset_name = splitted_path[1]
if show_dialog:
return asset_tools.duplicate_asset_with_dialog(
asset_name=asset_name,
package_path=asset_path,
original_object=get_asset_by_path(from_path)
)
else:
return asset_tools.duplicate_asset(
asset_name=asset_name, package_path=asset_path,
original_object=get_asset_by_path(from_path)
)
def rename_asset_dialog(from_path='', to_path='', show_dialog=True):
"""
This function will also work on assets of the type level.
(But might be really slow if the level is huge)
:param from_path: Asset path to rename
:param to_path: Renamed asset path
:param show_dialog: True if you want to show the confirm pop-up
:return: True if the operation succeeds
"""
asset_path = os.path.dirname(to_path)
asset_name = os.path.basename(to_path)
rename_data = unreal.AssetRenameData(
asset=get_asset_by_path(from_path),
new_package_path=asset_path,
new_name=asset_name
)
if show_dialog: # this currently doesn't work in UE 5.0 TODO: test it in 5.1+
return asset_tools.rename_assets_with_dialog(assets_and_names=[rename_data])
else:
return asset_tools.rename_assets(assets_and_names=[rename_data])
def save_asset(path='', force_save=True):
"""
:param path: Asset path
:param force_save:
:return: True if the operation succeeds
"""
return unreal.EditorAssetLibrary.save_asset(
asset_to_save=path,
only_if_is_dirty=not force_save
)
def save_directory(path='', force_save=True, recursive=True):
"""
:param path: Directory path
:param force_save:
:param recursive:
:return: True if the operation succeeds
"""
return unreal.EditorAssetLibrary.save_directory(
directory_path=path,
only_if_is_dirty=not force_save,
recursive=recursive
)
def get_all_dirty_packages():
"""
:return: The assets that need to be saved
"""
packages = []
for x in unreal.EditorLoadingAndSavingUtils.get_dirty_content_packages():
packages.append(x)
for x in unreal.EditorLoadingAndSavingUtils.get_dirty_map_packages():
packages.append(x)
return packages
def save_all_dirty_packages(show_dialog=False):
"""
:param show_dialog: True if you want to see the confirm pop-up
:return: True if the operation succeeds
"""
if bool(show_dialog):
return unreal.EditorLoadingAndSavingUtils.save_dirty_packages_with_dialog(
save_map_packages=True,
save_content_packages=True
)
else:
return unreal.EditorLoadingAndSavingUtils.save_dirty_packages(
save_map_packages=True,
save_content_packages=True
)
def save_packages(packages_path=None, show_dialog=False):
"""
save the given packages that is dirty only
:type packages_path: list[str]
:param show_dialog: True if you want to see the confirm pop-up
:return: True if the operation succeeds
"""
if packages_path is None:
packages_path = []
packages = [get_package_from_path(p) for p in packages_path]
if show_dialog:
return unreal.EditorLoadingAndSavingUtils.save_packages_with_dialog(
packages_to_save=packages,
only_dirty=False # note that only_dirty=False
)
else:
return unreal.EditorLoadingAndSavingUtils.save_packages(
packages_to_save=packages,
only_dirty=False
)
#######################################################################
# def import_my_assets_example():
# texture_task = build_import_task('C:/project/.TGA', '/project/')
# sound_task = build_import_task('C:/project/.WAV', '/project/')
# static_mesh_task = build_import_task(
# 'C:/project/.FBX',
# '/project/',
# options=build_sm_import_options()
# )
# skeletal_mesh_task = build_import_task(
# 'C:/project/.FBX',
# '/project/',
# options=build_skm_import_options('/project/')
# )
# animation_task = build_import_task(
# 'C:/project/.FBX',
# '/project/',
# options=build_anim_import_options('/project/')
# )
# unreal.log(execute_import_tasks([texture_task, sound_task, static_mesh_task, skeletal_mesh_task]))
# # Not executing the animation_task at the same time of the skeletal_mesh_task because it look
# # like it does not work if it's the case. Pretty sure it's not normal.
# unreal.log(execute_import_tasks([animation_task]))
#######################################################################
def build_import_task(filename='', dest_path='', dest_name=None, options=None):
"""
:param filename: Windows file fullname of the asset you want to import
:param dest_path: Asset path
:param dest_name: Asset name
:param options: Import option object. Can be None for assets that does not usually
have a pop-up when importing. (e.g. Sound, Texture, etc.)
:return: The import task object
"""
task = unreal.AssetImportTask()
task.automated = True # no UI
#######################################################################
# if destination is not specified it will use the source name
#######################################################################
if dest_name is not None:
task.destination_name = dest_name
task.destination_path = dest_path
task.filename = filename
#######################################################################
# in this case the import will always override existed mesh if the name of asset already occupied
# Alternatively this can be changed to additive importing
#######################################################################
task.replace_existing = True
#######################################################################
# optional auto saving the asset after finishing importing
# which will trigger source control actions if there is any
# task.save = True
#######################################################################
task.set_editor_property('options', options)
return task
def execute_import_tasks(tasks=None):
"""
:param tasks: The import tasks object. You can get them from buildImportTask()
:return: The paths of successfully imported assets
"""
if tasks is None:
tasks = []
asset_tools.import_asset_tasks(tasks)
imported_asset_paths = []
for task in tasks:
for path in task.get_editor_property('imported_object_paths'):
imported_asset_paths.append(path)
return imported_asset_paths
def example_import_texture_asset():
source = r"/project/.tga"
directory = '/project/'
task = build_import_task(source, directory)
asset_paths = execute_import_tasks([task])
show_assets_in_cb(asset_paths)
def build_sm_import_options():
"""
:return: Import option object. The basic import options for importing a static mesh
"""
options = unreal.FbxImportUI()
# unreal.FbxImportUI
options.import_mesh = True
options.mesh_type_to_import = unreal.FBXImportType.FBXIT_STATIC_MESH
options.import_textures = False
options.import_materials = False
options.import_as_skeletal = False
# unreal.FbxMeshImportData
import_data = options.static_mesh_import_data
import_data.import_translation = unreal.Vector(0.0, 0.0, 0.0)
import_data.import_rotation = unreal.Rotator(0.0, 0.0, 0.0)
import_data.import_uniform_scale = 1.0
#######################################################################
# unreal.FbxStaticMeshImportData
# Calling the FbxStaticMeshImportData properties with . doesn't work in UE5.0
# TODO: try the following code again in UE 5.1+ and see if it is fixed
# import_data.combine_meshes = True
# import_data.generate_lightmap_u_vs = True
# import_data.auto_generate_collision = True
#######################################################################
import_data.set_editor_property('combine_meshes', True)
import_data.set_editor_property('generate_lightmap_u_vs', True)
import_data.set_editor_property('auto_generate_collision', True)
return options
def example_import_sm_asset():
source = r"/project/.fbx"
directory = '/project/'
task = build_import_task(source, directory, options=build_sm_import_options())
asset_paths = execute_import_tasks([task])
show_assets_in_cb(asset_paths)
def delete_directory(path=''):
"""
:param path: Directory path
:return: True if the operation succeeds
"""
return unreal.EditorAssetLibrary.delete_directory(directory_path=path)
def directory_exists(path=''):
"""
:param path: Directory path
:return: True if the directory exists
"""
return unreal.EditorAssetLibrary.does_directory_exist(directory_path=path)
def rename_directory(from_dir='', to_dir=''):
"""
:param from_dir: Directory path to rename
:param to_dir: Renamed directory path
:return: True if the operation succeeds
"""
return unreal.EditorAssetLibrary.rename_directory(
source_directory_path=from_dir,
destination_directory_path=to_dir
)
#######################################################################
# copy the following code to your script
#######################################################################
from UnrealUtils import _run
if __name__ == '__main__':
unreal.log(_run(locals()))
def set_material_instance_constant_parameter(mi_asset_path, parameter_name, parameter_value):
"""
example:
EditorAssetUtils.set_material_instance_constant_parameter('/project/.M_Solid_Red', 'BaseColor', (0,1,0))
:param mi_asset_path: the path to material instance asset
:param parameter_name: name of parameter to change
:param parameter_value: value of parameter to set
:return:
"""
mi_asset = get_asset_by_path(mi_asset_path)
#######################################################################
# get all parameters first and use it for looking up
#######################################################################
scalars = unreal.MaterialEditingLibrary.get_scalar_parameter_names(mi_asset)
switches = unreal.MaterialEditingLibrary.get_static_switch_parameter_names(mi_asset)
textures = unreal.MaterialEditingLibrary.get_texture_parameter_names(mi_asset)
vectors = unreal.MaterialEditingLibrary.get_vector_parameter_names(mi_asset)
#######################################################################
# try to get the correct type of parameter. If not valid type found raise exception
#######################################################################
if parameter_name in scalars:
setter = unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value
elif parameter_name in switches:
setter = unreal.MaterialEditingLibrary.set_material_instance_static_switch_parameter_value
elif parameter_name in textures: # unreal.Texture
setter = unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value
parameter_value = get_asset_by_path(parameter_value)
elif parameter_name in vectors:
setter = unreal.MaterialEditingLibrary.set_material_instance_vector_parameter_value
parameter_value = unreal.LinearColor(*parameter_value, 1.0)
else:
raise Exception(f'Unsupported type of parameter name {parameter_name}')
original_value = get_material_instance_constant_parameter(mi_asset_path, parameter_name)
setter(instance=mi_asset, parameter_name=parameter_name, value=parameter_value)
unreal.log(f'{mi_asset_path}.{parameter_name} is changed from {original_value} to {parameter_value}')
#######################################################################
# optional auto saving
# unreal.EditorAssetLibrary.save_asset(mi_asset_path)
#######################################################################
#######################################################################
# update the material viewport when it's opened
#######################################################################
unreal.MaterialEditingLibrary.update_material_instance(mi_asset)
def set_asset_property(asset_path, property_name, property_value):
"""
this only works for non-bp assets
:param asset_path: path of asset
:param property_name: name of property to set
:param property_value:
:return:
"""
asset = get_asset_by_path(asset_path)
original_value = asset.get_editor_property(property_name)
asset.set_editor_property(property_name, property_value)
unreal.log(f'{asset_path}.{property_name} is changed from {original_value} to {property_value}')
#######################################################################
# optional auto saving
# unreal.EditorAssetLibrary.save_asset(asset_path)
#######################################################################
return property_value
def get_asset_property(asset_path, property_name):
"""
this only works for non-bp assets
:param asset_path: path of asset
:param property_name: name of property to set
:return:
"""
asset = get_asset_by_path(asset_path)
property_value = asset.get_editor_property(property_name)
unreal.log(f'{asset_path}.{property_name} = {property_value}')
return property_value
|
import unreal
def is_camera(binding:unreal.MovieSceneBindingProxy):
"""
Check to see if binding is a Camera
:return: True if binding is a Camera
:rtype: Bool
"""
return binding.get_possessed_object_class() == unreal.CineCameraActor.static_class()
def is_instanced_camera(binding:unreal.MovieSceneBindingProxy):
"""
Check to see if binding is an Instancable Camera
:return: True if binding is a Instancable Camera
:rtype: Bool
"""
possesable_is_camera = False
possessable_children = len(binding.get_child_possessables()) > 0
if is_camera(binding) and possessable_children:
child = binding.get_child_possessables()[0]
possesable_is_camera = child.get_name() == "CameraComponent"
if possesable_is_camera:
return True
return False
|
import unreal
level_editor_subsystem:unreal.LevelEditorSubsystem = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem)
unreal_editor_subsystem:unreal.UnrealEditorSubsystem = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem)
editor_actor_subsystem:unreal.EditorActorSubsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
asset_library:unreal.EditorAssetLibrary = unreal.EditorAssetLibrary()
level_editor_subsystem.editor_set_game_view(True)
camera_actor:unreal.Actor = None
def find_camera_by_name(camera_name:str):
world = unreal_editor_subsystem.get_editor_world()
actors = unreal.GameplayStatics.get_all_actors_of_class(world, unreal.CameraActor)
for actor in actors:
if camera_name == actor.get_actor_label():
return actor
return None
def create_and_activate_camera(camera_name, location=unreal.Vector(0, 0, 300), rotation=unreal.Rotator(0, 0, 0)):
camera_actor = find_camera_by_name("spsync_temp_camera")
if camera_actor != None:
return camera_actor
camera_actor = editor_actor_subsystem.spawn_actor_from_class(unreal.CameraActor, location, rotation, True)
camera_actor.set_actor_label(camera_name)
level_editor_subsystem.pilot_level_actor(camera_actor)
return camera_actor
def sp_to_unreal_rotation(x, y, z, force_front_x_axis:bool = True):
sp_rotator:unreal.Rotator = unreal.Rotator(x, y, 360 - z)
if force_front_x_axis:
sp_rotator = unreal.Rotator(0, -90, 0).combine(sp_rotator)
sp_quaternion = sp_rotator.quaternion()
return unreal.Quat(-sp_quaternion.z, sp_quaternion.x, sp_quaternion.y, sp_quaternion.w).rotator().combine(unreal.Rotator(0, 0, 180))
def init_sync_camera():
global camera_actor
camera_actor = create_and_activate_camera("spsync_temp_camera")
level_editor_subsystem.editor_set_game_view(True)
def exit_sync_camera():
level_editor_subsystem.pilot_level_actor(None)
level_editor_subsystem.editor_set_game_view(False)
current_camera_actor = find_camera_by_name("spsync_temp_camera")
if current_camera_actor != None:
editor_actor_subsystem.destroy_actor(current_camera_actor)
def sync_camera(px:float, py:float, pz:float, rx:float, ry:float, rz:float, fov:float, scale:float, force_front_x_axis:bool = True):
global camera_actor
selected_actors = editor_actor_subsystem.get_selected_level_actors()
root_transform:unreal.Transform = None
for actor in selected_actors:
root_transform = actor.get_actor_transform()
positon:unreal.Vector = unreal.Vector(px, py, pz)
if force_front_x_axis:
positon = unreal.Rotator(0, 90, 0).transform().transform_location(positon)
positon = unreal.Vector(positon.z , -positon.x, positon.y)
positon = unreal.Vector.multiply_float(positon, scale)
rotator:unreal.Rotator = sp_to_unreal_rotation(rx, ry, rz, force_front_x_axis)
"""
if root_transform == None:
unreal_editor_subsystem.set_level_viewport_camera_info(positon, rotator)
else:
unreal_editor_subsystem.set_level_viewport_camera_info(root_transform.transform_location(positon), root_transform.transform_rotation(rotator))
level_editor_subsystem.editor_invalidate_viewports()
"""
if root_transform == None:
camera_actor.set_actor_location_and_rotation(positon, rotator, False, False)
else:
camera_actor.set_actor_location_and_rotation(root_transform.transform_location(positon), root_transform.transform_rotation(rotator), False, False)
camera_component = camera_actor.get_component_by_class(unreal.CameraComponent)
if camera_component:
camera_component.set_editor_property("constrain_aspect_ratio", False)
camera_component.set_editor_property("field_of_view", fov)
level_editor_subsystem.editor_invalidate_viewports()
|
# Copyright Epic Games, Inc. All Rights Reserved.
import os
import unreal
#-------------------------------------------------------------------------------
class PlatformBase(unreal.Platform):
name = "Linux"
autosdk_name = "Linux_x64"
env_var = "LINUX_MULTIARCH_ROOT"
def _get_version_ue4(self):
dot_cs = self.get_unreal_context().get_engine().get_dir()
dot_cs /= "Source/project/.cs"
return Platform._get_version_helper_ue4(dot_cs, "ExpectedSDKVersion")
def _get_version_ue5(self):
dot_cs = "Source/project/"
version = self._get_version_helper_ue5(dot_cs + ".Versions.cs")
return version or self._get_version_helper_ue5(dot_cs + ".cs")
def _get_cook_form(self, target):
if target == "game": return "Linux" if self.get_unreal_context().get_engine().get_version_major() > 4 else "LinuxNoEditor"
if target == "client": return "LinuxClient"
if target == "server": return "LinuxServer"
#-------------------------------------------------------------------------------
class Platform(PlatformBase):
def _read_env(self):
env_var = PlatformBase.env_var
value = os.getenv(env_var)
if value:
yield env_var, value
return
version = self.get_version()
extras_dir = self.get_unreal_context().get_engine().get_dir() / "Extras"
for suffix in ("AutoSDK/", "ThirdPartyNotUE/SDKs/"):
value = extras_dir / suffix / f"HostLinux/Linux_x64/{version}/"
if (value / "x86_64-unknown-linux-gnu/bin").is_dir():
yield env_var, value
return
yield env_var, f"Linux_x64/{version}/"
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)
ue_context = self.get_unreal_context()
engine_dir = ue_context.get_engine().get_dir()
engine_bin_dir = str(engine_dir / "Binaries/Linux")
if ld_lib_path := os.getenv("LD_LIBRARY_PATH"):
ld_lib_path += ":" + str(engine_bin_dir)
else:
ld_lib_path = str(engine_bin_dir)
env = exec_context.get_env()
env["LD_LIBRARY_PATH"] = ld_lib_path
cmd = exec_context.create_runnable(binary_path, *args)
cmd.launch()
return True
|
import unreal
import re
throwable_sm_assets = []
throwable_bp_assets = []
# output = False
output = True
def logit0(info):
unreal.log(info)
def logit1(info):
if output:
unreal.log_warning(info)
def logit2(info):
unreal.log_error(info)
all_level_actors = unreal.EditorLevelLibrary.get_all_level_actors()
def fix_label_prefix():
p_static = re.compile('\d\d\d_Pickups_StaticReference')
p_throwable = re.compile('\d\d\d_ThrowableBreakable')
p_ThrowableBP = re.compile('^BP_.*_Throwable_C')
StaticRefCount = 0
ThrowableCount = 0
specials = {} #=Dictionary of special replacement. BP Name -> Original Item Name In Level
specials['BP_Panzer_Officer_Hat'] = 'Panzer_Officer_hat'
specials['BP_Wehrmacht_Soldier_Helmet_M'] = 'HelmetGermany'
for actor in all_level_actors:
# if str(actor.get_name())=='BP_BindersClose3':
# logit1(dir(actor))
# logit1(actor.get_full_name())
# logit1(actor.get_fname())
# if str(actor.get_name())=='BP_BindersClose2':
# if str(actor.get_name())=='HelmetGermany13':
# #logit1(dir(actor))
# logit1(actor.get_full_name())
# logit1(actor.get_fname())
if (len((p_static.findall(actor.get_full_name())))):#item in StaticReferrence Level
logit1("Static Reference Object = " + actor.get_name())# + " / type = " + str(type(actor)))
StaticRefCount += 1
if (len(p_ThrowableBP.findall(actor.get_full_name()))):#check if item is throwable BP
logit2('Warning: '+ str(actor.get_fname()) + " is Throwable but in the StaticReference Level! Please check.")
if (len((p_throwable.findall(actor.get_full_name())))):#Item in ThrowableBreakable Level
if not actor.is_child_actor():#Item is not child actor like breakables
logit1("ThrowableBreakable Object = " + actor.get_name())# + " / type = " + str(type(actor)))
if (len(p_ThrowableBP.findall(actor.get_full_name()))):#check if item is throwable BP
ThrowableCount += 1
if str(actor.get_actor_label()).startswith('S_'):
logit1(str(actor.get_fname()) + " is BP Actor with wrong prefix")
old_name = str(actor.get_actor_label())
new_name = old_name.replace('S_','BP_')
actor.set_actor_label(new_name)
logit0(old_name + ' --> ' + new_name + ' done.')
if str(actor.get_actor_label()).startswith('SM_'):
logit1(str(actor.get_fname()) + " is BP Actor with wrong prefix")
old_name = str(actor.get_actor_label())
new_name = old_name.replace('SM_','BP_')
actor.set_actor_label(new_name)
logit0(old_name + ' --> ' + new_name + ' done.')
continue
else:
actor_special = False
for key in specials.keys():#check all special objects
p_spe = re.compile('^'+key)
p_spe1 = re.compile('^'+specials[key])
if len(p_spe.findall(actor.get_full_name())):
ThrowableCount += 1
actor_special = True
logit1('^^^special replacement^^^')
if len(p_spe1.findall(actor.get_name())):
old_name = str(actor.get_actor_label())
new_name = old_name.replace(specials[key],key)
actor.set_actor_label(new_name)
logit0(old_name + ' --> ' + new_name + ' done.')
continue
if actor_special == False:
logit2('Warning: '+ str(actor.get_fname()) + " is not Throwable/Special but in the ThrowableBreakable Level! Please check.")
else:
logit1('Child Object = '+ str(actor.get_fname()))
logit0('Objects Count of StaticReference = '+ str(StaticRefCount))
logit0('Objects Count of ThrowableBreakable = '+ str(ThrowableCount))
logit0('DONE')
fix_label_prefix()
|
import unreal
from typing import Any
from pamux_unreal_tools.generated.material_expression_wrappers import *
from pamux_unreal_tools.base.material_expression.material_expression_container_builder_base import MaterialExpressionContainerBuilderBase
from pamux_unreal_tools.utils.asset_cache import AssetCache
class LayerInputs:
@staticmethod
def get(layer_name = ""):
return [
f"{layer_name}Albedo",
f"{layer_name}ColorOverlay",
f"{layer_name}ColorOverlayIntensity",
f"{layer_name}Contrast",
f"{layer_name}ContrastVariation",
f"{layer_name}Roughness",
f"{layer_name}RoughnessIntensity",
f"{layer_name}NormalIntensity",
f"{layer_name}Normal",
f"{layer_name}Displacement",
f"{layer_name}UVParams",
f"{layer_name}Rotation",
f"{layer_name}DoTextureBomb",
f"{layer_name}DoRotationVariation",
f"{layer_name}BombCellScale",
f"{layer_name}BombPatternScale",
f"{layer_name}BombRandomOffset",
f"{layer_name}BombRotationVariation",
f"{layer_name}OpacityStrength",
f"{layer_name}OpacityAdd",
f"{layer_name}OpacityContrast"
]
def __init__(self, builder: MaterialExpressionContainerBuilderBase, roughnessTextureTypeSuffix = "R"):
self.albedo = TextureObjectParameter(f"{builder.layer_name}Albedo")
self.albedo.texture.set(AssetCache.get_layer_texture(builder.layer_name, "A"))
self.colorOverlay = VectorParameter(f"{builder.layer_name}ColorOverlay", unreal.LinearColor(0.5, 0.5, 0.5, 1.0))
self.colorOverlayIntensity = ScalarParameter(f"{builder.layer_name}ColorOverlayIntensity", 0.0)
self.contrast = ScalarParameter(f"{builder.layer_name}Contrast", 1.0)
self.contrastVariation = ScalarParameter(f"{builder.layer_name}ContrastVariation", 0.0)
self.roughness = TextureObjectParameter(f"{builder.layer_name}Roughness")
self.roughness.texture.set(AssetCache.get_layer_texture(builder.layer_name, roughnessTextureTypeSuffix))
self.roughnessIntensity = ScalarParameter(f"{builder.layer_name}RoughnessVariation", 1.0)
self.normalIntensity = ScalarParameter(f"{builder.layer_name}NormalIntensity", 0.0)
self.normal = TextureObjectParameter(f"{builder.layer_name}Normal", None)
self.normal.sampler_type.set(unreal.MaterialSamplerType.SAMPLERTYPE_NORMAL)
self.normal.texture.set(AssetCache.get_layer_texture(builder.layer_name, "N"))
self.displacement = TextureObjectParameter(f"{builder.layer_name}Displacement")
self.displacement.texture.set(AssetCache.get_layer_texture(builder.layer_name, "D"))
self.uvParams = VectorParameter(f"{builder.layer_name}UVParams", unreal.LinearColor(1.0, 1.0, 0.5, 0.5))
self.rotation = ScalarParameter(f"{builder.layer_name}Rotation", 0.0)
self.doTextureBomb = StaticBoolParameter(f"{builder.layer_name}DoTextureBomb", True)
self.doRotationVariation = StaticBoolParameter(f"{builder.layer_name}DoRotationVariation", True)
self.bombCellScale = ScalarParameter(f"{builder.layer_name}BombCellScale", 0.0)
self.bombPatternScale = ScalarParameter(f"{builder.layer_name}BombPatternScale", 0.0)
self.bombRandomOffset = ScalarParameter(f"{builder.layer_name}BombRandomOffset", 0.0)
self.bombRotationVariation = ScalarParameter(f"{builder.layer_name}BombRotationVariation", 0.0)
self.opacityStrength = ScalarParameter(f"{builder.layer_name}OpacityStrength", 1.0)
self.opacityAdd = ScalarParameter(f"{builder.layer_name}OpacityAdd", 0.0)
self.opacityContrast = ScalarParameter(f"{builder.layer_name}OpacityContrast", 1.0)
|
import unreal
AssetTools = unreal.AssetToolsHelpers.get_asset_tools()
MaterialEditLibrary = unreal.MaterialEditingLibrary
EditorAssetLibrary = unreal.EditorAssetLibrary
#Create New Material
MeshPaintMaterial = AssetTools.create_asset("M_MeshPaint", "/project/", unreal.Material, unreal.MaterialFactoryNew())
#Add texture params for each surface
base_colors = []
normals = []
orm = []
#Create Vertex Color Nodes
NodePositionX = -500
NodePositionY = -300
VertexColorNode_Color = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionVertexColor.static_class(), NodePositionX, NodePositionY * 10)
VertexColorNode_Color.set_editor_property('Desc', 'Base_Color')
VertexColorNode_Normal = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionVertexColor.static_class(), NodePositionX, NodePositionY * 8)
VertexColorNode_Color.set_editor_property('Desc', 'Normal')
VertexColorNode_R = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionVertexColor.static_class(), NodePositionX, NodePositionY * 6)
VertexColorNode_Color.set_editor_property('Desc', 'R_Occlusion')
VertexColorNode_G = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionVertexColor.static_class(), NodePositionX, NodePositionY * 4)
VertexColorNode_Color.set_editor_property('Desc', 'Roughness')
VertexColorNode_B = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionVertexColor.static_class(), NodePositionX, NodePositionY * 2)
VertexColorNode_Color.set_editor_property('Desc', 'Metallic')
#Create One minus nodes
OneMinusNodeColor = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionOneMinus.static_class(), NodePositionX * 2, NodePositionY * 10)
OneMinusNodeNormal = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionOneMinus.static_class(), NodePositionX * 2, NodePositionY * 8)
OneMinusNode_R = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionOneMinus.static_class(), NodePositionX * 2, NodePositionY * 6)
OneMinusNode_G = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionOneMinus.static_class(), NodePositionX * 2, NodePositionY * 4)
OneMinusNode_B = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionOneMinus.static_class(), NodePositionX * 2, NodePositionY * 2)
#Create Base Color, Normal and Orm Texture Parameters
for i in range(5):
#Create Texture Params
BaseColorParam = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionTextureSampleParameter2D.static_class(), NodePositionX, NodePositionY + i * 150)
NormalParam = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionTextureSampleParameter2D.static_class(), NodePositionX, NodePositionY + i * 150)
ORMParam = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionTextureSampleParameter2D.static_class(), NodePositionX, NodePositionY + i * 150)
#Set names and sample types
BaseColorParam.set_editor_property("ParameterName", unreal.Name("BaseColor_{}".format(i)))
BaseColorParam.set_editor_property('sampler_source', unreal.SamplerSourceMode.SSM_WRAP_WORLD_GROUP_SETTINGS)
NormalParam.set_editor_property("ParameterName", unreal.Name("Normal_{}".format(i)))
NormalParam.set_editor_property('sampler_source', unreal.SamplerSourceMode.SSM_WRAP_WORLD_GROUP_SETTINGS)
NormalParam.set_editor_property('sampler_type', unreal.MaterialSamplerType.SAMPLERTYPE_NORMAL)
ORMParam.set_editor_property("ParameterName", unreal.Name("ORM_{}".format(i)))
ORMParam.set_editor_property('sampler_source', unreal.SamplerSourceMode.SSM_WRAP_WORLD_GROUP_SETTINGS)
ORMParam.set_editor_property('sampler_type', unreal.MaterialSamplerType.SAMPLERTYPE_NORMAL)
#append parameters to their arrays
base_colors.append(BaseColorParam)
normals.append(NormalParam)
orm.append(ORMParam)
#define lerp arrays
base_color_lerps = []
normal_lerps = []
orm_r_lerps = []
orm_g_lerps = []
orm_b_lerps = []
for i in range(5):
base_color_lerp = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionLinearInterpolate.static_class(), NodePositionX, NodePositionY + i *200)
normal_lerp = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionLinearInterpolate.static_class(), NodePositionX, NodePositionY + i * 200)
orm_r_lerp = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionLinearInterpolate.static_class(), NodePositionX, NodePositionY + i * 200)
orm_g_lerp = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionLinearInterpolate.static_class(), NodePositionX, NodePositionY + i * 200)
orm_b_lerp = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionLinearInterpolate.static_class(), NodePositionX, NodePositionY + i * 200)
base_color_lerps.append(base_color_lerp)
normal_lerps.append(normal_lerp)
orm_r_lerps.append(orm_r_lerp)
orm_g_lerps.append(orm_g_lerp)
orm_b_lerps.append(orm_b_lerp)
#Connect Base Color Connections
#Connect Base Color Params to Lerps
MaterialEditLibrary.connect_material_expressions(base_colors[0], '', base_color_lerps[0], 'B')
MaterialEditLibrary.connect_material_expressions(base_colors[1], '', base_color_lerps[1], 'B')
MaterialEditLibrary.connect_material_expressions(base_colors[2], '', base_color_lerps[2], 'B')
MaterialEditLibrary.connect_material_expressions(base_colors[3], '', base_color_lerps[3], 'B')
MaterialEditLibrary.connect_material_expressions(base_colors[4], '', base_color_lerps[4], 'B')
MaterialEditLibrary.connect_material_expressions(base_colors[4], '', base_color_lerps[0], 'A')
MaterialEditLibrary.connect_material_expressions(OneMinusNodeColor, '', base_color_lerps[0], 'Alpha')
#Connect Vertex Color Node to Base Color Lerps
MaterialEditLibrary.connect_material_expressions(VertexColorNode_Color, 'A', OneMinusNodeColor, '')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_Color, 'R', base_color_lerps[1], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_Color, 'G', base_color_lerps[2], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_Color, 'B', base_color_lerps[3], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_Color, 'A', base_color_lerps[4], 'Alpha')
# Make Lerp Connections
MaterialEditLibrary.connect_material_expressions(base_color_lerps[0], '', base_color_lerps[1], 'A')
MaterialEditLibrary.connect_material_expressions(base_color_lerps[1], '', base_color_lerps[2], 'A')
MaterialEditLibrary.connect_material_expressions(base_color_lerps[2], '', base_color_lerps[3], 'A')
MaterialEditLibrary.connect_material_expressions(base_color_lerps[3], '', base_color_lerps[4], 'A')
#Connect Last Lerp to the Base Color Channel
MaterialEditLibrary.connect_material_property(base_color_lerps[4], '', unreal.MaterialProperty.MP_BASE_COLOR)
#Make Normal Map Connections
#Connect Normal Params to Lerps
MaterialEditLibrary.connect_material_expressions(normals[0], '', normal_lerps[0], 'B')
MaterialEditLibrary.connect_material_expressions(normals[1], '', normal_lerps[1], 'B')
MaterialEditLibrary.connect_material_expressions(normals[2], '', normal_lerps[2], 'B')
MaterialEditLibrary.connect_material_expressions(normals[3], '', normal_lerps[3], 'B')
MaterialEditLibrary.connect_material_expressions(normals[4], '', normal_lerps[4], 'B')
MaterialEditLibrary.connect_material_expressions(normals[4], '', normal_lerps[0], 'A')
MaterialEditLibrary.connect_material_expressions(OneMinusNodeNormal, '', normal_lerps[0], 'Alpha')
#Connect Vertex Color Node to Normal Lerps
MaterialEditLibrary.connect_material_expressions(VertexColorNode_Normal, 'A', OneMinusNodeNormal, '')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_Normal, 'R', normal_lerps[1], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_Normal, 'G', normal_lerps[2], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_Normal, 'B', normal_lerps[3], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_Normal, 'A', normal_lerps[4], 'Alpha')
# Make Lerp Connections
MaterialEditLibrary.connect_material_expressions(normal_lerps[0], '', normal_lerps[1], 'A')
MaterialEditLibrary.connect_material_expressions(normal_lerps[1], '', normal_lerps[2], 'A')
MaterialEditLibrary.connect_material_expressions(normal_lerps[2], '', normal_lerps[3], 'A')
MaterialEditLibrary.connect_material_expressions(normal_lerps[3], '', normal_lerps[4], 'A')
#Connect Last Lerp to the Normal Channel
MaterialEditLibrary.connect_material_property(normal_lerps[4], '', unreal.MaterialProperty.MP_NORMAL)
#Make Ambient Occlusion Connections
#Connect ORM Red Channel(R) Params to Lerps
MaterialEditLibrary.connect_material_expressions(orm[0], 'R', orm_r_lerps[0], 'B')
MaterialEditLibrary.connect_material_expressions(orm[1], 'R', orm_r_lerps[1], 'B')
MaterialEditLibrary.connect_material_expressions(orm[2], 'R', orm_r_lerps[2], 'B')
MaterialEditLibrary.connect_material_expressions(orm[3], 'R', orm_r_lerps[3], 'B')
MaterialEditLibrary.connect_material_expressions(orm[4], 'R', orm_r_lerps[4], 'B')
MaterialEditLibrary.connect_material_expressions(orm[4], 'R', orm_r_lerps[0], 'A')
MaterialEditLibrary.connect_material_expressions(OneMinusNode_R, '', orm_r_lerps[0], 'Alpha')
#Connect Vertex Color Node to ORM_R Lerps
MaterialEditLibrary.connect_material_expressions(VertexColorNode_R, 'A', OneMinusNode_R, '')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_R, 'R', orm_r_lerps[1], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_R, 'G', orm_r_lerps[2], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_R, 'B', orm_r_lerps[3], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_R, 'A', orm_r_lerps[4], 'Alpha')
# Make Lerp Connections
MaterialEditLibrary.connect_material_expressions(orm_r_lerps[0], '', orm_r_lerps[1], 'A')
MaterialEditLibrary.connect_material_expressions(orm_r_lerps[1], '', orm_r_lerps[2], 'A')
MaterialEditLibrary.connect_material_expressions(orm_r_lerps[2], '', orm_r_lerps[3], 'A')
MaterialEditLibrary.connect_material_expressions(orm_r_lerps[3], '', orm_r_lerps[4], 'A')
#Connect Last Lerp to the Ambient Occlusion Channel
MaterialEditLibrary.connect_material_property(orm_r_lerps[4], '', unreal.MaterialProperty.MP_AMBIENT_OCCLUSION)
#Make Roughness Connections
#Connect ORM Green Channel(G) Params to Lerps
MaterialEditLibrary.connect_material_expressions(orm[0], 'G', orm_g_lerps[0], 'B')
MaterialEditLibrary.connect_material_expressions(orm[1], 'G', orm_g_lerps[1], 'B')
MaterialEditLibrary.connect_material_expressions(orm[2], 'G', orm_g_lerps[2], 'B')
MaterialEditLibrary.connect_material_expressions(orm[3], 'G', orm_g_lerps[3], 'B')
MaterialEditLibrary.connect_material_expressions(orm[4], 'G', orm_g_lerps[4], 'B')
MaterialEditLibrary.connect_material_expressions(orm[4], 'G', orm_g_lerps[0], 'A')
MaterialEditLibrary.connect_material_expressions(OneMinusNode_G, '', orm_g_lerps[0], 'Alpha')
#Connect Vertex Color Node to ORM_G Lerps
MaterialEditLibrary.connect_material_expressions(VertexColorNode_G, 'A', OneMinusNode_G, '')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_G, 'R', orm_g_lerps[1], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_G, 'G', orm_g_lerps[2], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_G, 'B', orm_g_lerps[3], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_G, 'A', orm_g_lerps[4], 'Alpha')
# Make Lerp Connections
MaterialEditLibrary.connect_material_expressions(orm_g_lerps[0], '', orm_g_lerps[1], 'A')
MaterialEditLibrary.connect_material_expressions(orm_g_lerps[1], '', orm_g_lerps[2], 'A')
MaterialEditLibrary.connect_material_expressions(orm_g_lerps[2], '', orm_g_lerps[3], 'A')
MaterialEditLibrary.connect_material_expressions(orm_g_lerps[3], '', orm_g_lerps[4], 'A')
#Connect Last Lerp to the Ambient Occlusion Channel
MaterialEditLibrary.connect_material_property(orm_g_lerps[4], '', unreal.MaterialProperty.MP_ROUGHNESS)
#Make Metallic Connections
#Connect ORM Blue Channel(B) Params to Lerps
MaterialEditLibrary.connect_material_expressions(orm[0], 'B', orm_b_lerps[0], 'B')
MaterialEditLibrary.connect_material_expressions(orm[1], 'B', orm_b_lerps[1], 'B')
MaterialEditLibrary.connect_material_expressions(orm[2], 'B', orm_b_lerps[2], 'B')
MaterialEditLibrary.connect_material_expressions(orm[3], 'B', orm_b_lerps[3], 'B')
MaterialEditLibrary.connect_material_expressions(orm[4], 'B', orm_b_lerps[4], 'B')
MaterialEditLibrary.connect_material_expressions(orm[4], 'B', orm_b_lerps[0], 'A')
MaterialEditLibrary.connect_material_expressions(OneMinusNode_B, '', orm_b_lerps[0], 'Alpha')
#Connect Vertex Color Node to ORM_B Lerps
MaterialEditLibrary.connect_material_expressions(VertexColorNode_B, 'A', OneMinusNode_B, '')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_B, 'R', orm_b_lerps[1], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_B, 'G', orm_b_lerps[2], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_B, 'B', orm_b_lerps[3], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_B, 'A', orm_b_lerps[4], 'Alpha')
# Make Lerp Connections
MaterialEditLibrary.connect_material_expressions(orm_b_lerps[0], '', orm_b_lerps[1], 'A')
MaterialEditLibrary.connect_material_expressions(orm_b_lerps[1], '', orm_b_lerps[2], 'A')
MaterialEditLibrary.connect_material_expressions(orm_b_lerps[2], '', orm_b_lerps[3], 'A')
MaterialEditLibrary.connect_material_expressions(orm_b_lerps[3], '', orm_b_lerps[4], 'A')
#Connect Last Lerp to the Ambient Occlusion Channel
MaterialEditLibrary.connect_material_property(orm_b_lerps[4], '', unreal.MaterialProperty.MP_METALLIC)
#Create Material Instance
MeshPaintInstance = AssetTools.create_asset("MeshPaintInstance", "/project/", unreal.MaterialInstanceConstant, unreal.MaterialInstanceConstantFactoryNew())
MaterialEditLibrary.set_material_instance_parent(MeshPaintInstance, MeshPaintMaterial)
MeshPaintInstance.set_editor_property("Parent", MeshPaintMaterial)
MaterialEditLibrary.update_material_instance(MeshPaintInstance)
#Save Material and Instance
EditorAssetLibrary.save_asset("/project/", True)
EditorAssetLibrary.save_asset("/project/", True)
|
import unreal
import AssetFunctions
import EditorFunctions
import PythonHelpers
import QtFunctions
import WorldFunctions
def showAssetsInContentBrowser_EXAMPLE():
paths = ['/project/', '/project/', '/project/']
AssetFunctions.showAssetsInContentBrowser(paths)
def openAssets_EXAMPLE():
paths = ['/project/', '/project/', '/project/']
AssetFunctions.openAssets(paths)
def createDirectory_EXAMPLE():
operation_succeeded = AssetFunctions.createDirectory('/project/')
print operation_succeeded
def duplicateDirectory_EXAMPLE():
operation_succeeded = AssetFunctions.duplicateDirectory('/project/', '/project/')
print operation_succeeded
def deleteDirectory_EXAMPLE():
operation_succeeded = AssetFunctions.deleteDirectory('/project/')
print operation_succeeded
def directoryExist_EXAMPLE():
exist = AssetFunctions.directoryExist('/project/')
print exist
def renameDirectory_EXAMPLE():
operation_succeeded = AssetFunctions.renameDirectory('/project/', '/project/')
print operation_succeeded
def duplicateAsset_EXAMPLE():
operation_succeeded = AssetFunctions.duplicateAsset('/project/', '/project/')
print operation_succeeded
def deleteAsset_EXAMPLE():
operation_succeeded = AssetFunctions.deleteAsset('/project/')
print operation_succeeded
def assetExist_EXAMPLE():
exist = AssetFunctions.assetExist('/project/')
print exist
def renameAsset_EXAMPLE():
operation_succeeded = AssetFunctions.renameAsset('/project/', '/project/')
print operation_succeeded
def duplicateAssetDialog_EXAMPLE():
operation_succeeded = AssetFunctions.duplicateAssetDialog('/project/', '/project/', True)
print operation_succeeded
def renameAssetDialog_EXAMPLE():
operation_succeeded = AssetFunctions.duplicateAssetDialog('/project/', '/project/', True)
print operation_succeeded
def saveAsset_EXAMPLE():
operation_succeeded = AssetFunctions.saveAsset('/project/', True)
print operation_succeeded
def saveDirectory_EXAMPLE():
operation_succeeded = AssetFunctions.saveDirectory('/project/', True, True)
print operation_succeeded
def importMyAssets_EXAMPLE():
texture_task = AssetFunctions.buildImportTask('C:/project/.TGA', '/project/')
sound_task = AssetFunctions.buildImportTask('C:/project/.WAV', '/project/')
static_mesh_task = AssetFunctions.buildImportTask('C:/project/.FBX', '/project/', AssetFunctions.buildStaticMeshImportOptions())
skeletal_mesh_task = AssetFunctions.buildImportTask('C:/project/.FBX', '/project/', AssetFunctions.buildSkeletalMeshImportOptions())
animation_task = AssetFunctions.buildImportTask('C:/project/.FBX', '/project/', AssetFunctions.buildAnimationImportOptions('/project/'))
print AssetFunctions.executeImportTasks([texture_task, sound_task, static_mesh_task, skeletal_mesh_task])
# Not executing the animation_task at the same time of the skeletal_mesh_task because it look like it does not work if it's the case. Pretty sure it's not normal.
print AssetFunctions.executeImportTasks([animation_task])
def spawnBlueprintActor_EXAMPLE():
path = '/project/'
location = unreal.Vector(1000.0, 400.0, 0.0)
rotation = unreal.Rotator(90.0, 0.0, 0.0)
scale = unreal.Vector(1.0, 1.0, 5.0)
properties = {'tags': ['MyFirstTag', 'MySecondTag'], 'hidden': False}
print WorldFunctions.spawnBlueprintActor(path, location, rotation, scale, None, properties)
def executeSlowTask_EXAMPLE():
quantity_steps_in_slow_task = 1000
with unreal.ScopedSlowTask(quantity_steps_in_slow_task, 'My Slow Task Text ...') as slow_task:
slow_task.make_dialog(True)
for x in range(quantity_steps_in_slow_task):
if slow_task.should_cancel_EXAMPLE():
break
slow_task.enter_progress_frame(1, 'My Slow Task Text ... ' + str(x) + ' / ' + str(quantity_steps_in_slow_task))
# Execute slow logic here
print 'Executing Slow Task'
def cast_EXAMPLE():
obj = unreal.load_asset('/project/')
if PythonHelpers.cast(obj, unreal.Texture2D):
print 'Cast Succeeded'
else:
print 'Cast Failed'
def spawnQtWindow_EXAMPLE():
import QtWindowOne
print QtFunctions.spawnQtWindow(QtWindowOne.QtWindowOne)
def getAllActors_EXAMPLE():
print WorldFunctions.getAllActors(False, unreal.StaticMeshActor, 'MyTag', None)
def getSelectedActors_EXAMPLE():
print getSelectedActors()
def selectActors_EXAMPLE():
all_actors = getAllActors()
actors_to_select = []
for x in range(len(all_actors)):
if x % 2:
actors_to_select.append(all_actors[x])
def clearActorSelection_EXAMPLE():
selectActors()
def focusAllViewportsOnSelectedActors_EXAMPLE():
focusViewportOnActor(False)
def focusActiveViewportOnRandomActor_EXAMPLE():
actors_in_world = unreal.GameplayStatics.get_all_actors_of_class(unreal.EditorLevelLibrary.get_editor_world(), unreal.Actor)
random_actor_in_world = actors_in_world[random.randrange(len(actors_in_world))]
focusViewportOnActor(True, random_actor_in_world)
def createGenericAsset_EXAMPLE():
base_path = '/project/'
generic_assets = [
[base_path + 'sequence', unreal.LevelSequence, unreal.LevelSequenceFactoryNew()],
[base_path + 'material', unreal.Material, unreal.MaterialFactoryNew()],
[base_path + 'world', unreal.World, unreal.WorldFactory()],
[base_path + 'particle_system', unreal.ParticleSystem, unreal.ParticleSystemFactoryNew()],
[base_path + 'paper_flipbook', unreal.PaperFlipbook, unreal.PaperFlipbookFactory()],
[base_path + 'data_table', unreal.DataTable, unreal.DataTableFactory()], # Will not work
]
for asset in generic_assets:
print createGenericAsset(asset[0], True, asset[1], asset[2])
# Cpp ########################################################################################################################################################################################
def getSelectedAssets_EXAMPLE():
print AssetFunctions.getSelectedAssets()
def setSelectedAssets_EXAMPLE():
asset_paths = ['/project/', '/project/', '/project/', '/project/']
AssetFunctions.setSelectedAssets(asset_paths)
def getSelectedFolders_EXAMPLE():
print AssetFunctions.getSelectedFolders()
def setSelectedFolders_EXAMPLE():
folder_paths = ['/project/', '/project/', '/project/', '/project/']
AssetFunctions.setSelectedFolders(folder_paths)
def getAllOpenedAssets_EXAMPLE():
print AssetFunctions.getAllOpenedAssets()
def closeAssets_EXAMPLE():
asset_objects = AssetFunctions.getAllOpenedAssets()
AssetFunctions.closeAssets(asset_objects)
def setDirectoryColor_EXAMPLE():
base_path = '/project/'
path = base_path + 'BasicLinearColor'
color = unreal.LinearColor(0, 1, 1, 1)
AssetFunctions.setDirectoryColor(path, color)
AssetFunctions.createDirectory(path) # Note: Only call this line if the folder is not already created
def setDirectoryColorGradient_EXAMPLE():
base_path = '/project/'
for x in range(100, 400):
# Get Gradient Color
z = x - 100
if z < 100:
r = 1.0 - z / 100.0
g = 0.0 + z / 100.0
b = 0.0
elif z < 200:
r = 0.0
g = 1.0 - (z - 100) / 100.0
b = 0.0 + (z - 100) / 100.0
else:
r = 0.0 + (z - 200) / 100.0
g = 0.0
b = 1.0 - (z - 200) / 100.0
color = unreal.LinearColor(r, g, b, 1)
# Set Directory Color
path = base_path + str(x)
AssetFunctions.setDirectoryColor(path, color)
AssetFunctions.createDirectory(path) # Note: Only call this line if the folder is not already created
def executeConsoleCommand_EXAMPLE():
console_commands = ['r.ScreenPercentage 0.1', 'r.Color.Max 6', 'stat fps', 'stat unit']
for x in console_commands:
EditorFunctions.executeConsoleCommand(x)
def getAllProperties_EXAMPLE():
obj = unreal.Actor()
object_class = obj.get_class()
for x in PythonHelpers.getAllProperties(object_class):
y = x
while len(y) < 50:
y = ' ' + y
print y + ' : ' + str(obj.get_editor_property(x))
def setViewportLocationAndRotation_EXAMPLE():
viewport_index = getActiveViewportIndex()
setViewportLocationAndRotation(viewport_index, unreal.Vector(0.0, 0.0, 0.0), unreal.Rotator(0.0, 90.0, 0.0))
def snapViewportToActor_EXAMPLE():
actors_in_world = unreal.GameplayStatics.get_all_actors_of_class(unreal.EditorLevelLibrary.get_editor_world(), unreal.Actor)
random_actor_in_world = actors_in_world[random.randrange(len(actors_in_world))]
viewport_index = getActiveViewportIndex()
snapViewportToActor(viewport_index, random_actor_in_world)
|
# Copyright Epic Games, Inc. All Rights Reserved.
import os
import unreal
#-------------------------------------------------------------------------------
class Platform(unreal.Platform):
name = "Mac"
def _read_env(self):
yield from ()
def _get_version_ue4(self):
dot_cs = self.get_unreal_context().get_engine().get_dir()
dot_cs /= "Source/project/.cs"
return Platform._get_version_helper_ue4(dot_cs, "MinMacOSVersion")
def _get_version_ue5(self):
dot_cs = "Source/project/"
version = self._get_version_helper_ue5(dot_cs + ".Versions.cs")
return version or self._get_version_helper_ue5(dot_cs + ".cs")
def _get_cook_form(self, target):
if target == "game": return "Mac" if self.get_unreal_context().get_engine().get_version_major() > 4 else "MacNoEditor"
if target == "client": return "MacClient"
if target == "server": return "MacServer"
def _launch(self, exec_context, stage_dir, binary_path, args):
if stage_dir:
bins_index = binary_path.find("/project/")
if bins_index >= 0:
base_dir = stage_dir
base_dir += os.path.basename(binary_path[:bins_index])
base_dir += "/project/"
else:
raise EnvironmentError(f"Unable to calculate base directory from '{binary_path}'")
args = (*args, "-basedir=" + base_dir)
cmd = exec_context.create_runnable(binary_path, *args)
cmd.launch()
return True
|
import unreal
import json
# instances of unreal classes
editor_util = unreal.EditorUtilityLibrary()
system_lib = unreal.SystemLibrary()
# prefix mapping
prefix_mapping = {}
with open("/project/.json","r") as json_file:
prefix_mapping = json.loads(json_file.read())
# get the selected assets
selected_assets = editor_util.get_selected_assets()
num_assets = len(selected_assets)
prefixed = 0
for asset in selected_assets:
# get the class instance and the clear text name
asset_name = system_lib.get_object_name(asset)
asset_class = asset.get_class()
class_name = system_lib.get_class_display_name(asset_class)
# get the prefix for the given class
class_prefix = prefix_mapping.get(class_name, None)
if class_prefix is None:
unreal.log_warning("No mapping for asset {} of type {}".format(asset_name, class_name))
continue
if not asset_name.startswith(class_prefix):
# rename the asset and add prefix
new_name = class_prefix + asset_name
editor_util.rename_asset(asset, new_name)
prefixed +=1
unreal.log("Prefixed {} of type {} with{}".format(asset_name, class_name, new_name))
else:
unreal.log("Asset {} of type {} is already prefixed with".format(asset_name, class_name))
unreal.log("Prefixed {} of {} assets".format(prefixed, num_assets))
|
# Copyright Epic Games, Inc. All Rights Reserved.
import os
import sys
import unreal
import unrealcmd
import unreal.cmdline
from pathlib import Path
#-------------------------------------------------------------------------------
def _get_ip():
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("172.31.255.255", 1))
ret = s.getsockname()[0]
except:
ret = "127.0.0.1"
finally:
s.close()
return ret
#-------------------------------------------------------------------------------
class _Attachable(object):
attach = unrealcmd.Opt(False, "Attach a debugger to the launched process")
def _get_debugger(self, name=None):
name = name or ("vs" if os.name == "nt" else "lldb")
ue_context = self.get_unreal_context()
channel = self.get_channel()
debuggers = channel.get_extendable("debuggers")
try:
debugger_class = debuggers.get_extension_class(name)
return debugger_class.construct(ue_context)
except ValueError:
raise ValueError(f"Unknown debugger '{name}'. Valid list: [{','.join([x[0] for x in debuggers.read_extensions()])}]")
def attach_to(self, pid, *, transport=None, host_ip=None):
debugger = self._get_debugger()
return debugger.attach(pid, transport, host_ip)
def debug(self, cmd, *args):
debugger = self._get_debugger()
exec_context = self.get_exec_context()
return debugger.debug(exec_context, cmd, *args)
#-------------------------------------------------------------------------------
class _RunCmd(unrealcmd.Cmd):
_variant = unrealcmd.Arg("development", "Build variant to launch")
runargs = unrealcmd.Arg([str], "Arguments passed on to the process being launched")
build = unrealcmd.Opt(False, "Build the target prior to running it")
def _build(self, target, variant, platform):
if target.get_type() == unreal.TargetType.EDITOR:
build_cmd = ("_build", "editor", variant)
else:
platform = platform or unreal.Platform.get_host()
build_cmd = ("_build", "target", target.get_name(), platform, variant)
import subprocess
ret = subprocess.run(build_cmd)
if ret.returncode:
raise SystemExit(ret.returncode)
def get_binary_path(self, target, platform=None):
ue_context = self.get_unreal_context()
if isinstance(target, str):
target = ue_context.get_target_by_name(target)
else:
target = ue_context.get_target_by_type(target)
if self.args.build:
self._build(target, self.args.variant, platform)
variant = unreal.Variant.parse(self.args.variant)
if build := target.get_build(variant, platform):
if build := build.get_binary_path():
return build
raise EnvironmentError(f"No {self.args.variant} build found for target '{target.get_name()}'")
#-------------------------------------------------------------------------------
class Editor(_RunCmd, _Attachable, unrealcmd.MultiPlatformCmd):
""" Launches the editor """
noproject = unrealcmd.Opt(False, "Start the editor without specifying a project")
variant = _RunCmd._variant
def main(self):
self.use_all_platforms()
ue_context = self.get_unreal_context()
binary_path = self.get_binary_path(unreal.TargetType.EDITOR)
args = (*unreal.cmdline.read_ueified(*self.args.runargs),)
if (project := ue_context.get_project()) and not self.args.noproject:
args = (project.get_path(), *args)
wants_terminal = "-stdout" in (x.lower() for x in self.args.runargs)
if wants_terminal and binary_path.suffix == "exe":
binary_path = binary_path[:-4]
binary_path += "-Cmd.exe"
if self.args.attach:
self.debug(binary_path, *args)
return
exec_context = self.get_exec_context()
editor = exec_context.create_runnable(str(binary_path), *args);
if wants_terminal or not self.is_interactive() or os.name != "nt":
import uelogprinter
printer = uelogprinter.Printer()
printer.run(editor)
return editor.get_return_code()
else:
editor.launch()
#-------------------------------------------------------------------------------
class Commandlet(_RunCmd, _Attachable, unrealcmd.MultiPlatformCmd):
""" Runs a commandlet """
commandlet = unrealcmd.Arg(str, "Name of the commandlet to run")
variant = _RunCmd._variant
def complete_commandlet(self, prefix):
ue_context = self.get_unreal_context()
for dot_h in ue_context.glob("Source/project/*.h"):
if "Commandlet.h" in dot_h.name:
yield dot_h.name[:-12]
def main(self):
self.use_all_platforms()
binary_path = self.get_binary_path(unreal.TargetType.EDITOR)
if binary_path.suffix == ".exe":
binary_path = binary_path.parent / (binary_path.stem + "-Cmd.exe")
args = (
"-run=" + self.args.commandlet,
*unreal.cmdline.read_ueified(*self.args.runargs),
)
if project := self.get_unreal_context().get_project():
args = (project.get_path(), *args)
if self.args.attach:
self.debug(str(binary_path), *args)
return
exec_context = self.get_exec_context()
cmd = exec_context.create_runnable(str(binary_path), *args);
if not self.is_interactive():
cmd.run()
else:
import uelogprinter
printer = uelogprinter.Printer()
printer.run(cmd)
return cmd.get_return_code()
#-------------------------------------------------------------------------------
class _ProgramTarget(_RunCmd, _Attachable, unrealcmd.MultiPlatformCmd):
def _main_impl(self):
self.use_all_platforms()
binary_path = self.get_binary_path(self.args.target)
args = (*unreal.cmdline.read_ueified(*self.args.runargs),)
if self.args.attach:
self.debug(str(binary_path), *args)
return
launch_kwargs = {}
if not sys.stdout.isatty():
launch_kwargs = { "silent" : True }
exec_context = self.get_exec_context()
runnable = exec_context.create_runnable(str(binary_path), *args);
runnable.launch(**launch_kwargs)
return True if runnable.is_gui() else runnable.wait()
#-------------------------------------------------------------------------------
class Program(_ProgramTarget):
""" Launches the specified program """
program = unrealcmd.Arg(str, "Name of the program to run")
variant = _RunCmd._variant
def complete_program(self, prefix):
ue_context = self.get_unreal_context()
for depth in ("*", "*/*"):
for target_cs in ue_context.glob(f"Source/Programs/{depth}/*.Target.cs"):
yield target_cs.name[:-10]
def main(self):
self.args.target = self.args.program
return self._main_impl()
#-------------------------------------------------------------------------------
class Target(_ProgramTarget):
""" Runs a name target on the host platform. """
target = unrealcmd.Arg(str, "Name of the target to run")
variant = _RunCmd._variant
def complete_target(self, prefix):
#seen = set()
#for name, _ in self.get_unreal_context().read_targets():
#if name not in seen:
#seen.add(name)
#yield name
pass
def main(self):
return self._main_impl()
#-------------------------------------------------------------------------------
class _Runtime(_RunCmd, _Attachable):
""" When using --attach to debug to a process running on a devkit it is expected
that the Visual Studio solution is already open (i.e. '.sln open' has been run
prior to '.run ... --attach'). """
platform = unrealcmd.Arg("", "Platform to run on")
variant = _RunCmd._variant
trace = unrealcmd.Opt((False, ""), "Add command line argument to trace to development host")
cooked = unrealcmd.Opt(False, "Use cooked data instead of staged data (local only)")
onthefly = unrealcmd.Opt(False, "Add the -filehostip= argument.")
binpath = unrealcmd.Opt("", "Override the binary that is launched")
datadir = unrealcmd.Opt("", "Use and alternative staged/packaged directory")
def _main_impl(self, target_type):
ue_context = self.get_unreal_context()
platform = self.args.platform
if not platform:
platform = unreal.Platform.get_host()
platform = self.get_platform(platform)
platform_name = platform.get_name()
project = ue_context.get_project()
if not project:
raise EnvironmentError(f"An active project is required to launch a {target_type.name.lower()} instance")
cook_form = platform.get_cook_form(target_type.name.lower())
stage_dir = project.get_dir() / f"Saved/StagedBuilds/{cook_form}"
# Allow the user to override the data directory used.
if self.args.datadir:
if self.args.cooked:
self.print_warning("Ignoring --cooked because --datadir was given")
self.args.cooked = False
stage_dir = Path(self.args.datadir).absolute()
if not stage_dir.is_dir():
self.print_error(f"Directory {stage_dir} does not exist")
return False
if not (stage_dir / "Engine").is_dir():
self.print_warning(f"An Engine/ directory is expected in '{stage_dir}'")
# I probably shouldn't do this, but some platforms need this file to be
# able to run with data served from the host PC. But I want to be explicit
# and clear what command line arguments are given
# Find the file in a manner that maintains case.
cmdline_txt = None
maybe_names = (
"UECommandLine.txt",
"uecommandline.txt",
"UE4CommandLine.txt",
"ue4commandline.txt",
)
for maybe_name in maybe_names:
cmdline_txt = stage_dir / maybe_name
if not cmdline_txt.is_file():
continue
cmdline_txt = cmdline_txt.resolve() # corrects case on Windows
dest_txt = cmdline_txt.parent / (cmdline_txt.stem + "_old_ushell.txt")
if not dest_txt.is_file():
cmdline_txt.rename(dest_txt)
break
else:
cmdline_txt = None
if cmdline_txt is not None:
cmdline_txt.open("wb").close()
# Get the path to the binary to execute
if self.args.binpath:
binary_path = Path(self.args.binpath).resolve()
if not binary_path.is_file():
raise ValueError(f"Binary not found; '{binary_path}'")
else:
binary_path = self.get_binary_path(target_type, platform_name)
# The user can opt-in to using cooked data instead of staged data
if self.args.cooked:
stage_dir = None
if platform.get_name() != unreal.Platform.get_host():
raise ValueError(f"The '--cooked' option may only be used when launching on {unreal.Platform.get_host()}")
# Validate data directories
if stage_dir:
if not stage_dir.is_dir():
suffix = "Client" if target_type == unreal.TargetType.CLIENT else ""
stage_dir = project.get_dir() / f"Saved/StagedBuilds/{platform_name}{suffix}/"
if not stage_dir.is_dir():
raise EnvironmentError(f"No staged data found for '{cook_form}'")
else:
cook_dir = project.get_dir() / f"Saved/Cooked/{cook_form}/"
if not cook_dir.is_dir():
sandboxed = next((x for x in self.args.runargs if "-sandbox=" in x), None)
if sandboxed:
self.print_warning(f"No cooked data found for '{cook_form}'")
else:
raise EnvironmentError(f"No cooked data found for '{cook_form}'")
# Condition command line with -filehostip
has_filehostip = False
for arg in self.args.runargs:
if "-filehostip" in arg.lower():
has_filehostip = True
break
else:
if self.args.onthefly:
self.args.runargs = (*self.args.runargs, "-filehostip=" + _get_ip())
has_filehostip = True
# The project argument.
project_arg = project.get_name()
if not has_filehostip:
project_arg = f"../../../{project_arg}/{project_arg}.uproject"
# Build arguments
args = (
project_arg,
*unreal.cmdline.read_ueified(*self.args.runargs),
)
if not self.args.cooked:
args = (*args, "-pak")
if self.args.trace is not False:
args = (*args, "-tracehost=" + _get_ip())
if self.args.trace:
args = (*args, "-trace=" + self.args.trace)
# Launch the runtime
stage_dir = str(stage_dir) + "/" if stage_dir else ""
exec_context = self.get_exec_context()
instance = platform.launch(exec_context, stage_dir, str(binary_path), args)
if not instance:
raise RuntimeError("An error occurred while launching.")
# Attach a debugger
if self.args.attach:
if type(instance) is tuple:
attach_ok = False
pid, devkit_ip = instance
# If there is no devkit involved we can try and use
if devkit_ip == None:
attach_ok = self.attach_to(pid)
# Otherwise we're using VS to attach and that's only on Windows
elif vs_transport := getattr(platform, "vs_transport", None):
print("Attaching to", pid, "on", devkit_ip, "with", vs_transport)
attach_ok = self.attach_to(pid, transport=vs_transport, host_ip=devkit_ip)
# Tell the user stuff
if attach_ok:
print("Debugger attached successfully")
else:
self.print_warning("Unable to attach a debugger")
return
self.print_warning(f"--attach is not currently supported on {platform.get_name()}")
#-------------------------------------------------------------------------------
class Game(_Runtime):
""" Launches the game runtime. """
def complete_platform(self, prefix):
yield from super().complete_platform(prefix)
yield "editor"
def main(self):
if self.args.platform == "editor":
editor = Editor()
editor._channel = self._channel
args = (self.args.variant, "--", *self.args.runargs, "-game")
if self.args.build: args = ("--build", *args)
if self.args.attach: args = ("--attach", *args)
return editor.invoke(args)
return self._main_impl(unreal.TargetType.GAME)
#-------------------------------------------------------------------------------
class Client(_Runtime):
""" Launches the game client. """
def main(self):
return self._main_impl(unreal.TargetType.CLIENT)
#-------------------------------------------------------------------------------
class Server(_Runtime):
""" Launches the server binary. """
complete_platform = ("win64", "linux")
def main(self):
self.args.runargs = (*self.args.runargs, "-log", "-unattended")
return self._main_impl(unreal.TargetType.SERVER)
|
# Copyright Epic Games, Inc. All Rights Reserved.
import os
import unreal
#-------------------------------------------------------------------------------
class Platform(unreal.Platform):
name = "Mac"
def _read_env(self):
yield from ()
def _get_version_ue4(self):
dot_cs = self.get_unreal_context().get_engine().get_dir()
dot_cs /= "Source/project/.cs"
return Platform._get_version_helper_ue4(dot_cs, "MinMacOSVersion")
def _get_version_ue5(self):
dot_cs = "Source/project/"
version = self._get_version_helper_ue5(dot_cs + ".Versions.cs")
return version or self._get_version_helper_ue5(dot_cs + ".cs")
def _get_cook_form(self, target):
if target == "game": return "Mac" if self.get_unreal_context().get_engine().get_version_major() > 4 else "MacNoEditor"
if target == "client": return "MacClient"
if target == "server": return "MacServer"
def _launch(self, exec_context, stage_dir, binary_path, args):
if stage_dir:
bins_index = binary_path.find("/project/")
if bins_index >= 0:
base_dir = stage_dir
base_dir += os.path.basename(binary_path[:bins_index])
base_dir += "/project/"
else:
raise EnvironmentError(f"Unable to calculate base directory from '{binary_path}'")
args = (*args, "-basedir=" + base_dir)
cmd = exec_context.create_runnable(binary_path, *args)
cmd.launch()
return True
|
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 26 10:05:01 2024
@author: WillQuantique
"""
import unreal
def associate_control_rig_with_metahuman_in_sequence(control_rig_path, metahuman_mesh_path, sequence_path, spawn_location, spawn_rotation):
# Load the assets
control_rig_asset = unreal.load_asset(control_rig_path)
metahuman_mesh_asset = unreal.load_asset(metahuman_mesh_path)
sequence_asset = unreal.load_asset(sequence_path)
# Check if assets were loaded successfully
if not control_rig_asset or not metahuman_mesh_asset or not sequence_asset:
print("Error loading assets.")
return
# Spawn the skeletal mesh actor
world = unreal.EditorLevelLibrary.get_editor_world()
skeletal_mesh_actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.SkeletalMeshActor, spawn_location, spawn_rotation)
skeletal_mesh_component = skeletal_mesh_actor.get_component_by_class(unreal.SkeletalMeshComponent)
skeletal_mesh_component.set_skeletal_mesh(metahuman_mesh_asset)
# Ensure the Level Sequence is accessible
sequence = unreal.LevelSequence.cast(sequence_asset)
# Manually create a possessable for the skeletal mesh actor and add it to the sequence
possessable_guid = sequence.add_possessable(skeletal_mesh_actor)
possessable = sequence.find_possessable(possessable_guid)
if possessable is not None:
sequence.set_possessable_name(possessable_guid, skeletal_mesh_actor.get_name())
# Manually bind the possessable to the spawned actor
binding = unreal.MovieSceneObjectBindingID(possessable_guid, unreal.MovieSceneObjectBindingSpace.LOCAL)
unreal.LevelSequenceEditorBlueprintLibrary.bind_possessable_to_actor(sequence, possessable, skeletal_mesh_actor)
else: print("ma vie pour merul")
# Attempt to add a control rig track to the sequence directly
if possessable_guid:
control_rig_track = sequence.add_control_rig_track(possessable_guid)
control_rig_track.add_control_rig(control_rig_asset)
else : print("nul")
# Example usage
control_rig_path = '/project/'
metahuman_mesh_path = "/project/"
sequence_path = "/project/"
spawn_location = unreal.Vector(0, 0, 0)
spawn_rotation = unreal.Rotator(0, 0, 0)
associate_control_rig_with_metahuman_in_sequence(control_rig_path, metahuman_mesh_path, sequence_path, spawn_location, spawn_rotation)
|
# Package import
import unreal
# Utility import
import control_rig_utils
@unreal.uclass()
class ControlRigBPExt(unreal.BlueprintFunctionLibrary):
@unreal.ufunction(params = [unreal.ControlRigBlueprint], ret=unreal.Array(unreal.RigElementKey), static = True, meta=dict(Category="Control Rig Blueprint Ext"))
def GetSelectedControls(rig):
"""
Returns the controls that are selected in the hierarchy panel. These return in a first-in/last-out manner
:param rig: The rig we are looking at
:type rig: unreal.ControlRigBlueprint
:return: A list of the selected object
:rtype: list[unreal.RigElementKey]
"""
return rig.get_hierarchy_modifier().get_selection()
@unreal.ufunction(params=[unreal.ControlRigBlueprint, unreal.Name], ret=unreal.RigElementKey, static = True, meta=dict(Category="Control Rig Blueprint Ext"))
def GetIndexByControlName(rig, control_name):
"""
Given a name, returns the associated RigElementKey.
:param rig: The control rig object
:type rig: unreal.ControlRigBlueprint
:param control_name: The path of the key to query
:type control_name: str
:return: The RigElementKeys with the given name, if any
:rtype: unreal.RigElementKey
"""
hierarchy_mod = rig.get_hierarchy_modifier()
indexes = hierarchy_mod.get_elements()
for ind in indexes:
if ind.name == control_name:
return ind
return None
@unreal.ufunction(params=[unreal.ControlRigBlueprint], static = True, meta=dict(Category="Control Rig Blueprint Ext"))
def CopyPasteSelectedGlobalXform(rig):
"""
Given a selection, copy the global transform from the first control into the initial transform of the second
control
:param rig: The control rig object
:type rig: unreal.ControlRigBlueprint
:return: Nothing
:rtype: None
"""
hierarchy_mod = rig.get_hierarchy_modifier()
selection = hierarchy_mod.get_selection()
if not len(selection) == 2:
unreal.log("Not enough Control Rig controls selected")
return
global_xform = hierarchy_mod.get_global_transform(selection[1])
hierarchy_mod.set_initial_global_transform(selection[0], global_xform)
@unreal.ufunction(params = [unreal.ControlRigBlueprint, unreal.RigElementType], ret=unreal.Array(unreal.RigElementKey), static = True, meta=dict(Category="Control Rig Blueprint Ext"))
def CreateRigElement(rig, element_type):
"""
Given an element type, create a RigElement of that type. If any RigElement is selected, the new element will have the selected element's global transform as initial.
:param rig: The control rig object
:type rig: unreal.ControlRigBlueprint
:return: elements
:rtype: list[unreal.RigElementKey]
"""
elements = control_rig_utils.create_rig_element_key(rig, element_type)
return elements
@unreal.ufunction(params = [unreal.ControlRigBlueprint, unreal.RigElementKey, unreal.RigElementKey], static = True, meta=dict(Category="Control Rig Blueprint Ext"))
def ParentRigElements(rig, parent, child):
"""
Given 2 rig elements, parent one to the other in the rig hierarchy
:param rig: The control rig object
:type rig: unreal.ControlRigBlueprint
:param parent: The parent element
:type parent: unreal.RigElementKey
:param child: The child element
:type child: unreal.RigElementKey
:return: elements
:rtype: list[unreal.RigElementKey]
"""
hierarchy_mod = rig.get_hierarchy_modifier()
hierarchy_mod.reparent_element(child, parent)
@unreal.ufunction(params = [unreal.ControlRigBlueprint], static = True, meta=dict(Category="Control Rig Blueprint Ext"))
def UpdateSelectedElementsInitialTransfromFromCurrentGlobal(rig):
"""
Get selected rig elements, take the current transforms as the initial transforms
:param rig: The control rig object
:type rig: unreal.ControlRigBlueprint
:return: Nothing
:rtype: None
"""
hierarchy_mod = rig.get_hierarchy_modifier()
selection = hierarchy_mod.get_selection()
for item in selection:
updated_xform = hierarchy_mod.get_global_transform(item)
hierarchy_mod.set_initial_global_transform(item, updated_xform)
@unreal.ufunction(params = [unreal.ControlRigBlueprint], static = True, meta=dict(Category="Control Rig Blueprint Ext"))
def ZeroSelectedElementsInitialTransfrom(rig):
"""
Set selected rig elements' intial transform to default
:param rig: The control rig object
:type rig: unreal.ControlRigBlueprint
:return: Nothing
:rtype: None
"""
hierarchy_mod = rig.get_hierarchy_modifier()
selection = hierarchy_mod.get_selection()
for item in selection:
updated_xform = unreal.Transform(location = [0,0,0], rotation = [0,0,0], scale = [1,1,1])
hierarchy_mod.set_initial_global_transform(item, updated_xform)
@unreal.ufunction(params=[unreal.ControlRigBlueprint], static = True, meta=dict(Category="Control Rig Blueprint Ext"))
def CopyPasteSelectedGizmos(rig):
"""
Copy the first selected control gizmo attributes and paste it to the second control.
:param rig: The control rig object
:type rig: unreal.ControlRigBlueprint
:return: Nothing
:rtype: None
"""
hierarchy_mod = rig.get_hierarchy_modifier()
selection = hierarchy_mod.get_selection()
if not len(selection) == 2:
return
src_element = control_rig_utils.cast_key_to_type(rig, selection[1])
dst_element = control_rig_utils.cast_key_to_type(rig, selection[0])
if type(src_element) != unreal.RigControl and type(dst_element) != unreal.RigControl:
return
gizmo_name = src_element.get_editor_property("gizmo_name")
gizmo_color = src_element.get_editor_property("gizmo_color")
gizmo_transform = src_element.get_editor_property("gizmo_transform")
gizmo_enabled = src_element.get_editor_property("gizmo_enabled")
dst_element.set_editor_property("gizmo_name", gizmo_name)
dst_element.set_editor_property("gizmo_color", gizmo_color)
dst_element.set_editor_property("gizmo_transform", gizmo_transform)
dst_element.set_editor_property("gizmo_enabled", gizmo_enabled)
hierarchy_mod.set_control(dst_element)
@unreal.ufunction(params=[unreal.ControlRigBlueprint, unreal.LinearColor], static = True, meta=dict(Category="Control Rig Blueprint Ext"))
def EditGizmoColor(rig, color):
"""
Given a color, set selected controls' gizmo to that color
:param rig: The control rig object
:type rig: unreal.ControlRigBlueprint
:param color: The color object
:type color: unreal.LinearColor
:return: Nothing
:rtype: None
"""
hierarchy_mod = rig.get_hierarchy_modifier()
selection = hierarchy_mod.get_selection()
rig_elements = control_rig_utils.get_elements_by_rig_type(rig, selection, unreal.RigControl)
for rig_element in rig_elements:
rig_element.set_editor_property("gizmo_color", color)
hierarchy_mod.set_control(rig_element)
@unreal.ufunction(params=[unreal.ControlRigBlueprint, unreal.Transform()], static = True, meta=dict(Category="Control Rig Blueprint Ext"))
def EditGizmoTransform(rig, transform):
"""
Given a transform, set selected controls' gizmo to that color
:param rig: The control rig object
:type rig: unreal.ControlRigBlueprint
:param transform: The transform object
:type transform: unreal.Transform
:return: Nothing
:rtype: None
"""
hierarchy_mod = rig.get_hierarchy_modifier()
selection = hierarchy_mod.get_selection()
rig_elements = control_rig_utils.get_elements_by_rig_type(rig, selection, unreal.RigControl)
for rig_element in rig_elements:
rig_element.set_editor_property("gizmo_transform", transform)
hierarchy_mod.set_control(rig_element)
@unreal.ufunction(params=[unreal.ControlRigBlueprint, bool], static = True, meta=dict(Category="Control Rig Blueprint Ext"))
def EditGizmoEnabled(rig, is_enabled):
"""
Given a boolean, set selected controls' gizmo to that color
:param rig: The control rig object
:type rig: unreal.ControlRigBlueprint
:param is_enabled: is gizmo enabled
:type is_enabled: bool
:return: Nothing
:rtype: None
"""
hierarchy_mod = rig.get_hierarchy_modifier()
selection = hierarchy_mod.get_selection()
rig_elements = control_rig_utils.get_elements_by_rig_type(rig, selection, unreal.RigControl)
for rig_element in rig_elements:
rig_element.set_editor_property("gizmo_enabled", is_enabled)
hierarchy_mod.set_control(rig_element)
@unreal.ufunction(params=[unreal.ControlRigBlueprint, str], static = True, meta=dict(Category="Control Rig Blueprint Ext"))
def EditGizmoName(rig, gizmo_name):
"""
Given a name, set selected controls' gizmo to that name
:param rig: The control rig object
:type rig: unreal.ControlRigBlueprint
:param gizmo_name: Gizmo name
:type gizmo_name: str
:return: Nothing
:rtype: None
"""
hierarchy_mod = rig.get_hierarchy_modifier()
selection = hierarchy_mod.get_selection()
rig_elements = control_rig_utils.get_elements_by_rig_type(rig, selection, unreal.RigControl)
for rig_element in rig_elements:
rig_element.set_editor_property("gizmo_name", gizmo_name)
hierarchy_mod.set_control(rig_element)
@unreal.ufunction(params=[unreal.ControlRigBlueprint, str, str], static = True, meta=dict(Category="Control Rig Blueprint Ext"))
def SearchAndReplaceRigElementNames(rig, search_string, replace_string):
"""
Given a string, search for it in the selected rig elements' name
and replace it with another string in the selected rig elements' name
:param rig: The control rig object
:type rig: unreal.ControlRigBlueprint
:param search_string: search for string
:type search_string: string
:param replace_string: string for replace
:type replace_string: string
:return: Nothing
:rtype: None
"""
hierarchy_mod = rig.get_hierarchy_modifier()
selection = hierarchy_mod.get_selection()
if not selection:
return
for item in selection:
src_name = str(item.get_editor_property("name"))
new_name = src_name.replace(search_string, replace_string)
hierarchy_mod.rename_element(item, new_name)
@unreal.ufunction(params=[unreal.ControlRigBlueprint, str, bool], static = True, meta=dict(Category="Control Rig Blueprint Ext"))
def AddStringPrefixOrSuffixToSelected(rig, insert_text, is_suffix):
"""
Given a string, insert it at the start or end of the selected rig elements' name
:param rig: The control rig object
:type rig: unreal.ControlRigBlueprint
:param insert_text: the insert string
:type insert_text: string
:param is_suffix: adding it to the end or start?
:type is_suffix: bool
:return: Nothing
:rtype: None
"""
hierarchy_mod = rig.get_hierarchy_modifier()
selection = hierarchy_mod.get_selection()
if not selection:
return
for item in selection:
src_name = str(item.get_editor_property("name"))
new_name = "{0}_{1}".format(insert_text, src_name)
if is_suffix:
new_name = "{0}_{1}".format(src_name, insert_text)
hierarchy_mod.rename_element(item, new_name)
@unreal.ufunction(params=[unreal.ControlRigBlueprint, str, int, int], static = True, meta=dict(Category="Control Rig Blueprint Ext"))
def RenameAndNumberSelectedControls(rig, name, start_number, number_padding):
"""
Given a name, start number, and number padding, set selected rig elements' name to a newly created name
:param rig: The control rig object
:type rig: unreal.ControlRigBlueprint
:param name: replacement name
:type name: string
:param start_number: start number for numberring items
:type start_number: int
:param number_padding: this many digits padded for text
:type number_padding: int
:return: Nothing
:rtype: None
"""
hierarchy_mod = rig.get_hierarchy_modifier()
selection = hierarchy_mod.get_selection()
if not selection:
return
x = start_number
for item in selection:
new_name = "{0}_{1}".format(name, str(x).zfill(number_padding))
hierarchy_mod.rename_element(item, new_name)
x+=1
@unreal.ufunction(params=[unreal.ControlRigBlueprint], ret=unreal.Array(str), static = True, meta=dict(Category="Control Rig Blueprint Ext"))
def GetControlGizmoListFromRig(rig):
"""
Get a list of gizmo names from rig
:param rig: The control rig object
:type rig: unreal.ControlRigBlueprint
:return: Nothing
:rtype: None
"""
gizmo_library = rig.get_editor_property("gizmo_library")
gizmos = gizmo_library.get_editor_property("gizmos")
gizmo_names = []
for gizmo in gizmos:
gizmo_names.append(gizmo.get_editor_property("gizmo_name"))
return gizmo_names
print("Control Rig Ext Loaded")
|
# coding: utf-8
import sys as __sys
try:
import unreal
# /project/ Files\Epic Games\UE_4.26\Engine\Plugins\Experimental\PythonScriptPlugin\Content\Python
import debugpy_unreal
import remote_execution
# command
# https://docs.unrealengine.com/project/.html
@unreal.uclass()
class EditorUtil(unreal.GlobalEditorUtilityBase):
""""""
@unreal.uclass()
class GetEditorAssetLibrary(unreal.EditorAssetLibrary):
""""""
@unreal.uclass()
class GetEditorLevelLibrary(unreal.EditorLevelLibrary):
""""""
@unreal.uclass()
class MaterialEditingLib(unreal.MaterialEditingLibrary):
""""""
@unreal.uclass()
class GetAnimationLibrary(unreal.AnimationLibrary):
""""""
def execute_console_command(script):
# UE4Editor.exe Project.uproject -ExecCmds=”Automation RunTests テスト名;Quit” -game
# unreal.PythonScriptLibrary.execute_python_command("任意のスクリプトかパス")
Editor = GetEditorLevelLibrary().get_editor_world()
unreal.SystemLibrary.execute_console_command(Editor, script)
def editor_utility(euw_path):
"""https://kinnaji.com/project/#上級編 レベル【★★★★】"""
EUS = unreal.EditorUtilitySubsystem()
EUWBP = unreal.load_object(None, euw_path) # euw_path = /project/.EUW_Test
EUS.spawn_and_register_tab(EUWBP)
def uname(item):
"""compatible for asset and"""
for asset in GetEditorAssetLibrary().list_assets("/Game/"):
if asset.endswith(item):
return asset
for actor in GetEditorLevelLibrary().get_all_level_actors():
if item in actor.get_name():
return EditorUtil().get_actor_reference(actor.get_full_name().split(":")[1])
raise Exception
stubs = unreal.SystemLibrary.get_project_directory() + "/project/.py"
__sys.modules[__name__] = __sys.modules["unreal"]
execute_console_command("DumpConsoleCommands")
tools = unreal.AssetToolsHelpers.get_asset_tools()
except (ImportError, KeyError):
from yurlungur.core.env import App as __App
run, shell, end, _ = __App("unreal")._actions
class Timeline(object):
def __init__(self, project):
self.project = project
self.timeline = project.GetCurrentTimeline()
self.media = project.GetMediaPool()
self.clips = self.media.GetRootFolder().GetClips().values()
def __repr__(self):
return
def __getitem__(self, val):
return
@property
def current(self):
return self.timeline
def imports(self, *args):
self.media.AppendToTimeline(*args)
self.timeline = self.project.GetCurrentTimeline()
return self
@property
def tracks(self):
return Track(self.timeline)
class Track(object):
def __init__(self, timeline):
self.timeline = timeline
self.track = timeline.GetCurrentVideoItem()
def __repr__(self):
return self.track.GetName()
def __getitem__(self, val):
assert isinstance(val, int)
if 0 < val < self.timeline.GetTrackCount("video"):
self.track = self.timeline.GetItemsInTrack("video", val)
return self
@property
def current(self):
return self.timeline.GetCurrentVideoItem()
@property
def clips(self):
return Item(self.track)
class Item(object):
def __init__(self, track):
self.track = track
def __repr__(self):
return self.track.GetName() + self.track.GetDuration()
def __getitem__(self, val):
return self
def exports(self, path):
return self.track.ExportFusionComp(path, 1)
def delete(self, name):
return self.track.DeleteFusionCompByName(name)
# print(unreal.SequencerScriptingRange().get_end_frame())
# print(unreal.SequencerScriptingRangeExtensions().get_end_seconds())
# LevelSequence = unreal.find_asset('/project/')
# bindings = LevelSequence.get_bindings()
# for b in bindings:
# if b.get_display_name() == 'CubeTest':
#
# # bindingsの中のトラック。Transformとか
# tracks = b.get_tracks()
# for t in tracks:
# # 例 : Transformの中のメンバー
# sections = t.get_sections()
# for s in sections:
# # 例 : Transformの中のチャンネル。物によって型が違う
# channels = s.get_channels()
# for c in channels:
# keys = c.get_keys()
# for k in keys:
# c.remove_key(k)
#
# for i in range(0, 5):
# FNumber = unreal.FrameNumber(30 * i)
# Event = unreal.MovieSceneEvent()
# #loc x にキーを追加
# channels[0].add_key(FNumber, 1)
#
# # マスタートラックを取得
# MasterTracks = LevelSequence.get_master_tracks()
# for MasterTrack in MasterTracks:
# for Section in MasterTrack.get_sections():
# for Channel in Section.get_channels():
# Keys = Channel.get_keys()
# for Key in Keys:
# Channel.remove_key(Key)
# for i in range(0, 5):
# FNumber = unreal.FrameNumber(30 * i)
# Event = unreal.MovieSceneEvent()
# Channel.add_key(FNumber, Event)
# 4 エクスポート unreal.AnimSequenceExporterFBX()
# export_task = unreal.AssetExportTask()
# export_task.automated = True
# export_task.exporter = unreal.AnimSequenceExporterFBX[]
# export_task.filename = "MyOutputPath"
# export_task.object = sequence_to_export
# unreal.Exporter.run_asset_export_task(export_task)
|
# 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 an HDA and then
set 2 geometry inputs: one node input and one object path parameter
input. 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 unreal
_g_wrapper = None
def get_test_hda_path():
return '/project/.subnet_test_2_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 get_cylinder_asset_path():
return '/project/.Cylinder'
def get_cylinder_asset():
return unreal.load_object(None, get_cylinder_asset_path())
def configure_inputs(in_wrapper):
print('configure_inputs')
# Unbind from the delegate
in_wrapper.on_post_instantiation_delegate.remove_callable(configure_inputs)
# Deprecated input functions
# in_wrapper.set_input_type(0, unreal.HoudiniInputType.GEOMETRY)
# in_wrapper.set_input_objects(0, (get_geo_asset(), ))
# in_wrapper.set_input_type(1, unreal.HoudiniInputType.GEOMETRY)
# in_wrapper.set_input_objects(1, (get_geo_asset(), ))
# in_wrapper.set_input_import_as_reference(1, True)
# Create a geometry input
geo_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPIGeoInput)
# Set the input objects/assets for this input
geo_asset = get_geo_asset()
geo_input.set_input_objects((geo_asset, ))
# Set the transform of the input geo
geo_input.set_input_object_transform_offset(
0,
unreal.Transform(
(200, 0, 100),
(45, 0, 45),
(2, 2, 2),
)
)
# copy the input data to the HDA as node input 0
in_wrapper.set_input_at_index(0, geo_input)
# We can now discard the API input object
geo_input = None
# Create a another geometry input
geo_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPIGeoInput)
# Set the input objects/assets for this input (cylinder in this case)
geo_asset = get_cylinder_asset()
geo_input.set_input_objects((geo_asset, ))
# Set the transform of the input geo
geo_input.set_input_object_transform_offset(
0,
unreal.Transform(
(-200, 0, 0),
(0, 0, 0),
(2, 2, 2),
)
)
# copy the input data to the HDA as input parameter 'objpath1'
in_wrapper.set_input_parameter('objpath1', geo_input)
# We can now discard the API input object
geo_input = None
# Set the subnet_test HDA to output its first input
in_wrapper.set_int_parameter_value('enable_geo', 1)
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))
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, 'get_input_object_transform_offset'):
print('\t\t\tObject Transform Offset: {0}'.format(in_input.get_input_object_transform_offset(idx)))
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_wrapper
# instantiate an asset with auto-cook enabled
_g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform())
# Configure inputs on_post_instantiation, after instantiation, but before first cook
_g_wrapper.on_post_instantiation_delegate.add_callable(configure_inputs)
# Bind on_post_processing, after cook + output creation
_g_wrapper.on_post_processing_delegate.add_callable(print_inputs)
if __name__ == '__main__':
run()
|
# SPDX-FileCopyrightText: 2018-2025 Xavier Loux (BleuRaven)
#
# SPDX-License-Identifier: GPL-3.0-or-later
# ----------------------------------------------
# Blender For UnrealEngine
# https://github.com/project/-For-UnrealEngine-Addons
# ----------------------------------------------
import unreal
from typing import Any, Dict, List
from .. import import_module_unreal_utils
from .. import import_module_tasks_class
from ..asset_types import ExportAssetType, AssetFileTypeEnum
def set_animation_sample_rate(itask: import_module_tasks_class.ImportTask, asset_additional_data: Dict[str, Any], asset_type: ExportAssetType, filetype: AssetFileTypeEnum) -> None:
if isinstance(itask.task_option, unreal.InterchangeGenericAssetsPipeline):
if asset_type.is_skeletal_animation():
if asset_additional_data and "animation_frame_rate_denominator" in asset_additional_data and "animation_frame_rate_numerator" in asset_additional_data:
if filetype.value == AssetFileTypeEnum.GLTF.value:
# Interchange use sample rate to set the animation frame rate.
sequencer_frame_rate_denominator = asset_additional_data['animation_frame_rate_denominator']
sequencer_frame_rate_numerator = asset_additional_data['animation_frame_rate_numerator']
# For GLTF, the sample rate is the frame rate.
animation_sample_rate = sequencer_frame_rate_numerator / sequencer_frame_rate_denominator
print("Set GLTF animation sample rate to:", animation_sample_rate)
animation_pipeline = itask.get_igap_animation()
animation_pipeline.set_editor_property('custom_bone_animation_sample_rate', animation_sample_rate)
animation_pipeline.set_editor_property('snap_to_closest_frame_boundary', True)
return
# For other file types, use automatic sample rate.
animation_pipeline = itask.get_igap_animation()
animation_pipeline.set_editor_property('custom_bone_animation_sample_rate', 0)
def apply_post_import_assets_changes(itask: import_module_tasks_class.ImportTask, asset_data: Dict[str, Any], filetype: AssetFileTypeEnum) -> None:
"""Applies post-import changes based on whether Interchange or FBX is used."""
if isinstance(itask.task_option, unreal.InterchangeGenericAssetsPipeline):
apply_interchange_post_import(itask, asset_data, filetype)
else:
apply_fbxui_post_import(itask, asset_data)
def cleanup_imported_assets(anim_sequences: List[unreal.AnimSequence], desired_asset_name: str, main_asset_name: str) -> None:
'''
anim_sequences: List of imported animation sequences to clean up.
desired_asset_name: The desired name of the animation.
main_asset_name: The name of the animation to use and rename.
'''
if len(anim_sequences) == 0:
print(f"anim_sequences is empty.")
elif len(anim_sequences) == 1:
if anim_sequences[0].get_name() != desired_asset_name:
import_module_unreal_utils.renamed_asset_name(anim_sequences[0], desired_asset_name)
elif len(anim_sequences) > 1:
# If more than one animation sequence is imported, rename the main one and delete the rest.
desired_asset_found: bool = False
main_asset_found: bool = False
for anim_seq in anim_sequences:
if anim_seq.get_name() == desired_asset_name:
desired_asset_found = True
elif anim_seq.get_name() == main_asset_name:
main_asset_found = True
if desired_asset_found:
# Remove all imported assets except the desired one.
for anim_seq in anim_sequences:
if anim_seq.get_name() != desired_asset_name:
unreal.EditorAssetLibrary.delete_asset(anim_seq.get_path_name())
elif main_asset_found:
# If the desired asset is not found, rename the main asset to the desired name.
for anim_seq in anim_sequences:
if anim_seq.get_name() == main_asset_name:
import_module_unreal_utils.renamed_asset_name(anim_seq, desired_asset_name)
else:
unreal.EditorAssetLibrary.delete_asset(anim_seq.get_path_name())
else:
# If neither the desired asset nor the main asset is found.
# Rename the first imported animation sequence as the desired asset.
for x, anim_seq in enumerate(anim_sequences):
if x == 0:
import_module_unreal_utils.renamed_asset_name(anim_seq, desired_asset_name)
else:
unreal.EditorAssetLibrary.delete_asset(anim_seq.get_path_name())
def apply_interchange_post_import(itask: import_module_tasks_class.ImportTask, asset_data: Dict[str, Any], filetype: AssetFileTypeEnum) -> None:
if filetype.value == AssetFileTypeEnum.FBX.value:
# When Import FBX animation using the Interchange it create "Anim_0_Root" and "Root_MorphAnim_0".
# I'm not sure if that a bug... So remove I "Root_MorphAnim_0" or other animations and I rename "Anim_0_Root".
imported_assets = itask.get_imported_anim_sequences()
cleanup_imported_assets(imported_assets, asset_data["asset_import_name"], "Anim_0_Root")
elif filetype.value == AssetFileTypeEnum.GLTF.value:
# For glTF I got exactly the same issue but with "Body" and "Scene".
# So remove I "Body" or other animations and I rename "Scene".
# Scene it the name the the scene in Blender at the export.
imported_assets = itask.get_imported_anim_sequences()
cleanup_imported_assets(imported_assets, asset_data["asset_import_name"], "Scene")
def apply_fbxui_post_import(itask: import_module_tasks_class.ImportTask, asset_data: Dict[str, Any]) -> None:
"""Applies post-import changes for FBX pipeline."""
# When Import FBX animation using FbxImportUI it create a skeletal mesh and the animation at this side.
# I'm not sure if that a bug too... So remove the extra mesh
imported_anim_sequence = itask.get_imported_anim_sequence()
if imported_anim_sequence is None:
# If Imported Anim Sequence is None it maybe imported the asset as Skeletal Mesh.
skeleta_mesh_assset = itask.get_imported_skeletal_mesh()
if skeleta_mesh_assset:
# If Imported as Skeletal Mesh Search the real Anim Sequence
path = skeleta_mesh_assset.get_path_name()
base_name = path.split('.')[0]
anim_asset_name = f"{base_name}_anim.{base_name.split('/')[-1]}_anim"
desired_anim_path = f"{base_name}.{base_name.split('/')[-1]}"
animAsset = import_module_unreal_utils.load_asset(anim_asset_name)
if animAsset is not None:
# Remove the imported skeletal mesh and rename te anim sequence with his correct name.
unreal.EditorAssetLibrary.delete_asset(path)
unreal.EditorAssetLibrary.rename_asset(anim_asset_name, desired_anim_path)
else:
fail_reason = f"animAsset {asset_data['asset_name']} not found after import: {anim_asset_name}"
return fail_reason, None
|
# 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, 'get_object_transform_offset'):
print('\t\t\tObject Transform Offset: {0}'.format(in_input.get_object_transform_offset(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 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
from typing import Dict, Any, List, Tuple
import base64
import os
import mss
import time
import tempfile # Used to find the OS's temporary folder
from utils import unreal_conversions as uc
from utils import logging as log
def handle_spawn(command: Dict[str, Any]) -> Dict[str, Any]:
"""
Handle a spawn command
Args:
command: The command dictionary containing:
- actor_class: Actor class name/path or mesh path (e.g., "/project/" or "/project/.SM_Barrel01")
- location: [X, Y, Z] coordinates (optional)
- rotation: [Pitch, Yaw, Roll] in degrees (optional)
- scale: [X, Y, Z] scale factors (optional)
- actor_label: Optional custom name for the actor
Returns:
Response dictionary with success/failure status and additional info
"""
try:
# Extract parameters
actor_class_name = command.get("actor_class", "Cube")
location = command.get("location", (0, 0, 0))
rotation = command.get("rotation", (0, 0, 0))
scale = command.get("scale", (1, 1, 1))
actor_label = command.get("actor_label")
unreal.log(f"Spawn command: Class: {actor_class_name}, Label: {actor_label}")
# Convert parameters to Unreal types
loc = uc.to_unreal_vector(location)
rot = uc.to_unreal_rotator(rotation)
scale_vector = uc.to_unreal_vector(scale)
actor = None
gen_actor_utils = unreal.GenActorUtils
# Check if it's a mesh path (e.g., "/Game/.../SM_Barrel01.SM_Barrel01")
if actor_class_name.startswith("/Game") and "." in actor_class_name:
# Try loading as a static mesh
mesh = unreal.load_object(None, actor_class_name)
if isinstance(mesh, unreal.StaticMesh):
actor = gen_actor_utils.spawn_static_mesh_actor(actor_class_name, loc, rot, scale_vector, actor_label or "")
else:
# Fallback to actor class if not a mesh
actor = gen_actor_utils.spawn_actor_from_class(actor_class_name, loc, rot, scale_vector, actor_label or "")
else:
# Handle basic shapes or actor classes
shape_map = {"cube": "Cube", "sphere": "Sphere", "cylinder": "Cylinder", "cone": "Cone"}
actor_class_lower = actor_class_name.lower()
if actor_class_lower in shape_map:
proper_name = shape_map[actor_class_lower]
actor = gen_actor_utils.spawn_basic_shape(proper_name, loc, rot, scale_vector, actor_label or "")
else:
actor = gen_actor_utils.spawn_actor_from_class(actor_class_name, loc, rot, scale_vector, actor_label or "")
if not actor:
unreal.log_error(f"Failed to spawn actor of type {actor_class_name}")
return {"success": False, "error": f"Failed to spawn actor of type {actor_class_name}"}
actor_name = actor.get_actor_label()
unreal.log(f"Spawned actor: {actor_name} at {loc}")
return {"success": True, "actor_name": actor_name}
except Exception as e:
unreal.log_error(f"Error spawning actor: {str(e)}")
return {"success": False, "error": str(e)}
def handle_take_screenshot(command):
"""
Takes a screenshot using the HighResShot console command with a deterministic filename.
This is the most reliable method for engine-based screenshots.
"""
# 1. Create a unique, absolute file path in the OS's temp directory.
# This ensures we have a clean place to work with guaranteed write permissions.
temp_dir = tempfile.gettempdir()
unique_filename = f"unreal_mcp_screenshot_{int(time.time())}.png"
# Use forward slashes, as this is more reliable for Unreal console commands
screenshot_path = os.path.join(temp_dir, unique_filename).replace('\\', '/')
try:
# 2. Construct the console command with the full, absolute filename.
console_command = f'HighResShot 1 filename="{screenshot_path}"'
unreal.log(f"Executing screenshot command: {console_command}")
# Execute the command in the editor world context
unreal.SystemLibrary.execute_console_command(unreal.EditorLevelLibrary.get_editor_world(), console_command)
# 3. Poll for the file's existence instead of using a fixed sleep time.
# This is much more reliable than a fixed wait.
max_wait_seconds = 5
wait_interval = 0.2
time_waited = 0
file_created = False
while time_waited < max_wait_seconds:
if os.path.exists(screenshot_path):
file_created = True
break
time.sleep(wait_interval)
time_waited += wait_interval
if not file_created:
return {"success": False, "error": f"Command was executed, but the output file was not found at the specified path: {screenshot_path}"}
# 4. Read the file, encode it, and prepare the response
with open(screenshot_path, 'rb') as image_file:
image_data = image_file.read()
base64_encoded_data = base64.b64encode(image_data).decode('utf-8')
return {
"success": True,
"data": base64_encoded_data,
"mime_type": "image/png"
}
except Exception as e:
return {"success": False, "error": f"The screenshot process failed with an exception: {str(e)}"}
finally:
# 5. Clean up the temporary screenshot file from the temp directory
if os.path.exists(screenshot_path):
try:
os.remove(screenshot_path)
except Exception as e_cleanup:
unreal.log_error(f"Failed to delete temporary screenshot file '{screenshot_path}': {e_cleanup}")
def handle_create_material(command: Dict[str, Any]) -> Dict[str, Any]:
"""
Handle a create_material command
Args:
command: The command dictionary containing:
- material_name: Name for the new material
- color: [R, G, B] color values (0-1)
Returns:
Response dictionary with success/failure status and material path if successful
"""
try:
# Extract parameters
material_name = command.get("material_name", "NewMaterial")
color = command.get("color", (1, 0, 0))
log.log_command("create_material", f"Name: {material_name}, Color: {color}")
# Use the C++ utility class
gen_actor_utils = unreal.GenActorUtils
color_linear = uc.to_unreal_color(color)
material = gen_actor_utils.create_material(material_name, color_linear)
if not material:
log.log_error("Failed to create material")
return {"success": False, "error": "Failed to create material"}
material_path = f"/project/{material_name}"
log.log_result("create_material", True, f"Path: {material_path}")
return {"success": True, "material_path": material_path}
except Exception as e:
log.log_error(f"Error creating material: {str(e)}", include_traceback=True)
return {"success": False, "error": str(e)}
def handle_get_all_scene_objects(command: Dict[str, Any]) -> Dict[str, Any]:
try:
level = unreal.EditorLevelLibrary.get_level(unreal.EditorLevelLibrary.get_editor_world())
actors = unreal.GameplayStatics.get_all_actors_of_class(level, unreal.Actor)
result = [
{"name": actor.get_name(), "class": actor.get_class().get_name(), "location": [actor.get_actor_location().x, actor.get_actor_location().y, actor.get_actor_location().z]}
for actor in actors
]
return {"success": True, "actors": result}
except Exception as e:
return {"success": False, "error": str(e)}
def handle_create_project_folder(command: Dict[str, Any]) -> Dict[str, Any]:
try:
folder_path = command.get("folder_path")
full_path = f"/Game/{folder_path}"
unreal.EditorAssetLibrary.make_directory(full_path)
return {"success": True, "message": f"Created folder at {full_path}"}
except Exception as e:
return {"success": False, "error": str(e)}
def handle_get_files_in_folder(command: Dict[str, Any]) -> Dict[str, Any]:
try:
folder_path = f"/Game/{command.get('folder_path')}"
files = unreal.EditorAssetLibrary.list_assets(folder_path, recursive=False)
return {"success": True, "files": [str(f) for f in files]}
except Exception as e:
return {"success": False, "error": str(e)}
def handle_add_input_binding(command: Dict[str, Any]) -> Dict[str, Any]:
try:
action_name = command.get("action_name")
key = command.get("key")
# Correctly access the InputSettings singleton
input_settings = unreal.InputSettings.get_input_settings()
# Create the input action mapping
action_mapping = unreal.InputActionKeyMapping(action_name=action_name, key=unreal.InputCoreTypes.get_key(key))
# Add the mapping to the input settings
input_settings.add_action_mapping(action_mapping)
# Save the changes to the config file
input_settings.save_config()
return {"success": True, "message": f"Added input binding {action_name} -> {key}"}
except Exception as e:
return {"success": False, "error": str(e)}
|
#!/project/ python
# -*- coding: utf-8 -*-
"""
Module that contains installer related functions for Autodesk Maya
"""
# System global imports
# software specific imports
import unreal
# mca python imports
from mca.common.utils import fileio
def rename_asset(new_name=None):
"""
Renames a selected asset
:param str new_name: new string name.
"""
if not new_name:
new_name = 'SK_HealingSkull'
system_lib = unreal.SystemLibrary()
editor_util = unreal.EditorUtilityLibrary()
string_lib = unreal.StringLibrary()
asset_lib = unreal.EditorAssetLibrary()
# get the selected assets
selected_assets = editor_util.get_selected_assets()
if not selected_assets:
unreal.log(f"Selected Please Select an Asset!")
return
asset = selected_assets[0]
asset_name = system_lib.get_object_name(asset)
unreal.log(f'Asset Name: {asset}\nAsset Path: {asset_lib.get_path_name_for_loaded_asset(asset)}')
editor_util.rename_asset(asset, new_name)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.