text
stringlengths 15
267k
|
|---|
# -*- coding: utf-8 -*-
import unreal
import os
from Utilities.Utils import Singleton
from Utilities.Utils import cast
import Utilities
import QueryTools
import re
import types
import collections
from .import Utils
global _r
COLUMN_COUNT = 2
class DetailData(object):
def __init__(self):
self.filter_str = ""
self.filteredIndexToIndex = []
self.hisCrumbObjsAndNames = [] #list[(obj, propertyName)]
self.attributes = None
self.filtered_attributes = None
self.plains = []
self.riches = []
self.selected = set()
def check_line_id(self, line_id, column_count):
from_line = line_id * column_count
to_line = (line_id + 1) * column_count
assert len(self.plains) == len(self.riches), "len(self.plains) != len(self.riches)"
if 0 <= from_line < len(self.plains) and 0 <= to_line <= len(self.plains):
return True
else:
unreal.log_error(f"Check Line Id Failed: {line_id}, plains: {len(self.plains)}, rich: {len(self.riches)}")
return False
def get_plain(self, line_id, column_count):
assert self.check_line_id(line_id, column_count), "check line id failed."
return self.plains[line_id * 2 : line_id * 2 + 2]
def get_rich(self, line_id, column_count):
assert self.check_line_id(line_id, column_count), "check line id failed."
return self.riches[line_id * 2: line_id * 2 + 2]
class ObjectDetailViewer(metaclass=Singleton):
def __init__(self, jsonPath):
self.jsonPath = jsonPath
self.data = unreal.PythonBPLib.get_chameleon_data(self.jsonPath)
self.ui_checkbox_single_mode = "CheckBoxSingleMode"
self.ui_checkbox_compare_mode = "CheckBoxCompareMode"
self.ui_left_group = "LeftDetailGroup"
self.ui_right_group = "RightDetailGroup"
self.ui_button_refresh = "RefreshCompareButton"
self.ui_detailListLeft = "ListViewLeft"
self.ui_detailListRight = "ListViewRight"
self.ui_hisObjsBreadcrumbLeft = 'ObjectHisBreadcrumbLeft'
self.ui_hisObjsBreadcrumbRight = 'ObjectHisBreadcrumbRight'
# self.ui_headRowLeft = "HeaderRowLeft"
# self.ui_headRowRight = "HeaderRowRight"
self.ui_labelLeft = "LabelLeft"
self.ui_labelRight = "LabelRight"
self.ui_info_output = "InfoOutput"
self.ui_rightButtonsGroup = "RightButtonsGroup" # used for compare mode
self.ui_rightListGroup = "RightListGroup"
self.ui_refreshButtonGroup = "RefreshButtonGroup"
self.reset()
def on_close(self):
self.reset()
def reset(self):
self.showBuiltin = True
self.showOther = True
self.showProperties = True
self.showEditorProperties = True
self.showParamFunction = True
self.compareMode = False
self.left = None
self.right = None
self.leftSearchText = ""
self.rightSearchText = ""
self.left_rich = None
self.left_plain = None
self.var = None
self.diff_count = 0
def update_log_text(self, bRight):
bShowRight = self.compareMode
result = ""
for side_str in ["left", "right"] if bShowRight else ["left"]:
bRight = side_str != "left"
ui_breadcrumb = self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft
breadcrumbs = self.right.hisCrumbObjsAndNames if bRight else self.left.hisCrumbObjsAndNames
crumbCount = self.data.get_breadcrumbs_count_string(ui_breadcrumb)
if bRight:
result += "\t\t\t"
result += "{} crumb: {} hisObj: {}".format(side_str, crumbCount, len(breadcrumbs))
if self.compareMode:
result = f"{result}\t\t\tdiff count: {self.diff_count}"
self.data.set_text(self.ui_info_output, result)
def get_color_by(self, attr : Utils.attr_detail):
if attr.bCallable_builtin:
return "DarkTurquoise".lower()
if attr.bCallable_other:
return "RoyalBlue".lower()
if attr.bEditorProperty:
return "LimeGreen".lower()
if attr.bOtherProperty:
return "yellow"
def get_color(self, typeStr):
if typeStr == "property":
return 'white'
if typeStr == "return_type":
return 'gray'
if typeStr == "param":
return 'gray'
def get_name_with_rich_text(self, attr:Utils.attr_detail):
name_color = self.get_color_by(attr)
param_color = self.get_color("param")
return_type_color = self.get_color("return_type")
if attr.bProperty:
return "\t<RichText.{}>{}</>".format(name_color, attr.name)
else:
if attr.param_str:
return "\t<RichText.{}>{}(</><RichText.{}>{}</><RichText.{}>)</>".format(name_color, attr.name
, param_color, attr.param_str
, name_color)
else:
if attr.bCallable_other:
return "\t<RichText.{}>{}</>".format(name_color, attr.name)
else:
return "\t<RichText.{}>{}()</><RichText.{}> {}</>".format(name_color, attr.name
, return_type_color, attr.return_type_str)
def get_name_with_plain_text(self, attr:Utils.attr_detail):
if attr.bProperty:
return "\t{}".format(attr.name)
else:
if attr.param_str:
return "\t{}({})".format( attr.name, attr.param_str)
else:
if attr.bCallable_other:
return "\t{}".format( attr.name)
else:
return "\t{}() {}".format(attr.name,attr.return_type_str)
def filter(self, data:DetailData):
result = []
indices = []
for i, attr in enumerate(data.attributes):
if not self.showEditorProperties and attr.bEditorProperty:
continue
if not self.showProperties and attr.bOtherProperty:
continue
if not self.showParamFunction and attr.bHasParamFunction:
continue
if not self.showBuiltin and attr.bCallable_builtin:
continue
if not self.showOther and attr.bCallable_other:
continue
if data.filter_str:
if data.filter_str.lower() not in attr.display_result.lower() and data.filter_str not in attr.display_name.lower() :
continue
result.append(attr)
indices.append(i)
return result, indices
def show_data(self, data:DetailData, ui_listView):
flatten_list_items = []
flatten_list_items_plain = []
for i, attr in enumerate(data.filtered_attributes):
# print(f"{i}: {attr.name} {attr.display_name}, {attr.display_result} ")
attr.check()
assert attr.display_name, f"display name null {attr.display_name}"
assert isinstance(attr.display_result, str), f"display result null {attr.display_result}"
result_str = attr.display_result
if len(result_str) > 200:
result_str = result_str[:200] + "......"
flatten_list_items.extend([self.get_name_with_rich_text(attr), result_str])
flatten_list_items_plain.extend([self.get_name_with_plain_text(attr), result_str])
data.riches = flatten_list_items
data.plains = flatten_list_items_plain
data.selected.clear()
self.data.set_list_view_multi_column_items(ui_listView, flatten_list_items, 2)
def query_and_push(self, obj, propertyName, bPush, bRight): #bPush: whether add Breadcrumb nor not, call by property
if bRight:
ui_Label = self.ui_labelRight
ui_listView = self.ui_detailListRight
ui_breadcrumb = self.ui_hisObjsBreadcrumbRight
else:
ui_Label = self.ui_labelLeft
ui_listView = self.ui_detailListLeft
ui_breadcrumb = self.ui_hisObjsBreadcrumbLeft
data = self.right if bRight else self.left
data.attributes = Utils.ll(obj)
data.filtered_attributes, data.filteredIndexToIndex = self.filter(data)
self.show_data(data, ui_listView)
# set breadcrumb
if propertyName and len(propertyName) > 0:
label = propertyName
else:
if isinstance(obj, unreal.Object):
label = obj.get_name()
else:
label = obj.__str__()
if bPush: # push
# print(f"%%% push: {propertyName}, label {label}")
data.hisCrumbObjsAndNames.append((obj, propertyName))
self.data.push_breadcrumb_string(ui_breadcrumb, label, label)
self.data.set_text(ui_Label, "{} type: {}".format(label, type(obj)) )
crumbCount = self.data.get_breadcrumbs_count_string(ui_breadcrumb)
if bRight:
assert len(self.right.hisCrumbObjsAndNames) == crumbCount, "hisCrumbObjsAndNames count not match {} {}".format(len(self.right.hisCrumbObjsAndNames), crumbCount)
else:
assert len(self.left.hisCrumbObjsAndNames) == crumbCount, "hisCrumbObjsAndNames count not match {} {}".format(len(self.left.hisCrumbObjsAndNames), crumbCount)
self.update_log_text(bRight)
def clear_and_query(self, obj, bRight):
# first time query
self.data.clear_breadcrumbs_string(self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft)
if not self.right:
self.right = DetailData()
if not self.left:
self.left = DetailData()
data = self.right if bRight else self.left
data.hisCrumbObjsAndNames = [] #clear his-Object at first time query
if bRight:
assert len(self.right.hisCrumbObjsAndNames) == 0, "len(self.right.hisCrumbObjsAndNames) != 0"
else:
assert len(self.left.hisCrumbObjsAndNames) == 0, "len(self.left.hisCrumbObjsAndNames) != 0"
self.query_and_push(obj, "", bPush=True, bRight=bRight)
self.apply_compare_if_needed()
self.update_log_text(bRight)
def update_ui_by_mode(self):
self.data.set_is_checked(self.ui_checkbox_compare_mode, self.compareMode)
self.data.set_is_checked(self.ui_checkbox_single_mode, not self.compareMode)
bCollapsed = not self.compareMode
self.data.set_collapsed(self.ui_rightButtonsGroup, bCollapsed)
self.data.set_collapsed(self.ui_right_group, bCollapsed)
self.data.set_collapsed(self.ui_button_refresh, bCollapsed)
def on_checkbox_SingleMode_Click(self, state):
self.compareMode = False
self.update_ui_by_mode()
def on_checkbox_CompareMode_Click(self, state):
self.compareMode = True
self.update_ui_by_mode()
def on_button_Refresh_click(self):
self.apply_compare_if_needed()
def on_button_SelectAsset_click(self, bRightSide):
selectedAssets = Utilities.Utils.get_selected_assets()
if len(selectedAssets) == 0:
return
self.clear_and_query(selectedAssets[0], bRightSide)
def on_button_QuerySelected_click(self, bRightSide):
# query component when any component was selected, otherwise actor
obj = Utilities.Utils.get_selected_comp()
if not obj:
obj = Utilities.Utils.get_selected_actor()
if obj:
self.clear_and_query(obj, bRightSide)
def on_drop(self, bRightSide, *args, **kwargs):
if "assets" in kwargs and kwargs["assets"]:
asset = unreal.load_asset(kwargs["assets"][0])
if asset:
self.clear_and_query(asset, bRightSide)
return
if "actors" in kwargs and kwargs["actors"]:
actor = unreal.PythonBPLib.find_actor_by_name(kwargs["actors"][0], unreal.EditorLevelLibrary.get_editor_world())
if actor:
print(actor)
self.clear_and_query(actor, bRightSide)
return
item_count = 0
for k, v in kwargs.items():
item_count += len(v)
if item_count == 0:
selected_comp = Utilities.Utils.get_selected_comp()
if selected_comp:
self.clear_and_query(selected_comp, bRightSide)
def log_r_warning(self):
unreal.log_warning("Assign the global var: '_r' with the MenuItem: 'select X --> _r' on Python Icon menu")
def on_button_Query_R_click(self, r_obj, bRightSide=False):
print("on_button_Query_R_click call")
if not r_obj:
return
self.clear_and_query(r_obj, bRightSide)
def on_list_double_click_do(self, index, bRight):
# print ("on_listview_DetailList_mouse_button_double_click {} bRight: {}".format(index, bRight))
data = self.right if bRight else self.left
typeBlacklist = [int, float, str, bool] #, types.NotImplementedType]
real_index = data.filteredIndexToIndex[index] if data.filteredIndexToIndex else index
assert 0 <= real_index < len(data.attributes)
currentObj, _ = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames) - 1]
attr_name = data.attributes[real_index].name
objResult, propertyName = self.try_get_object(data, currentObj, attr_name)
if not objResult or objResult is currentObj: # equal
return
if isinstance(objResult, str) and "skip call" in objResult.lower():
return
if type(objResult) in typeBlacklist:
return
if isinstance(objResult, collections.Iterable):
if type(objResult[0]) in typeBlacklist:
return
nextObj = objResult[0]
nextPropertyName = str(propertyName) + "[0]"
else:
nextObj = objResult
nextPropertyName = str(propertyName)
self.query_and_push(nextObj, nextPropertyName, bPush=True, bRight=bRight)
self.apply_compare_if_needed()
self.update_log_text(bRight)
def on_listview_DetailListRight_mouse_button_double_click(self, index):
self.on_list_double_click_do(index, bRight=True)
def on_listview_DetailListLeft_mouse_button_double_click(self, index):
self.on_list_double_click_do(index, bRight=False)
def on_breadcrumbtrail_click_do(self, item, bRight):
ui_hisObjsBreadcrumb = self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft
data = self.right if bRight else self.left
count = self.data.get_breadcrumbs_count_string(ui_hisObjsBreadcrumb)
print ("on_breadcrumbtrail_ObjectHis_crumb_click: {} count: {} len(data.hisCrumbObjsAndNames): {}".format(item, count, len(data.hisCrumbObjsAndNames)))
while len(data.hisCrumbObjsAndNames) > count:
data.hisCrumbObjsAndNames.pop()
nextObj, name = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames) - 1]
if not bRight:
assert self.left.hisCrumbObjsAndNames == data.hisCrumbObjsAndNames, "self.left.hisCrumbObjsAndNames = data.hisCrumbObjsAndNames"
self.query_and_push(nextObj, name, bPush=False, bRight=bRight)
self.apply_compare_if_needed()
self.update_log_text(bRight=bRight)
def on_breadcrumbtrail_ObjectHisLeft_crumb_click(self, item):
self.on_breadcrumbtrail_click_do(item, bRight=False)
def on_breadcrumbtrail_ObjectHisRight_crumb_click(self, item):
self.on_breadcrumbtrail_click_do(item, bRight=True)
def remove_address_str(self, strIn):
return re.sub(r'\(0x[0-9,A-F]{16}\)', '', strIn)
def apply_compare_if_needed(self):
if not self.compareMode:
return
lefts = self.left.filtered_attributes if self.left.filtered_attributes else self.left.attributes
rights = self.right.filtered_attributes if self.right.filtered_attributes else self.right.attributes
if not lefts:
lefts = []
if not rights:
rights = []
leftIDs = []
rightIDs = []
for i, left_attr in enumerate(lefts):
for j, right_attr in enumerate(rights):
if right_attr.name == left_attr.name:
if right_attr.result != left_attr.result:
leftIDs.append(i)
rightIDs.append(j)
break
self.data.set_list_view_multi_column_selections(self.ui_detailListLeft, leftIDs)
self.data.set_list_view_multi_column_selections(self.ui_detailListRight, rightIDs)
self.diff_count = len(leftIDs)
def apply_search_filter(self, text, bRight):
_data = self.right if bRight else self.left
_data.filter_str = text if len(text) else ""
_data.filtered_attributes, _data.filteredIndexToIndex = self.filter(_data)
ui_listView = self.ui_detailListRight if bRight else self.ui_detailListLeft
self.show_data(_data, ui_listView)
self.apply_compare_if_needed()
def on_searchbox_FilterLeft_text_changed(self, text):
self.apply_search_filter(text, bRight=False)
def on_searchbox_FilterLeft_text_committed(self, text):
self.apply_search_filter(text, bRight=False)
def on_searchbox_FilterRight_text_changed(self, text):
self.apply_search_filter(text, bRight=True)
def on_searchbox_FilterRight_text_committed(self, text):
self.apply_search_filter(text, bRight=True)
def apply_filter(self):
_datas = [self.left, self.right]
_isRight = [False, True]
for data, bRight in zip(_datas, _isRight):
if len(data.hisCrumbObjsAndNames) > 0:
nextObj, name = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames)-1]
self.query_and_push(nextObj, name, bPush=False, bRight=bRight)
self.apply_compare_if_needed()
self.update_log_text(bRight=False) #
def try_get_object(self, data, obj, name:str):
index = -1
attribute = None
for i, attr in enumerate(data.attributes):
if attr.name == name:
index = i
attribute = attr
assert index >= 0
return attribute.result, name
def ui_on_checkbox_ShowBuiltin_state_changed(self, bEnabled):
self.showBuiltin = bEnabled
self.apply_filter()
def ui_on_checkbox_ShowOther_state_changed(self, bEnabled):
self.showOther = bEnabled
self.apply_filter()
def ui_on_checkbox_ShowProperties_state_changed(self, bEnabled):
self.showProperties = bEnabled
self.apply_filter()
def ui_on_checkbox_ShowEditorProperties_state_changed(self, bEnabled):
self.showEditorProperties = bEnabled
self.apply_filter()
def ui_on_checkbox_ShowParamFunction_state_changed(self, bEnabled):
self.showParamFunction = bEnabled
self.apply_filter()
def ui_on_listview_DetailList_selection_changed(self, bRight):
data = [self.left, self.right][bRight]
list_view = [self.ui_detailListLeft, self.ui_detailListRight][bRight]
selected_indices = set(self.data.get_list_view_multi_column_selection(list_view))
added = selected_indices - data.selected
de_selected = data.selected - selected_indices
for i, lineId in enumerate(added):
self.data.set_list_view_multi_column_line(list_view, lineId, data.get_plain(lineId, column_count=COLUMN_COUNT)
, rebuild_list=True if i == len(added)-1 and len(de_selected) == 0 else False)
for i, lineId in enumerate(de_selected):
self.data.set_list_view_multi_column_line(list_view, lineId, data.get_rich(lineId, column_count=COLUMN_COUNT)
, rebuild_list=True if i == len(de_selected)-1 else False)
data.selected = selected_indices
|
# Copyright Epic Games, Inc. All Rights Reserved.
import os
import unreal
#-------------------------------------------------------------------------------
class Platform(unreal.Platform):
name = "TVOS"
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 "TVOS"
if target == "client": return "TVOSClient"
|
import unreal
#import unreal module
from typing import List
#import typing module for 'clearer' annotation
##But, this is not Typescript though, :(
_seek_parent_material: unreal.Material
#pick from editor
_seek_parent_material_class: object = _seek_parent_material.get_class()
compare_seek_parent_material_class = unreal.Material().get_class()
compare_class: object = unreal.MaterialInstanceConstant().get_class()
asset_lib: unreal.EditorAssetLibrary = unreal.EditorAssetLibrary
util_lib: unreal.EditorUtilityLibrary = unreal.EditorUtilityLibrary
if _seek_parent_material_class == compare_seek_parent_material_class :
selected_list : List[object] = util_lib.get_selected_assets()
for each in selected_list :
classof = each.get_class()
if classof == compare_class :
if each.parent == _seek_parent_material :
need_to_print: str = each.get_name() + ' => ' + _seek_parent_material.get_name() + ' => OK '
unreal.log(need_to_print)
else :
need_to_print: str = each.get_name() + ' ≠> ' + _seek_parent_material.get_name()
unreal.log_warning(need_to_print)
else :
need_to_print: str = each.get_name() + ' <≠> Not MaterialInstanceConstant '
unreal.log_error(need_to_print)
else:
unreal.log_error('Parent is not unreal.Material()')
|
#!/project/ python3
"""
Sprite Sheet Processor - Python Implementation
==============================================
This Python script replicates the C++ SpriteSheetProcessor functionality using
Unreal Engine's Python Editor Scripting API. It provides automated sprite sheet
processing for Paper2D system with the same features as the C++ version.
Features:
- Automatic texture import from RawAssets folder
- Paper2D texture settings optimization
- Grid-based sprite extraction (6x8 default)
- Individual sprite texture creation
- Paper2D sprite generation with proper pivots
- Flipbook animation creation (8 animations, 6 frames each)
Author: Generated Python equivalent of C++ SpriteSheetProcessor
"""
import unreal
import os
from enum import IntEnum
class AnimationType(IntEnum):
"""Enumeration for different animation types corresponding to sprite sheet rows"""
IDLE = 0
MOVE = 1
ATTACK_SIDEWAYS = 2
ATTACK_SIDEWAYS2 = 3
ATTACK_DOWNWARDS = 4
ATTACK_DOWNWARDS2 = 5
ATTACK_UPWARDS = 6
ATTACK_UPWARDS2 = 7
class SpriteSheetInfo:
"""Configuration structure for sprite sheet processing parameters"""
def __init__(self, columns=6, rows=8, source_texture_path="/project/", destination_path="/project/"):
self.columns = columns
self.rows = rows
self.source_texture_path = source_texture_path
self.destination_path = destination_path
class SpriteSheetProcessor:
"""Main processor class that handles sprite sheet import and processing"""
def __init__(self):
self.generated_sprites = []
self.generated_flipbooks = []
def process_sprite_sheet(self, texture_name, sprite_info=None):
"""
Main processing function that orchestrates the entire workflow
Args:
texture_name (str): Name of the texture file (without extension)
sprite_info (SpriteSheetInfo): Configuration for processing
Returns:
bool: True if processing was successful, False otherwise
"""
if sprite_info is None:
sprite_info = SpriteSheetInfo()
# Step 1: Import texture from RawAssets
print(f"Starting sprite sheet processing for: {texture_name}")
imported_texture = self.import_texture(texture_name, sprite_info)
if not imported_texture:
print(f"ERROR: Failed to import texture: {texture_name}")
return False
print(f"Successfully imported texture: {texture_name}")
# Step 2: Extract individual sprites
extracted_sprites = self.extract_sprites(imported_texture, sprite_info)
if not extracted_sprites:
print(f"ERROR: Failed to extract sprites from texture: {texture_name}")
return False
print(f"Successfully extracted {len(extracted_sprites)} sprites")
# Step 3: Create flipbook animations
created_animations = self.create_animations(extracted_sprites, sprite_info)
if not created_animations:
print(f"ERROR: Failed to create animations from sprites")
return False
print(f"Successfully created {len(created_animations)} animations")
# Store results
self.generated_sprites = extracted_sprites
self.generated_flipbooks = created_animations
print(f"Sprite sheet processing completed successfully!")
print(f"Generated {len(extracted_sprites)} sprites and {len(created_animations)} animations")
return True
def import_texture(self, texture_name, sprite_info):
"""
Import texture from RawAssets folder and apply Paper2D settings
Args:
texture_name (str): Name of the texture file
sprite_info (SpriteSheetInfo): Processing configuration
Returns:
unreal.Texture2D: Imported and configured texture, or None if failed
"""
try:
# Construct file paths
project_dir = unreal.Paths.project_dir()
raw_asset_path = os.path.join(project_dir, "RawAssets", f"{texture_name}.png")
destination_path = f"/Game/{texture_name}"
print(f"Importing texture from: {raw_asset_path}")
print(f"Destination path: {destination_path}")
# Check if file exists
if not os.path.exists(raw_asset_path):
print(f"ERROR: Source texture file does not exist: {raw_asset_path}")
return None
# Use AssetTools to import the texture
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
import_task = unreal.AssetImportTask()
import_task.set_editor_property('automated', True)
import_task.set_editor_property('destination_name', texture_name)
import_task.set_editor_property('destination_path', '/Game')
import_task.set_editor_property('filename', raw_asset_path)
import_task.set_editor_property('replace_existing', True)
import_task.set_editor_property('save', True)
# Execute import
asset_tools.import_asset_tasks([import_task])
# Load the imported texture
imported_texture = unreal.EditorAssetLibrary.load_asset(destination_path)
if not imported_texture:
print(f"ERROR: Failed to load imported texture: {destination_path}")
return None
# Apply Paper2D texture settings
if not self.apply_paper2d_texture_settings(imported_texture):
print(f"WARNING: Failed to apply Paper2D settings to texture: {texture_name}")
print(f"Successfully imported and configured texture: {texture_name}")
return imported_texture
except Exception as e:
print(f"ERROR: Exception during texture import: {e}")
return None
def apply_paper2d_texture_settings(self, texture):
"""
Apply optimal Paper2D settings to the imported texture
Args:
texture (unreal.Texture2D): Texture to configure
Returns:
bool: True if settings were applied successfully
"""
try:
if not texture:
return False
# Apply Paper2D optimized settings
texture.set_editor_property('filter', unreal.TextureFilter.TF_NEAREST)
texture.set_editor_property('mip_gen_settings', unreal.TextureMipGenSettings.TMGS_NO_MIPMAPS)
texture.set_editor_property('compression_settings', unreal.TextureCompressionSettings.TC_EDITOR_ICON)
texture.set_editor_property('srgb', False)
texture.set_editor_property('lod_group', unreal.TextureGroup.TEXTUREGROUP_PIXELS2D)
texture.set_editor_property('never_stream', True)
texture.set_editor_property('power_of_two_mode', unreal.TexturePowerOfTwoSetting.NONE)
# Save the asset
unreal.EditorAssetLibrary.save_asset(texture.get_path_name())
print(f"Applied Paper2D texture settings to: {texture.get_name()}")
return True
except Exception as e:
print(f"ERROR: Failed to apply texture settings: {e}")
return False
def extract_sprites(self, texture, sprite_info):
"""
Extract individual sprites from the sprite sheet texture
Args:
texture (unreal.Texture2D): Source sprite sheet texture
sprite_info (SpriteSheetInfo): Grid configuration
Returns:
list: List of created PaperSprite objects
"""
extracted_sprites = []
try:
if not texture:
print("ERROR: Texture is None")
return extracted_sprites
# Get texture dimensions
texture_width = texture.blueprint_get_size_x()
texture_height = texture.blueprint_get_size_y()
# Calculate sprite dimensions
sprite_width = texture_width / sprite_info.columns
sprite_height = texture_height / sprite_info.rows
print(f"Texture dimensions: {texture_width}x{texture_height}")
print(f"Grid: {sprite_info.columns}x{sprite_info.rows}")
print(f"Sprite size: {sprite_width}x{sprite_height}")
# Create sprites for each grid cell
for row in range(sprite_info.rows):
for col in range(sprite_info.columns):
sprite_name = f"{texture.get_name()}_R{row}_C{col}"
package_path = f"/project/{sprite_name}"
# Create the sprite
sprite = self.create_paper_sprite(texture, sprite_name, package_path,
col * sprite_width, row * sprite_height,
sprite_width, sprite_height)
if sprite:
extracted_sprites.append(sprite)
print(f"Created sprite: {sprite_name} at ({col * sprite_width}, {row * sprite_height})")
else:
print(f"ERROR: Failed to create sprite: {sprite_name}")
print(f"Successfully extracted {len(extracted_sprites)} sprites")
return extracted_sprites
except Exception as e:
print(f"ERROR: Exception during sprite extraction: {e}")
return extracted_sprites
def create_paper_sprite(self, source_texture, sprite_name, package_path, x, y, width, height):
"""
Create a Paper2D sprite from a region of the source texture
Args:
source_texture (unreal.Texture2D): Source texture
sprite_name (str): Name for the new sprite
package_path (str): Asset path for the sprite
x, y (float): Top-left position of the sprite region
width, height (float): Dimensions of the sprite region
Returns:
unreal.PaperSprite: Created sprite or None if failed
"""
try:
# Use AssetTools to create the sprite
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
# Create the sprite asset
sprite = asset_tools.create_asset(sprite_name, '/project/', unreal.PaperSprite, None)
if not sprite:
print(f"ERROR: Failed to create sprite asset: {sprite_name}")
return None
# Configure the sprite properties
sprite.set_editor_property('source_texture', source_texture)
sprite.set_editor_property('source_uv', unreal.Vector2D(x, y))
sprite.set_editor_property('source_dimension', unreal.Vector2D(width, height))
# Set pivot to center
sprite.set_editor_property('pivot_mode', unreal.SpritePivotMode.CENTER_CENTER)
# Save the sprite
unreal.EditorAssetLibrary.save_asset(sprite.get_path_name())
return sprite
except Exception as e:
print(f"ERROR: Failed to create Paper2D sprite {sprite_name}: {e}")
return None
def create_animations(self, sprites, sprite_info):
"""
Create flipbook animations from the extracted sprites
Args:
sprites (list): List of PaperSprite objects
sprite_info (SpriteSheetInfo): Grid configuration
Returns:
list: List of created PaperFlipbook objects
"""
created_animations = []
try:
if len(sprites) != sprite_info.rows * sprite_info.columns:
print(f"ERROR: Sprite count mismatch. Expected: {sprite_info.rows * sprite_info.columns}, Got: {len(sprites)}")
return created_animations
# Create one animation per row
for row in range(sprite_info.rows):
anim_type = AnimationType(row)
animation_name = self.get_animation_name(anim_type)
package_path = f"/project/{animation_name}"
# Create the flipbook animation
flipbook = self.create_flipbook_animation(sprites, sprite_info, row, animation_name, package_path)
if flipbook:
created_animations.append(flipbook)
print(f"Created animation: {animation_name} with {sprite_info.columns} frames")
else:
print(f"ERROR: Failed to create animation: {animation_name}")
print(f"Successfully created {len(created_animations)} animations")
return created_animations
except Exception as e:
print(f"ERROR: Exception during animation creation: {e}")
return created_animations
def create_flipbook_animation(self, sprites, sprite_info, row, animation_name, package_path):
"""
Create a single flipbook animation from a row of sprites
Args:
sprites (list): List of all sprites
sprite_info (SpriteSheetInfo): Grid configuration
row (int): Row index for this animation
animation_name (str): Name for the animation
package_path (str): Asset path for the flipbook
Returns:
unreal.PaperFlipbook: Created flipbook or None if failed
"""
try:
# Use AssetTools to create the flipbook
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
# Create the flipbook asset
flipbook = asset_tools.create_asset(animation_name, '/project/', unreal.PaperFlipbook, None)
if not flipbook:
print(f"ERROR: Failed to create flipbook asset: {animation_name}")
return None
# Create key frames for this row
key_frames = []
for col in range(sprite_info.columns):
sprite_index = row * sprite_info.columns + col
if sprite_index < len(sprites) and sprites[sprite_index]:
# Create key frame
key_frame = unreal.PaperFlipbookKeyFrame()
key_frame.set_editor_property('sprite', sprites[sprite_index])
key_frame.set_editor_property('frame_run', 1)
key_frames.append(key_frame)
# Set the key frames
flipbook.set_editor_property('key_frames', key_frames)
flipbook.set_editor_property('frames_per_second', 12.0)
# Save the flipbook
unreal.EditorAssetLibrary.save_asset(flipbook.get_path_name())
return flipbook
except Exception as e:
print(f"ERROR: Failed to create flipbook animation {animation_name}: {e}")
return None
def get_animation_name(self, anim_type):
"""
Get the animation name string for a given animation type
Args:
anim_type (AnimationType): Type of animation
Returns:
str: Animation name
"""
animation_names = {
AnimationType.IDLE: "Idle",
AnimationType.MOVE: "Move",
AnimationType.ATTACK_SIDEWAYS: "AttackSideways",
AnimationType.ATTACK_SIDEWAYS2: "AttackSideways2",
AnimationType.ATTACK_DOWNWARDS: "AttackDownwards",
AnimationType.ATTACK_DOWNWARDS2: "AttackDownwards2",
AnimationType.ATTACK_UPWARDS: "AttackUpwards",
AnimationType.ATTACK_UPWARDS2: "AttackUpwards2"
}
return animation_names.get(anim_type, "Unknown")
# Convenience functions for easy script execution
def process_warrior_sprite_sheet():
"""Process the default Warrior_Blue sprite sheet"""
processor = SpriteSheetProcessor()
sprite_info = SpriteSheetInfo(columns=6, rows=8)
return processor.process_sprite_sheet("Warrior_Blue", sprite_info)
def process_custom_sprite_sheet(texture_name, columns=6, rows=8):
"""Process a custom sprite sheet with specified grid dimensions"""
processor = SpriteSheetProcessor()
sprite_info = SpriteSheetInfo(columns=columns, rows=rows)
return processor.process_sprite_sheet(texture_name, sprite_info)
# Main execution for testing
if __name__ == "__main__":
print("=== Sprite Sheet Processor - Python Implementation ===")
print("Processing Warrior_Blue sprite sheet...")
success = process_warrior_sprite_sheet()
if success:
print("✓ Sprite sheet processing completed successfully!")
else:
print("✗ Sprite sheet processing failed!")
|
"""
>>> python -m tests.unreal.init_test
"""
from xrfeitoria.rpc import remote_unreal
from xrfeitoria.utils import setup_logger
from ..utils import __timer__, _init_unreal
@remote_unreal()
def test_unreal():
import unreal # fmt: skip
unreal.log('test')
def init_test(debug: bool = False, dev: bool = False, background: bool = False):
logger = setup_logger(level='DEBUG' if debug else 'INFO')
with __timer__('init unreal'):
with _init_unreal(dev_plugin=dev, background=background) as xf_runner:
test_unreal()
logger.info('🎉 [bold green]init tests passed!')
if __name__ == '__main__':
import argparse
args = argparse.ArgumentParser()
args.add_argument('--debug', action='store_true')
args.add_argument('--dev', action='store_true')
args.add_argument('--background', '-b', action='store_true')
args = args.parse_args()
init_test(debug=args.debug, dev=args.dev, background=args.background)
|
import unreal
import os
import random
'''
TO USE:
1. change NUM_PAIRS_IMAGES to whatever number of pairs you want
2. change base_directory to the UE5 Data folder in the PAIR repo wherever that is stored on your computer
3. In unreal, click on "tools" (in the top bar), scroll down to near the bottom, and click "Execute Python Script"
4. The script should run and take screenshots that will be stored in the "Images" and "Labels" folders in UE5 Data
5. The first time you run the script it skips a lot of pairs for whatever reason, so run it once with not very many pairs
and then delete that data and run it using the real number of pairs you wanted
'''
# number of pairs of images you want
NUM_PAIRS_IMAGES = 700
base_directory = r"/project/ Year 2\Semester 1\ECE528\Project\PAIR\Training Data\UE5 Data"
# the max distance the camera can move between each picture (x, y, z)
MAX_DISTANCE = unreal.Vector(1000, 1000, 300)
# the max rotation that can happen from 0, 0, 0 (roll, pitch, yaw)
MAX_ROTATION = unreal.Rotator(10, 10, 30)
# height and width in pixels for the screenshots
SS_HEIGHT = 672
SS_WIDTH = 672
# Helper functions
def calculate_differences(old_location, new_location, old_rotation, new_rotation):
print("old location:", old_location)
print("new location:", new_location)
delta_position = new_location - old_location
print("delta:", delta_position)
delta_x = abs(delta_position.x / 1000.0) # convert unreal units to meters
delta_y = abs(delta_position.y / 1000.0)
delta_z = abs(delta_position.z / 1000.0)
delta_pitch = abs(new_rotation.pitch - old_rotation.pitch)
delta_roll = abs(new_rotation.roll - old_rotation.roll)
delta_yaw = abs(new_rotation.yaw - old_rotation.yaw)
return (delta_x, delta_y, delta_z, delta_pitch, delta_roll, delta_yaw)
def get_scene_bounds():
all_actors = unreal.EditorLevelLibrary.get_all_level_actors()
min_point = unreal.Vector(float('inf'), float('inf'), float('inf'))
max_point = unreal.Vector(float('-inf'), float('-inf'), float('-inf'))
for actor in all_actors:
if isinstance(actor, unreal.StaticMeshActor):
actor_location, actor_extent = actor.get_actor_bounds(only_colliding_components=False)
# Ignoring skybox
if (actor_extent.x > 1000000):
continue
min_point.x = min(min_point.x, actor_location.x - actor_extent.x)
min_point.y = min(min_point.y, actor_location.y - actor_extent.y)
min_point.z = min(min_point.z, actor_location.z - actor_extent.z)
max_point.x = max(max_point.x, actor_location.x + actor_extent.x)
max_point.y = max(max_point.y, actor_location.y + actor_extent.y)
max_point.z = max(max_point.z, actor_location.z + actor_extent.z)
return min_point, max_point
def save_label(label_path, label_data):
with open(label_path, 'w') as file:
file.write(",".join(map(str, label_data)))
class OnTick(object):
image_directory = os.path.join(base_directory, "Images")
label_directory = os.path.join(base_directory, "Labels")
def __init__(self):
camera_actors = unreal.GameplayStatics().get_all_actors_of_class(unreal.EditorLevelLibrary.get_editor_world(), unreal.CameraActor)
if len(camera_actors) == 0:
print(None, "Error: Could not find any CameraActor in the level.")
else:
self.camera_actor = camera_actors[0]
print(None, f"Found {len(camera_actors)} CameraActor actors!")
print(None, f"CameraActor: {self.camera_actor.get_name()}")
os.makedirs(self.image_directory, exist_ok=True)
os.makedirs(self.label_directory, exist_ok=True)
self.min_point, self.max_point = get_scene_bounds()
def start(self):
self.tickcount = 200
self.slate_post_tick_handle = unreal.register_slate_post_tick_callback(self.__tick__)
def move_camera(self, max_distance=MAX_DISTANCE, max_rotation=MAX_ROTATION, offset=1000):
current_location = self.camera_actor.get_actor_location()
random_offset = unreal.Vector(
random.uniform(-max_distance.x, max_distance.x),
random.uniform(-max_distance.y, max_distance.y),
random.uniform(-max_distance.z, max_distance.z)
)
new_location = current_location + random_offset
new_location.x = max(min(new_location.x, self.max_point.x - offset), self.min_point.x + offset)
new_location.y = max(min(new_location.y, self.max_point.y - offset), self.min_point.y + offset)
new_location.z = max(min(new_location.z, self.max_point.z - offset), self.min_point.z + offset)
random_pitch = random.uniform(-max_rotation.pitch, max_rotation.pitch)
random_roll = random.uniform(-max_rotation.roll, max_rotation.roll)
random_yaw = random.uniform(-max_rotation.yaw, max_rotation.yaw)
new_rotation = unreal.Rotator(random_pitch, random_yaw, random_roll)
self.camera_actor.set_actor_location(new_location, sweep=True, teleport=True)
self.camera_actor.set_actor_rotation(new_rotation, teleport_physics=True)
return new_location, new_rotation
def take_screenshot_1(self):
self.pair_id = self.tickcount // 2
self.pair_folder = os.path.join(self.image_directory, f"pair_{self.pair_id:05d}")
os.makedirs(self.pair_folder, exist_ok=True)
first_image_path = os.path.join(self.pair_folder, "image1.png")
print("Taking screenshot 1 for pair " + str(self.pair_id))
unreal.AutomationLibrary.take_high_res_screenshot(
SS_WIDTH,
SS_HEIGHT,
first_image_path,
camera=self.camera_actor,
comparison_tolerance=unreal.ComparisonTolerance.HIGH,
delay=0.0
)
def take_screenshot_2(self):
initial_location = self.camera_actor.get_actor_location()
initial_rotation = self.camera_actor.get_actor_rotation()
new_location, new_rotation = self.move_camera()
second_image_path = os.path.join(self.pair_folder, "image2.png")
print("\nTaking screenshot 2 for pair " + str(self.pair_id))
unreal.AutomationLibrary.take_high_res_screenshot(
SS_WIDTH,
SS_HEIGHT,
second_image_path,
camera=self.camera_actor,
comparison_tolerance=unreal.ComparisonTolerance.HIGH,
delay=0.0
)
label_data = calculate_differences(initial_location, new_location, initial_rotation, new_rotation)
label_path = os.path.join(self.label_directory, f"pair_{self.pair_id:05d}.txt")
save_label(label_path, label_data)
def __tick__(self, deltatime):
# Function called every tick
try:
if (self.tickcount < NUM_PAIRS_IMAGES * 2):
print(". ")
print("Time since last tick:", deltatime) # Print the deltatime just for sanity check so we know a tick was made
if (self.tickcount % 2 == 0):
self.take_screenshot_1()
else:
self.take_screenshot_2()
self.tickcount = self.tickcount + 1
else:
print("Finished! Unregistering tick handler")
unreal.unregister_slate_post_tick_callback(self.slate_post_tick_handle)
except Exception as error:
print("ERROR:", error)
try:
print("unregistering tick after error")
unreal.unregister_slate_post_tick_callback(self.slate_post_tick_handle)
except Exception as error:
print("exception in unregistering tick")
pass
instance = OnTick()
instance.start()
|
import unreal
# Create all assets and objects we'll use
lvs = unreal.VariantManagerLibrary.create_level_variant_sets_asset("LVS", "/Game/")
lvs_actor = unreal.VariantManagerLibrary.create_level_variant_sets_actor(lvs)
if lvs is None or lvs_actor is None:
print ("Failed to spawn either the LevelVariantSets asset or the LevelVariantSetsActor!")
quit()
# Create a variant set and add it to lvs
var_set1 = unreal.VariantSet()
var_set1.set_display_text("My VariantSet")
lvs.add_variant_set(var_set1)
# Create a variant and add it to var_set1
var1 = unreal.Variant()
var1.set_display_text("Variant 1")
var_set1.add_variant(var1)
# Create a test actor and add it to var1. The test actor has almost all possible types of capturable properties
location = unreal.Vector()
rotation = unreal.Rotator()
test_actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.VariantManagerTestActor, location, rotation)
var1.add_actor_binding(test_actor)
capturable_props = unreal.VariantManagerLibrary.get_capturable_properties(test_actor)
captured_props = []
print ("Capturable properties for actor '" + test_actor.get_actor_label() + "':")
for prop in capturable_props:
print ("\t" + prop)
# All test properties are named like 'Captured____Property'
# The check here avoids capturing generic Actor properties like 'Can be Damaged'
if str(prop).startswith('Captured') and str(prop).endswith('Property'):
new_prop = var1.capture_property(test_actor, prop)
captured_props.append(new_prop)
for prop in captured_props:
type_str = prop.get_property_type_string()
# Set a value for a property depending on its type
if type_str == "bool":
prop.set_value_bool(True)
elif type_str == "int":
prop.set_value_int(2)
elif type_str == "float":
prop.set_value_float(2.0)
elif type_str == "object":
cube = unreal.EditorAssetLibrary.load_asset("StaticMesh'/project/.Cube'")
prop.set_value_object(cube)
elif type_str == "strint":
prop.set_value_string("new string")
elif type_str == "rotator":
prop.set_value_rotator(unreal.Rotator(11, 12, 13))
elif type_str == "color":
prop.set_value_color(unreal.Color(21, 22, 23, 24))
elif type_str == "linear_color":
prop.set_value_linear_color(unreal.LinearColor(0.31, 0.32, 0.33, 0.34))
elif type_str == "vector":
prop.set_value_vector(unreal.Vector(41, 42, 43))
elif type_str == "quat":
prop.set_value_quat(unreal.Quat(0.51, 0.52, 0.53, 0.54))
elif type_str == "vector4":
prop.set_value_vector4(unreal.Vector4(6.1, 6.2, 6.3, 6.4))
elif type_str == "Vector2D":
prop.set_value_vector2d(unreal.Vector2D(7.1, 7.2))
elif type_str == "int_Point":
prop.set_value_int_point(unreal.IntPoint(81, 82))
# Easier to print using getattr
for prop in captured_props:
type_str = prop.get_property_type_string()
print (getattr(prop, "get_value_" + type_str)())
|
# General BP Maker
##Runs with Unreal Python Module
import unreal
import re
def get_bp_c_by_name(__bp_dir:str) -> str :
__bp_c = __bp_dir + '_C'
return __bp_c
def get_bp_mesh_comp (__bp_c:str) :
#source_mesh = ue.load_asset(__mesh_dir)
loaded_bp_c = unreal.EditorAssetLibrary.load_blueprint_class(__bp_c)
bp_c_obj = unreal.get_default_object(loaded_bp_c)
loaded_comp = bp_c_obj.get_editor_property('Mesh')
return loaded_comp
ar_asset_lists :list = []
ar_asset_lists :list = unreal.EditorUtilityLibrary.get_selected_assets()
SkeletalMesh = ar_asset_lists[0]
print (ar_asset_lists[0])
str_selected_asset :str = ''
if len(ar_asset_lists) > 0 :
str_selected_asset = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(ar_asset_lists[0])
#str_selected_asset = str(ar_asset_lists[0])
#print(str_selected_asset)
path = str_selected_asset.rsplit('/', 1)[0] + '/'
name = str_selected_asset.rsplit('/', 1)[1]
name = name.rsplit('.', 1)[1]
BaseBP :str = '/project/'
BaseAnimBP :str = '/project/'
Basepath :str = path
assetPath :str = Basepath + '/project/'
bsNames :list = ["IdleRun_BS_Peaceful", "IdleRun_BS_Battle", "Down_BS", "Groggy_BS", "LockOn_BS", "Airborne_BS"]
BPPath :str = Basepath + '/Blueprints/' + name + "_Blueprint"
AnimBPPath :str = Basepath + '/Blueprints/' + name + "_AnimBP"
Base1D :str = Basepath + "Base_BS_1D"
Base2D :str = Basepath + "Base_BS_2D"
for each in bsNames:
bsDir = assetPath + each
if each == "LockOn_BS":
unreal.EditorAssetLibrary.duplicate_asset(Base2D,bsDir)
else:
unreal.EditorAssetLibrary.duplicate_asset(Base1D,bsDir)
Skeleton = ar_asset_lists[0].skeleton
#ABP Skeleton Set
asset_bp = unreal.EditorAssetLibrary.duplicate_asset(BaseBP,BPPath)
AnimBP = unreal.EditorAssetLibrary.duplicate_asset(BaseAnimBP,AnimBPPath)
AnimBP.set_editor_property("target_skeleton", Skeleton)
#BP Component Set
_bp_ = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(asset_bp)
_abp_ = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(AnimBP)
_bp_c = get_bp_c_by_name(_bp_)
_abp_c = get_bp_c_by_name(_abp_)
loaded_abp = unreal.EditorAssetLibrary.load_blueprint_class(_abp_c)
bp_mesh_comp = get_bp_mesh_comp(_bp_c)
bp_mesh_comp.set_editor_property('skeletal_mesh',ar_asset_lists[0])
bp_mesh_comp.set_editor_property('anim_class', loaded_abp)
|
import unreal
import logging
import re
# --- Script Configuration ---
# Set to True to see what the script will do without making any changes.
# Set to False to perform the actual assignments.
DRY_RUN = False
# !!! IMPORTANT !!!
# 1. SET THIS TO THE FULL, EXACT CONTENT BROWSER PATH FOR THE SKELETAL MESH ASSET.
# The path has been corrected to remove the incorrect "/Game/" prefix.
FULL_SKELETAL_MESH_PATH = "/project/"
# --- Helper Function ---
def get_all_descendants(parent_actor):
"""
Recursively finds all descendant actors of a given parent actor.
This is a robust way to traverse the hierarchy that works across UE versions.
"""
descendants = []
immediate_children = parent_actor.get_attached_actors()
for child in immediate_children:
descendants.append(child)
descendants.extend(get_all_descendants(child))
return descendants
# --- Main Logic ---
def assign_skeletal_meshes_to_crowd():
"""
Finds all SkeletalMeshComponents in the selected actor's hierarchy
and assigns a predefined Skeletal Mesh asset.
Includes a DRY_RUN mode to test without applying changes.
"""
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s', force=True)
if DRY_RUN:
logging.warning("--- Starting Skeletal Mesh Assignment [DRY RUN MODE] ---")
logging.warning("No changes will be made to the scene.")
else:
logging.info("--- Starting Skeletal Mesh Assignment [LIVE MODE] ---")
# ** Pre-execution check to see if the main asset exists **
logging.info(f"Verifying asset path: '{FULL_SKELETAL_MESH_PATH}'")
if not unreal.EditorAssetLibrary.does_asset_exist(FULL_SKELETAL_MESH_PATH):
logging.error("--- SCRIPT HALTED ---")
logging.error(f"FATAL: The specified Skeletal Mesh asset could not be found.")
logging.error("Please verify the FULL_SKELETAL_MESH_PATH variable is correct and try again.")
return
skeletal_mesh_asset = unreal.load_asset(FULL_SKELETAL_MESH_PATH)
if not skeletal_mesh_asset:
logging.error("--- SCRIPT HALTED ---")
logging.error(f"FATAL: Asset exists but could not be loaded. Asset may be corrupted or unloadable.")
return
logging.info("Asset verified successfully. Proceeding with assignments.")
# 1. Get the user's current actor selection
selected_actors = unreal.EditorLevelLibrary.get_selected_level_actors()
if not selected_actors:
logging.error("No actor selected. Please select the main parent actor for the crowd and run again.")
return
if len(selected_actors) > 1:
logging.warning("Multiple actors selected. Processing only the first one.")
parent_actor = selected_actors[0]
logging.info(f"Parent Actor Selected: '{parent_actor.get_actor_label()}'")
# 2. Get the full hierarchy
actors_to_process = [parent_actor] + get_all_descendants(parent_actor)
logging.info(f"Found {len(actors_to_process)} total actors in the hierarchy to process.")
success_count = 0
fail_count = 0 # This should theoretically be 0 now, but good to keep.
# 3. Iterate through each actor
for actor in actors_to_process:
actor_label = actor.get_actor_label()
skeletal_mesh_component = actor.get_component_by_class(unreal.SkeletalMeshComponent)
if not skeletal_mesh_component:
logging.debug(f"Actor '{actor_label}' has no SkeletalMeshComponent. Skipping.")
continue
logging.info(f"Processing '{actor_label}'...")
# 4. Assign the pre-loaded asset
if DRY_RUN:
logging.info(f" -> [DRY RUN] Would assign '{skeletal_mesh_asset.get_name()}' to '{actor_label}'.")
else:
skeletal_mesh_component.set_skeletal_mesh(skeletal_mesh_asset)
logging.info(f" -> SUCCESS: Assigned '{skeletal_mesh_asset.get_name()}' to '{actor_label}'.")
success_count += 1
logging.info("--- Script Finished ---")
summary_prefix = "[DRY RUN] " if DRY_RUN else ""
logging.info(f"{summary_prefix}Summary: {success_count} assignments would be successful, {fail_count} would fail.")
# --- Run the main function ---
assign_skeletal_meshes_to_crowd()
|
import unreal
import logging
logger = logging.getLogger(__name__)
from pamux_unreal_tools.generated.material_expression_wrappers import *
from pamux_unreal_tools.utils.types import *
from pamux_unreal_tools.base.material_expression.material_expression_container_builder_base import MaterialExpressionContainerBuilderBase
from pamux_unreal_tools.examples.M_Landscape_Master.material_functions.MF_TextureCellBombing_Landscape import MF_TextureCellBombing_Landscape
from pamux_unreal_tools.builders.material_function_builder import MaterialFunctionBuilder
from pamux_unreal_tools.utils.node_pos import NodePos, CurrentNodePos
from pamux_unreal_tools.base.material_function.material_function_outputs_base import MaterialFunctionOutputs
from pamux_unreal_tools.interfaces.IBlend_Overlay import IBlend_Overlay
from pamux_unreal_tools.interfaces.ICheapContrast_RGB import ICheapContrast_RGB
from pamux_unreal_tools.interfaces.IHeightLerp import IHeightLerp
from pamux_unreal_tools.interfaces.IMultiplyAdd import IMultiplyAdd
from pamux_unreal_tools.interfaces.IBreakOutFloat4Components import IBreakOutFloat4Components
from pamux_unreal_tools.interfaces.ICustomRotator import ICustomRotator
from pamux_unreal_tools.examples.M_Landscape_Master.interfaces.ILandscapeBaseMaterial import ILandscapeBaseMaterial
from pamux_unreal_tools.examples.M_Landscape_Master.interfaces.ITextureCellBombing_Landscape import ITextureCellBombing_Landscape
from pamux_unreal_tools.impl.material_function_impl import MaterialFunctionImpl
from pamux_unreal_tools.examples.M_Landscape_Master.material_functions.base.layer_inputs import LayerInputs
class MF_LandscapeBaseMaterial:
@staticmethod
def load_MF(builder):
return builder.load_MF("/project/",
LayerInputs.get(),
["Result", "Height"])
class Dependencies:
def __init__(self, builder: MaterialExpressionContainerBuilderBase) -> None:
self.blend_Overlay = builder.load_Blend_Overlay()
self.cheapContrast_RGB = builder.load_CheapContrast_RGB()
self.heightLerp = builder.load_HeightLerp()
self.multiplyAdd = builder.load_MultiplyAdd()
self.breakOutFloat4Components = builder.load_BreakOutFloat4Components()
self.customRotator = builder.load_CustomRotator()
self.MF_TextureCellBombing_Landscape = MF_TextureCellBombing_Landscape.load_MF(builder)
class Inputs:
def __init__(self, builder: MaterialExpressionContainerBuilderBase):
self.albedo = builder.build_FunctionInput("Albedo", 0, TTextureObject_Color(), True, True)
self.colorOverlay = builder.build_FunctionInput("ColorOverlay", 1, Vec3f(1.0, 1.0, 1.0), True, True)
self.colorOverlayIntensity = builder.build_FunctionInput("ColorOverlayIntensity", 2, 1.0, True, True)
self.contrast = builder.build_FunctionInput("Contrast", 3, 0.0, True, True)
self.contrastVariation = builder.build_FunctionInput("ContrastVariation", 4, 1.0, True, True)
self.roughness = builder.build_FunctionInput("Roughness", 5, TTextureObject_Color(), True, True)
self.roughnessIntensity = builder.build_FunctionInput("RoughnessIntensity", 6, 1.0, True, True)
self.normal = builder.build_FunctionInput("Normal", 7, TTextureObject_Normal(), True, True)
self.normalIntensity = builder.build_FunctionInput("NormalIntensity", 8, 0.0, True, True)
self.displacement = builder.build_FunctionInput("Displacement", 9, TTextureObject_Color(), True, True)
self.uvParams = builder.build_FunctionInput("UVParams", 10, Vec4f(1.0, 1.0, 0.5, 0.5), True, True)
self.rotation = builder.build_FunctionInput("Rotation", 11, 0.0, True, True)
self.doTextureBomb = builder.build_FunctionInput("DoTextureBomb", 12, True, True, True)
self.doRotationVariation = builder.build_FunctionInput("DoRotationVariation", 13, False, True, True)
self.bombCellScale = builder.build_FunctionInput("BombCellScale", 14, 1.0, True, True)
self.bombPatternScale = builder.build_FunctionInput("BombPatternScale", 15, 1.0, True, True)
self.bombRandomOffset = builder.build_FunctionInput("BombRandomOffset", 16, 0.0, True, True)
self.bombRotationVariation = builder.build_FunctionInput("BombRotationVariation", 17, 0.0, True, True)
self.opacityStrength = builder.build_FunctionInput("OpacityStrength", 18, 1.0, True, True)
self.opacityAdd = builder.build_FunctionInput("OpacityAdd", 19, 0.0, True, True)
self.opacityContrast = builder.build_FunctionInput("OpacityContrast", 20, 1.0, True, True)
class Builder(MaterialFunctionBuilder):
def __init__(self):
super().__init__(
"/project/",
MF_LandscapeBaseMaterial.Dependencies,
MF_LandscapeBaseMaterial.Inputs,
MaterialFunctionOutputs.ResultAndHeight)
def __call_cellBombing(self, textureMap, uvParams):
call = self.dependencies.MF_TextureCellBombing_Landscape.call()
call.outputs.result.add_rt()
call.inputs.texture.comesFrom(textureMap)
call.inputs.uVs.comesFrom(uvParams)
call.inputs.cellScale.comesFrom(self.inputs.bombCellScale)
call.inputs.patternScale.comesFrom(self.inputs.bombPatternScale)
call.inputs.doRotationVariation.comesFrom(self.inputs.doRotationVariation)
call.inputs.randomOffsetVariation.comesFrom(self.inputs.bombRandomOffset)
call.inputs.randomRotationVariation.comesFrom(self.inputs.bombRotationVariation)
if textureMap == self.inputs.normal:
call.inputs.isNormalMap.comesFrom(StaticBool(True))
return call
def __build_uvParams(self):
call = self.dependencies.breakOutFloat4Components.call()
call.inputs.float4.comesFrom(self.inputs.uvParams)
uvParamsRG = AppendVector(call.outputs.r, call.outputs.g)
uvParamsBA = AppendVector(call.outputs.b, call.outputs.a)
landscapeLayerCoords = LandscapeLayerCoords()
landscapeLayerCoords.mapping_type.set(unreal.TerrainCoordMappingType.TCMT_AUTO)
landscapeLayerCoords.custom_uv_type.set(unreal.LandscapeCustomizedCoordType.LCCT_NONE)
multiply = Multiply(landscapeLayerCoords, uvParamsRG)
call = self.dependencies.customRotator.call()
call.add_rt()
call.inputs.uVs.comesFrom(multiply)
call.inputs.rotationCenter.comesFrom(uvParamsBA)
call.inputs.rotationAngle.comesFrom(self.inputs.rotation)
return call
def __build_switched(self, uvParams, cellBombed):
textureSample = TextureSample()
textureSample.RGB.add_rt()
textureSample.UVs.comesFrom(uvParams)
textureSample.tex.comesFrom(cellBombed)
textureSample.sampler_source.set(unreal.SamplerSourceMode.SSM_WRAP_WORLD_GROUP_SETTINGS)
textureSample.sampler_type.set(unreal.MaterialSamplerType.SAMPLERTYPE_COLOR)
textureSample.automatic_view_mip_bias.set(True)
return StaticSwitch(
cellBombed.outputs.result,
textureSample.RGB,
self.inputs.doTextureBomb)
def __build_qualitySwitchAlbedo(self, switchedAlbedo):
call = self.dependencies.blend_Overlay.call()
call.inputs.base.comesFrom(switchedAlbedo)
call.inputs.blend.comesFrom(self.inputs.colorOverlay)
qualitySwitch = QualitySwitch()
qualitySwitch.add_rt()
qualitySwitch.default.comesFrom(call.outputs.result)
qualitySwitch.low.comesFrom(Multiply(switchedAlbedo, self.inputs.colorOverlay))
return qualitySwitch.output
def __build_finalAlbedo(self, lerpedAlbedo, switchedDisplacement):
cheapContrast_RGB = self.dependencies.cheapContrast_RGB.call()
cheapContrast_RGB.inputs._in.comesFrom(lerpedAlbedo)
cheapContrast_RGB.inputs.contrast.comesFrom(self.inputs.contrast)
heightLerp = self.dependencies.heightLerp.call()
heightLerp.inputs.a.comesFrom(lerpedAlbedo)
heightLerp.inputs.b.comesFrom(cheapContrast_RGB)
heightLerp.inputs.transitionPhase.comesFrom(self.inputs.contrastVariation)
heightLerp.inputs.heightTexture.comesFrom(switchedDisplacement)
qualitySwitch = QualitySwitch()
qualitySwitch.add_rt()
qualitySwitch.default.comesFrom(heightLerp.outputs.results)
qualitySwitch.low.comesFrom(lerpedAlbedo)
return qualitySwitch
def build(self):
qualitySwitch = QualitySwitch()
qualitySwitch.add_rt()
qualitySwitch.default.comesFrom(self.inputs.doTextureBomb)
qualitySwitch.low.comesFrom(StaticBool(False))
uvParams = self.__build_uvParams()
albedo = self.__call_cellBombing(self.inputs.albedo, uvParams)
switchedAlbedo = self.__build_switched(uvParams, albedo)
qualitySwitchedAlbedo = self.__build_qualitySwitchAlbedo(switchedAlbedo)
lerpedAlbedo = LinearInterpolate(switchedAlbedo, qualitySwitchedAlbedo, self.inputs.colorOverlayIntensity)
roughness = self.__call_cellBombing(self.inputs.roughness, uvParams)
switchedRoughness = self.__build_switched(uvParams, roughness)
finalRoughness = Multiply(switchedRoughness, self.inputs.roughnessIntensity)
displacement = self.__call_cellBombing(self.inputs.displacement, uvParams)
switchedDisplacement = self.__build_switched(uvParams, displacement)
finalDisplacement = Add(Multiply(Power(switchedDisplacement, self.inputs.opacityContrast), self.inputs.opacityStrength), self.inputs.opacityAdd)
normal = self.__call_cellBombing(self.inputs.normal, uvParams)
switchedNormal = self.__build_switched(uvParams, normal)
finalNormal = self.dependencies.multiplyAdd.call()
finalNormal.inputs.base.comesFrom(switchedNormal)
finalNormal.inputs.add.comesFrom(AppendVector(AppendVector(self.inputs.normalIntensity, self.inputs.normalIntensity), Constant(0.0)))
finalAlbedo = self.__build_finalAlbedo(lerpedAlbedo, switchedDisplacement)
makeMaterialAttributes = MakeMaterialAttributes()
makeMaterialAttributes.baseColor.comesFrom(finalAlbedo)
makeMaterialAttributes.roughness.comesFrom(finalRoughness)
makeMaterialAttributes.normal.comesFrom(finalNormal.outputs.result)
makeMaterialAttributes.opacity.comesFrom(finalDisplacement)
breakMaterialAttributes = BreakMaterialAttributes(makeMaterialAttributes)
componentMask = ComponentMask(breakMaterialAttributes.opacity, "R")
makeMaterialAttributes.connectTo(self.outputs.result)
componentMask.connectTo(self.outputs.height)
|
# 本脚本主要用于调试,python调用蓝图库c++
import unreal
unreal.TookitBPLibrary.export_actors_to_json()
|
import unreal
import os
from pathlib import Path
import tempfile
def take_screenshot() -> str:
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_file:
screenshot_path = temp_file.name
unreal.AutomationLibrary.take_high_res_screenshot(640, 520, screenshot_path)
return screenshot_path
return ""
except Exception:
return ""
def main():
path = take_screenshot()
if path:
print(path)
else:
print("Failed to take screenshot")
if __name__ == "__main__":
main()
|
from enum import Enum
from typing import List, Dict, Any
class ValidationErrorType(Enum):
MISSING_COLUMN = "컬럼 누락"
MISSING_ASSET = "필수 에셋 누락"
DUPLICATE_VALUE = "중복 값"
INVALID_REFERENCE = "잘못된 참조"
INVALID_VALUE = "잘못된 값"
class ValidationError:
def __init__(self, error_type: ValidationErrorType, sheet_name: str, column_name: str, details: str):
self.error_type = error_type
self.sheet_name = sheet_name
self.column_name = column_name
self.details = details
def __str__(self):
if self.error_type == ValidationErrorType.MISSING_COLUMN:
return f"{self.sheet_name}시트에 {self.column_name} 컬럼이 존재하지 않습니다."
elif self.error_type == ValidationErrorType.MISSING_ASSET:
return f"{self.sheet_name}시트의 {self.column_name}컬럼은 {self.details}이라는 에셋이 반드시 존재하고 있어야 합니다."
elif self.error_type == ValidationErrorType.DUPLICATE_VALUE:
return f"{self.sheet_name}시트의 {self.column_name}컬럼은 유니크한 값이어야 합니다."
elif self.error_type == ValidationErrorType.INVALID_REFERENCE:
return f"{self.sheet_name}시트의 {self.column_name}컬럼은 {self.details}"
elif self.error_type == ValidationErrorType.INVALID_VALUE:
return f"{self.sheet_name}시트의 {self.column_name}컬럼: {self.details}"
class DataValidator:
def __init__(self, sheet_name: str):
self.sheet_name = sheet_name
self.errors: List[ValidationError] = []
def check_required_columns(self, data: List[Dict], required_columns: List[str]) -> bool:
"""필수 컬럼 존재 여부 확인"""
if not data:
return False
actual_columns = data[0].keys()
for column in required_columns:
if column not in actual_columns:
self.errors.append(ValidationError(
ValidationErrorType.MISSING_COLUMN,
self.sheet_name,
column,
""
))
return len(self.errors) == 0
def check_unique_values(self, data: List[Dict], column: str) -> bool:
"""컬럼의 유니크 값 검사"""
values = {}
for row in data:
value = row.get(column)
if value in values:
self.errors.append(ValidationError(
ValidationErrorType.DUPLICATE_VALUE,
self.sheet_name,
column,
f"중복된 값: {value}"
))
return False
values[value] = True
return True
def check_asset_exists(self, asset_path: str, column_name: str) -> bool:
"""에셋 존재 여부 확인"""
import unreal
if not unreal.EditorAssetLibrary.does_asset_exist(asset_path):
self.errors.append(ValidationError(
ValidationErrorType.MISSING_ASSET,
self.sheet_name,
column_name,
asset_path
))
return False
return True
def check_reference_exists(self, value: str, reference_table: str, reference_column: str, column_name: str) -> bool:
"""다른 테이블의 컬럼 참조 확인"""
# 참조 테이블 데이터 가져오기
import unreal
data_table = unreal.load_asset(reference_table)
if not data_table:
self.errors.append(ValidationError(
ValidationErrorType.INVALID_REFERENCE,
self.sheet_name,
column_name,
f"{reference_table} 테이블을 찾을 수 없습니다."
))
return False
# 참조 값 존재 확인
found = False
for row in data_table.get_row_names():
if str(row) == value:
found = True
break
if not found:
self.errors.append(ValidationError(
ValidationErrorType.INVALID_REFERENCE,
self.sheet_name,
column_name,
f"{reference_table}의 {reference_column}에 존재하는 값이어야 합니다."
))
return False
return True
def show_errors(self) -> bool:
"""발견된 모든 에러를 표시"""
if not self.errors:
return True
import unreal
message = "데이터 검증 오류:\n\n"
for error in self.errors:
message += f"- {str(error)}\n"
unreal.EditorDialog.show_message(
"데이터 검증 실패",
message,
unreal.AppMsgType.OK
)
return False
|
import unreal
selected : list = unreal.EditorUtilityLibrary.get_selected_assets() #get selected assets using editorUtilityLib
for staticMesh in selected :
meshNaniteSettings : bool = staticMesh.get_editor_property('nanite_settings')
print
if meshNaniteSettings.enabled : #if true
meshNaniteSettings.enabled = False #off nanite setting
unreal.StaticMeshEditorSubsystem().set_nanite_settings(staticMesh,meshNaniteSettings, apply_changes=True)
else :
print('Nanite is Disabled')
|
import unreal
# Instances of unreal classes
editor_util = unreal.EditorUtilityLibrary()
layer_sis = unreal.LayersSubsystem()
editor_filter_lib = unreal.EditorFilterLibrary()
# Get the selected material and selected static mesh actors
selected_assets = editor_util.get_selected_assets()
materials = editor_filter_lib.by_class(selected_assets, unreal.Material)
if len(materials) < 1:
unreal.log_warning("Please select a material to be assigned")
else:
material = materials[0]
material_name = material.get_fname()
unreal.log(f"Assigning material '{material_name}' to selected static meshes")
actors = layer_sis.get_selected_actors()
static_mesh_actors = editor_filter_lib.by_class(actors, unreal.StaticMeshActor)
for actor in static_mesh_actors:
actor_name = actor.get_fname()
# Get the static mesh component and assign the material
actor_mesh_component = actor.static_mesh_component
actor_mesh_component.set_material(0, material)
unreal.log(f"Assigning material '{material_name}' to actor {actor_name}")
|
import unreal
# Create all assets and objects we'll use
lvs = unreal.VariantManagerLibrary.create_level_variant_sets_asset("LVS", "/Game/")
lvs_actor = unreal.VariantManagerLibrary.create_level_variant_sets_actor(lvs)
if lvs is None or lvs_actor is None:
print ("Failed to spawn either the LevelVariantSets asset or the LevelVariantSetsActor!")
quit()
# Create a variant set and add it to lvs
var_set1 = unreal.VariantSet()
var_set1.set_display_text("My VariantSet")
lvs.add_variant_set(var_set1)
# Create a variant and add it to var_set1
var1 = unreal.Variant()
var1.set_display_text("Variant 1")
var_set1.add_variant(var1)
# Create a test actor and add it to var1. The test actor has almost all possible types of capturable properties
location = unreal.Vector()
rotation = unreal.Rotator()
test_actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.VariantManagerTestActor, location, rotation)
var1.add_actor_binding(test_actor)
capturable_props = unreal.VariantManagerLibrary.get_capturable_properties(test_actor)
captured_props = []
print ("Capturable properties for actor '" + test_actor.get_actor_label() + "':")
for prop in capturable_props:
print ("\t" + prop)
# All test properties are named like 'Captured____Property'
# The check here avoids capturing generic Actor properties like 'Can be Damaged'
if str(prop).startswith('Captured') and str(prop).endswith('Property'):
new_prop = var1.capture_property(test_actor, prop)
captured_props.append(new_prop)
for prop in captured_props:
type_str = prop.get_property_type_string()
# Set a value for a property depending on its type
if type_str == "bool":
prop.set_value_bool(True)
elif type_str == "int":
prop.set_value_int(2)
elif type_str == "float":
prop.set_value_float(2.0)
elif type_str == "object":
cube = unreal.EditorAssetLibrary.load_asset("StaticMesh'/project/.Cube'")
prop.set_value_object(cube)
elif type_str == "strint":
prop.set_value_string("new string")
elif type_str == "rotator":
prop.set_value_rotator(unreal.Rotator(11, 12, 13))
elif type_str == "color":
prop.set_value_color(unreal.Color(21, 22, 23, 24))
elif type_str == "linear_color":
prop.set_value_linear_color(unreal.LinearColor(0.31, 0.32, 0.33, 0.34))
elif type_str == "vector":
prop.set_value_vector(unreal.Vector(41, 42, 43))
elif type_str == "quat":
prop.set_value_quat(unreal.Quat(0.51, 0.52, 0.53, 0.54))
elif type_str == "vector4":
prop.set_value_vector4(unreal.Vector4(6.1, 6.2, 6.3, 6.4))
elif type_str == "Vector2D":
prop.set_value_vector2d(unreal.Vector2D(7.1, 7.2))
elif type_str == "int_Point":
prop.set_value_int_point(unreal.IntPoint(81, 82))
# Easier to print using getattr
for prop in captured_props:
type_str = prop.get_property_type_string()
print (getattr(prop, "get_value_" + type_str)())
|
import unreal
util_lib = unreal.EditorUtilityLibrary
red_lib = unreal.RedArtToolkitBPLibrary
bp, = unreal.EditorUtilityLibrary.get_selected_assets()
parent = red_lib.get_blueprint_parent_class(bp)
print(parent)
material = unreal.load_asset('/project/.M_Sanji01_L_body')
bp_gc = unreal.load_object(None, "%s_C" % bp.get_path_name())
bp_cdo = unreal.get_default_object(bp_gc)
for comp in red_lib.get_cdo_inherited_components(bp_cdo):
comp_name = comp.get_name()
if comp_name == 'FaceRenderer':
# materials = comp.get_editor_property("outline_multi_pass_materials")
# comp.set_editor_property("outline_multi_pass_materials",[material])
materials = comp.get_editor_property("layered_base_material")
print(materials)
mesh, = unreal.EditorUtilityLibrary.get_selected_assets()
print (mesh.get_outer())
|
"""
UEMCP Error Handling Framework
Provides decorators, validators, and error types to reduce try/catch boilerplate
while improving error specificity and consistency.
"""
import functools
import inspect
from typing import Any, Dict, List, Optional, Union
import unreal
from utils import log_debug, log_error
# ============================================================================
# Custom Exception Types - More specific than generic Exception
# ============================================================================
class UEMCPError(Exception):
"""Base exception for all UEMCP operations."""
def __init__(self, message: str, operation: str = None, details: Dict = None):
self.message = message
self.operation = operation or "unknown"
self.details = details or {}
super().__init__(self.message)
def to_dict(self) -> Dict[str, Any]:
"""Convert to standardized error response format."""
return {"success": False, "error": self.message, "operation": self.operation, "details": self.details}
class ValidationError(UEMCPError):
"""Raised when input validation fails."""
pass
class ProcessingError(UEMCPError):
"""Raised when operations fail during execution."""
pass
# ============================================================================
# Input Validation Framework
# ============================================================================
class ValidationRule:
"""Base class for validation rules."""
def validate(self, value: Any, field_name: str) -> Optional[str]:
"""Validate a value. Returns error message if invalid, None if valid."""
raise NotImplementedError
class RequiredRule(ValidationRule):
"""Validates that a value is not None or empty."""
def validate(self, value: Any, field_name: str) -> Optional[str]:
if value is None:
return f"{field_name} is required"
if isinstance(value, (str, list, dict)) and len(value) == 0:
return f"{field_name} cannot be empty"
return None
class TypeRule(ValidationRule):
"""Validates that a value is of the expected type."""
def __init__(self, expected_type: Union[type, tuple], allow_none: bool = False):
self.expected_type = expected_type
self.allow_none = allow_none
def validate(self, value: Any, field_name: str) -> Optional[str]:
if value is None and self.allow_none:
return None
if not isinstance(value, self.expected_type):
expected_name = getattr(self.expected_type, "__name__", str(self.expected_type))
actual_name = type(value).__name__
if self.allow_none:
return f"{field_name} must be {expected_name} or None, got {actual_name}"
else:
return f"{field_name} must be {expected_name}, got {actual_name}"
return None
class ListLengthRule(ValidationRule):
"""Validates that a list has the expected length."""
def __init__(self, expected_length: int, allow_none: bool = False):
self.expected_length = expected_length
self.allow_none = allow_none
def validate(self, value: Any, field_name: str) -> Optional[str]:
if value is None and self.allow_none:
return None
if not isinstance(value, (list, tuple)):
return f"{field_name} must be a list or tuple"
if len(value) != self.expected_length:
return f"{field_name} must have {self.expected_length} elements, got {len(value)}"
return None
class NumericRangeRule(ValidationRule):
"""Validates that a numeric value is within a range."""
def __init__(self, min_val: float = None, max_val: float = None):
self.min_val = min_val
self.max_val = max_val
def validate(self, value: Any, field_name: str) -> Optional[str]:
if not isinstance(value, (int, float)):
return f"{field_name} must be numeric"
if self.min_val is not None and value < self.min_val:
return f"{field_name} must be >= {self.min_val}"
if self.max_val is not None and value > self.max_val:
return f"{field_name} must be <= {self.max_val}"
return None
class AssetPathRule(ValidationRule):
"""Validates that an asset path is properly formatted."""
def validate(self, value: Any, field_name: str) -> Optional[str]:
if not isinstance(value, str):
return f"{field_name} must be a string"
if not value.startswith("/"):
return f"{field_name} must start with '/'"
if len(value.split("/")) < 3:
return f"{field_name} must be a valid asset path like '/project/'"
return None
class FileExistsRule(ValidationRule):
"""Validates that a file or directory path exists on the filesystem."""
def validate(self, value: Any, field_name: str) -> Optional[str]:
import os
if not isinstance(value, str):
return f"{field_name} must be a string"
if not os.path.exists(value):
return f"{field_name} path does not exist: {value}"
return None
class OffsetRule(ValidationRule):
"""
Validates offset parameter - accepts both dict {x,y,z} and list [x,y,z] formats.
Examples:
# Dict format
{"x": 0, "y": 0, "z": 0}
# List format
[0, 0, 0]
"""
def validate(self, value: Any, field_name: str) -> Optional[str]:
if value is None:
return None
if isinstance(value, dict):
# Dict format: {x: 0, y: 0, z: 0}
required_keys = {"x", "y", "z"}
if not required_keys.issubset(value.keys()):
missing = required_keys - value.keys()
return f"{field_name} dict missing keys: {missing}"
if not all(isinstance(value[k], (int, float)) for k in required_keys):
return f"{field_name} dict values must be numeric"
return None
elif isinstance(value, (list, tuple)):
# Array format: [x, y, z]
if len(value) != 3:
return f"{field_name} array must have 3 elements [x, y, z]"
if not all(isinstance(v, (int, float)) for v in value):
return f"{field_name} array elements must be numeric"
return None
else:
return f"{field_name} must be a dict {{x,y,z}} or array [x,y,z]"
def validate_inputs(validation_schema: Dict[str, List[ValidationRule]]):
"""
Decorator that validates function inputs against a schema.
Args:
validation_schema: Dict mapping parameter names to list of validation rules
Example:
@validate_inputs({
'assetPath': [RequiredRule(), AssetPathRule()],
'location': [RequiredRule(), ListLengthRule(3)],
'scale': [TypeRule(list), ListLengthRule(3)]
})
def spawn_actor(assetPath, location, scale=[1,1,1]):
# Function body here - inputs are already validated!
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
# Get function signature to map args to parameter names
sig = inspect.signature(func)
bound_args = sig.bind(*args, **kwargs)
bound_args.apply_defaults()
# Validate each parameter according to schema
for param_name, rules in validation_schema.items():
if param_name in bound_args.arguments:
value = bound_args.arguments[param_name]
for rule in rules:
error_msg = rule.validate(value, param_name)
if error_msg:
raise ValidationError(
error_msg,
operation=func.__name__,
details={"parameter": param_name, "value": str(value)},
)
return func(*args, **kwargs)
return wrapper
return decorator
# ============================================================================
# Error Handling Decorators
# ============================================================================
def handle_unreal_errors(operation_name: str = None):
"""
Decorator that catches and converts UE-specific errors to UEMCPError types.
Args:
operation_name: Name of the operation for error context
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
op_name = operation_name or func.__name__
try:
return func(*args, **kwargs)
# Specific UE error handling
except AttributeError as e:
if "unreal" in str(e).lower():
raise ProcessingError(
f"Unreal Engine API error: {str(e)}",
operation=op_name,
details={"error_type": "AttributeError"},
) from e
raise # Re-raise if not UE-related
except RuntimeError as e:
if any(keyword in str(e).lower() for keyword in ["unreal", "editor", "asset", "actor"]):
raise ProcessingError(
f"Unreal Engine runtime error: {str(e)}",
operation=op_name,
details={"error_type": "RuntimeError"},
) from e
raise # Re-raise if not UE-related
# Keep specific UEMCP errors as-is
except UEMCPError:
raise
return wrapper
return decorator
def safe_operation(operation_type: str = "operation"):
"""
Decorator that provides safe execution with standardized error handling.
Args:
operation_type: Type of operation (actor, asset, viewport, etc.)
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
result = func(*args, **kwargs)
# Ensure result is properly formatted
if not isinstance(result, dict):
return {"success": True, "result": result}
if "success" not in result:
result["success"] = True
return result
except UEMCPError as e:
log_error(f"{operation_type} operation failed: {e.message}")
return e.to_dict()
except Exception as e:
# Last resort for truly unexpected errors
log_error(f"Unexpected error in {operation_type} operation: {str(e)}")
return {
"success": False,
"error": f"Unexpected {operation_type} error: {str(e)}",
"operation": func.__name__,
"details": {"error_type": type(e).__name__},
}
return wrapper
return decorator
# ============================================================================
# Utility Functions for Common Validations
# ============================================================================
def require_actor(actor_name: str) -> unreal.Actor:
"""
Find and return an actor by name, raising ProcessingError if not found.
Args:
actor_name: Name of the actor to find
Returns:
unreal.Actor: The found actor
Raises:
ProcessingError: If actor is not found
"""
from utils import find_actor_by_name # Import here to avoid circular imports
actor = find_actor_by_name(actor_name)
if not actor:
raise ProcessingError(
f"Actor '{actor_name}' not found in level", operation="find_actor", details={"actor_name": actor_name}
)
return actor
def require_asset(asset_path: str) -> unreal.Object:
"""
Load and return an asset, raising ProcessingError if not found or invalid.
Args:
asset_path: Path to the asset
Returns:
unreal.Object: The loaded asset
Raises:
ProcessingError: If asset cannot be loaded
"""
from utils import load_asset # Import here to avoid circular imports
asset = load_asset(asset_path)
if not asset:
raise ProcessingError(
f"Could not load asset: {asset_path}", operation="load_asset", details={"asset_path": asset_path}
)
return asset
def validate_location(location: List[float], field_name: str = "location"):
"""Validate location parameter."""
if not isinstance(location, (list, tuple)):
raise ValidationError(f"{field_name} must be a list or tuple")
if len(location) != 3:
raise ValidationError(f"{field_name} must have 3 elements [X, Y, Z]")
if not all(isinstance(x, (int, float)) for x in location):
raise ValidationError(f"{field_name} elements must be numeric")
def validate_rotation(rotation: List[float], field_name: str = "rotation"):
"""Validate rotation parameter."""
if not isinstance(rotation, (list, tuple)):
raise ValidationError(f"{field_name} must be a list or tuple")
if len(rotation) != 3:
raise ValidationError(f"{field_name} must have 3 elements [Roll, Pitch, Yaw]")
if not all(isinstance(x, (int, float)) for x in rotation):
raise ValidationError(f"{field_name} elements must be numeric")
# ============================================================================
# Context Managers for Resource Management
# ============================================================================
class DisableViewportUpdates:
"""Context manager to temporarily disable viewport updates for performance."""
def __enter__(self):
try:
unreal.EditorLevelLibrary.set_level_viewport_realtime(False)
log_debug("Disabled viewport updates for performance")
except Exception as e:
log_debug(f"Could not disable viewport updates: {str(e)}")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
try:
unreal.EditorLevelLibrary.set_level_viewport_realtime(True)
log_debug("Re-enabled viewport updates")
except Exception as e:
log_error(f"Failed to re-enable viewport updates: {str(e)}")
# ============================================================================
# Example Usage and Tests
# ============================================================================
if __name__ == "__main__":
# Example of how to use the new error handling framework
@validate_inputs(
{
"assetPath": [RequiredRule(), AssetPathRule()],
"location": [RequiredRule(), ListLengthRule(3)],
"name": [TypeRule(str)],
}
)
@handle_unreal_errors("spawn_actor")
@safe_operation("actor")
def example_spawn_actor(assetPath: str, location: List[float], name: str = None):
"""Example function showing the new error handling pattern."""
# No try/catch needed! Validation and error handling are automatic
# These will throw specific errors if they fail
asset = require_asset(assetPath)
# Business logic without error handling boilerplate
from utils import create_transform
ue_location, ue_rotation, ue_scale = create_transform(location, [0, 0, 0], [1, 1, 1])
# This might raise ProcessingError which will be caught and converted
actor = unreal.EditorLevelLibrary.spawn_actor_from_object(asset, ue_location, ue_rotation)
if not actor:
raise ProcessingError("Failed to spawn actor from asset")
if name:
actor.set_actor_label(name)
return {"actor_name": actor.get_actor_label(), "location": location, "asset_path": assetPath}
|
"""Test script for UnrealMCP basic commands.
This script tests the basic scene and Python execution commands available in the UnrealMCP bridge.
Make sure Unreal Engine is running with the UnrealMCP plugin enabled before running this script.
"""
import sys
import os
import json
from mcp.server.fastmcp import FastMCP, Context
# Add the MCP directory to sys.path so we can import unreal_mcp_bridge
mcp_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if mcp_dir not in sys.path:
sys.path.insert(0, mcp_dir)
from unreal_mcp_bridge import send_command
def test_scene_info():
"""Test getting scene information."""
print("\n1. Testing get_scene_info...")
try:
response = send_command("get_scene_info")
print(f"Get Scene Info Response: {json.dumps(response, indent=2)}")
return response["status"] == "success"
except Exception as e:
print(f"Error testing get_scene_info: {e}")
return False
def test_object_creation():
"""Test creating objects in the scene."""
print("\n2. Testing create_object...")
try:
params = {
"type": "StaticMeshActor",
"location": [0, 0, 100],
"label": "TestCube"
}
response = send_command("create_object", params)
print(f"Create Object Response: {json.dumps(response, indent=2)}")
return response["status"] == "success"
except Exception as e:
print(f"Error testing create_object: {e}")
return False
def test_python_execution():
"""Test Python execution in Unreal Engine."""
print("\n3. Testing execute_python...")
test_code = """
import unreal
print("Python executing in Unreal Engine!")
world = unreal.EditorLevelLibrary.get_editor_world()
print(f"Current level: {world.get_name()}")
actors = unreal.EditorLevelLibrary.get_all_level_actors()
print(f"Number of actors in level: {len(actors)}")
"""
try:
response = send_command("execute_python", {"code": test_code})
print(f"Python Execution Response: {json.dumps(response, indent=2)}")
return response["status"] == "success"
except Exception as e:
print(f"Error testing Python execution: {e}")
return False
def main():
"""Run all basic command tests."""
print("Starting UnrealMCP basic command tests...")
print("Make sure Unreal Engine is running with the UnrealMCP plugin enabled!")
try:
results = {
"get_scene_info": test_scene_info(),
"create_object": test_object_creation(),
"execute_python": test_python_execution()
}
print("\nTest Results:")
print("-" * 40)
for test_name, success in results.items():
status = "✓ PASS" if success else "✗ FAIL"
print(f"{status} - {test_name}")
print("-" * 40)
if all(results.values()):
print("\nAll basic tests passed successfully!")
else:
print("\nSome tests failed. Check the output above for details.")
sys.exit(1)
except Exception as e:
print(f"\nError during testing: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
|
'''
File:
Author:
Date:
Description:
Other Notes:
'''
import time
import unreal
# ar_lib = unreal.ARLibrary()
#
# cam = unreal.getARTexture()
# ar_lib.get_camera_image()
#
# cam = unreal.CameraActor(name='CineCameraActor')
# Get main camera - Confirmed if CAMERA is selected
actor = unreal.EditorLevelLibrary.get_selected_level_actors()
print(actor)
# Learn about camera from it's 'scene_component' class
scene = actor[0].scene_component
#home = scene.get_world_location()
home = unreal.Vector(x=-150, y=-60, z=150)
print(f"HOME Camera location: {home}")
# Move the camera either one of two ways:
# A) Set the actual location & rotation - Confirmed
# scene.set_world_location(new_location=, sweep=False, teleport=True)
# scene.set_world_rotation(new_rotation=, sweep=False, teleport=True)
#
# B) Set relative offset
# scene.add_world_offset()
# scene.add_world_rotation()
'''
Below works, but from a single script call, the effects will only be applied
IF there is an offset by the end of the script. If you move, then move back,
nothing in the editor will change.
'''
# Move first
x = home.x
y = home.y
z = home.z
scene.set_world_location(new_location=[x+30,y,z], sweep=False, teleport=True)
current_loc = scene.get_world_location()
print(f"ALTERED Camera location: {current_loc}")
#time.sleep(2)
# Save changes
# editor = unreal.EditorLoadingAndSavingUtils
# editor.save_dirty_packages(True, True)
# unreal.EditorUtilityLibrary.set_actor_selection_state(scene, True)
# unreal.EditorLevelLibrary.set_level_dirty()
# unreal.EditorAssetLibrary.save_loaded_asset(actor)
# unreal.EditorLevelLibrary.save_current_level()
# Move Second
time.sleep(2)
x = home.x
y = home.y
z = home.z
scene.set_world_location(new_location=[x-30,y,z], sweep=False, teleport=True)
current_loc = scene.get_world_location()
print(f"ALTERED Camera location: {current_loc}")
# scene.set_world_location(new_location=home, sweep=False, teleport=True)
|
# Copyright Epic Games, Inc. All Rights Reserved
"""
This script handles processing jobs for a specific queue asset
"""
import unreal
from .render_queue_jobs import render_jobs
from .utils import (
get_asset_data,
movie_pipeline_queue,
update_queue
)
def setup_queue_parser(subparser):
"""
This method adds a custom execution function and args to a queue subparser
:param subparser: Subparser for processing custom sequences
"""
# Set the name of the job
subparser.add_argument(
"queue",
type=str,
help="The name or path to a movie pipeline queue."
)
# Add option to only load the contents of the queue. By default,
# this will only load the queue and render its contents
subparser.add_argument(
"--load",
action="store_true",
help="Load the contents of the queue asset. By default the queue asset will loaded and render its contents.",
)
# We will use the level sequence and the map as our context for
# other subsequence arguments.
subparser.add_argument(
"--jobs",
type=str,
nargs="+",
help="A list of jobs to execute in the queue. "
"If no jobs are provided, all jobs in the queue will be rendered.",
)
# Function to process arguments
subparser.set_defaults(func=_process_args)
def render_queue_asset(
queue_name,
only_load=False,
shots=None,
jobs=None,
all_shots=False,
is_cmdline=False,
is_remote=False,
user=None,
remote_batch_name=None,
remote_job_preset=None,
executor_instance=None,
output_dir_override=None,
output_filename_override=None
):
"""
Render using a Movie Render Queue asset
:param str queue_name: The name of the Queue asset
:param bool only_load: Only load the queue asset. This is usually used when you need to process intermediary steps before rendering
:param list shots: Shots to render from the queue.
:param list jobs: The list job to render in the Queue asset.
:param bool all_shots: Flag to render all shots in a job in the queue.
:param bool is_cmdline: Flag to determine if the job is a commandline job
:param bool is_remote: Flag to determine if the jobs should be rendered remote
:param str user: Render user
:param str remote_batch_name: Batch name for remote renders
:param str remote_job_preset: Remote render job preset
:param executor_instance: Movie Pipeline executor instance
:param str output_dir_override: Movie Pipeline output directory override
:param str output_filename_override: Movie Pipeline filename format override
:return: MRQ Executor
"""
# The queue subsystem behaves like a singleton so
# clear all the jobs in the current queue.
movie_pipeline_queue.delete_all_jobs()
# Get the queue data asset package path by name or by path
# Create a new queue from the queue asset
movie_pipeline_queue.copy_from(
get_asset_data(queue_name, "MoviePipelineQueue").get_asset()
)
# If we only want to load the queue asset, then exit after loading.
# If we want to shut down the editor as well, then do so
if only_load:
if is_cmdline:
unreal.SystemLibrary.quit_editor()
return None
if not movie_pipeline_queue.get_jobs():
# Make sure we have jobs in the queue to work with
raise RuntimeError("There are no jobs in the queue!!")
# Allow executing the render queue in its current loaded state
if all_shots or (any([shots, jobs])):
update_queue(
jobs=jobs,
shots=shots,
all_shots=all_shots,
user=user
)
try:
# Execute the render. This will execute the render based on whether
# its remote or local
executor = render_jobs(
is_remote,
remote_batch_name=remote_batch_name,
remote_job_preset=remote_job_preset,
is_cmdline=is_cmdline,
executor_instance=executor_instance,
output_dir_override=output_dir_override,
output_filename_override=output_filename_override
)
except Exception:
raise
return executor
def _process_args(args):
"""
Function to process the arguments for the sequence subcommand
:param args: Parsed Arguments from parser
"""
return render_queue_asset(
args.queue,
only_load=args.load,
shots=args.shots,
jobs=args.jobs,
all_shots=args.all_shots,
is_remote=args.remote,
is_cmdline=args.cmdline,
user=args.user,
remote_batch_name=args.batch_name,
remote_job_preset=args.deadline_job_preset,
output_dir_override=args.output_override,
output_filename_override=args.filename_override
)
|
import unreal
import sys
from PySide2 import QtWidgets, QtUiTools, QtGui
#Import UE python lib
#import ui.qwidget_import_asset as q_import_asset
# RELOAD MODULE
import importlib
sys.path.append('C:/project/')
sys.path.append('C:/project/')
sys.path.append('C:/project/')
WINDOW_NAME = 'M2 - Menu'
UI_FILE_FULLNAME = __file__.replace('.py', '.ui')
class QtWindowImport(QtWidgets.QWidget):
def __init__(self, parent=None):
super(QtWindowImport, self).__init__(parent)
self.aboutToClose = None # This is used to stop the tick when the window is closed
self.widget = QtUiTools.QUiLoader().load(UI_FILE_FULLNAME)
self.widget.setParent(self)
self.setWindowTitle(WINDOW_NAME)
self.setGeometry(100, 100, self.widget.width(), self.widget.height())
self.layout = QtWidgets.QVBoxLayout(self)
self.layout.addWidget(self.widget)
self.setLayout(self.layout)
# importAssetButton
self.widget.convertToMi.clicked.connect(self.convert_to_mi)
def convert_to_mi(self):
#import m2_unreal.convert_to_mi as convert_to_mi
#importlib.reload(convert_to_mi)
#convert_to_mi.convert_to_mi()
print()
app = None
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
widget = QtWindowImport()
widget.show()
unreal.parent_external_window_to_slate(widget.winId())
|
import unreal
def world_outliner():
# instances of unreal classes
editor_level_lib = unreal.EditorLevelLibrary()
editor_filter_lib = unreal.EditorFilterLibrary()
# get all actors and filter down to specific elements
actors = editor_level_lib.get_all_level_actors()
static_meshes = editor_filter_lib.by_class(actors, unreal.StaticMeshActor)
reflection_cap = editor_filter_lib.by_class(actors, unreal.ReflectionCapture)
blueprints = editor_filter_lib.by_class(actors, "BP_")
moved = 0
# create a mapping between folder names and arrays
mapping = {
"StaticMeshActors": static_meshes,
"ReflectionCaptures": reflection_cap,
"Blueprints": blueprints
}
for folder_name in mapping:
# for every list of actors, set new folder path
for actor in mapping[folder_name]:
actor_name = actor.get_fname()
actor.set_folder_path(folder_name)
unreal.log("Moved {} into {}".format(actor_name, folder_name))
moved += 1
unreal.log("Moved {} actors into folders".format(moved))
|
# 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()
|
import os
import csv
import json
import tempfile
import unreal
from urllib import request, parse
from scripts.common.utils import get_sheet_data
from ..common.column_handler import ColumnHandler
# 상수 정의
SHEET_ID = "1jeq0WdGMsOcAEtW_p__-daOn22ZFoCm67UWgLh6p6CA"
GID = "301417934"
TABLE_PATH = "/project/"
# 고정 경로 매핑
FIXED_PATHS = {
'LV_TestMap': '/project/.TestMap',
'LV_Test01': '/project/.Test01',
'CAM_TestMap': '/project/.TestMap_Camera',
'LIT_TestMap_DAY': '/project/.CommonEnvironment_Clear',
'BP_Test01': '/project/.BP_Test01'
}
class AssetPathCache:
def __init__(self):
self._cache = {}
self._asset_index = {}
self._initialized = False
self._duplicate_assets = {} # 중복 에셋 추적용
def initialize(self):
"""에셋 레지스트리에서 모든 에셋을 가져와서 인덱스 생성"""
if self._initialized:
return
print("에셋 인덱스 초기화 중...")
asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
# 한 번에 모든 에셋 가져오기
ar_filter = unreal.ARFilter(
package_paths=["/Game"], # /Game 전체 검색
recursive_paths=True
)
assets = asset_registry.get_assets(ar_filter)
# 에셋 인덱스 생성 및 중복 검사
for asset in assets:
package_path = str(asset.package_name)
package_path_lower = package_path.lower()
path_parts = package_path_lower.split('/')
asset_name = path_parts[-1]
# 에셋 중복 검사
if asset_name in self._duplicate_assets:
self._duplicate_assets[asset_name].append(package_path)
else:
self._duplicate_assets[asset_name] = [package_path]
# 에셋 이름으로 인덱싱 (대소문자 구분 없이)
if asset_name not in self._asset_index:
self._asset_index[asset_name] = []
self._asset_index[asset_name].append(package_path)
print(f"에셋 인덱스 생성 완료: {len(self._asset_index)} 개의 에셋")
self._initialized = True
def get_path(self, asset_name):
"""캐시된 에셋 경로 반환"""
# 캐시 확인
if asset_name in self._cache:
return self._cache[asset_name]
# 고정 경로 확인
if asset_name in FIXED_PATHS:
self._cache[asset_name] = FIXED_PATHS[asset_name]
return self._cache[asset_name]
# 인덱스에서 검색 (대소문자 구분 없이)
asset_name_lower = asset_name.lower()
if asset_name_lower in self._asset_index:
# 여러 경로 중에서 가장 적절한 것 선택
paths = self._asset_index[asset_name_lower]
for path in paths:
# LIT_ 파일의 경우 LightingLevel 폴더에 있는지 확인
if asset_name.startswith('LIT_') and 'LightingLevel' in path:
full_path = f"{path}.{asset_name}"
self._cache[asset_name] = full_path
return full_path
# CAM_ 파일의 경우 PhotoSpot 폴더에 있는지 확인
elif asset_name.startswith('CAM_') and 'PhotoSpot' in path:
full_path = f"{path}.{asset_name}"
self._cache[asset_name] = full_path
return full_path
# BP_ 파일의 경우 SubLevel 폴더에 있는지 확인
elif asset_name.startswith('BP_') and 'SubLevel' in path:
full_path = f"{path}.{asset_name}"
self._cache[asset_name] = full_path
return full_path
# LV_ 또는 SZ_ 파일의 경우 MainLevel 폴더에 있는지 확인
elif (asset_name.startswith('LV_') or asset_name.startswith('SZ_')) and 'MainLevel' in path:
full_path = f"{path}.{asset_name}"
self._cache[asset_name] = full_path
return full_path
# 특정 폴더를 찾지 못한 경우 첫 번째 경로 사용
if paths:
full_path = f"{paths[0]}.{asset_name}"
self._cache[asset_name] = full_path
return full_path
# 찾지 못한 경우
self._cache[asset_name] = ""
return ""
def check_asset_duplicates(self, asset_name):
"""에셋 중복 검사"""
asset_name_lower = asset_name.lower()
if asset_name_lower in self._duplicate_assets:
paths = self._duplicate_assets[asset_name_lower]
if len(paths) > 1:
return paths
return None
# 전역 캐시 인스턴스 생성
asset_cache = AssetPathCache()
def find_asset_path(asset_name):
"""에셋 경로 찾기 (캐시 사용)"""
# 캐시 초기화 확인
if not asset_cache._initialized:
asset_cache.initialize()
path = asset_cache.get_path(asset_name)
if path:
print(f"에셋 찾음 {asset_name}: {path}")
else:
print(f"에셋을 찾을 수 없음: {asset_name}")
return path
def show_duplicate_warning(duplicate_assets):
"""중복 파일 경고 창 표시"""
dialog = unreal.EditorDialog()
message = "다음 파일들이 중복되어 임포트가 중지되었습니다:\n\n"
message += "\n".join(duplicate_assets) # 중복된 파일명만 표시
dialog.show_message(
"경고",
message,
unreal.AppMsgType.OK,
unreal.AppReturnType.OK
)
def set_file_writable(file_path):
"""파일의 읽기 전용 속성을 해제"""
if os.path.exists(file_path):
try:
import stat
current_permissions = os.stat(file_path).st_mode
os.chmod(file_path, current_permissions | stat.S_IWRITE)
print(f"파일 쓰기 권한 설정됨: {file_path}")
return True
except Exception as e:
print(f"파일 권한 변경 실패: {str(e)}")
return False
return True
def checkout_and_make_writable(asset_path):
"""에셋을 소스 컨트롤에서 checkout하고 쓰기 가능하게 만듦"""
try:
# 에셋이 존재하는지 확인
if not unreal.EditorAssetLibrary.does_asset_exist(asset_path):
print(f"에셋이 존재하지 않음: {asset_path}")
return {'success': False, 'error': f"에셋이 존재하지 않습니다: {asset_path}"}
# 에셋 로드
asset = unreal.EditorAssetLibrary.load_asset(asset_path)
if not asset:
print(f"에셋을 로드할 수 없음: {asset_path}")
return {'success': False, 'error': f"에셋을 로드할 수 없습니다: {asset_path}"}
# 소스 컨트롤 상태 확인
try:
source_control = unreal.EditorUtilityLibrary.get_source_control_provider()
if source_control and source_control.is_enabled():
state = source_control.get_state(asset_path)
if state:
other_user = state.get_other_user()
if other_user:
error_msg = f"{other_user}에 의해 에셋이 잠겨있습니다. {other_user}에게 문의해주세요."
print(f"⚠️ {error_msg}")
return {'success': False, 'error': error_msg}
except Exception as e:
print(f"소스 컨트롤 상태 확인 중 오류 발생: {str(e)}")
# 에셋 체크아웃 시도
try:
if not unreal.EditorAssetLibrary.checkout_loaded_asset(asset):
print(f"⚠️ 에셋 체크아웃 실패: {asset_path}")
return {'success': False, 'error': "에셋이 잠겨있습니다. 소스 컨트롤 상태를 확인해주세요."}
except Exception as e:
print(f"체크아웃 중 오류 발생: {str(e)}")
return {'success': False, 'error': f"체크아웃 중 오류 발생: {str(e)}"}
print(f"✅ 에셋이 체크아웃됨: {asset_path}")
# 에셋의 실제 파일 경로 가져오기
package_path = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(asset)
if not package_path:
print(f"에셋 경로를 찾을 수 없음: {asset_path}")
return {'success': False, 'error': f"에셋 경로를 찾을 수 없습니다: {asset_path}"}
# 파일 쓰기 가능하게 만들기
if not set_file_writable(package_path):
print(f"파일을 쓰기 가능하게 만들 수 없음: {package_path}")
return {'success': False, 'error': f"파일을 쓰기 가능하게 만들 수 없습니다: {package_path}"}
print(f"✅ 에셋이 쓰기 가능하게 설정됨: {asset_path}")
return {'success': True}
except Exception as e:
print(f"에셋 설정 중 오류 발생: {str(e)}")
return {'success': False, 'error': str(e)}
def import_table(sheet_id=SHEET_ID, gid=GID):
try:
print(f"=== 레벨 데이터 임포트 시작 ===")
print("테이블 정보:")
print(f"- Sheet ID: {sheet_id}")
print(f"- GID: {gid}")
print(f"- 테이블 경로: {TABLE_PATH}")
data = get_sheet_data(sheet_id, gid)
if not data:
return {'success': False, 'error': '데이터를 가져올 수 없습니다.'}
# 에셋 checkout
checkout_result = checkout_and_make_writable(TABLE_PATH)
if not checkout_result['success']:
print(f"체크아웃 실패: {checkout_result['error']}")
return checkout_result
# 데이터 테이블 생성 또는 로드
data_table = unreal.EditorAssetLibrary.load_asset(TABLE_PATH)
if not data_table:
data_table = unreal.EditorAssetLibrary.make_new_data_table_asset(TABLE_PATH, unreal.DataTable)
if not data_table:
print(f"데이터 테이블 생성 실패: {TABLE_PATH}")
return {'success': False, 'error': '데이터 테이블을 생성할 수 없습니다.'}
# 컬럼 핸들러 설정
column_handler = ColumnHandler("레벨 데이터")
column_handler.set_required_columns(['ID'])
column_handler.add_handled_columns(['ID', 'Level'])
# 컬럼 검증
if not column_handler.process_columns(data):
return {'success': False, 'error': '컬럼 검증 실패'}
# 데이터 처리 및 저장
if process_and_save_data(data_table, data):
print(f"데이터 테이블 업데이트 성공 ({len(data)}행)")
return {'success': True, 'count': len(data)}
return {'success': False, 'error': '데이터 처리 중 오류가 발생했습니다.'}
except Exception as e:
print(f"실패: {str(e)}")
import traceback
traceback.print_exc()
return {'success': False, 'error': str(e)}
def get_level_info(level_id):
"""특정 레벨 ID의 정보 반환"""
try:
data = get_sheet_data(SHEET_ID, GID)
if not data:
return None
for row in data[1:]:
if row.get('ID') == level_id:
return {
'ID': row.get('ID'),
'Level': row.get('Level'),
'Thumb': f"/project/{row.get('ID')}/PhotoSpot1",
# 필요한 다른 필드들 추가
}
return None
except Exception as e:
print(f"레벨 정보 가져오기 실패: {str(e)}")
return None
def process_and_save_data(data_table, data):
try:
# CSV 파일 생성
temp_dir = tempfile.gettempdir()
temp_csv_path = os.path.join(temp_dir, "temp_level_data.csv")
fieldnames = ['Name', 'Level']
with open(temp_csv_path, 'w', encoding='utf-8', newline='') as outfile:
writer = csv.DictWriter(outfile, fieldnames=fieldnames)
writer.writeheader()
for row in data:
level_id = str(row.get('ID', '')).strip()
if not level_id:
continue
level_path = str(row.get('Level', '')).strip()
if not level_path:
level_path = find_asset_path(level_id)
new_row = {
'Name': level_id,
'Level': level_path
}
writer.writerow(new_row)
# 데이터 테이블 임포트 설정
struct_path = "/project/.CinevStreamingLevelData" # 수정된 구조체 경로
row_struct = unreal.load_object(None, struct_path)
if not row_struct:
print(f"구조체를 찾을 수 없습니다: {struct_path}")
return False
# CSV 임포트 설정
factory = unreal.CSVImportFactory()
factory.automated_import_settings.import_row_struct = row_struct
# 임포트 태스크 설정
task = unreal.AssetImportTask()
task.filename = temp_csv_path
task.destination_path = os.path.dirname(TABLE_PATH)
task.destination_name = os.path.basename(TABLE_PATH).replace("/Game/", "")
task.replace_existing = True
task.automated = True
task.save = True
task.factory = factory
# 데이터 테이블 임포트 실행
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
asset_tools.import_asset_tasks([task])
# 임시 파일 삭제
try:
os.remove(temp_csv_path)
print(f"임시 파일 삭제됨: {temp_csv_path}")
except Exception as e:
print(f"임시 파일 삭제 실패: {e}")
# 콘텐츠 브라우저 새로고침
try:
content_browser = unreal.get_editor_subsystem(unreal.ContentBrowserSubsystem)
content_browser.refresh_folder(os.path.dirname(TABLE_PATH))
except Exception as e:
print(f"콘텐츠 브라우저 새로고침 실패: {e}")
return True
except Exception as e:
print(f"데이터 처리 중 오류 발생: {str(e)}")
return False
|
import unreal
import os
import subprocess
def open_project_directory():
project_dir = unreal.SystemLibrary.get_project_directory()
print(project_dir)
subprocess.run(['explorer', os.path.realpath(project_dir)])
print('Completed')
open_project_directory()
|
import os
import json
import unreal
from ueGear import helpers, assets
import ueGear.sequencer.bindings as seq_bindings
# Dictionary containing default FBX export options
DEFAULT_SEQUENCE_FBX_EXPORT_OPTIONS = {
"ascii": True,
"level_of_detail": False,
}
def get_current_level_sequence():
"""
Returns the current opened root/master level sequence asset.
:return: current level sequence.
:rtype: LevelSequence or None
"""
return (
unreal.LevelSequenceEditorBlueprintLibrary.get_current_level_sequence()
)
def get_subsequence_tracks(sequence: unreal.LevelSequence = None):
"""
Gets all tracks that are sub-sequence tracks.
:return: List of MovieSceneSubTrack, that exist in the sequence
:rtype: [unreal.MovieSceneSubTrack]
"""
if sequence is None:
sequence = get_current_level_sequence()
return sequence.find_tracks_by_exact_type(unreal.MovieSceneSubTrack)
def get_subsequences(track: unreal.MovieSceneSubTrack):
"""
Gets all sequences that exist in the Sub sequence track.
:return: List of MovieSceneSequences, that were part of the track.
:rtype: [unreal.MovieSceneSequence]
"""
sequences = []
for section in track.get_sections():
sequences.append(section.get_sequence())
return sequences
def get_framerate(sequence: unreal.MovieSceneSequence = None):
"""
Gets the sequencer's frame rate.
:return: Frame rate for the specified sequencer. Frames per second.
:rtype: int | None
"""
if sequence is None:
sequence = get_current_level_sequence()
if sequence is None:
return None
return sequence.get_display_rate().numerator
def track_section_to_dict(section):
"""
Parses given sequence track section and returns a dictionary with the data of the sequence track section.
:param unreal.MovieSceneSection or unreal.MovieSceneCameraCutSection or unreal.MovieScene3DTransformTrack or unreal.MovieSceneCinematicShotSection section:
movie scene sequence track section to convert into a dictionary.
:return: sequence track section dictionary.
:rtype: dict
"""
section_type = section.get_class().get_name()
section_data = {
"type": section_type,
"is_active": section.is_active(),
"is_locked": section.is_locked(),
"channels": list(),
}
for channel in section.get_all_channels():
channel_data = {
"name": str(channel.get_editor_property("channel_name"))
}
section_data["channels"].append(channel_data)
if section_type == "MovieSceneCinematicShotSection":
section_data["name"] = section.get_shot_display_name()
section_data["range"] = {
"has_start": section.has_start_frame(),
"start": section.get_start_frame(),
"has_end": section.has_end_frame(),
"end": section.get_end_frame(),
}
section_sequence = section.get_sequence()
if section_sequence:
section_data["sequence"] = sequence_to_dict(section_sequence)
elif section_type == "MovieSceneCameraCutSection":
section_data["range"] = {
"has_start": section.has_start_frame(),
"start": section.get_start_frame(),
"has_end": section.has_end_frame(),
"end": section.get_end_frame(),
}
return section_data
def track_to_dict(track):
"""
Parses given sequence track and returns a dictionary with the data of the sequence track.
:param unreal.MovieSceneTrack track: movie scene sequence track to convert into a dictionary.
:return: sequence track dictionary.
:rtype: dict
"""
track_data = {
"name": str(track.get_display_name()),
"type": track.get_class().get_name(),
"sections": list(),
}
for section in track.get_sections():
track_data["sections"].append(track_section_to_dict(section))
return track_data
def sequence_to_dict(sequence):
"""
Parses given sequence and returns a dictionary with the data of the sequence.
:param unreal.MovieSceneSequence sequence: movie scene sequence to convert ito a dictionary.
:return: sequence dictionary.
:rtype: dict
"""
sequence_data = dict()
for master_trak in sequence.find_master_tracks_by_type(
unreal.MovieSceneTrack
):
sequence_data["master_tracks"].append(track_to_dict(master_trak))
for binding in sequence.get_bindings():
binding_data = {
"name": str(binding.get_display_name()),
"id": binding.get_id().to_string(),
"tracks": list(),
}
for track in binding.get_tracks():
binding_data["tracks"].append(track_to_dict(track))
sequence_data["bindings"].append(binding_data)
return sequence_data
def sequence_to_json(sequence):
"""
Converts given sequence into a JSON compatible serialized string.
:param unreal.MovieSceneSequence sequence: movie scene sequence to convert ito a dictionary.
:return: serialized JSON compatible sequence.
:rtype: str
"""
return json.dumps(sequence_to_dict(sequence))
def get_bound_objects(sequence: unreal.LevelSequence):
"""
Returns objects in the current map that are bound to the given sequence.
:param unreal.LevelSequence sequence: sequence to get bound objects of.
:return: list of bound objects.
:rtype: [unreal.Object]
"""
world = unreal.get_editor_subsystem(
unreal.UnrealEditorSubsystem
).get_editor_world()
sequence_range = sequence.get_playback_range()
seq_bound_objs = unreal.SequencerTools.get_bound_objects(
world,
sequence,
sequence.get_bindings(),
sequence_range
)
bound_objs = []
for entry in seq_bound_objs:
bound_objs.extend(entry.bound_objects)
return bound_objs
def get_bound_object(track: unreal.MovieSceneBindingProxy, sequence: unreal.LevelSequence = None):
"""
Queries the active Level Sequencer for the Objects that are bound to
the input Track ( MovieSceneBindingProxy ).
:return: Bound objects that exist on the track input..
:rtype: [unreal.Object]
"""
seq_tools = unreal.SequencerTools()
editor_system = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem)
if sequence is None:
sequence = get_current_level_sequence()
world = editor_system.get_editor_world()
range = sequence.get_playback_range()
seq_bound_objs = seq_tools.get_bound_objects(world,
sequence,
[track],
range)
bound_objs = []
for entry in seq_bound_objs:
bound_objs.extend(entry.bound_objects)
return bound_objs
def get_selected_cameras():
"""
Gets the Camera Bindings, from the selected Sequence Tracks.
:return: Array of Camera bindings.
:rtype: [unreal.MovieSceneBindingProxy]
"""
print(" DEBUG: Get Selected Cameras")
cameras = []
lvl_seq_bpl = unreal.LevelSequenceEditorBlueprintLibrary
# Track that is an objects and not an objects attribute.
bindings = lvl_seq_bpl.get_selected_bindings()
for binding in bindings:
if seq_bindings.is_instanced_camera(binding):
# Instanced Camera
cameras.append(binding)
elif seq_bindings.is_camera(binding):
# Camera
cameras.append(binding)
return cameras
def import_fbx_camera(name: str, sequence: unreal.LevelSequence, fbx_path: str):
"""
Imports the Camera FBX into the specified level sequencer. It overrides the camera that
exists in the sequence and has a matching name.
"""
camera_track = None
# Looks over the Possessables for the correct name
tracks = sequence.get_possessables()
for track in tracks:
if track.get_display_name() == name and seq_bindings.is_camera(track):
camera_track = track
break
# Looks over the Spawnables for the correct name
if camera_track is None:
tracks = sequence.get_spawnables()
for track in tracks:
if track.get_display_name() == name and \
seq_bindings.is_instanced_camera(track):
camera_track = track
break
if camera_track is None:
unreal.log_error(f"Camera Track `{name}` was not found")
return
editor_system = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem)
world = editor_system.get_editor_world()
fbx_config = unreal.MovieSceneUserImportFBXSettings()
seq_tools = unreal.SequencerTools()
fbx_config.set_editor_property("match_by_name_only", False)
fbx_config.set_editor_property("replace_transform_track", True)
fbx_config.set_editor_property("create_cameras", False)
seq_tools.import_level_sequence_fbx(world,
sequence,
[camera_track],
fbx_config,
fbx_path)
def export_fbx_sequence(
sequence,
directory,
root_sequence=None,
fbx_filename="",
export_options=None,
):
"""
Exports a FBX from Unreal sequence.
:param unreal.LevelSequence sequence: sequence to export.
:param str directory: directory where FBX sequence will be exported.
:param str fbx_filename: optional file name for the FBX.
:param dict export_options: dictionary containing all the FBX export settings to use.
:return: exported FBX file path.
:rtype: str
"""
fbx_path = helpers.clean_path(
os.path.join(
directory, "{}.fbx".format(fbx_filename or sequence.get_name())
)
)
world = unreal.get_editor_subsystem(
unreal.UnrealEditorSubsystem
).get_editor_world()
bindings = sequence.get_bindings()
master_tracks = sequence.get_master_tracks()
export_options = export_options or DEFAULT_SEQUENCE_FBX_EXPORT_OPTIONS
fbx_export_options = unreal.FbxExportOption()
for name, value in export_options.items():
try:
fbx_export_options.set_editor_property(name, value)
except Exception:
unreal.log_warning(
"Was not possible to set FBX Export property: {}: {}".format(
name, value
)
)
export_fbx_params = unreal.SequencerExportFBXParams(
world,
sequence,
root_sequence,
bindings,
master_tracks,
fbx_export_options,
fbx_path,
)
result = unreal.SequencerTools.export_level_sequence_fbx(export_fbx_params)
return fbx_path if result else ""
def export_fbx_binding(binding: unreal.MovieSceneBindingProxy,
path: str,
sequence: unreal.LevelSequence = None):
"""
Exports the object that relates to the track, to the path specified, as an fbx.
Example: Camera track, would export the camera object to the specified location.
:param unreal.MovieSceneBindingProxy bindings: binding to export.
:param str path: Full path to directory, where the fbxs will be exported.
:param sequence, optional: LevelSequence that the bindings belong to, else it
assumes to be the Active Sequncer.
:return: The FBX export location.
:rtype: str
"""
editor_system = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem)
world = editor_system.get_editor_world()
fbx_config = unreal.FbxExportOption()
seq_tools = unreal.SequencerTools()
if sequence is None:
sequence = get_current_level_sequence()
export_path = path + str(binding.get_display_name())
seq_fbx_params = unreal.SequencerExportFBXParams(world=world,
sequence=sequence,
bindings=[binding],
override_options=fbx_config,
fbx_file_name=export_path
)
complete = seq_tools.export_level_sequence_fbx(seq_fbx_params)
if complete:
return export_path + ".fbx"
return None
def export_fbx_bindings(bindings: list, path: str, sequence: unreal.LevelSequence = None):
"""
Exports the MovieSceneBindingProxy as an fbx, to the path specified.
:param [unreal.MovieSceneBindingProxy] bindings: bindings to export.
:param str path: Full path to directory, where the fbxs will be exported.
:param sequence, optional: LevelSequence that the bindings belong to, else it
assumes to be the Active Sequncer.
:return: The FBX export locations.
:rtype: [str]
"""
export_paths = []
if sequence is None:
sequence = get_current_level_sequence()
for proxy_bind in bindings:
fbx_path = export_fbx_binding(
binding=proxy_bind,
path=path)
export_paths.append(fbx_path)
return export_paths
def remove_sequence_camera(level_sequence_name="", camera_name=""):
"""
Removes the camera from the given sequence with given name.
:param str level_sequence_name: name of the sequence that contains the camera.
:param str camera_name: name of the camera to remove.
:return: True if the camera was removed successfully; False otherwise.
:rtype: bool
"""
level_sequence_asset = unreal.load_asset(level_sequence_name)
if not level_sequence_asset:
return False
sequence_bindings = level_sequence_asset.get_bindings()
camera_bind = None
for binding in sequence_bindings:
if binding.get_name() or binding.get_display_name() == camera_name:
camera_bind = binding
break
if not camera_bind:
return False
unreal.LevelSequenceEditorBlueprintLibrary.close_level_sequence()
children_component = camera_bind.get_child_possessables() or list()
for child_component in children_component:
child_component.remove()
camera_tracks = camera_bind.get_tracks()
for camera_track in camera_tracks:
camera_bind.remove_track(camera_track)
camera_bind.remove()
unreal.LevelSequenceEditorBlueprintLibrary.refresh_current_level_sequence()
unreal.EditorAssetLibrary.save_loaded_asset(level_sequence_asset)
return True
# TODO: This needs to return unreal.MovieSceneSequence and not unreal.SubSections
def get_subsequences(level_sequence_name):
"""
Returns a list of sequences from the given sequence name.
:param str level_sequence_name: name of the sequence whose subsequences we want to retrieve.
:return: list of sequence subsequences.
:rtype: list(unreal.LevelSequence)
"""
level_sequence_asset = unreal.load_asset(level_sequence_name)
if not level_sequence_asset:
return list()
found_subscene_track = None
tracks = level_sequence_asset.get_master_tracks()
for track in tracks:
if track.get_class() == unreal.MovieSceneSubTrack.static_class():
found_subscene_track = track
break
return (
found_subscene_track.get_sections() if found_subscene_track else list()
)
def get_sequencer_playback_range(sequence: unreal.MovieSceneSequence = None):
"""
Gets the Start and End frame of the sequence provided, else defaults to
active sequence.
If Sequence has no start or end, then None is returned.
:return: The Start and End Frame of the playback range.
:rtype: [int, int]
"""
playback_data = None
start_frame = None
end_frame = None
if sequence is None:
playback_data = get_current_level_sequence().get_playback_range()
else:
playback_data = sequence.get_playback_range()
if playback_data.has_start():
start_frame = playback_data.get_start_frame()
if playback_data.has_end():
end_frame = playback_data.get_end_frame()
return start_frame, end_frame
def get_sequencer_view_range(sequence: unreal.MovieSceneSequence = None):
"""
Gets the sequences view range.
If no sequence is specified, then defaults to current active level sequencer.
:return: The Start and End Frame of the view range.
:rtype: [int, int]
"""
start_frame = None
end_frame = None
if sequence is None:
sequence = get_current_level_sequence()
fps = sequence.get_display_rate().numerator
start_frame = round(sequence.get_view_range_start() * fps)
end_frame = round(sequence.get_view_range_end() * fps)
return start_frame, end_frame
def get_sequencer_work_range(sequence: unreal.MovieSceneSequence = None):
"""
Gets the sequences work range.
If no sequence is specified, then defaults to current active level sequencer.
:return: The Start and End Frame of the work range.
:rtype: [int, int]
"""
start_frame = None
end_frame = None
if sequence is None:
sequence = get_current_level_sequence()
fps = sequence.get_display_rate().numerator
start_frame = round(sequence.get_work_range_start() * fps)
end_frame = round(sequence.get_work_range_end() * fps)
return start_frame, end_frame
def open_sequencer(level_sequence_path: str):
"""
Opens the Sequencer UI in Unreal with the sequencer file.
level_sequencer_path: Needs to be a PackageName (Start with /Game )
:return: The LevelSequence that was opened inside the Sequencer.
:rtype: unreal.LevelSequence
"""
# Check if path is an Object path, if so remove the .##
if level_sequence_path.find(".") > -1:
level_sequence_path = level_sequence_path.split(".")[0]
if not assets.asset_exists(level_sequence_path):
return
# Converts path to Asset
asset_data = unreal.EditorAssetLibrary.find_asset_data(level_sequence_path)
asset_editor = unreal.get_editor_subsystem(unreal.AssetEditorSubsystem)
# Opens the Sequencer
asset_editor.open_editor_for_assets([asset_data.get_asset()])
return asset_data.get_asset()
|
import unreal
selected_asset = unreal.EditorUtilityLibrary.get_selected_assets()[0]
|
"""Python execution commands for Unreal Engine.
This module contains commands for executing Python code in Unreal Engine.
"""
import sys
import os
from mcp.server.fastmcp import Context
# Import send_command from the parent module
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from unreal_mcp_bridge import send_command
def register_all(mcp):
"""Register all Python execution commands with the MCP server."""
@mcp.tool()
def execute_python(ctx: Context, code: str = None, file: str = None) -> str:
"""Execute Python code or a Python script file in Unreal Engine.
This function allows you to execute arbitrary Python code directly in the Unreal Engine
environment. You can either provide Python code as a string or specify a path to a Python
script file to execute.
The Python code will have access to the full Unreal Engine Python API, including the 'unreal'
module, allowing you to interact with and manipulate the Unreal Engine editor and its assets.
Args:
code: Python code to execute as a string. Can be multiple lines.
file: Path to a Python script file to execute.
Note:
- You must provide either code or file, but not both.
- The output of the Python code will be visible in the Unreal Engine log.
- The Python code runs in the Unreal Engine process, so it has full access to the engine.
- Be careful with destructive operations as they can affect your project.
Examples:
# Execute simple Python code
execute_python(code="print('Hello from Unreal Engine!')")
# Get information about the current level
execute_python(code='''
import unreal
level = unreal.EditorLevelLibrary.get_editor_world()
print(f"Current level: {level.get_name()}")
actors = unreal.EditorLevelLibrary.get_all_level_actors()
print(f"Number of actors: {len(actors)}")
''')
# Execute a Python script file
execute_python(file="D:/project/.py")
"""
try:
if not code and not file:
return "Error: You must provide either 'code' or 'file' parameter"
if code and file:
return "Error: You can only provide either 'code' or 'file', not both"
params = {}
if code:
params["code"] = code
if file:
params["file"] = file
response = send_command("execute_python", params)
# Handle the response
if response["status"] == "success":
return f"Python execution successfu/project/{response['result']['output']}"
elif response["status"] == "error":
# New format with detailed error information
result = response.get("result", {})
output = result.get("output", "")
error = result.get("error", "")
# Format the response with both output and error information
response_text = "Python execution failed with error/project/"
if output:
response_text += f"--- Output ---\n{output}\n\n"
if error:
response_text += f"--- Error ---\n{error}"
return response_text
else:
return f"Error: {response['message']}"
except Exception as e:
return f"Error executing Python: {str(e)}"
|
import unreal
level_actors = unreal.EditorLevelLibrary.get_selected_level_actors()
light_function = unreal.EditorAssetLibrary.load_asset('/project/')
for i in level_actors :
i.set_light_function_material(light_function)
unreal.log('Light Function Assigned ')
|
# Copyright (c) <2021> Side Effects Software Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. The name of Side Effects Software may not be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
""" Example script that instantiates an HDA using the API and then
setting some parameter values after instantiation but before the
first cook.
"""
import unreal
_g_wrapper = None
def get_test_hda_path():
return '/project/.pig_head_subdivider_v01'
def get_test_hda():
return unreal.load_object(None, get_test_hda_path())
def on_post_instantiation(in_wrapper):
print('on_post_instantiation')
# in_wrapper.on_post_instantiation_delegate.remove_callable(on_post_instantiation)
# Set some parameters to create instances and enable a material
in_wrapper.set_bool_parameter_value('add_instances', True)
in_wrapper.set_int_parameter_value('num_instances', 8)
in_wrapper.set_bool_parameter_value('addshader', True)
def run():
# get the API singleton
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
global _g_wrapper
# instantiate an asset with auto-cook enabled
_g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform())
# Bind on_post_instantiation (before the first cook) callback to set parameters
_g_wrapper.on_post_instantiation_delegate.add_callable(on_post_instantiation)
if __name__ == '__main__':
run()
|
# Copyright (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 uses unreal.ActorIterator to iterate over all
HoudiniAssetActors in the editor world, creates API wrappers for them, and
logs all of their parameter tuples.
"""
import unreal
def run():
# Get the API instance
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
# Get the editor world
editor_subsystem = None
world = None
try:
# In UE5 unreal.EditorLevelLibrary.get_editor_world is deprecated and
# unreal.UnrealEditorSubsystem.get_editor_world is the replacement,
# but unreal.UnrealEditorSubsystem does not exist in UE4
editor_subsystem = unreal.UnrealEditorSubsystem()
except AttributeError:
world = unreal.EditorLevelLibrary.get_editor_world()
else:
world = editor_subsystem.get_editor_world()
# Iterate over all Houdini Asset Actors in the editor world
for houdini_actor in unreal.ActorIterator(world, unreal.HoudiniAssetActor):
if not houdini_actor:
continue
# Print the name and label of the actor
actor_name = houdini_actor.get_name()
actor_label = houdini_actor.get_actor_label()
print(f'HDA Actor (Name, Label): {actor_name}, {actor_label}')
# Wrap the Houdini asset actor with the API
wrapper = unreal.HoudiniPublicAPIAssetWrapper.create_wrapper(world, houdini_actor)
if not wrapper:
continue
# Get all parameter tuples of the HDA
parameter_tuples = wrapper.get_parameter_tuples()
if parameter_tuples is None:
# The operation failed, log the error message
error_message = wrapper.get_last_error_message()
if error_message is not None:
print(error_message)
continue
print(f'# Parameter Tuples: {len(parameter_tuples)}')
for name, data in parameter_tuples.items():
print(f'\tParameter Tuple Name: {name}')
type_name = None
values = None
if data.bool_values:
type_name = 'Bool'
values = '; '.join(('1' if v else '0' for v in data.bool_values))
elif data.float_values:
type_name = 'Float'
values = '; '.join((f'{v:.4f}' for v in data.float_values))
elif data.int32_values:
type_name = 'Int32'
values = '; '.join((f'{v:d}' for v in data.int32_values))
elif data.string_values:
type_name = 'String'
values = '; '.join(data.string_values)
if not type_name:
print('\t\tEmpty')
else:
print(f'\t\t{type_name} Values: {values}')
if __name__ == '__main__':
run()
|
# Create Virtuos Menu
# Nguyen PHi Hung
import unreal_uiutils
from unreal_utils import AssetRegistryPostLoad
import unreal
def extend_editor():
# Create standard menu entry
me_reloadbutton = unreal_uiutils.create_menu_button(
name="ReloadBtn",
label="Reload",
command_string="import importlib; import unreal_startup; importlib.reload(unreal_startup); unreal_startup.reload()",
)
me_quitbutton = unreal_uiutils.create_menu_button(
name="QuitUnrealBtn",
label="Quit Unreal",
command_string="SystemLib.quit_editor()",
)
# 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("Python", "Python")
section = new_mainmenu.add_section("python.menu", "Python Tools")
new_mainmenu.add_menu_entry("python.menu", me_reloadbutton)
new_mainmenu.add_menu_entry("python.menu", me_quitbutton)
new_entry = unreal.ToolMenuEntryExtensions.init_menu_entry(
new_mainmenu.menu_name,
"submenu",
"Test Sub Menu",
"nothing here",
unreal.ToolMenuStringCommandType.COMMAND,
"command",
"",
)
print(f"Script Object: {new_entry.script_object}")
# Extend Asset Context Menu
sub_asset_context_menu = unreal_uiutils.extend_toolmenu(unreal_uiutils.get_asset_context_menu(), "PythonAssetContextMenu", "Python Asset Actions")
sub_asset_context_menu.add_section("python.assetmenu", "Tools")
action_sampleassetprint = unreal_uiutils.create_menu_button(
name="SampleAssetTool",
label="Print Selected Assets",
command_string='print(UtilLibrary.get_selected_assets())',
)
sub_asset_context_menu.add_menu_entry("python.assetmenu", action_sampleassetprint)
# Extend Asset Context Menu - Only show for Level Sequence Asset
sequence_contextmenu = unreal_uiutils.get_sequence_asset_context_menu()
sub_sequence_context_menu = unreal_uiutils.extend_toolmenu(sequence_contextmenu, "PythonSequenceContextMenu", "Python Sequence Actions")
sub_sequence_context_menu.add_section("python.sequencemenu", "Tools")
action_samplesequenceprint = unreal_uiutils.create_menu_button(
name="SampleSequenceTool",
label="Print Selected Assets",
command_string='print(UtilLibrary.get_selected_assets())',
)
sub_sequence_context_menu.add_menu_entry("python.sequencemenu", action_samplesequenceprint)
# Extend Actor Context Menu
actor_context_menu = unreal_uiutils.get_actor_context_menu()
actor_context_menu.add_section("python.actoractions", "Python Tools")
#!NOTE: The submenu can only be seen when right click in viewport and not the outliner
sub_actor_context_menu = actor_context_menu.add_sub_menu(actor_context_menu.menu_name, "python.actoractions", "PythonActorContextMenu", "Python Actor Actions")
# is_sub_actor_context_menu_registered = unreal.ToolMenus.get().is_menu_registered(sub_actor_context_menu.menu_name)
# if not is_sub_actor_context_menu_registered:
# unreal.ToolMenus.get().register_menu(sub_actor_context_menu.menu_name, actor_context_menu.menu_name)
# print("{} - is registered {}".format(sub_actor_context_menu.menu_name, is_sub_actor_context_menu_registered))
sub_actor_context_menu.add_section("python.actormenu", "Tools")
action_sampleactorprint = unreal_uiutils.create_menu_button(
name="SampleActorTool",
label="Print Selected Actor",
command_string='print(LevelLibrary.get_selected_level_actors())',
)
sub_actor_context_menu.add_menu_entry("python.actormenu", action_sampleactorprint)
# actor_context_menu.add_menu_entry("python.actoractions", action_sampleactorprint)
# AssetRegistryPostLoad.register_callback(extend_editor)
extend_editor()
|
import unreal
'''
Non UFUNCTION functions as we cannot call ufunctions within ufunctions unless if nested
'''
def cast_key_to_type(rig, rig_key):
"""
Given an element key and its parent hierarchy modifier, returns the object of the correct type
:param rig: The rig we are looking at
:type rig: unreal.ControlRigBlueprint
:param rig_key: The key to query
:type rig_key: unreal.RigElementKey
:return: The casted type for the key
:rtype: unreal.RigBone | unreal.RigControl | unreal.RigSpace | unreal.RigCurve
"""
hierarchy_mod = rig.get_hierarchy_modifier()
if rig_key.type == unreal.RigElementType.BONE:
return hierarchy_mod.get_bone(rig_key)
elif rig_key.type == unreal.RigElementType.SPACE:
return hierarchy_mod.get_space(rig_key)
elif rig_key.type == unreal.RigElementType.CONTROL:
return hierarchy_mod.get_control(rig_key)
elif rig_key.type == unreal.RigElementType.CURVE:
return hierarchy_mod.get_curve(rig_key)
else:
return None
def get_selected_controls(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()
def create_rig_element_key(rig, key_type):
"""
Given a RigElementType, add desired rig element to the rig with specific identifier.
If there are selected rig elements, this will add desired rig element with selected transforms and name attached.
:param rig: The rig we are looking at
:type rig: unreal.ControlRigBlueprint
:param key_type: enum value of Rig Element Type
:type key_type: unreal.RigElementType value
:return: A list of the selected object
:rtype: list[unreal.RigElementKey] | list[]
"""
element_list = []
if key_type == unreal.RigElementType.BONE:
type_name = "bone"
elif key_type == unreal.RigElementType.SPACE:
type_name = "space"
elif key_type == unreal.RigElementType.CONTROL:
type_name = "ctrl"
elif key_type == unreal.RigElementType.CURVE:
type_name = "curve"
elif key_type == unreal.RigElementType.NONE or key_type == unreal.RigElementType.ALL:
return element_list
hierarchy_mod = rig.get_hierarchy_modifier()
selection = hierarchy_mod.get_selection()
if not selection:
global_xform = unreal.Transform()
element_name = type_name
element = add_element_with_init_transform(hierarchy_mod, element_name, key_type, global_xform)
element_list.append(element)
for item in selection:
global_xform = hierarchy_mod.get_global_transform(item)
element_name = "{0}_{1}".format(item.get_editor_property("Name"), type_name)
element = add_element_with_init_transform(hierarchy_mod, element_name, key_type, global_xform)
element_list.append(element)
return element_list
def add_element_with_init_transform(hierarchy_mod, element_name, key_type, global_xform):
"""
Create a new element to the control rig hiearchy with a given name, element type, and initial transform
:param hierarchy_mod: The control rig hierarchy object
:type hierarchy_mod: unreal.ControlRigHierarchyModifier
:param element_name: name of the new element
:type element_name: str
:param key_type: what RigElementType it will be
:type key_type: unreal.RigElementType value
:param global_xform: the initial transform
:type global_xform: unreal.Transform
:return: Nothing
:rtype: None
"""
element = add_element_to_hierarchy_mod(hierarchy_mod, element_name, key_type)
if key_type != unreal.RigElementType.CURVE:
hierarchy_mod.set_initial_global_transform(element, global_xform)
return element
def add_element_to_hierarchy_mod(hierarchy_mod, element_name, key_type):
"""
Create a new element to the control rig hiearchy with a given name and element type
:param hierarchy_mod: The control rig hierarchy object
:type hierarchy_mod: unreal.ControlRigHierarchyModifier
:param element_name: name of the new element
:type element_name: str
:param key_type: what RigElementType it will be
:type key_type: unreal.RigElementType value
:return: Nothing
:rtype: None
"""
if key_type == unreal.RigElementType.BONE:
element = hierarchy_mod.add_bone(element_name)
elif key_type == unreal.RigElementType.SPACE:
element = hierarchy_mod.add_space(element_name)
elif key_type == unreal.RigElementType.CONTROL:
element = hierarchy_mod.add_control(element_name)
elif key_type == unreal.RigElementType.CURVE:
element = hierarchy_mod.add_curve(element_name)
else:
element = None
return element
def edit_element_property(hierarchy_mod, rig_element, property, value):
"""
Given a rig element, edit the given property with the given value
:param hierarchy_mod: The control rig hierarchy object
:type hierarchy_mod: unreal.ControlRigHierarchyModifier
:param rig_element: The rig element key object
:type rig: unreal.RigElementKey
:param property: property name
:type property: string
:param value: value for the property
:type value: object
:return: Nothing
:rtype: None
"""
rig_element.set_editor_property(property, value)
hierarchy_mod.set_control(rig_element)
def get_elements_by_rig_type(rig, selection, rig_element_type):
"""
Given a boolean, set selected controls' gizmo to that color
:param rig: The control rig object
:type rig: unreal.ControlRigBlueprint
:param selection: list of RigElementKeys
:type selection: list[unreal.RigElementKey]
:param rig_element_type: class type of desired rig type
:type rig_element_type: unreal.uclass
:return: return_list
:rtype: list[rig_element_type] | list[]
"""
return_list = []
if not selection:
return return_list
for item in selection:
rig_element = cast_key_to_type(rig, item)
if type(rig_element) != rig_element_type:
continue
return_list.append(rig_element)
return return_list
|
import unreal
import json
import os
# === Use tkinter to open Windows file dialog ===
import tkinter as tk
from tkinter import filedialog
def choose_json_file():
root = tk.Tk()
root.withdraw() # Hide the root window
file_path = filedialog.askopenfilename(
title="Choose JSON File",
filetypes=[("JSON Files", "*.json")],
initialdir="H:/project/"
)
return file_path if file_path else None
# === Select JSON File ===
json_path = choose_json_file()
if not json_path:
unreal.log_error("No JSON file selected. Aborting.")
raise SystemExit()
# The rest of your original script follows below without change...
# === Paths ===
content_root = "/Game/"
content_dir = "H:/project/"
# === Load JSON Data ===
with open(json_path, 'r') as f:
data = json.load(f)
# === Global Configuration ===
GLOBAL_SCALE = unreal.Vector(1.0, 1.0, 1.0)
spawned_count = 0
def safe_scale(vec):
return unreal.Vector(
max(min(vec.x, 100.0), 0.01),
max(min(vec.y, 100.0), 0.01),
max(min(vec.z, 100.0), 0.01)
)
def create_convex_brush(convex_elem, location, rotation, scale, name):
verts = convex_elem.get("VertexData", [])
if not verts:
return None
brush = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.Brush, location, rotation)
if not brush:
return None
converted = [unreal.Vector(v["X"] * scale.x, v["Y"] * scale.y, v["Z"] * scale.z) for v in verts]
builder = unreal.BrushBuilder()
builder.poly_flag = 0
builder.vertices = converted
brush.set_actor_label(name + "_Brush")
print(f"🧱 Created convex brush for {name} with {len(converted)} verts")
return brush
for obj in data:
props = obj.get("Properties") or {}
obj_type = obj.get("Type", "")
name = obj.get("Name", "Unnamed")
location = props.get("RelativeLocation", {"X": 0, "Y": 0, "Z": 0})
rotation = props.get("RelativeRotation", {"Pitch": 0, "Yaw": 0, "Roll": 0})
scale = props.get("RelativeScale3D", {"X": 1, "Y": 1, "Z": 1})
# Apply relative location, rotation, and scale
loc = unreal.Vector(location["X"], location["Y"], location["Z"])
rot = unreal.Rotator(rotation["Roll"], rotation["Pitch"], rotation["Yaw"]) # Adjusted axes
scl = unreal.Vector(scale["X"], scale["Y"], scale["Z"]) * GLOBAL_SCALE # Apply global scaling here
# === Blocking Volumes with Convex Geometry ===
if obj_type == "BlockingVolume" and "BodySetup" in props:
convex_elems = props["BodySetup"].get("AggGeom", {}).get("ConvexElems", [])
for i, convex in enumerate(convex_elems):
create_convex_brush(convex, loc, rot, scl, f"{name}_Part{i}")
spawned_count += 1
continue
# === Static Mesh Placement ===
elif "StaticMesh" in props and isinstance(props["StaticMesh"], dict):
mesh_path_raw = props["StaticMesh"].get("ObjectPath", "")
if mesh_path_raw:
mesh_file = os.path.basename(mesh_path_raw).split(".")[0]
print(f"🕵️♂️ Searching for mesh: {mesh_file}") # Log the mesh name being searched
# Search entire content directory for matching .uasset
found_path = None
for root, _, files in os.walk(content_dir):
for file in files:
if file.lower() == mesh_file.lower() + ".uasset":
relative = os.path.relpath(root, content_dir).replace("\\", "/")
found_path = content_root + relative + "/" + mesh_file
print(f"✅ Found asset: {found_path}") # Log found asset path
break
if found_path:
break
if found_path:
static_mesh = unreal.EditorAssetLibrary.load_asset(found_path)
# Verify if the asset is a valid StaticMesh
if static_mesh and isinstance(static_mesh, unreal.StaticMesh):
actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.StaticMeshActor, loc, rot)
if actor:
actor.set_actor_scale3d(scl)
actor.set_actor_label(name)
smc = actor.static_mesh_component
smc.set_static_mesh(static_mesh)
smc.set_editor_property("mobility", unreal.ComponentMobility.MOVABLE)
print(f"🧱 Placed StaticMeshActor: {name} using mesh {found_path}")
spawned_count += 1
else:
print(f"❌ Failed to spawn actor for {name}")
else:
print(f"⚠️ Asset found but not a valid StaticMesh: {found_path} for {name}")
else:
print(f"❌ Could not locate asset for mesh: {mesh_file} (original path: {mesh_path_raw})")
continue
# === Fallback Generic Actor ===
if obj_type == "BlockingVolume":
actor_class = unreal.BlockingVolume
else:
actor_class = unreal.Actor
actor = unreal.EditorLevelLibrary.spawn_actor_from_class(actor_class, loc, rot)
if actor:
actor.set_actor_scale3d(scl)
actor.set_actor_label(name)
spawned_count += 1
print(f"✅ Spawned {obj_type}: {name} at {loc} with rotation {rot} and scale {scl}")
print(f"🎉 Total objects placed: {spawned_count}")
|
import unreal
import json
e_util = unreal.EditorUtilityLibrary()
a_util = unreal.EditorAssetLibrary()
str_util = unreal.StringLibrary()
sys_util = unreal.SystemLibrary()
l_util = unreal.EditorLevelLibrary()
result_dict = {}
actors = l_util.get_selected_level_actors()
# des = unreal.DataLayerEditorSubsystem()
layers = []
for act in actors:
act_type = type(act)
# actor_data_layers = act.get_editor_property('data_layers')
# layer_names = [str(des.get_data_layer(layer).get_data_layer_label()) for layer in actor_data_layers]
if act_type == unreal.PackedLevelInstance:
id_name = act.get_name()
asset_path = act.get_class().get_full_name().split(' ')[-1]
asset_type = "PackedLevelInstance"
elif act_type == unreal.StaticMeshActor:
id_name = act.get_name()
act_component = act.static_mesh_component
asset_path = act_component.static_mesh.get_full_name().split(' ')[-1]
asset_type = "StaticMeshActor"
else:
continue
actor_folder_path = str(act.get_folder_path())
# print(asset_path)
# print(actor_folder_path)
location = act.get_actor_location()
tx = location.x
ty = location.y
tz = location.z
rotation = act.get_actor_rotation()
pitch = rotation.pitch
yaw = rotation.yaw
roll = rotation.roll
scale = act.get_actor_scale3d()
sx = scale.x
sy = scale.y
sz = scale.z
result_dict [id_name] = [
asset_path,
asset_type,
actor_folder_path,
[tx,ty,tz],[pitch,yaw,roll],[sx,sy,sz]
]
json_path = "d:/actor_list_dark.json"
with open(json_path, 'w') as f:
json.dump(result_dict, f, indent=4)
# print(act.get_actor_rotation())
# print(act.get_actor_scale3d())
import unreal
import json
e_util = unreal.EditorUtilityLibrary()
a_util = unreal.EditorAssetLibrary()
str_util = unreal.StringLibrary()
sys_util = unreal.SystemLibrary()
l_util = unreal.EditorLevelLibrary()
json_path = "d:/actor_list_dark.json"
with open(json_path) as f:
data = json.load(f)
des = unreal.DataLayerEditorSubsystem()
# layer_names = ['Campfire Replace','Campfire Geometry','Dark World']
# [des.rename_data_layer(des.create_data_layer(),name) for name in layer_names]
for key,value in data.items():
asset_type = value[1]
asset_path = value[0]
folder_path = value[2]
data_layers = value[-1]
location = unreal.Vector(x=value[3][0],y=value[3][1],z=value[3][2])
rotation = unreal.Rotator(pitch=value[4][0],roll=value[4][2],yaw=value[4][1])
scale = unreal.Vector(x=value[5][0],y=value[5][1],z=value[5][2])
asset_node = a_util.load_asset(asset_path)
actor_node = l_util.spawn_actor_from_object(asset_node, location, rotation)
actor_node.set_actor_scale3d(scale)
actor_node.set_folder_path(folder_path)
|
import unreal
selected_assets = unreal.EditorUtilityLibrary.get_selected_assets()
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
loaded_subsystem = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem)
asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
counter = 0
deleted_assets = ""
for asset in selected_assets:
path_name = asset.get_path_name().split('.')[0]
list = asset_registry.get_dependencies(path_name, unreal.AssetRegistryDependencyOptions(include_soft_package_references = True,
include_hard_package_references = True,include_searchable_names = True,
include_soft_management_references = True,
include_hard_management_references = True))
for dependency in list:
print(str(dependency))
|
import unreal
from pathlib import Path
import os
""" 常用功能/通用functions"""
sys_lib = unreal.SystemLibrary()
string_lib = unreal.StringLibrary()
editor_lib = unreal.EditorUtilityLibrary
staticmesh_subsys = unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem)
subobject_subsys = unreal.get_engine_subsystem(unreal.SubobjectDataSubsystem)
editor_util_subsys = unreal.get_editor_subsystem(unreal.EditorUtilitySubsystem)
def get_asset_name(asset):
"""资产名"""
asset_name = asset.get_name()
return asset_name
def get_asset_dir(asset):
"""资产所在路径,剔除资产本身文件名"""
asset_path_name = asset.get_path_name()
asset_dir = unreal.Paths.get_path(asset_path_name)
return asset_dir
def get_selected_dir():
selected_assets = unreal.EditorUtilityLibrary.get_selected_assets()
selected_folders_path = unreal.EditorUtilityLibrary.get_selected_folder_paths()
if len(selected_assets) != 0:
asset = selected_assets[0]
if isinstance(asset, unreal.Object):
asset_dir_path = get_asset_dir(asset)
if len(selected_folders_path) != 0:
folder_path = selected_folders_path[0]
asset_dir_path = string_lib.split(folder_path, "/All")[1]
return asset_dir_path
def get_asset_path(asset):
"""资产完整路径,包含资产本身资源名"""
asset_path = asset.get_path_name()
return asset_path
def get_asset_class_name(asset):
"""资产Class名"""
asset_class = asset.get_class()
asset_class = sys_lib.get_class_display_name(asset_class)
return asset_class
def filter_class(assets, class_name: str):
"""筛选某种类型的资产"""
filtered_assets = []
# filteredAssets = None
for asset in assets:
asset_class = asset.get_class()
asset_class = sys_lib.get_class_display_name(asset_class)
if asset_class == class_name:
filtered_assets.append(asset)
return filtered_assets
def get_materials(mesh):
"""获取StaticMesh的材质列表"""
materials = None
staticmesh_component = unreal.StaticMeshComponent()
staticmesh_component.set_static_mesh(mesh)
materials = unreal.StaticMeshComponent.get_materials(staticmesh_component)
return materials
def get_material_slot_names(mesh):
"""获取StaticMesh的材质插槽列表"""
staticmesh_component = unreal.StaticMeshComponent()
staticmesh_component.set_static_mesh(mesh)
mat_slot_names = unreal.StaticMeshComponent.get_material_slot_names(
staticmesh_component
)
return mat_slot_names
def get_materials_data(mesh):
"""获取StaticMesh完整的材质信息,matIndex,matSlotName,material,输出Dict
Example:
matDict=getSMMateriaDict(staticMesh)
for index in range(len(materials_data["index"])):
slot_name = materials_data["slot_name"][index]
material = materials_data["material"][index]
"""
materials_data = {"index": [], "slot_name": [], "material": []}
SM_component = unreal.StaticMeshComponent()
SM_component.set_static_mesh(mesh)
mat_slot_names = unreal.StaticMeshComponent.get_material_slot_names(SM_component)
for slot_name in mat_slot_names:
mat_index = unreal.StaticMeshComponent.get_material_index(
SM_component, slot_name
)
material = unreal.StaticMeshComponent.get_material(SM_component, mat_index)
materials_data["index"].append(mat_index)
materials_data["slot_name"].append(slot_name)
materials_data["material"].append(material)
return materials_data
def get_blueprint_components(blueprint):
"""获取蓝图子物件列表"""
components = []
root_data_handle = subobject_subsys.k2_gather_subobject_data_for_blueprint(
blueprint
)
for handle in root_data_handle:
sub_object = subobject_subsys.k2_find_subobject_data_from_handle(handle)
components.append(
unreal.SubobjectDataBlueprintFunctionLibrary.get_object(sub_object)
)
return components
class Blueprint:
def get_handels(blueprint):
"""获取蓝图子物件列表的handle"""
# # components = []
# handles=[]
root_data_handle = subobject_subsys.k2_gather_subobject_data_for_blueprint(
blueprint
)
# for handle in root_data_handle:
# sub_object = subobject_subsys.k2_find_subobject_data_from_handle(handle)
# handles.append(sub_object)
return root_data_handle
def get_handle_component(handle):
"""从handle得到components"""
# components = []
sub_object = subobject_subsys.k2_find_subobject_data_from_handle(handle)
component = unreal.SubobjectDataBlueprintFunctionLibrary.get_object(sub_object)
return component
def get_blueprint_class(path: str) -> unreal.Class:
blueprint_asset = unreal.load_asset(path)
blueprint_class = unreal.load_object(
None, blueprint_asset.generated_class().get_path_name()
)
return blueprint_class
def get_default_object(asset) -> unreal.Object:
bp_gen_class = unreal.load_object(None, asset.generated_class().get_path_name())
default_object = unreal.get_default_object(bp_gen_class)
return default_object
def split_keywords(input_text) -> list:
"""分割输入的字符串,输出关键字列表"""
input_text = string_lib.replace(input_text, " ", "")
input_text = string_lib.replace(input_text, '"', "")
keywords = input_text.split(",")
return keywords
def run_widget(widget_path):
"""运行widget utility blueprint"""
editor_util_subsys.spawn_and_register_tab(
unreal.EditorAssetLibrary.load_asset(widget_path)
)
def dict_compare(d1, d2):
"""比较两个字典,输出增加,删除,修改,相同的键值对"""
d1_keys = set(d1.keys())
d2_keys = set(d2.keys())
shared_keys = d1_keys.intersection(d2_keys)
added = d1_keys - d2_keys
added = list(added)
removed = d2_keys - d1_keys
removed = list(removed)
modified = {o: (d1[o], d2[o]) for o in shared_keys if d1[o] != d2[o]}
modified = set(modified.keys())
modified = list(modified)
same = set(o for o in shared_keys if d1[o] == d2[o])
same = list(same)
return added, removed, modified, same
def make_log_file(log_file_path, content, mode="APPEND"):
if mode == "REPLACE":
if os.path.exists(log_file_path):
os.remove(log_file_path)
elif mode == "APPEND":
with open(log_file_path, "a") as f:
f.write(str(content)) # 向文件中写入内容
f.close() # 关闭文件
def read_log_file(log_file_path):
content = None
log = {}
if os.path.exists(log_file_path):
f = open(log_file_path, "r")
for line in f.readlines():
content = line
line_split = string_lib.split(line, " | ")
value = line_split[1].replace("\n", "")
log[line_split[0]] = value
f.close()
content = log
else:
print(log_file_path + " log not exist")
return content
def check_subfolder(file_path, mesh_dir):
mesh_dir = mesh_dir + "/"
subfolder = ""
file_dir = file_path.split(mesh_dir)
if len(file_dir) > 1:
if "/" in file_dir[1]:
file_dir = string_lib.split(
file_dir[1], "/", search_dir=unreal.SearchDir.FROM_END
)[0]
subfolder = "/" + file_dir
return subfolder
def spilt_file_name(file_path):
file_name = file_path.split("/")[-1]
file_name = file_name.split(".")[0]
return file_name
|
"""
查看Unreal Engine中所有可用的菜单
"""
import unreal
def list_menu(num=1000):
menu_list = set()
for i in range(num):
obj = unreal.find_object(None,"/project/.ToolMenus_0:RegisteredMenu_%s" % i)
if not obj:
obj = unreal.find_object(None,f"/project/.ToolMenus_0:ToolMenu_{i}")
if not obj:
continue
menu_name = str(obj.menu_name)
if menu_name == "None":
continue
menu_list.add(menu_name)
return list(menu_list)
print(list_menu())
|
import unreal
from Lib import __lib_topaz__ as topaz
assets = topaz.get_selected_assets()
## execution here ##
for each in assets :
if each.__class__ == unreal.Blueprint :
comps = topaz.get_component_by_class(each, unreal.StaticMeshComponent)
for comp in comps :
static_mesh : unreal.StaticMesh = comp.static_mesh
if static_mesh is not None :
__desired_triangle_percentage__ = 0.1
nanite_settings : unreal.MeshNaniteSettings = static_mesh.get_editor_property('nanite_settings')
nanite_settings.enabled = True
nanite_settings.keep_percent_triangles = __desired_triangle_percentage__
static_mesh.set_editor_property('nanite_settings', nanite_settings)
#print(nanite_settings.keep_percent_triangles)
if each.__class__ == unreal.StaticMesh :
if each is not None :
__desired_triangle_percentage__ = 0.1
nanite_settings : unreal.MeshNaniteSettings = each.get_editor_property('nanite_settings')
nanite_settings.enabled = True
nanite_settings.set_editor_property('keep_percent_triangles', __desired_triangle_percentage__)
each.set_editor_property('nanite_settings', nanite_settings)
print('OK')
|
# -*- 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.getargspec(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 == ''):
# 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
|
from mca.ue import pyunreal as pue
from mca.ue.pyunreal import general
from mca.ue.tools.scripteditor import script_editor_ui
import unreal
reload(script_editor_ui)
reload(script_editor_ui)
reload(pue)
reload(general)
sk_skel = pue.selected()
skel_mesh = sk_skel[0]
print(skel_mesh)
print(skel_mesh.get_class())
print(type(skel_mesh))
# print(skel_mesh.get_class())
# skel_mesh = unreal.SkeletalMesh(skel_mesh)
skel = pue.PySkelMesh(skel_mesh)
print(skel)
print(pue)
print(skel_mesh.get_name())
[print(x) for x in dir(skel_mesh)]
sm_skel = pue.selected()
sm = sm_skel[0]
print(sm.get_name())
|
import unreal
# Get all actors in the current level
actors = unreal.EditorLevelLibrary.get_all_level_actors()
# Dictionary to store unique stencil values per class
class_stencil_map = {}
stencil_counter = 1 # Start stencil values from 1
# Store results for printing
results = []
# Loop through each actor
for actor in actors:
actor_class = actor.get_class().get_name() # Get actor class name
# Assign a new stencil value if class is not in the dictionary
if actor_class not in class_stencil_map:
class_stencil_map[actor_class] = stencil_counter
stencil_counter += 1 # Increment for next class
stencil_value = class_stencil_map[actor_class]
# Get all mesh components in the actor
mesh_components = actor.get_components_by_class(unreal.StaticMeshComponent)
for mesh in mesh_components:
# Enable custom depth rendering
mesh.set_editor_property("render_custom_depth", True)
# Set stencil value based on class
mesh.set_editor_property("custom_depth_stencil_value", stencil_value)
# Store result for this actor
results.append(f"Actor: {actor.get_name()} | Class: {actor_class} | Stencil Value: {stencil_value}")
# Print the final results
print("\n--- Stencil Values Assigned ---")
for res in results:
print(res)
print("\nStencil values updated for all actors!")
|
import unreal
import csv
import os
# Настройки секвенции
SEQUENCE_PATH = "/project/" # Путь к секвенции в UE
FPS = 60 # Кадров в секунду
NUM_LIGHTS = 64 # Количество светильников
FIRST_LIGHT_INDEX = 0 # Начальный индекс светильников
# Получаем абсолютный путь к файлам
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
DMX_PATH = os.path.join(SCRIPT_DIR, "New_Animation.chan") # Путь к исходному DMX файлу
CSV_PATH = os.path.join(SCRIPT_DIR, "New_Animation.csv") # Путь к CSV файлу
INTENSITY_MULTIPLIER = 1300.0 # Множитель интенсивности
def log(message):
"""Вспомогательная функция для логирования"""
unreal.log(f"[DMX Import] {message}")
print(f"[DMX Import] {message}")
def convert_dmx_to_csv(input_file, output_file):
"""Конвертирует DMX файл в CSV формат"""
log(f"Converting DMX file: {input_file} -> {output_file}")
# Читаем входной файл
with open(input_file, 'r') as f:
lines = f.readlines()
# Подготавливаем заголовки для CSV
headers = ['frame'] + [f'light_{i}' for i in range(64)] # Добавляем столбец frame
# Открываем выходной CSV файл
with open(output_file, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(headers) # Записываем заголовки
# Обрабатываем каждую строку
frame_number = 0 # Счетчик кадров
for line in lines:
# Пропускаем комментарии и пустые строки
if line.startswith('#') or not line.strip():
continue
# Разбиваем строку на значения
values = line.strip().split()
# Конвертируем значения из 0-255 в 0-1
normalized_values = [float(val) / 255.0 for val in values]
# Добавляем номер кадра в начало строки
row_data = [frame_number] + normalized_values
# Записываем данные в CSV
writer.writerow(row_data)
frame_number += 1 # Увеличиваем счетчик кадров
log(f"Conversion completed! Created {frame_number} frames")
def import_dmx_to_sequencer():
log("Starting DMX import process...")
# Проверяем, нужно ли конвертировать DMX файл
if not os.path.exists(CSV_PATH) or os.path.getmtime(DMX_PATH) > os.path.getmtime(CSV_PATH):
log("CSV file doesn't exist or DMX file is newer. Converting...")
if not os.path.exists(DMX_PATH):
log(f"ERROR: DMX file not found: {DMX_PATH}")
return None
convert_dmx_to_csv(DMX_PATH, CSV_PATH)
else:
log("Using existing CSV file")
log(f"CSV file path: {CSV_PATH}")
# Загружаем или создаем секвенцию
log("Loading or creating sequence...")
sequence = unreal.load_asset(SEQUENCE_PATH, unreal.LevelSequence)
if not sequence:
log(f"Sequence not found at {SEQUENCE_PATH}, creating new one...")
sequence = unreal.AssetToolsHelpers.get_asset_tools().create_asset(
SEQUENCE_PATH.split('/')[-1],
'/'.join(SEQUENCE_PATH.split('/')[:-1]),
unreal.LevelSequence,
unreal.LevelSequenceFactoryNew()
)
log("Sequence ready")
# Читаем CSV файл
log("Reading CSV file...")
with open(CSV_PATH, 'r') as f:
csv_reader = csv.reader(f)
# Читаем заголовок и создаём карту <имя_колонки -> индекс>
headers = next(csv_reader)
header_indices = {h: idx for idx, h in enumerate(headers)}
log(f"CSV headers detected: {headers}")
# Считываем все оставшиеся строки как данные кадров
frame_data = list(csv_reader)
total_frames = len(frame_data)
duration_seconds = total_frames / FPS
log(f"Read {total_frames} frames from CSV")
log(f"Animation duration will be {duration_seconds:.2f} seconds at {FPS} FPS")
# Получаем все Spot Light актеры в сцене
log("Getting editor subsystem...")
world = unreal.EditorLevelLibrary.get_editor_world()
log("Getting actors from level...")
try:
log("Getting all actors...")
all_actors = unreal.GameplayStatics.get_all_actors_of_class(world, unreal.SpotLight)
log(f"Found {len(all_actors)} spot lights")
except Exception as e:
log(f"Error getting actors: {str(e)}")
return None
spot_lights = {}
# Находим все Spot Light актеры и сохраняем их в словарь
log("Processing found actors...")
for actor in all_actors:
log(f"Processing actor: {actor.get_name()}")
for i in range(NUM_LIGHTS):
if actor.get_name() == f"SpotLight_{i}":
spot_lights[i] = actor
log(f"Matched SpotLight_{i}")
log(f"Found {len(spot_lights)} matching spot lights in the scene")
if not spot_lights:
log("No matching spot lights found! Make sure you have SpotLight_0 through SpotLight_63 in your scene")
return None
# Устанавливаем частоту кадров для секвенции
log(f"Setting sequence frame rate to {FPS} fps...")
sequence.set_display_rate(unreal.FrameRate(FPS, 1))
# Для каждого светильника создаем binding и track в секвенции
log("Creating animation tracks...")
total_lights = len(spot_lights)
for light_idx, (light_index, light_actor) in enumerate(spot_lights.items(), 1):
log(f"Processing SpotLight_{light_index} ({light_idx}/{total_lights})...")
try:
# Получаем LightComponent из актёра
light_component = light_actor.get_component_by_class(unreal.LightComponent)
if not light_component:
log(f"No LightComponent found for SpotLight_{light_index}")
continue
# Получаем имя компонента
component_name = light_component.get_name()
log(f"Found light component: {component_name}")
# Попробуем создать binding для компонента напрямую
try:
# Вариант 1: Binding для компонента
binding = sequence.add_possessable(light_component)
property_path = "Intensity"
log(f"Created component binding for {component_name}")
except:
# Вариант 2: Binding для актёра с путём к компоненту
binding = sequence.add_possessable(light_actor)
property_path = f"{component_name}.Intensity"
log(f"Created actor binding, will use path: {property_path}")
log(f"Created binding for SpotLight_{light_index}")
# Создаём трек для свойства Intensity
intensity_track = binding.add_track(unreal.MovieSceneFloatTrack)
intensity_track.set_property_name_and_path("Intensity", property_path)
log(f"Created intensity track with path: {property_path}")
# Создаем секцию для трека
intensity_section = intensity_track.add_section()
# Получаем канал через правильный метод
channels = intensity_section.get_all_channels()
if not channels:
log(f"No channels found for SpotLight_{light_index}")
continue
intensity_channel = channels[0]
log(f"Got channel for SpotLight_{light_index}")
# Добавляем ключи для каждого кадра
log(f"Adding {total_frames} keyframes for SpotLight_{light_index}...")
frames_processed = 0
for frame_num, frame_values in enumerate(frame_data):
try:
# Получаем значение яркости для текущего светильника (0-1)
column_name = f"light_{light_index}"
if column_name not in header_indices:
# Если в CSV нет соответствующей колонки, пропускаем
continue
brightness_idx = header_indices[column_name]
if brightness_idx >= len(frame_values):
continue
brightness = float(frame_values[brightness_idx])
# Создаем ключ на текущем кадре
frame_time = unreal.FrameNumber(frame_num)
intensity_channel.add_key(
frame_time,
brightness * INTENSITY_MULTIPLIER,
0.0,
unreal.MovieSceneTimeUnit.DISPLAY_RATE
)
frames_processed += 1
# Показываем прогресс каждые 100 кадров
if frames_processed % 100 == 0:
log(f"Progress for SpotLight_{light_index}: {frames_processed}/{total_frames} frames")
except Exception as e:
log(f"Error adding keyframe {frame_num} for SpotLight_{light_index}: {str(e)}")
continue
log(f"Finished adding {frames_processed} keyframes for SpotLight_{light_index}")
except Exception as e:
log(f"Error processing SpotLight_{light_index}: {str(e)}")
continue
log(f"Import completed! Created {total_frames} frames for {len(spot_lights)} lights")
log(f"Total animation duration: {duration_seconds:.2f} seconds")
return sequence
if __name__ == '__main__':
import_dmx_to_sequencer()
|
# 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 math
import unreal
@unreal.uclass()
class CurveInputExample(unreal.PlacedEditorUtilityBase):
# Use a FProperty to hold the reference to the API wrapper we create in
# run_curve_input_example
_asset_wrapper = unreal.uproperty(unreal.HoudiniPublicAPIAssetWrapper)
@unreal.ufunction(meta=dict(BlueprintCallable=True, CallInEditor=True))
def run_curve_input_example(self):
# Get the API instance
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
# Ensure we have a running session
if not api.is_session_valid():
api.create_session()
# Load our HDA uasset
example_hda = unreal.load_object(None, '/project/.copy_to_curve_1_0')
# Create an API wrapper instance for instantiating the HDA and interacting with it
wrapper = api.instantiate_asset(example_hda, instantiate_at=unreal.Transform())
if wrapper:
# Pre-instantiation is the earliest point where we can set parameter values
wrapper.on_pre_instantiation_delegate.add_function(self, '_set_initial_parameter_values')
# Jumping ahead a bit: we also want to configure inputs, but inputs are only available after instantiation
wrapper.on_post_instantiation_delegate.add_function(self, '_set_inputs')
# Jumping ahead a bit: we also want to print the outputs after the node has cook and the plug-in has processed the output
wrapper.on_post_processing_delegate.add_function(self, '_print_outputs')
self.set_editor_property('_asset_wrapper', wrapper)
@unreal.ufunction(params=[unreal.HoudiniPublicAPIAssetWrapper], meta=dict(CallInEditor=True))
def _set_initial_parameter_values(self, in_wrapper):
""" Set our initial parameter values: disable upvectorstart and set the scale to 0.2. """
# Uncheck the upvectoratstart parameter
in_wrapper.set_bool_parameter_value('upvectoratstart', False)
# Set the scale to 0.2
in_wrapper.set_float_parameter_value('scale', 0.2)
# Since we are done with setting the initial values, we can unbind from the delegate
in_wrapper.on_pre_instantiation_delegate.remove_function(self, '_set_initial_parameter_values')
@unreal.ufunction(params=[unreal.HoudiniPublicAPIAssetWrapper], meta=dict(CallInEditor=True))
def _set_inputs(self, in_wrapper):
""" Configure our inputs: input 0 is a cube and input 1 a helix. """
# Create an empty geometry input
geo_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPIGeoInput)
# Load the cube static mesh asset
cube = unreal.load_object(None, '/project/.Cube')
# Set the input object array for our geometry input, in this case containing only the cube
geo_input.set_input_objects((cube, ))
# Set the input on the instantiated HDA via the wrapper
in_wrapper.set_input_at_index(0, geo_input)
# 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)
# 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)
# unbind from the delegate, since we are done with setting inputs
in_wrapper.on_post_instantiation_delegate.remove_function(self, '_set_inputs')
@unreal.ufunction(params=[unreal.HoudiniPublicAPIAssetWrapper], meta=dict(CallInEditor=True))
def _print_outputs(self, in_wrapper):
""" Print the outputs that were generated by the HDA (after a cook) """
num_outputs = in_wrapper.get_num_outputs()
print('num_outputs: {}'.format(num_outputs))
if num_outputs > 0:
for output_idx in range(num_outputs):
identifiers = in_wrapper.get_output_identifiers_at(output_idx)
print('\toutput index: {}'.format(output_idx))
print('\toutput type: {}'.format(in_wrapper.get_output_type_at(output_idx)))
print('\tnum_output_objects: {}'.format(len(identifiers)))
if identifiers:
for identifier in identifiers:
output_object = in_wrapper.get_output_object_at(output_idx, identifier)
output_component = in_wrapper.get_output_component_at(output_idx, identifier)
is_proxy = in_wrapper.is_output_current_proxy_at(output_idx, identifier)
print('\t\tidentifier: {}'.format(identifier))
print('\t\toutput_object: {}'.format(output_object.get_name() if output_object else 'None'))
print('\t\toutput_component: {}'.format(output_component.get_name() if output_component else 'None'))
print('\t\tis_proxy: {}'.format(is_proxy))
print('')
def run():
# Spawn CurveInputExample and call run_curve_input_example
curve_input_example_actor = unreal.EditorLevelLibrary.spawn_actor_from_class(CurveInputExample.static_class(), unreal.Vector.ZERO, unreal.Rotator())
curve_input_example_actor.run_curve_input_example()
if __name__ == '__main__':
run()
|
# coding: utf-8
import unreal
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-vrm")
parser.add_argument("-rig")
parser.add_argument("-meta")
args = parser.parse_args()
print(args.vrm)
#print(dummy[3])
humanoidBoneList = [
"hips",
"leftUpperLeg",
"rightUpperLeg",
"leftLowerLeg",
"rightLowerLeg",
"leftFoot",
"rightFoot",
"spine",
"chest",
"upperChest", # 9 optional
"neck",
"head",
"leftShoulder",
"rightShoulder",
"leftUpperArm",
"rightUpperArm",
"leftLowerArm",
"rightLowerArm",
"leftHand",
"rightHand",
"leftToes",
"rightToes",
"leftEye",
"rightEye",
"jaw",
"leftThumbProximal", # 24
"leftThumbIntermediate",
"leftThumbDistal",
"leftIndexProximal",
"leftIndexIntermediate",
"leftIndexDistal",
"leftMiddleProximal",
"leftMiddleIntermediate",
"leftMiddleDistal",
"leftRingProximal",
"leftRingIntermediate",
"leftRingDistal",
"leftLittleProximal",
"leftLittleIntermediate",
"leftLittleDistal",
"rightThumbProximal",
"rightThumbIntermediate",
"rightThumbDistal",
"rightIndexProximal",
"rightIndexIntermediate",
"rightIndexDistal",
"rightMiddleProximal",
"rightMiddleIntermediate",
"rightMiddleDistal",
"rightRingProximal",
"rightRingIntermediate",
"rightRingDistal",
"rightLittleProximal",
"rightLittleIntermediate",
"rightLittleDistal", #54
]
humanoidBoneParentList = [
"", #"hips",
"hips",#"leftUpperLeg",
"hips",#"rightUpperLeg",
"leftUpperLeg",#"leftLowerLeg",
"rightUpperLeg",#"rightLowerLeg",
"leftLowerLeg",#"leftFoot",
"rightLowerLeg",#"rightFoot",
"hips",#"spine",
"spine",#"chest",
"chest",#"upperChest" 9 optional
"chest",#"neck",
"neck",#"head",
"chest",#"leftShoulder", # <-- upper..
"chest",#"rightShoulder",
"leftShoulder",#"leftUpperArm",
"rightShoulder",#"rightUpperArm",
"leftUpperArm",#"leftLowerArm",
"rightUpperArm",#"rightLowerArm",
"leftLowerArm",#"leftHand",
"rightLowerArm",#"rightHand",
"leftFoot",#"leftToes",
"rightFoot",#"rightToes",
"head",#"leftEye",
"head",#"rightEye",
"head",#"jaw",
"leftHand",#"leftThumbProximal",
"leftThumbProximal",#"leftThumbIntermediate",
"leftThumbIntermediate",#"leftThumbDistal",
"leftHand",#"leftIndexProximal",
"leftIndexProximal",#"leftIndexIntermediate",
"leftIndexIntermediate",#"leftIndexDistal",
"leftHand",#"leftMiddleProximal",
"leftMiddleProximal",#"leftMiddleIntermediate",
"leftMiddleIntermediate",#"leftMiddleDistal",
"leftHand",#"leftRingProximal",
"leftRingProximal",#"leftRingIntermediate",
"leftRingIntermediate",#"leftRingDistal",
"leftHand",#"leftLittleProximal",
"leftLittleProximal",#"leftLittleIntermediate",
"leftLittleIntermediate",#"leftLittleDistal",
"rightHand",#"rightThumbProximal",
"rightThumbProximal",#"rightThumbIntermediate",
"rightThumbIntermediate",#"rightThumbDistal",
"rightHand",#"rightIndexProximal",
"rightIndexProximal",#"rightIndexIntermediate",
"rightIndexIntermediate",#"rightIndexDistal",
"rightHand",#"rightMiddleProximal",
"rightMiddleProximal",#"rightMiddleIntermediate",
"rightMiddleIntermediate",#"rightMiddleDistal",
"rightHand",#"rightRingProximal",
"rightRingProximal",#"rightRingIntermediate",
"rightRingIntermediate",#"rightRingDistal",
"rightHand",#"rightLittleProximal",
"rightLittleProximal",#"rightLittleIntermediate",
"rightLittleIntermediate",#"rightLittleDistal",
]
for i in range(len(humanoidBoneList)):
humanoidBoneList[i] = humanoidBoneList[i].lower()
for i in range(len(humanoidBoneParentList)):
humanoidBoneParentList[i] = humanoidBoneParentList[i].lower()
######
reg = unreal.AssetRegistryHelpers.get_asset_registry();
##
rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints()
print(rigs)
for r in rigs:
s:str = r.get_path_name()
ss:str = args.rig
if (s.find(ss) < 0):
print("no rig")
else:
rig = r
#rig = rigs[10]
h_mod = rig.get_hierarchy_modifier()
#elements = h_mod.get_selection()
#sk = rig.get_preview_mesh()
#k = sk.skeleton
#print(k)
#print(sk.bone_tree)
#
#kk = unreal.RigElementKey(unreal.RigElementType.BONE, "hipssss");
#kk.name = ""
#kk.type = 1;
#print(h_mod.get_bone(kk))
#print(h_mod.get_elements())
### 全ての骨
modelBoneListAll = []
modelBoneNameList = []
#for e in reversed(h_mod.get_elements()):
# if (e.type != unreal.RigElementType.BONE):
# h_mod.remove_element(e)
for e in h_mod.get_elements():
if (e.type == unreal.RigElementType.BONE):
modelBoneListAll.append(e)
modelBoneNameList.append("{}".format(e.name).lower())
# else:
# h_mod.remove_element(e)
print(modelBoneListAll[0])
#exit
#print(k.get_editor_property("bone_tree")[0].get_editor_property("translation_retargeting_mode"))
#print(k.get_editor_property("bone_tree")[0].get_editor_property("parent_index"))
#unreal.select
#vrmlist = unreal.VrmAssetListObject
#vrmmeta = vrmlist.vrm_meta_object
#print(vrmmeta.humanoid_bone_table)
#selected_actors = unreal.EditorLevelLibrary.get_selected_level_actors()
#selected_static_mesh_actors = unreal.EditorFilterLibrary.by_class(selected_actors,unreal.StaticMeshActor.static_class())
#static_meshes = np.array([])
## meta 取得
reg = unreal.AssetRegistryHelpers.get_asset_registry();
a = reg.get_all_assets();
if (args.meta):
for aa in a:
if (aa.get_editor_property("object_path") == args.meta):
v:unreal.VrmMetaObject = aa
vv = aa.get_asset()
if (vv == None):
for aa in a:
if (aa.get_editor_property("object_path") == args.vrm):
v:unreal.VrmAssetListObject = aa
vv = v.get_asset().vrm_meta_object
print(vv)
meta = vv
#v:unreal.VrmAssetListObject = None
#if (True):
# a = reg.get_assets_by_path(args.vrm)
# a = reg.get_all_assets();
# for aa in a:
# if (aa.get_editor_property("object_path") == args.vrm):
# v:unreal.VrmAssetListObject = aa
#v = unreal.VrmAssetListObject.cast(v)
#print(v)
#unreal.VrmAssetListObject.vrm_meta_object
#meta = v.vrm_meta_object()
#meta = unreal.EditorFilterLibrary.by_class(asset,unreal.VrmMetaObject.static_class())
print (meta)
#print(meta[0].humanoid_bone_table)
### モデル骨のうち、ヒューマノイドと同じもの
### 上の変換テーブル
humanoidBoneToModel = {"" : ""}
humanoidBoneToModel.clear()
### modelBoneでループ
#for bone_h in meta.humanoid_bone_table:
for bone_h_base in humanoidBoneList:
bone_h = None
for e in meta.humanoid_bone_table:
if ("{}".format(e).lower() == bone_h_base):
bone_h = e;
break;
print("{}".format(bone_h))
if (bone_h==None):
continue
bone_m = meta.humanoid_bone_table[bone_h]
try:
i = modelBoneNameList.index(bone_m.lower())
except:
i = -1
if (i < 0):
continue
if ("{}".format(bone_h).lower() == "upperchest"):
continue;
humanoidBoneToModel["{}".format(bone_h).lower()] = "{}".format(bone_m).lower()
if ("{}".format(bone_h).lower() == "chest"):
#upperchestがあれば、これの次に追加
bh = 'upperchest'
print("upperchest: check begin")
for e in meta.humanoid_bone_table:
if ("{}".format(e).lower() != 'upperchest'):
continue
bm = "{}".format(meta.humanoid_bone_table[e]).lower()
if (bm == ''):
continue
humanoidBoneToModel[bh] = bm
humanoidBoneParentList[10] = "upperchest"
humanoidBoneParentList[12] = "upperchest"
humanoidBoneParentList[13] = "upperchest"
print("upperchest: find and insert parent")
break
print("upperchest: check end")
parent=None
control_to_mat={None:None}
count = 0
### 骨名からControlへのテーブル
name_to_control = {"dummy_for_table" : None}
print("loop begin")
###### root
key = unreal.RigElementKey(unreal.RigElementType.SPACE, 'root_s')
space = h_mod.get_space(key)
if (space.get_editor_property('index') < 0):
space = h_mod.add_space('root_s', space_type=unreal.RigSpaceType.SPACE)
else:
space = key
key = unreal.RigElementKey(unreal.RigElementType.CONTROL, 'root_c')
control = h_mod.get_control(key)
if (control.get_editor_property('index') < 0):
control = h_mod.add_control('root_c',
space_name=space.name,
gizmo_color=[1.0, 0.0, 0.0, 1.0],
)
else:
control = key
h_mod.reparent_element(control, space)
parent = control
cc = h_mod.get_control(control)
cc.set_editor_property('gizmo_visible', False)
h_mod.set_control(cc)
for ee in humanoidBoneToModel:
element = humanoidBoneToModel[ee]
humanoidBone = ee
modelBoneNameSmall = element
# 対象の骨
#modelBoneNameSmall = "{}".format(element.name).lower()
#humanoidBone = modelBoneToHumanoid[modelBoneNameSmall];
boneNo = humanoidBoneList.index(humanoidBone)
print("{}_{}_{}__parent={}".format(modelBoneNameSmall, humanoidBone, boneNo,humanoidBoneParentList[boneNo]))
# 親
if count != 0:
parent = name_to_control[humanoidBoneParentList[boneNo]]
# 階層作成
bIsNew = False
name_s = "{}_s".format(humanoidBone)
key = unreal.RigElementKey(unreal.RigElementType.SPACE, name_s)
space = h_mod.get_space(key)
if (space.get_editor_property('index') < 0):
space = h_mod.add_space(name_s, space_type=unreal.RigSpaceType.SPACE)
bIsNew = True
else:
space = key
name_c = "{}_c".format(humanoidBone)
key = unreal.RigElementKey(unreal.RigElementType.CONTROL, name_c)
control = h_mod.get_control(key)
if (control.get_editor_property('index') < 0):
control = h_mod.add_control(name_c,
space_name=space.name,
gizmo_color=[1.0, 0.0, 0.0, 1.0],
)
#h_mod.get_control(control).gizmo_transform = gizmo_trans
if (24<=boneNo & boneNo<=53):
gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.1, 0.1, 0.1])
else:
gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1, 1, 1])
if (17<=boneNo & boneNo<=18):
gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1, 1, 1])
cc = h_mod.get_control(control)
cc.set_editor_property('gizmo_transform', gizmo_trans)
cc.set_editor_property('control_type', unreal.RigControlType.ROTATOR)
h_mod.set_control(cc)
#h_mod.set_control_value_transform(control,gizmo_trans)
bIsNew = True
else:
control = key
if (bIsNew == True):
h_mod.reparent_element(control, space)
# テーブル登録
name_to_control[humanoidBone] = control
print(humanoidBone)
# ロケータ 座標更新
# 不要な上層階層を考慮
gTransform = h_mod.get_global_transform(modelBoneListAll[modelBoneNameList.index(modelBoneNameSmall)])
if count == 0:
bone_initial_transform = gTransform
else:
#bone_initial_transform = h_mod.get_initial_transform(element)
bone_initial_transform = gTransform.multiply(control_to_mat[parent].inverse())
h_mod.set_initial_transform(space, bone_initial_transform)
control_to_mat[control] = gTransform
# 階層修正
h_mod.reparent_element(space, parent)
count += 1
if (count >= 500):
break
|
# -*- coding: utf-8 -*-
import unreal
import os
from Utilities.Utils import Singleton
from Utilities.Utils import cast
import Utilities
import QueryTools
import re
import types
import collections
from .import Utils
global _r
COLUMN_COUNT = 2
class DetailData(object):
def __init__(self):
self.filter_str = ""
self.filteredIndexToIndex = []
self.hisCrumbObjsAndNames = [] #list[(obj, propertyName)]
self.attributes = None
self.filtered_attributes = None
self.plains = []
self.riches = []
self.selected = set()
def check_line_id(self, line_id, column_count):
from_line = line_id * column_count
to_line = (line_id + 1) * column_count
assert len(self.plains) == len(self.riches), "len(self.plains) != len(self.riches)"
if 0 <= from_line < len(self.plains) and 0 <= to_line <= len(self.plains):
return True
else:
unreal.log_error(f"Check Line Id Failed: {line_id}, plains: {len(self.plains)}, rich: {len(self.riches)}")
return False
def get_plain(self, line_id, column_count):
assert self.check_line_id(line_id, column_count), "check line id failed."
return self.plains[line_id * 2 : line_id * 2 + 2]
def get_rich(self, line_id, column_count):
assert self.check_line_id(line_id, column_count), "check line id failed."
return self.riches[line_id * 2: line_id * 2 + 2]
class ObjectDetailViewer(metaclass=Singleton):
def __init__(self, jsonPath):
self.jsonPath = jsonPath
self.data = unreal.PythonBPLib.get_chameleon_data(self.jsonPath)
self.ui_checkbox_single_mode = "CheckBoxSingleMode"
self.ui_checkbox_compare_mode = "CheckBoxCompareMode"
self.ui_left_group = "LeftDetailGroup"
self.ui_right_group = "RightDetailGroup"
self.ui_button_refresh = "RefreshCompareButton"
self.ui_detailListLeft = "ListViewLeft"
self.ui_detailListRight = "ListViewRight"
self.ui_hisObjsBreadcrumbLeft = 'ObjectHisBreadcrumbLeft'
self.ui_hisObjsBreadcrumbRight = 'ObjectHisBreadcrumbRight'
# self.ui_headRowLeft = "HeaderRowLeft"
# self.ui_headRowRight = "HeaderRowRight"
self.ui_labelLeft = "LabelLeft"
self.ui_labelRight = "LabelRight"
self.ui_info_output = "InfoOutput"
self.ui_rightButtonsGroup = "RightButtonsGroup" # used for compare mode
self.ui_rightListGroup = "RightListGroup"
self.ui_refreshButtonGroup = "RefreshButtonGroup"
self.reset()
def on_close(self):
self.reset()
def on_map_changed(self, map_change_type_str):
# remove the reference, avoid memory leaking when load another map.
if map_change_type_str == "TearDownWorld":
self.reset(bResetParameter=False)
else:
pass # skip: LoadMap, SaveMap, NewMap
def reset(self, bResetParameter=True):
if bResetParameter:
self.showBuiltin = True
self.showOther = True
self.showProperties = True
self.showEditorProperties = True
self.showParamFunction = True
self.compareMode = False
self.left = None
self.right = None
self.leftSearchText = ""
self.rightSearchText = ""
self.left_rich = None
self.left_plain = None
self.var = None
self.diff_count = 0
self.clear_ui_info()
def clear_ui_info(self):
for text_ui in [self.ui_info_output, self.ui_labelLeft, self.ui_labelRight]:
self.data.set_text(text_ui, "")
self.data.set_list_view_multi_column_items(self.ui_detailListLeft, [], 2)
self.data.set_list_view_multi_column_items(self.ui_detailListRight, [], 2)
for ui_breadcrumb in [self.ui_hisObjsBreadcrumbRight, self.ui_hisObjsBreadcrumbLeft]:
crumbCount = self.data.get_breadcrumbs_count_string(ui_breadcrumb)
for i in range(crumbCount):
self.data.pop_breadcrumb_string(ui_breadcrumb)
def update_log_text(self, bRight):
bShowRight = self.compareMode
result = ""
for side_str in ["left", "right"] if bShowRight else ["left"]:
bRight = side_str != "left"
ui_breadcrumb = self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft
breadcrumbs = self.right.hisCrumbObjsAndNames if bRight else self.left.hisCrumbObjsAndNames
crumbCount = self.data.get_breadcrumbs_count_string(ui_breadcrumb)
if bRight:
result += "\t\t\t"
result += "{} crumb: {} hisObj: {}".format(side_str, crumbCount, len(breadcrumbs))
if self.compareMode:
result = f"{result}\t\t\tdiff count: {self.diff_count}"
self.data.set_text(self.ui_info_output, result)
def get_color_by(self, attr : Utils.attr_detail):
if attr.bCallable_builtin:
return "DarkTurquoise".lower()
if attr.bCallable_other:
return "RoyalBlue".lower()
if attr.bEditorProperty:
return "LimeGreen".lower()
if attr.bOtherProperty:
return "yellow"
def get_color(self, typeStr):
if typeStr == "property":
return 'white'
if typeStr == "return_type":
return 'gray'
if typeStr == "param":
return 'gray'
def get_name_with_rich_text(self, attr:Utils.attr_detail):
name_color = self.get_color_by(attr)
param_color = self.get_color("param")
return_type_color = self.get_color("return_type")
if attr.bProperty:
return "\t<RichText.{}>{}</>".format(name_color, attr.name)
else:
if attr.param_str:
return "\t<RichText.{}>{}(</><RichText.{}>{}</><RichText.{}>)</>".format(name_color, attr.name
, param_color, attr.param_str
, name_color)
else:
if attr.bCallable_other:
return "\t<RichText.{}>{}</>".format(name_color, attr.name)
else:
return "\t<RichText.{}>{}()</><RichText.{}> {}</>".format(name_color, attr.name
, return_type_color, attr.return_type_str)
def get_name_with_plain_text(self, attr:Utils.attr_detail):
if attr.bProperty:
return "\t{}".format(attr.name)
else:
if attr.param_str:
return "\t{}({})".format( attr.name, attr.param_str)
else:
if attr.bCallable_other:
return "\t{}".format( attr.name)
else:
return "\t{}() {}".format(attr.name,attr.return_type_str)
def filter(self, data:DetailData):
result = []
indices = []
for i, attr in enumerate(data.attributes):
if not self.showEditorProperties and attr.bEditorProperty:
continue
if not self.showProperties and attr.bOtherProperty:
continue
if not self.showParamFunction and attr.bHasParamFunction:
continue
if not self.showBuiltin and attr.bCallable_builtin:
continue
if not self.showOther and attr.bCallable_other:
continue
if data.filter_str:
if data.filter_str.lower() not in attr.display_result.lower() and data.filter_str not in attr.display_name.lower() :
continue
result.append(attr)
indices.append(i)
return result, indices
def show_data(self, data:DetailData, ui_listView):
flatten_list_items = []
flatten_list_items_plain = []
for i, attr in enumerate(data.filtered_attributes):
# print(f"{i}: {attr.name} {attr.display_name}, {attr.display_result} ")
attr.check()
assert attr.display_name, f"display name null {attr.display_name}"
assert isinstance(attr.display_result, str), f"display result null {attr.display_result}"
result_str = attr.display_result
if len(result_str) > 200:
result_str = result_str[:200] + "......"
flatten_list_items.extend([self.get_name_with_rich_text(attr), result_str])
flatten_list_items_plain.extend([self.get_name_with_plain_text(attr), result_str])
data.riches = flatten_list_items
data.plains = flatten_list_items_plain
data.selected.clear()
self.data.set_list_view_multi_column_items(ui_listView, flatten_list_items, 2)
def query_and_push(self, obj, propertyName, bPush, bRight): #bPush: whether add Breadcrumb nor not, call by property
if bRight:
ui_Label = self.ui_labelRight
ui_listView = self.ui_detailListRight
ui_breadcrumb = self.ui_hisObjsBreadcrumbRight
else:
ui_Label = self.ui_labelLeft
ui_listView = self.ui_detailListLeft
ui_breadcrumb = self.ui_hisObjsBreadcrumbLeft
data = self.right if bRight else self.left
data.attributes = Utils.ll(obj)
data.filtered_attributes, data.filteredIndexToIndex = self.filter(data)
self.show_data(data, ui_listView)
# set breadcrumb
if propertyName and len(propertyName) > 0:
label = propertyName
else:
if isinstance(obj, unreal.Object):
label = obj.get_name()
else:
try:
label = obj.__str__()
except TypeError:
label = f"{obj}"
if bPush: # push
# print(f"%%% push: {propertyName}, label {label}")
data.hisCrumbObjsAndNames.append((obj, propertyName))
self.data.push_breadcrumb_string(ui_breadcrumb, label, label)
self.data.set_text(ui_Label, "{} type: {}".format(label, type(obj)) )
crumbCount = self.data.get_breadcrumbs_count_string(ui_breadcrumb)
if bRight:
assert len(self.right.hisCrumbObjsAndNames) == crumbCount, "hisCrumbObjsAndNames count not match {} {}".format(len(self.right.hisCrumbObjsAndNames), crumbCount)
else:
assert len(self.left.hisCrumbObjsAndNames) == crumbCount, "hisCrumbObjsAndNames count not match {} {}".format(len(self.left.hisCrumbObjsAndNames), crumbCount)
self.update_log_text(bRight)
def clear_and_query(self, obj, bRight):
# first time query
self.data.clear_breadcrumbs_string(self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft)
if not self.right:
self.right = DetailData()
if not self.left:
self.left = DetailData()
data = self.right if bRight else self.left
data.hisCrumbObjsAndNames = [] #clear his-Object at first time query
if bRight:
assert len(self.right.hisCrumbObjsAndNames) == 0, "len(self.right.hisCrumbObjsAndNames) != 0"
else:
assert len(self.left.hisCrumbObjsAndNames) == 0, "len(self.left.hisCrumbObjsAndNames) != 0"
self.query_and_push(obj, "", bPush=True, bRight= bRight)
self.apply_compare_if_needed()
self.update_log_text(bRight)
def update_ui_by_mode(self):
self.data.set_is_checked(self.ui_checkbox_compare_mode, self.compareMode)
self.data.set_is_checked(self.ui_checkbox_single_mode, not self.compareMode)
bCollapsed = not self.compareMode
self.data.set_collapsed(self.ui_rightButtonsGroup, bCollapsed)
self.data.set_collapsed(self.ui_right_group, bCollapsed)
self.data.set_collapsed(self.ui_button_refresh, bCollapsed)
def on_checkbox_SingleMode_Click(self, state):
self.compareMode = False
self.update_ui_by_mode()
def on_checkbox_CompareMode_Click(self, state):
self.compareMode = True
self.update_ui_by_mode()
def on_button_Refresh_click(self):
self.apply_compare_if_needed()
def on_button_SelectAsset_click(self, bRightSide):
selectedAssets = Utilities.Utils.get_selected_assets()
if len(selectedAssets) == 0:
return
self.clear_and_query(selectedAssets[0], bRightSide)
def on_button_QuerySelected_click(self, bRightSide):
# query component when any component was selected, otherwise actor
obj = Utilities.Utils.get_selected_comp()
if not obj:
obj = Utilities.Utils.get_selected_actor()
if obj:
self.clear_and_query(obj, bRightSide)
def on_drop(self, bRightSide, *args, **kwargs):
if "assets" in kwargs and kwargs["assets"]:
asset = unreal.load_asset(kwargs["assets"][0])
if asset:
self.clear_and_query(asset, bRightSide)
return
if "actors" in kwargs and kwargs["actors"]:
actor = unreal.PythonBPLib.find_actor_by_name(kwargs["actors"][0], unreal.EditorLevelLibrary.get_editor_world())
if actor:
print(actor)
self.clear_and_query(actor, bRightSide)
return
item_count = 0
for k, v in kwargs.items():
item_count += len(v)
if item_count == 0:
selected_comp = Utilities.Utils.get_selected_comp()
if selected_comp:
self.clear_and_query(selected_comp, bRightSide)
def log_r_warning(self):
unreal.log_warning("Assign the global var: '_r' with the MenuItem: 'select X --> _r' on Python Icon menu")
def on_button_Query_R_click(self, r_obj, bRightSide=False):
print("on_button_Query_R_click call")
if not r_obj:
return
self.clear_and_query(r_obj, bRightSide)
def on_list_double_click_do(self, index, bRight):
# print ("on_listview_DetailList_mouse_button_double_click {} bRight: {}".format(index, bRight))
data = self.right if bRight else self.left
typeBlacklist = [int, float, str, bool] #, types.NotImplementedType]
real_index = data.filteredIndexToIndex[index] if data.filteredIndexToIndex else index
assert 0 <= real_index < len(data.attributes)
currentObj, _ = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames) - 1]
attr_name = data.attributes[real_index].name
objResult, propertyName = self.try_get_object(data, currentObj, attr_name)
if not objResult or objResult is currentObj: # equal
return
if isinstance(objResult, str) and "skip call" in objResult.lower():
return
if type(objResult) in typeBlacklist:
return
if isinstance(objResult, collections.abc.Iterable):
if type(objResult[0]) in typeBlacklist:
return
nextObj = objResult[0]
nextPropertyName = str(propertyName) + "[0]"
else:
nextObj = objResult
nextPropertyName = str(propertyName)
self.query_and_push(nextObj, nextPropertyName, bPush=True, bRight=bRight)
self.apply_compare_if_needed()
self.update_log_text(bRight)
def on_listview_DetailListRight_mouse_button_double_click(self, index):
self.on_list_double_click_do(index, bRight=True)
def on_listview_DetailListLeft_mouse_button_double_click(self, index):
self.on_list_double_click_do(index, bRight=False)
def on_breadcrumbtrail_click_do(self, item, bRight):
ui_hisObjsBreadcrumb = self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft
data = self.right if bRight else self.left
count = self.data.get_breadcrumbs_count_string(ui_hisObjsBreadcrumb)
print ("on_breadcrumbtrail_ObjectHis_crumb_click: {} count: {} len(data.hisCrumbObjsAndNames): {}".format(item, count, len(data.hisCrumbObjsAndNames)))
while len(data.hisCrumbObjsAndNames) > count:
data.hisCrumbObjsAndNames.pop()
nextObj, name = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames) - 1]
if not bRight:
assert self.left.hisCrumbObjsAndNames == data.hisCrumbObjsAndNames, "self.left.hisCrumbObjsAndNames = data.hisCrumbObjsAndNames"
self.query_and_push(nextObj, name, bPush=False, bRight=False)
self.apply_compare_if_needed()
self.update_log_text(bRight=False)
def on_breadcrumbtrail_ObjectHisLeft_crumb_click(self, item):
self.on_breadcrumbtrail_click_do(item, bRight=False)
def on_breadcrumbtrail_ObjectHisRight_crumb_click(self, item):
self.on_breadcrumbtrail_click_do(item, bRight=True)
def remove_address_str(self, strIn):
return re.sub(r'\(0x[0-9,A-F]{16}\)', '', strIn)
def apply_compare_if_needed(self):
if not self.compareMode:
return
lefts = self.left.filtered_attributes if self.left.filtered_attributes else self.left.attributes
rights = self.right.filtered_attributes if self.right.filtered_attributes else self.right.attributes
if not lefts:
lefts = []
if not rights:
rights = []
leftIDs = []
rightIDs = []
for i, left_attr in enumerate(lefts):
for j, right_attr in enumerate(rights):
if right_attr.name == left_attr.name:
if right_attr.result != left_attr.result:
if isinstance(right_attr.result, unreal.Transform):
if right_attr.result.is_near_equal(left_attr.result, location_tolerance=1e-20, rotation_tolerance=1e-20, scale3d_tolerance=1e-20):
continue
leftIDs.append(i)
rightIDs.append(j)
break
self.data.set_list_view_multi_column_selections(self.ui_detailListLeft, leftIDs)
self.data.set_list_view_multi_column_selections(self.ui_detailListRight, rightIDs)
self.diff_count = len(leftIDs)
def apply_search_filter(self, text, bRight):
_data = self.right if bRight else self.left
_data.filter_str = text if len(text) else ""
_data.filtered_attributes, _data.filteredIndexToIndex = self.filter(_data)
ui_listView = self.ui_detailListRight if bRight else self.ui_detailListLeft
self.show_data(_data, ui_listView)
self.apply_compare_if_needed()
def on_searchbox_FilterLeft_text_changed(self, text):
self.apply_search_filter(text if text is not None else "", bRight=False)
def on_searchbox_FilterLeft_text_committed(self, text):
self.apply_search_filter(text if text is not None else "", bRight=False)
def on_searchbox_FilterRight_text_changed(self, text):
self.apply_search_filter(text if text is not None else "", bRight=True)
def on_searchbox_FilterRight_text_committed(self, text):
self.apply_search_filter(text if text is not None else "", bRight=True)
def apply_filter(self):
_datas = [self.left, self.right]
_isRight = [False, True]
for data, bRight in zip(_datas, _isRight):
if len(data.hisCrumbObjsAndNames) > 0:
nextObj, name = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames)-1]
self.query_and_push(nextObj, name, bPush=False, bRight=bRight)
self.apply_compare_if_needed()
self.update_log_text(bRight=False) #
def try_get_object(self, data, obj, name:str):
index = -1
attribute = None
for i, attr in enumerate(data.attributes):
if attr.name == name:
index = i
attribute = attr
assert index >= 0
return attribute.result, name
def ui_on_checkbox_ShowBuiltin_state_changed(self, bEnabled):
self.showBuiltin = bEnabled
self.apply_filter()
def ui_on_checkbox_ShowOther_state_changed(self, bEnabled):
self.showOther = bEnabled
self.apply_filter()
def ui_on_checkbox_ShowProperties_state_changed(self, bEnabled):
self.showProperties = bEnabled
self.apply_filter()
def ui_on_checkbox_ShowEditorProperties_state_changed(self, bEnabled):
self.showEditorProperties = bEnabled
self.apply_filter()
def ui_on_checkbox_ShowParamFunction_state_changed(self, bEnabled):
self.showParamFunction = bEnabled
self.apply_filter()
def ui_on_listview_DetailList_selection_changed(self, bRight):
data = [self.left, self.right][bRight]
list_view = [self.ui_detailListLeft, self.ui_detailListRight][bRight]
selected_indices = set(self.data.get_list_view_multi_column_selection(list_view))
added = selected_indices - data.selected
de_selected = data.selected - selected_indices
for i, lineId in enumerate(added):
self.data.set_list_view_multi_column_line(list_view, lineId, data.get_plain(lineId, column_count=COLUMN_COUNT)
, rebuild_list=True if i == len(added)-1 and len(de_selected) == 0 else False)
for i, lineId in enumerate(de_selected):
self.data.set_list_view_multi_column_line(list_view, lineId, data.get_rich(lineId, column_count=COLUMN_COUNT)
, rebuild_list=True if i == len(de_selected)-1 else False)
data.selected = selected_indices
|
# Copyright (c) <2021> Side Effects Software Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. The name of Side Effects Software may not be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unreal
""" Example script for instantiating an asset, cooking it and baking all of
its outputs.
"""
_g_wrapper = None
def get_test_hda_path():
return '/project/.pig_head_subdivider_v01'
def get_test_hda():
return unreal.load_object(None, get_test_hda_path())
def on_post_instantiation(in_wrapper):
print('on_post_instantiation')
# in_wrapper.on_post_instantiation_state_exited_delegate_delegate.remove_callable(on_post_instantiation)
# Set parameter values for the next cook
# in_wrapper.set_bool_parameter_value('add_instances', True)
# in_wrapper.set_int_parameter_value('num_instances', 8)
in_wrapper.set_parameter_tuples({
'add_instances': unreal.HoudiniParameterTuple(bool_values=(True, )),
'num_instances': unreal.HoudiniParameterTuple(int32_values=(8, )),
})
# Print all parameter values
param_tuples = in_wrapper.get_parameter_tuples()
print('parameter tuples: {}'.format(len(param_tuples) if param_tuples else 0))
if param_tuples:
for param_tuple_name, param_tuple in param_tuples.items():
print('parameter tuple name: {}'.format(param_tuple_name))
print('\tbool_values: {}'.format(param_tuple.bool_values))
print('\tfloat_values: {}'.format(param_tuple.float_values))
print('\tint32_values: {}'.format(param_tuple.int32_values))
print('\tstring_values: {}'.format(param_tuple.string_values))
# Force a cook/recook
in_wrapper.recook()
def on_post_bake(in_wrapper, success):
in_wrapper.on_post_bake_delegate.remove_callable(on_post_bake)
print('bake complete ... {}'.format('success' if success else 'failed'))
# Delete the hda after the bake
in_wrapper.delete_instantiated_asset()
global _g_wrapper
_g_wrapper = None
def on_post_process(in_wrapper):
print('on_post_process')
# in_wrapper.on_post_processing_delegate.remove_callable(on_post_process)
# Print out all outputs generated by the HDA
num_outputs = in_wrapper.get_num_outputs()
print('num_outputs: {}'.format(num_outputs))
if num_outputs > 0:
for output_idx in range(num_outputs):
identifiers = in_wrapper.get_output_identifiers_at(output_idx)
print('\toutput index: {}'.format(output_idx))
print('\toutput type: {}'.format(in_wrapper.get_output_type_at(output_idx)))
print('\tnum_output_objects: {}'.format(len(identifiers)))
if identifiers:
for identifier in identifiers:
output_object = in_wrapper.get_output_object_at(output_idx, identifier)
output_component = in_wrapper.get_output_component_at(output_idx, identifier)
is_proxy = in_wrapper.is_output_current_proxy_at(output_idx, identifier)
print('\t\tidentifier: {}'.format(identifier))
print('\t\toutput_object: {}'.format(output_object.get_name() if output_object else 'None'))
print('\t\toutput_component: {}'.format(output_component.get_name() if output_component else 'None'))
print('\t\tis_proxy: {}'.format(is_proxy))
print('')
# bind to the post bake delegate
in_wrapper.on_post_bake_delegate.add_callable(on_post_bake)
# Bake all outputs to actors
print('baking all outputs to actors')
in_wrapper.bake_all_outputs_with_settings(
unreal.HoudiniEngineBakeOption.TO_ACTOR,
replace_previous_bake=False,
remove_temp_outputs_on_success=False)
def run():
# get the API singleton
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
global _g_wrapper
# instantiate an asset, disabling auto-cook of the asset (so we have to
# call wrapper.reCook() to cook it)
_g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform(), enable_auto_cook=False)
# Bind to the on post instantiation delegate (before the first cook)
_g_wrapper.on_post_instantiation_delegate.add_callable(on_post_instantiation)
# Bind to the on post processing delegate (after a cook and after all
# outputs have been generated in Unreal)
_g_wrapper.on_post_processing_delegate.add_callable(on_post_process)
if __name__ == '__main__':
run()
|
import unreal
import time
current_time = time.time()
editor_actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
actors = editor_actor_subsystem.get_all_level_actors()
camera_actors = {}
for actor in actors:
if "camera" in actor.get_actor_label():
camera_actors[actor.get_actor_label()] = actor
camera_actors['camera0']
cc = camera_actors['camera0'].get_component_by_class(unreal.SceneCaptureComponent2D)
RT = cc.texture_target
cc.set_editor_property("bCaptureEveryFrame", True)
# light_actor.set_actor_location_and_rotation(unreal.Vector(*camera_location_list[i]), unreal.Rotator(*camera_rotation_list[i]), False, False)
folder_path = 'C:/project/'
editor_subsystem = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem)
world = editor_subsystem.get_editor_world()
# cc.capture_scene()
unreal.RenderingLibrary.export_render_target(world, RT, folder_path, f'{current_time}.png')
|
"""Provides base helper functionality for asset processing."""
import unreal
from ...utils.logging_config import logger
from ...utils.constants import SKELETAL_MESH_MAPPING
class BaseHelper:
"""Base helper class for asset processing operations."""
def __init__(self):
"""Initialize the helper with skeletal mesh mappings."""
self.skeletal_mesh_mapping = SKELETAL_MESH_MAPPING
def get_target_skeletal_mesh(self, character_name: str) -> unreal.SkeletalMesh:
"""
Retrieve the skeletal mesh asset for a given character.
Args:
character_name: Name of the character to fetch the mesh for
Returns:
unreal.SkeletalMesh or None: The loaded skeletal mesh asset
"""
try:
mesh_path = self.skeletal_mesh_mapping.get(character_name.lower())
if not mesh_path:
raise ValueError(f"Missing skeletal mesh mapping for: {character_name}")
mesh = unreal.load_asset(mesh_path)
if not mesh:
raise ValueError(f"Unable to load skeletal mesh at: {mesh_path}")
return mesh
except Exception as e:
logger.error(f"Skeletal mesh retrieval failed: {str(e)}")
return None
|
"""
@Author: Ihimu Ukpo
@License: MIT
@Email: user@example.com
@Description: This Python script removes invalid static meshes from actors in an Unreal Engine level.
@Version: 1.0
@Planned future updates: error handling for library opening, etc. Update script (if necessary) to Python 3.
"""
import unreal
# Get instances of unreal libraries necessary.
editor_level_lib = unreal.EditorLevelLibrary()
editor_filter_lib = unreal.EditorFilterLibrary()
# Get all the level actors
level_actors = editor_level_lib.get_all_level_actors()
# Filter the level actors by StaticMeshActor
static_mesh_actors = editor_filter_lib.by_class(level_actors, unreal.StaticMeshActor)
# Count of the number of deleted meshes
deleted_invalid_static_mesh_count = 0
# For each actor in the filtered results...
for actor in static_mesh_actors:
actor_name = actor.get_fname()
# Get the static mesh through the static mesh component
actor_mesh_comp = actor.static_mesh_component
actor_mesh = actor_mesh_comp.static_mesh
is_valid_actor = actor_mesh != None
# If mesh is invalid, destroy it.
if not is_valid_actor:
actor.destroy_actor()
deleted_invalid_static_mesh_count += 1
unreal.log("The Mesh Component of Actor {} is invalid and was deleted".format(actor_name))
unreal.log("Deleted {} Actors with invalid Mesh Component".format(deleted_invalid_static_mesh_count))
|
import unreal
level_lib = unreal.EditorLevelLibrary()
level_subsys = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem)
actor_subsys = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
editor_subsys = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem)
layers_subsys = unreal.get_editor_subsystem(unreal.LayersSubsystem)
subobj_subsys = unreal.get_engine_subsystem(unreal.SubobjectDataSubsystem)
sys_lib = unreal.SystemLibrary()
paths = unreal.Paths
SM_COMPONENT_CLASS = unreal.StaticMeshComponent.static_class()
CURRENT_LEVEL = editor_subsys.get_editor_world()
LOG_DIR = paths.project_log_dir()
selected_actors = actor_subsys.get_selected_level_actors()
all_level_actors = actor_subsys.get_all_level_actors()
LAYER_TICK="Debug_EventTick_Enabled"
def filter_actors_tick(actors):
"""筛选出所有的StaticMeshActor"""
filtered_actors = []
for actor in actors:
#检查是否Blueprint,不检查的话会包含UE自带组件“
is_bp=False
actor_class = actor.get_class()
if "Blueprint" in str(actor_class):
is_bp = True
if is_bp:
layers_subsys.remove_actor_from_layer(actor, LAYER_TICK) #清理上次检查添加的层
has_tick=unreal.Actor.is_actor_tick_enabled(actor)
# child_actors=actor.get_all_child_actors()
# for child in child_actors:
# has_tick=unreal.Actor.is_actor_tick_enabled(child)
if has_tick:
filtered_actors.append(actor)
return filtered_actors
def check_bp_event_tick(actors):
"""检查蓝图是否使用EventTick"""
current_level_path = CURRENT_LEVEL.get_path_name()
current_level_path = current_level_path.split(".")[0]
log_header = (
"BP Actor Event Tick 检查:\n"
+ "蓝图使用 Event Tick会有CPU开销,如非必须请关闭或使用别的实现方式\n"
)
log_header += f"\nCheckLevel: {current_level_path}\n\n"
tick_actors = filter_actors_tick(actors)
log_summary = (f"关卡中有 {len(tick_actors)} 个蓝图开启了 EventTick\n\n")
log_message = ""
task_name = "Checking Level Assets: "
asset_count = len(tick_actors)
current_step = 0
if len(tick_actors)>0:
with unreal.ScopedSlowTask(asset_count, task_name) as slowTask:
slowTask.make_dialog(True)
for actor in tick_actors:
current_step += 1
actor_label = actor.get_actor_label()
log_message += actor_label + "\n"
layers_subsys.add_actor_to_layer(actor, LAYER_TICK)
check_log = log_header +log_summary + log_message
check_log = str(check_log)
actor_subsys.set_selected_level_actors(tick_actors)
return check_log
def check_level_actors_event_tick(actors):
check_log = check_bp_event_tick(actors=actors)
print(check_log)
|
# /project/
# @CBgameDev Optimisation Script - LOG Static Meshes Assets With X Num Of Materials
# /project/
import unreal
import sys # So we can grab arguments fed into the python script
import os
EditAssetLib = unreal.EditorAssetLibrary()
StatMeshLib = unreal.EditorStaticMeshLibrary()
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
NumOfMatsToCheckFor = int(float(sys.argv[1])) # pull value sent with script
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()
if _assetClassName == "StaticMesh":
_staticMeshAsset = unreal.StaticMesh.cast(_assetData.get_asset())
_howManyMaterials = StatMeshLib.get_number_materials(_staticMeshAsset)
# unreal.log(StatMeshLib.get_number_materials(_staticMeshAsset))
if _howManyMaterials >= NumOfMatsToCheckFor:
LogStringsArray.append(" [%s] - %s ------------> At Path: %s \n" % (_howManyMaterials, _assetName, _assetPathName))
unreal.log("Asset Name: [%s] %s Path: %s \n" % (_howManyMaterials, _assetName, _assetPathName))
numOfOptimisations += 1
if ST.should_cancel():
break
ST.enter_progress_frame(1, asset)
# Write results into a log file
# /project/
TitleOfOptimisation = "LOG Static Meshes Assets With X Num Of Materials"
DescOfOptimisation = "Searches the entire project for static mesh assets that have a material count above the value that you have set"
SummaryMessageIntro = "-- Static Mesh Assets With Material Count Numbering >= %s --" % NumOfMatsToCheckFor
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
def set_screen_percentage(enable=True, value=200.0):
"""Set screen percentage for runtime performance scaling (affects PIE and builds)
Args:
enable (bool): Whether to enable custom screen percentage
value (float): Screen percentage value (10-400, where 100 = native resolution)
"""
# Clamp value to reasonable range
value = max(10.0, min(400.0, value))
# Method 1: Try CVarLibrary (preferred, no world context needed)
try:
if enable:
unreal.CVarLibrary.set_int_cvar("r.ScreenPercentage.Enable", 1)
unreal.CVarLibrary.set_int_cvar("r.DynamicRes.OperationMode", 0) # Disable dynamic resolution
unreal.CVarLibrary.set_float_cvar("r.ScreenPercentage", float(value))
print(f"Screen percentage set via CVarLibrary: {value}%")
else:
unreal.CVarLibrary.set_int_cvar("r.ScreenPercentage.Enable", 0)
unreal.CVarLibrary.set_int_cvar("r.DynamicRes.OperationMode", 1) # Re-enable dynamic resolution
unreal.CVarLibrary.set_float_cvar("r.ScreenPercentage", 100.0)
print("Screen percentage disabled via CVarLibrary (reset to 100%)")
return
except Exception as e:
print(f"CVarLibrary method failed: {e}")
# Method 2: Fallback to console commands
try:
world = unreal.EditorLevelLibrary.get_editor_world()
if enable:
commands = [
"r.ScreenPercentage.Enable 1",
"r.DynamicRes.OperationMode 0",
f"r.ScreenPercentage {int(value)}"
]
print(f"Screen percentage set via console commands: {value}%")
else:
commands = [
"r.ScreenPercentage.Enable 0",
"r.DynamicRes.OperationMode 1",
"r.ScreenPercentage 100"
]
print("Screen percentage disabled via console commands (reset to 100%)")
for cmd in commands:
unreal.SystemLibrary.execute_console_command(world, cmd)
except Exception as e:
print(f"Console command method failed: {e}")
print("Note: This affects runtime performance, not editor viewport preview")
def get_screen_percentage():
"""Get current screen percentage value"""
try:
enabled = unreal.CVarLibrary.get_int_cvar("r.ScreenPercentage.Enable")
value = unreal.CVarLibrary.get_float_cvar("r.ScreenPercentage")
dynamic_res = unreal.CVarLibrary.get_int_cvar("r.DynamicRes.OperationMode")
print(f"Screen Percentage Enabled: {bool(enabled)}")
print(f"Screen Percentage Value: {value}%")
print(f"Dynamic Resolution Mode: {dynamic_res} (0=disabled, 1=enabled)")
return {"enabled": bool(enabled), "value": value, "dynamic_res": dynamic_res}
except Exception as e:
print(f"Failed to get screen percentage: {e}")
return None
# Default behavior when running this script
enable_screen_percentage = True
screen_percentage_value = 200.0
set_screen_percentage(enable_screen_percentage, screen_percentage_value)
|
# Copyright 2018 Epic Games, Inc.
import unreal
import re
import sys
"""
Functions to import FBX into Unreal
"""
def _sanitize_name(name):
# Remove the default Shotgun versioning number if found (of the form '.v001')
name_no_version = re.sub(r'.v[0-9]{3}', '', name)
# Replace any remaining '.' with '_' since they are not allowed in Unreal asset names
return name_no_version.replace('.', '_')
def _generate_fbx_import_task(
filename,
destination_path,
destination_name=None,
replace_existing=True,
automated=True,
save=True,
materials=True,
textures=True,
as_skeletal=False
):
"""
Create and configure an Unreal AssetImportTask
:param filename: The fbx file to import,
:param destination_path: The Content Browser path where the asset will be placed.
:returns: The configured AssetImportTask.
"""
task = unreal.AssetImportTask()
task.filename = filename
task.destination_path = destination_path
# By default, destination_name is the filename without the extension
if destination_name is not None:
task.destination_name = destination_name
task.replace_existing = replace_existing
task.automated = automated
task.save = save
task.options = unreal.FbxImportUI()
task.options.import_materials = materials
task.options.import_textures = textures
task.options.import_as_skeletal = as_skeletal
task.options.static_mesh_import_data.combine_meshes = True
task.options.mesh_type_to_import = unreal.FBXImportType.FBXIT_STATIC_MESH
if as_skeletal:
task.options.mesh_type_to_import = unreal.FBXImportType.FBXIT_SKELETAL_MESH
return task
def import_fbx(filename, destination_path):
"""
Import the given FBX file under the given path.
:param filename: The fbx file to import,
:param destination_path: The Content Browser path where the asset will be placed.
"""
tasks = [_generate_fbx_import_task(filename, destination_path)]
unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks(tasks)
unreal.EditorLoadingAndSavingUtils.save_dirty_packages(False, True)
def main(argv):
import_fbx(*argv)
if __name__ == "__main__":
# Script arguments must be, in order:
# Path to FBX to import
# Unreal content browser path where to store the imported asset
main(sys.argv[1:])
|
# 本脚本用于导出当前场景中每个component下面所有body 的 relative transform和 basecolor 到 json文件中
import unreal
import json
def export_relative_trans_with_color(saved_json_folder : str):
actors = unreal.get_editor_subsystem(unreal.EditorActorSubsystem).get_all_level_actors()
transform_data = []
parent_actor = None
part_count = 0
for actor in actors:
if actor.get_actor_label().startswith("Part"):
part_count += 1
# 获取part的上一级actor
parent_actor = actor.get_attach_parent_actor() # 227A9600-000-601_1 / 227A9600-001-001_1 / 7029022-901_1 / 88640_U-2710
if not parent_actor:
continue
parent_transform = parent_actor.get_actor_transform()
# part相对于component的所有transform都是0
# unreal.log(f"ActorTransfomr: {actor.get_actor_transform().translation.x - parent_transform.translation.x}")
# unreal.log(f"ActorTransfomr: {actor.get_actor_transform().translation.y - parent_transform.translation.y}")
# unreal.log(f"ActorTransfomr: {actor.get_actor_transform().translation.z - parent_transform.translation.z}")
child_actors = actor.get_attached_actors()
# 每次执行之前清空transform_data
transform_data = []
assert(len(transform_data) <= 0)
for child_actor in child_actors:
if isinstance(child_actor, unreal.StaticMeshActor):
child_transform = child_actor.get_actor_transform()
# 计算相对变换: 父级的逆变换 * 子级的变换
relative_transform = parent_transform.inverse() * child_transform
relative_rotator = relative_transform.rotation.rotator()
# color = get_actor_base_color(child_actor)
transform_info = {
"name": child_actor.get_actor_label(),
# "location": {
# "x": relative_transform.translation.x,
# "y": relative_transform.translation.y,
# "z": relative_transform.translation.z
# },
# "rotation": {
# "roll": relative_rotator.roll,
# "pitch": relative_rotator.pitch,
# "yaw": relative_rotator.yaw
# },
# "scale": {
# "x": relative_transform.scale3d.x,
# "y": relative_transform.scale3d.y,
# "z": relative_transform.scale3d.z
# },
# "color": {
# "r": color.r,
# "g": color.g,
# "b": color.b,
# "a": color.a
# }
}
# body相对于component的transform都是0
# unreal.log(transform_info)
transform_data.append(transform_info)
file_path = f"{saved_json_folder}{parent_actor.get_actor_label()}.json"
with open(file_path, 'w') as json_file:
json.dump(transform_data, json_file, indent=4)
unreal.log(f"Transform {len(transform_data)} data exported to {file_path}")
unreal.log(f"Exported {part_count} Json to {saved_json_folder}")
export_relative_trans_with_color("C:/project/.json")
|
"""
Unreal Engine 5.6 Asset Import Script for Terminal Grounds
Imports generated art assets and sets up materials/settings
"""
import unreal
import os
import json
from pathlib import Path
from datetime import datetime
class TGAssetImporter:
def __init__(self):
self.editor_asset_lib = unreal.EditorAssetLibrary
self.asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
self.project_root = Path(r"/project/-Grounds")
self.log_path = self.project_root / "Docs" / "Phase4_Implementation_Log.md"
# Import mappings
self.import_mappings = {
"Content/project/": "/project/",
"Content/project/": "/project/",
"Content/project/": "/project/",
"Docs/project/": "/project/",
"Docs/project/": "/project/",
"Docs/project/": "/project/",
"Docs/project/": "/project/",
"Docs/project/": "/project/"
}
# Material instances tracker
self.created_materials = []
def log_import(self, message):
"""Log import action"""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(self.log_path, 'a') as f:
f.write(f"\n[{timestamp}] [UE IMPORT] {message}")
unreal.log(message)
def import_texture(self, source_path, destination_path):
"""Import a single texture asset"""
# Set up import task
task = unreal.AssetImportTask()
task.filename = str(source_path)
task.destination_path = destination_path
task.destination_name = source_path.stem
task.replace_existing = False
task.automated = True
task.save = True
# Configure texture import options
task.options = unreal.FbxImportUI()
# Execute import
self.asset_tools.import_asset_tasks([task])
# Get imported asset
asset_path = f"{destination_path}/{source_path.stem}"
texture = self.editor_asset_lib.load_asset(asset_path)
return texture
def configure_icon_texture(self, texture):
"""Configure texture settings for UI icons"""
if not texture:
return
# Set compression and LOD settings for icons
texture.compression_settings = unreal.TextureCompressionSettings.TC_EDITOR_ICON
texture.lod_group = unreal.TextureGroup.TEXTUREGROUP_UI
texture.srgb = True
texture.never_stream = True
# No mipmaps for UI
texture.mip_gen_settings = unreal.TextureMipGenSettings.TMGS_NO_MIPMAPS
# Save changes
self.editor_asset_lib.save_asset(texture.get_path_name())
def configure_decal_texture(self, texture):
"""Configure texture settings for decals"""
if not texture:
return
# Decal-appropriate settings
texture.compression_settings = unreal.TextureCompressionSettings.TC_DEFAULT
texture.lod_group = unreal.TextureGroup.TEXTUREGROUP_WORLD
texture.srgb = True
# Save changes
self.editor_asset_lib.save_asset(texture.get_path_name())
def create_decal_material_instance(self, texture, base_path):
"""Create material instance for decal"""
# Load master material
master_mat_path = "/project/"
master_mat = self.editor_asset_lib.load_asset(master_mat_path)
if not master_mat:
unreal.log_warning(f"Master material not found: {master_mat_path}")
return None
# Create material instance
mi_name = f"MI_TG_Decal_{texture.get_name()}"
mi_path = f"{base_path}/{mi_name}"
# Check if already exists
if self.editor_asset_lib.does_asset_exist(mi_path):
return self.editor_asset_lib.load_asset(mi_path)
# Create new instance
factory = unreal.MaterialInstanceConstantFactoryNew()
factory.parent = master_mat
mi_asset = self.asset_tools.create_asset(
asset_name=mi_name,
package_path=base_path,
asset_class=unreal.MaterialInstanceConstant,
factory=factory
)
if mi_asset:
# Set texture parameter
mi_asset.set_texture_parameter_value("BaseTexture", texture)
# Set default values
mi_asset.set_scalar_parameter_value("Opacity", 0.9)
mi_asset.set_scalar_parameter_value("Roughness", 0.6)
# For faction emblems, set appropriate tint
if "dir" in texture.get_name().lower():
mi_asset.set_vector_parameter_value("Tint", unreal.LinearColor(0.086, 0.102, 0.114, 1.0))
elif "vlt" in texture.get_name().lower():
mi_asset.set_vector_parameter_value("Tint", unreal.LinearColor(0.498, 0.549, 0.553, 1.0))
# Save
self.editor_asset_lib.save_asset(mi_asset.get_path_name())
self.created_materials.append(mi_path)
return mi_asset
def scan_for_new_assets(self, source_dir):
"""Scan directory for assets to import"""
source_path = self.project_root / source_dir
if not source_path.exists():
return []
assets_to_import = []
extensions = ['.png', '.jpg', '.jpeg', '.tga']
for ext in extensions:
for file_path in source_path.glob(f"*{ext}"):
# Skip if has metadata indicating already imported
meta_path = file_path.with_suffix('.json')
if meta_path.exists():
with open(meta_path, 'r') as f:
meta = json.load(f)
if meta.get('imported_to_ue', False):
continue
assets_to_import.append(file_path)
return assets_to_import
def import_directory(self, source_dir, destination_path):
"""Import all assets from a directory"""
assets = self.scan_for_new_assets(source_dir)
if not assets:
unreal.log(f"No new assets to import from {source_dir}")
return []
imported = []
for asset_path in assets:
unreal.log(f"Importing: {asset_path.name}")
# Import texture
texture = self.import_texture(asset_path, destination_path)
if texture:
# Configure based on type
if "icon" in source_dir.lower() or "icons" in destination_path.lower():
self.configure_icon_texture(texture)
elif "decal" in source_dir.lower() or "decals" in destination_path.lower():
self.configure_decal_texture(texture)
# Create material instance for decals
if "faction" in asset_path.stem.lower() or "emblem" in asset_path.stem.lower():
self.create_decal_material_instance(texture, destination_path)
imported.append({
'source': str(asset_path),
'destination': texture.get_path_name()
})
# Update metadata
meta_path = asset_path.with_suffix('.json')
if meta_path.exists():
with open(meta_path, 'r') as f:
meta = json.load(f)
meta['imported_to_ue'] = True
meta['ue_asset_path'] = texture.get_path_name()
meta['import_date'] = datetime.now().isoformat()
with open(meta_path, 'w') as f:
json.dump(meta, f, indent=2)
return imported
def run_full_import(self):
"""Run import for all configured directories"""
unreal.log("=" * 60)
unreal.log("Terminal Grounds Asset Import - Starting")
unreal.log("=" * 60)
total_imported = 0
for source_dir, dest_path in self.import_mappings.items():
unreal.log(f"\nProcessing: {source_dir} -> {dest_path}")
imported = self.import_directory(source_dir, dest_path)
total_imported += len(imported)
if imported:
self.log_import(f"Imported {len(imported)} assets from {source_dir}")
for item in imported:
unreal.log(f" ✓ {Path(item['source']).name} -> {item['destination']}")
# Summary
unreal.log("\n" + "=" * 60)
unreal.log(f"Import Complete: {total_imported} assets imported")
if self.created_materials:
unreal.log(f"Created {len(self.created_materials)} material instances")
unreal.log("=" * 60)
self.log_import(f"Import batch complete: {total_imported} assets, {len(self.created_materials)} materials")
return total_imported
def create_icon_preview_widget(self):
"""Create a UMG widget to preview all icons"""
# This would create a blueprint widget for icon preview
# Blueprint creation through Python is limited, so we log the instruction
unreal.log("\n📋 Icon Preview Widget Instructions:")
unreal.log("1. Create new Widget Blueprint: WBP_TG_IconPreview")
unreal.log("2. Add UniformGridPanel")
unreal.log("3. Use Python or Blueprint to populate with imported icons")
unreal.log(f"4. Icon assets are in: /project/")
def place_decals_in_test_level(self):
"""Place decals in test level for review"""
# Get current level
level = unreal.EditorLevelLibrary.get_editor_world()
if not level:
unreal.log_warning("No level loaded")
return
# Starting position for decal placement
x_pos = 0.0
y_pos = 0.0
spacing = 500.0
decal_materials = [path for path in self.created_materials if "decal" in path.lower()]
for i, mat_path in enumerate(decal_materials):
# Load material
material = self.editor_asset_lib.load_asset(mat_path)
if not material:
continue
# Spawn decal actor
decal_actor = unreal.EditorLevelLibrary.spawn_actor_from_class(
unreal.DecalActor,
location=unreal.Vector(x_pos, y_pos, 100.0),
rotation=unreal.Rotator(0, 0, 0)
)
if decal_actor:
# Set material
decal_component = decal_actor.get_component_by_class(unreal.DecalComponent)
if decal_component:
decal_component.set_decal_material(material)
decal_component.decal_size = unreal.Vector(128, 256, 256)
# Update position for next decal
x_pos += spacing
if (i + 1) % 5 == 0: # New row every 5 decals
x_pos = 0
y_pos += spacing
unreal.log(f"Placed {len(decal_materials)} decals in test level")
def main():
"""Main import function"""
importer = TGAssetImporter()
# Run full import
total = importer.run_full_import()
if total > 0:
# Create preview helpers
importer.create_icon_preview_widget()
# Place decals if any were created
if importer.created_materials:
importer.place_decals_in_test_level()
return total
# Execute if running in Unreal
if __name__ == '__main__':
main()
|
# This script describes the different ways of setting variant thumbnails via the Python API
import unreal
def import_texture(filename, contentpath):
task = unreal.AssetImportTask()
task.set_editor_property('filename', filename)
task.set_editor_property('destination_path', contentpath)
task.automated = True
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
asset_tools.import_asset_tasks([task])
asset_paths = task.get_editor_property("imported_object_paths")
if not asset_paths:
unreal.log_warning("No assets were imported!")
return None
return unreal.load_asset(asset_paths[0])
if __name__ == "__main__":
lvs = unreal.VariantManagerLibrary.create_level_variant_sets_asset("LVS", "/Game/")
lvs_actor = unreal.VariantManagerLibrary.create_level_variant_sets_actor(lvs)
if lvs is None or lvs_actor is None:
print ("Failed to spawn either the LevelVariantSets asset or the LevelVariantSetsActor!")
quit()
var_set1 = unreal.VariantSet()
var_set1.set_display_text("My VariantSet")
varTexture = unreal.Variant()
varTexture.set_display_text("From texture")
varPath = unreal.Variant()
varPath.set_display_text("From path")
varCam = unreal.Variant()
varCam.set_display_text("From cam")
varViewport = unreal.Variant()
varViewport.set_display_text("From viewport")
lvs.add_variant_set(var_set1)
var_set1.add_variant(varTexture)
var_set1.add_variant(varPath)
var_set1.add_variant(varCam)
var_set1.add_variant(varViewport)
# Set thumbnail from an unreal texture
texture = import_texture("/project/.jpg", "/project/")
if texture:
varTexture.set_thumbnail_from_texture(texture)
var_set1.set_thumbnail_from_texture(texture)
# Set thumbnail directly from a filepath
varPath.set_thumbnail_from_file("/project/.png")
# Set thumbnail from camera transform and properties
trans = unreal.Transform()
fov = 50
minZ = 50
gamma = 2.2
varCam.set_thumbnail_from_camera(lvs_actor, trans, fov, minZ, gamma)
# Set thumbnail directly from the active editor viewport
varViewport.set_thumbnail_from_editor_viewport()
|
import unreal
from Lib import __lib_topaz__ as topaz
selected_actors: list[unreal.Actor] = topaz.get_selected_level_actors()
for actor in selected_actors:
if len(selected_actors) > 0:
actor_class = actor.__class__
if actor_class == unreal.RectLight or unreal.SpotLight or unreal.PointLight:
actor_tags = actor.get_editor_property("tags")
if len(actor_tags) == 0:
actor_tags = ["ENV_Light"]
actor.set_editor_property("tags", actor_tags)
|
# Copyright Epic Games, Inc. All Rights Reserved.
import os
import unreal
import subprocess as sp
#-------------------------------------------------------------------------------
class _PlatformBase(unreal.Platform):
def _read_env(self):
yield from ()
def _get_version_ue4(self):
import re
dot_cs = self.get_unreal_context().get_engine().get_dir()
dot_cs /= "Source/project/.cs"
needles = (
("DefaultWindowsSdkVersion", re.compile(r'DefaultWindowsSdkVersion\s+=\s+("|[\w.]+\("|)([^"]+)"?\)?\s*;')),
("VersionNumber", re.compile(r'^\s+VersionNumber.Parse\(("([^"]+))')),
)
versions = []
try:
with open(dot_cs, "rt") as lines:
for line in lines:
for seed, needle in needles:
if seed not in line:
continue
m = needle.search(line)
if m:
versions.append(m.group(2))
except FileNotFoundError:
return
return self._get_version_string(versions)
def _get_version_ue5(self):
# Extract the Windows SDK version
dot_cs = self.get_unreal_context().get_engine().get_dir()
dot_cs /= "Source/project/"
version = self._get_version_ue5_path(dot_cs / "MicrosoftPlatformSDK.Versions.cs")
return version or self._get_version_ue5_path(dot_cs / "MicrosoftPlatformSDK.cs")
def _get_version_ue5_path(self, dot_cs):
import re
needle = re.compile(r'VersionNumber.Parse\("([\d.]+)"')
versions = []
try:
with open(dot_cs, "rt") as lines:
for line in (x for x in lines if "VersionNumber" in x):
if m := needle.search(line):
versions.append(m.group(1))
break
except FileNotFoundError:
pass
if not versions:
if sdk_version := self._get_version_helper_ue5(dot_cs):
versions.append(sdk_version)
else:
return
# Extract the Visual Studio toolchain version
vs_version = self._get_vs_toolchain_version_string(dot_cs)
if not vs_version:
vs_version = self._get_vs_toolchain_version_string(dot_cs.parent / "UEBuildWindows.cs")
if not vs_version:
return
versions.append(vs_version)
return self._get_version_string(versions)
def _get_vs_toolchain_version_string(self, dot_cs):
import re
try:
with open(dot_cs, "rt") as lines:
line_iter = iter(lines)
for line in line_iter:
if "PreferredVisualCppVersions" in line:
break
else:
return
version = None
for line in line_iter:
if "}" in line:
break
elif m := re.match(r'^\s+VersionNumberRange\.Parse\(.+, "([^"]+)', line):
version = m.group(1)
break
return version
except FileNotFoundError:
return
def _get_version_string(self, versions):
msvc_versions = list(x for x in versions if x >= "14.")
if not msvc_versions:
return
sdk_versions = list(x for x in versions if x.startswith("10."))
if not sdk_versions:
return
return max(sdk_versions) + "-" + max(msvc_versions)
#-------------------------------------------------------------------------------
class Platform(_PlatformBase):
name = "Win64"
config_name = "Windows"
autosdk_name = None
vs_transport = "Default"
def _get_cook_form(self, target):
if target == "game": return "Windows" if self.get_unreal_context().get_engine().get_version_major() > 4 else "WindowsNoEditor"
if target == "client": return "WindowsClient"
if target == "server": return "WindowsServer"
def _launch(self, exec_context, stage_dir, binary_path, args):
if stage_dir:
base_dir = binary_path.replace("\\", "/").split("/")
base_dir = "/".join(base_dir[-4:-1])
base_dir = stage_dir + base_dir
if not os.path.isdir(base_dir):
raise EnvironmentError(f"Failed to find base directory '{base_dir}'")
args = (*args, "-basedir=" + base_dir)
cmd = exec_context.create_runnable(binary_path, *args)
cmd.launch()
return (cmd.get_pid(), None)
def _kill(self, target):
target_name = None
context = self.get_unreal_context()
if target == "editor":
ue_version = context.get_engine().get_version_major()
target_name = "UE4Editor" if ue_version == 4 else "UnrealEditor"
elif target:
target_type = unreal.TargetType.parse(target)
target_name = context.get_target_by_type(target_type).get_name()
if target_name:
print(f"Terminating {target_name}*.exe")
sp.run(rf'taskkill.exe /f /fi "imagename eq {target_name}*"')
else:
self._kill("client")
self._kill("game")
|
"""
Updated validate_queue.py using common utilities
"""
import sys
import os
import unreal
# Add the common directory to Python path
script_dir = os.path.dirname(os.path.abspath(__file__))
common_dir = os.path.join(script_dir, 'lib')
if common_dir not in sys.path:
sys.path.append(common_dir)
# Import from common module
from render_queue_validation import validate_movie_render_queue
if __name__ == "__main__":
unreal.log(validate_movie_render_queue())
|
import unreal
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import ParseError
import sys
import os
# need to run the Deltagen_Import_look_variants
#get all variant set's names, variant's names and their ID
def getVariantSetsAndVariantFromFile():
print("Lising all variants")
variant_sets_dict = dict()
for variant_switch in rttDocument.findall('./project/'):
variant_set_name = variant_switch.find('Name').text
print("processing variant : " + variant_set_name)
variant_list = variant_switch.find('VariantList')
variants = variant_list.find('Variants')
variant_dict = dict()
for variant in variants:
# find variant
variant_name = variant.find('Name').text
variant_id = int(variant.find('VariantID').text)
variant_dict[variant_id] = variant_name
if variant_set_name in variant_sets_dict:
print("Error - Variant set already in dictionary")
else:
variant_sets_dict[variant_set_name] = variant_dict
return variant_sets_dict
# set var file from the arguments
var_file = sys.argv[-1]
# file exists
if os.path.exists(var_file):
print("Var file exist:", os.path.basename(var_file))
# If file not exist, the script stops
else:
print("file not exist")
sys.exit()
#clean package variant
# remove any actor in the package variants
# should we test that prototypeId of TargetDescription are VARIANTSWITCH_NODE_ID instead?
# should we have that clean in the C++ import instead?
bCleanPackageVariant = True
# This need to be dynamic directory, '/' should be at the end of content_output
content_output = "/project/"
LevelVariantSets_output = "/project/"
xml_data = ""
with open(var_file, "r", encoding='utf-8-sig') as file:
# xml parser does not like the "DAF::" string
xml_data = file.read().replace('DAF::', '')
try:
rttDocument = ET.fromstring(xml_data)
except ParseError as e:
print("parsing failed")
print(e.msg)
if rttDocument.tag != 'rttDocument':
print('parse error: first node is not <rttDocument>')
var_file_variant_sets_dict = getVariantSetsAndVariantFromFile()
assetSubsystem = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem)
if not assetSubsystem.does_asset_exist(LevelVariantSets_output+'LevelVariantSets'):
# create a new level variant set
#lvs = unreal.VariantManagerLibrary.create_level_variant_sets_asset('LookVariants', LevelVariantSets_output)
lvs = unreal.VariantManagerLibrary.create_level_variant_sets_asset('LevelVariantSets', LevelVariantSets_output)
else:
# use existing level variant set
lvs = assetSubsystem.load_asset(LevelVariantSets_output+'LevelVariantSets')
lvs_num_variant_set = lvs.get_num_variant_sets()
lvs_variant_set_names = dict()
for i in range(lvs_num_variant_set):
lvs_variant_set = lvs.get_variant_set(i)
lvs_variant_set_names[str(lvs_variant_set.get_display_text())] = lvs_variant_set
print(lvs_variant_set_names)
# loop through all variants in the var file
for variant_switch in rttDocument.findall('./project/'):
proto_id = variant_switch.find('PrototypeID')
dependencies = dict()
# process only package variants
if proto_id.text != 'PACKAGE_VARIANT':
continue
variant_set_name = variant_switch.find('Name').text
print("processing package variant : " + variant_set_name)
#retrieve current variant set from the LVS asset
lvs_current_variant_set = lvs.get_variant_set_by_name(variant_set_name)
if lvs_current_variant_set == None:
continue
print("Current Variant Set: " + str(lvs_current_variant_set.get_display_text()))
target_lists = variant_switch.find('TargetLists')
if target_lists is None:
print("target list is empty for variant set name:"+variant_set_name)
continue
target_description_list = target_lists.findall('TargetDescription')
if len(target_description_list) == 0:
print("target description is empty for variant set name:"+variant_set_name)
continue
for target_description in target_description_list:
if target_description.find('name') is None:
print("target description Name is empty for variant set name:"+variant_set_name)
continue
target_name = target_description.find('name').text.replace(' ', '_')
target_id = int(target_description.find('TargetID').text)
print(target_name)
if target_name in lvs_variant_set_names:
dependencies[target_id] = target_name
if len(dependencies) > 0:
print("process dependencies")
variant_list = variant_switch.find('VariantList')
variants = variant_list.find('Variants')
for variant in variants:
# find variant
variant_name = variant.find('Name').text
lvs_current_variant = lvs_current_variant_set.get_variant_by_name(variant_name)
if(lvs_current_variant == None):
continue
values = variant.find("Values")
value_list = values.findall("Value")
print("########################")
print("Current Variant: " + variant_name)
if len(value_list) == len(dependencies):
ind = 0
for value in value_list:
# process each dependency line
dependency_variant_set = lvs_variant_set_names[dependencies[ind]]
data_value = int(value.find('Data').text)
# check if dependency variant set exists in existing lvs
if str(dependency_variant_set.get_display_text()) in var_file_variant_sets_dict:
var_file_variant_dict = var_file_variant_sets_dict[str(dependency_variant_set.get_display_text())]
if data_value in var_file_variant_dict:
variant_name = var_file_variant_dict[data_value]
print(dependency_variant_set.get_display_text())
print(dependency_variant_set.get_variant_by_name(variant_name).get_display_text())
dependency = unreal.VariantDependency(dependency_variant_set,dependency_variant_set.get_variant_by_name(variant_name))
# Current import create actor connection instead of dependencies, cleaning before replacing by dependencies
if bCleanPackageVariant:
actors_to_remove = []
for index_actor in range(lvs_current_variant.get_num_actors()):
actors_to_remove.append(lvs_current_variant.get_actor(index_actor).get_name())
for a in actors_to_remove:
lvs_current_variant.remove_actor_binding_by_name(a)
lvs_current_variant.add_dependency(dependency)
ind = ind + 1
assetSubsystem.save_loaded_asset(lvs)
# clean references to lvs
lvs_variant_set_names.clear()
lvs_variant_set = None
lvs_current_variant = None
lvs_current_variant_set = None
dependency_variant_set = None
|
import unreal
""" Should be used with internal UE Python API
Auto generate LODs for static meshes"""
asset_reg = unreal.AssetRegistryHelpers.get_asset_registry()
asset_root_dir = '/project/'
assets = asset_reg.get_assets_by_path(asset_root_dir, recursive=True)
def generate_lods(static_mesh):
number_of_vertices = unreal.EditorStaticMeshLibrary.get_number_verts(static_mesh, 0)
if number_of_vertices < 10:
return
options = unreal.EditorScriptingMeshReductionOptions()
options.reduction_settings = [
unreal.EditorScriptingMeshReductionSettings(1.0, 1.0),
unreal.EditorScriptingMeshReductionSettings(0.8, 0.75),
unreal.EditorScriptingMeshReductionSettings(0.6, 0.5),
unreal.EditorScriptingMeshReductionSettings(0.4, 0.25)
]
options.auto_compute_lod_screen_size = True
unreal.EditorStaticMeshLibrary.set_lods(static_mesh, options)
unreal.EditorAssetLibrary.save_loaded_asset(static_mesh)
for asset in assets:
if asset.asset_class == "StaticMesh":
loaded_asset = unreal.EditorAssetLibrary.find_asset_data(asset.object_path).get_asset()
generate_lods(loaded_asset)
|
#!/project/ python3
"""
String Handling Test for MCP Server
This script tests string handling in the MCP Server.
It connects to the server, sends Python code with various string formats,
and verifies they are handled correctly.
"""
import socket
import json
import sys
def main():
"""Connect to the MCP Server and test string handling."""
try:
# Create socket
print("Connecting to MCP Server on localhost:13377...")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10) # 10 second timeout
# Connect to server
s.connect(("localhost", 13377))
print("✓ Connected successfully")
# Python code with various string formats
code = """
import unreal
import json
# Test 1: Basic string types
test_string1 = "This is a simple string with double quotes"
test_string2 = 'This is a simple string with single quotes'
test_string3 = \"\"\"This is a
multiline string\"\"\"
test_string4 = f"This is an f-string with {'interpolation'}"
test_string5 = "This string has escape sequences: \\n \\t \\\\ \\' \\""
test_string6 = r"This is a raw string with no escape processing: \n \t \\"
# Test 2: Print statements
print("Print statement 1: Simple string")
print(f"Print statement 2: F-string with {test_string2}")
print("Print statement 3: Multiple", "arguments", 123, test_string3)
print("Print statement 4: With escape sequences: \\n \\t")
# Test 3: Potentially problematic strings
test_string7 = "String with quotes: 'single' and \\"double\\""
test_string8 = 'String with quotes: "double" and \\'single\\''
test_string9 = "String with backslashes: \\ \\\\ \\n"
test_string10 = "String with special characters: 🐍 😊 🚀"
# Test 4: Unterminated strings (these are properly terminated but might be misinterpreted)
test_string11 = "String with a quote at the end: '"
test_string12 = 'String with a quote at the end: "'
test_string13 = "String with a backslash at the end: \\"
test_string14 = "String with multiple backslashes at the end: \\\\"
# Test 5: String concatenation
test_string15 = "Part 1 " + "Part 2"
test_string16 = "Multiple " + "parts " + "concatenated"
test_string17 = "Mixed " + 'quote' + " types"
# Collect results in a dictionary
results = {
"test1": test_string1,
"test2": test_string2,
"test3": test_string3,
"test4": test_string4,
"test5": test_string5,
"test6": test_string6,
"test7": test_string7,
"test8": test_string8,
"test9": test_string9,
"test10": test_string10,
"test11": test_string11,
"test12": test_string12,
"test13": test_string13,
"test14": test_string14,
"test15": test_string15,
"test16": test_string16,
"test17": test_string17
}
# Log the results
unreal.log("===== STRING TEST RESULTS =====")
for key, value in results.items():
unreal.log(f"{key}: {value}")
# Return the results as JSON
return json.dumps(results, indent=2)
"""
# Create command with multiple formats to try to make it work
command = {
"command": "execute_python",
"type": "execute_python",
"code": code,
"data": {
"code": code
}
}
# Send command
print("Sending execute_python command...")
command_str = json.dumps(command) + "\n" # Add newline
s.sendall(command_str.encode('utf-8'))
# Receive response
print("Waiting for response...")
response = b""
while True:
data = s.recv(4096)
if not data:
break
response += data
if b"\n" in data: # Check for newline which indicates end of response
break
# Close connection
s.close()
print("✓ Connection closed properly")
# Process response
if response:
response_str = response.decode('utf-8').strip()
try:
response_json = json.loads(response_str)
print("\n=== RESPONSE ===")
print(f"Status: {response_json.get('status', 'unknown')}")
if response_json.get('status') == 'success':
print("✓ String test successful")
result = response_json.get('result', {})
if isinstance(result, dict) and 'output' in result:
output = result['output']
print(f"Output length: {len(output)} characters")
print("First 200 characters of output:")
print(output[:200] + "..." if len(output) > 200 else output)
return True
else:
print("✗ String test failed")
print(f"Error: {response_json.get('message', 'Unknown error')}")
return False
except json.JSONDecodeError as e:
print(f"✗ Error parsing JSON response: {e}")
print(f"Raw response: {response_str}")
return False
else:
print("✗ No response received from server")
return False
except ConnectionRefusedError:
print("✗ Connection refused. Is the MCP Server running?")
return False
except socket.timeout:
print("✗ Connection timed out. Is the MCP Server running?")
return False
except Exception as e:
print(f"✗ Error: {e}")
return False
if __name__ == "__main__":
print("=== MCP Server String Handling Test ===")
success = main()
print("\n=== TEST RESULT ===")
if success:
print("✓ String handling test PASSED")
sys.exit(0)
else:
print("✗ String handling test FAILED")
sys.exit(1)
|
import unreal
import re
ar_asset_lists = []
ar_asset_lists = unreal.EditorUtilityLibrary.get_selected_assets()
print (ar_asset_lists[0])
str_selected_asset = ''
if len(ar_asset_lists) > 0 :
str_selected_asset = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(ar_asset_lists[0])
#str_selected_asset = str(ar_asset_lists[0])
print(str_selected_asset)
ar_numbers = re.findall("\d+", str_selected_asset)
i_number = ar_numbers[0]
print(ar_numbers)
print(i_number)
|
import unreal
import os
# Get the list of props from ADACA_extract
props_dir = "C:/project/"
props = [p.replace(".uasset", "") for p in os.listdir(props_dir) if p.startswith("Prop_") and p.endswith(".uasset")]
print(f"Weapons found: {props}")
package_path = "/project/"
factory = unreal.BlueprintFactory()
factory.set_editor_property("ParentClass", unreal.Actor)
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
for prop in props:
print(f"Creating blueprint Actor class for {prop}...")
new_asset = (asset_tools.create_asset(prop, package_path, None, factory))
# unreal.EditorAssetLibrary.save_loaded_asset(new_asset)
|
import unreal
""" Should be used with internal UE Python API
Auto generate LODs for static meshes"""
asset_reg = unreal.AssetRegistryHelpers.get_asset_registry()
asset_root_dir = '/project/'
assets = asset_reg.get_assets_by_path(asset_root_dir, recursive=True)
def generate_lods(static_mesh):
number_of_vertices = unreal.EditorStaticMeshLibrary.get_number_verts(static_mesh, 0)
if number_of_vertices < 10:
return
options = unreal.EditorScriptingMeshReductionOptions()
options.reduction_settings = [
unreal.EditorScriptingMeshReductionSettings(1.0, 1.0),
unreal.EditorScriptingMeshReductionSettings(0.8, 0.75),
unreal.EditorScriptingMeshReductionSettings(0.6, 0.5),
unreal.EditorScriptingMeshReductionSettings(0.4, 0.25)
]
options.auto_compute_lod_screen_size = True
unreal.EditorStaticMeshLibrary.set_lods(static_mesh, options)
unreal.EditorAssetLibrary.save_loaded_asset(static_mesh)
for asset in assets:
if asset.asset_class == "StaticMesh":
loaded_asset = unreal.EditorAssetLibrary.find_asset_data(asset.object_path).get_asset()
generate_lods(loaded_asset)
|
import unreal
cad_file_path = "c:/project/.3dxml"
directory_name = "/project/"
datasmith_scene = unreal.DatasmithSceneElement.construct_datasmith_scene_from_file(cad_file_path)
# set CAD import options
import_options = datasmith_scene.get_options()
import_options.base_options.scene_handling = unreal.DatasmithImportScene.CURRENT_LEVEL
tessellation_options = datasmith_scene.get_options(unreal.DatasmithCommonTessellationOptions)
if tessellation_options:
tessellation_options.options.chord_tolerance = 0.1
tessellation_options.options.max_edge_length = 0
tessellation_options.options.normal_tolerance = 15.0
result = datasmith_scene.import_scene(directory_name)
print (result.import_succeed)
|
import unreal
import numpy as np
import ParametersClass as pc
import CaptureImages as ci
import pandas as pd
import os
import airsim
import time
from multiprocessing import Process
TEST_MODE = 2
# SEARCH_MODE = "HIGH_FIDELITY"
SEARCH_MODE = "LOW_FIDELITY"
RESULTS_FILE_PATH = r"/project/"
CAMERA_NAME = "bottom_forward_thermal"
SCREENSHOTS_DIR = r"/project/"
BATCH_SIZE = 600
#Grabs Camera Actor
actors = unreal.EditorLevelLibrary.get_all_level_actors()
camera_actor = None
for actor in actors:
if (actor.get_name() == 'CineCameraActor_1'):
camera_actor = actor
break
unreal.EditorLevelLibrary.pilot_level_actor(camera_actor)
# Grab our PP Thermal Material
thermal_mat_inst = unreal.EditorAssetLibrary.load_asset("/project/")
# # Initializes data management dataframe
df = pd.DataFrame(columns=pc.get_cols_from_test(TEST_MODE))#.reset_index(drop=True)
#Create images folder within our results folder
images_dir = os.path.join(RESULTS_FILE_PATH, "images")
if(not os.path.exists(images_dir)):
os.mkdir(images_dir)
parameter_combinations = None
# if(TEST_MODE==1):
# #START OF TEST MODE 1------------------------------------------------------------------------------------------------------------------
# if(SEARCH_MODE=="LOW_FIDELITY"):
# #Set the parameters
# blend_weight_min=30
# blend_weight_max=100
# blend_weight_step=2
# brightness_min=40
# brightness_max=100
# brightness_step=2
# contrast_min=0
# contrast_max=100
# contrast_step=5
# cold_brightness_multiplier_min=0
# cold_brightness_multiplier_max=200
# cold_brightness_multiplier_step=10
# cold_power_min=-2
# cold_power_max=2
# cold_power_step=0.2
# hot_brightness_multiplier_min=0
# hot_brightness_multiplier_max=200
# hot_brightness_multiplier_step=10
# hot_power_min=-2
# hot_power_max=2
# hot_power_step=0.2
# sky_heat_min=0
# sky_heat_max=0.2
# sky_heat_step=0.05
# fire_heat_min=0
# fire_heat_max=1
# fire_heat_step=0.05
# ground_heat_correction_strength_min=0
# ground_heat_correction_strength_max=10000
# ground_heat_correction_strength_step=1000
# ground_heat_offset_min=0
# ground_heat_offset_max=1
# ground_heat_offset_step=0.1
# person_heat_multiplier_min=0
# person_heat_multiplier_max=25
# person_heat_multiplier_step=1
# target_ground_heat_min=0
# target_ground_heat_max=1
# target_ground_heat_step=0.1
# tree_correction_strength_min=0
# tree_correction_strength_max=10000
# tree_correction_strength_step=1000
# target_tree_heat_min=0
# target_tree_heat_max=1
# target_tree_heat_step=0.1
# vehicle_heat_multiplier_min=0
# vehicle_heat_multiplier_max=25
# vehicle_heat_multiplier_step=1
# elif(SEARCH_MODE=="HIGH_FIDELITY"):
# #Set the parameters
# blend_weight_min=30
# blend_weight_max=100
# blend_weight_step=0.5
# brightness_min=40
# brightness_max=100
# brightness_step=1
# contrast_min=0
# contrast_max=100
# contrast_step=1
# cold_brightness_multiplier_min=0
# cold_brightness_multiplier_max=200
# cold_brightness_multiplier_step=1
# cold_power_min=-2
# cold_power_max=2
# cold_power_step=0.1
# hot_brightness_multiplier_min=0
# hot_brightness_multiplier_max=10
# hot_brightness_multiplier_step=0.2
# hot_power_min=-2
# hot_power_max=2
# hot_power_step=0.1
# sky_heat_min=0
# sky_heat_max=0.2
# sky_heat_step=0.01
# fire_heat_min=0.8
# fire_heat_max=1
# fire_heat_step=0.05
# ground_heat_correction_strength_min=0
# ground_heat_correction_strength_max=10000
# ground_heat_correction_strength_step=10
# ground_heat_offset_min=0
# ground_heat_offset_max=1
# ground_heat_offset_step=0.02
# person_heat_multiplier_min=0
# person_heat_multiplier_max=25
# person_heat_multiplier_step=0.5
# target_ground_heat_min=0
# target_ground_heat_max=1
# target_ground_heat_step=0.01
# tree_correction_strength_min=0
# tree_correction_strength_max=10000
# tree_correction_strength_step=10
# target_tree_heat_min=0
# target_tree_heat_max=1
# target_tree_heat_step=0.01
# vehicle_heat_multiplier_min=0
# vehicle_heat_multiplier_max=25
# vehicle_heat_multiplier_step=0.5
# parameter_combinations = pc.Parameters(
# test_mode=TEST_MODE,
# blend_weight_min=blend_weight_min,
# blend_weight_max=blend_weight_max,
# blend_weight_step=blend_weight_step,
# brightness_min=brightness_min,
# brightness_max=brightness_max,
# brightness_step=brightness_step,
# contrast_min=contrast_min,
# contrast_max=contrast_max,
# contrast_step=contrast_step,
# cold_brightness_multiplier_min=cold_brightness_multiplier_min,
# cold_brightness_multiplier_max=cold_brightness_multiplier_max,
# cold_brightness_multiplier_step=cold_brightness_multiplier_step,
# cold_power_min=cold_power_min,
# cold_power_max=cold_power_max,
# cold_power_step=cold_power_step,
# hot_brightness_multiplier_min=hot_brightness_multiplier_min,
# hot_brightness_multiplier_max=hot_brightness_multiplier_max,
# hot_brightness_multiplier_step=hot_brightness_multiplier_step,
# hot_power_min=hot_power_min,
# hot_power_max=hot_power_max,
# hot_power_step=hot_power_step,
# sky_heat_min=sky_heat_min,
# sky_heat_max=sky_heat_max,
# sky_heat_step=sky_heat_step,
# fire_heat_min=fire_heat_min,
# fire_heat_max=fire_heat_max,
# fire_heat_step=fire_heat_step,
# ground_heat_correction_strength_min=ground_heat_correction_strength_min,
# ground_heat_correction_strength_max=ground_heat_correction_strength_max,
# ground_heat_correction_strength_step=ground_heat_correction_strength_step,
# ground_heat_offset_min=ground_heat_offset_min,
# ground_heat_offset_max=ground_heat_offset_max,
# ground_heat_offset_step=ground_heat_offset_step,
# person_heat_multiplier_min=person_heat_multiplier_min,
# person_heat_multiplier_max=person_heat_multiplier_max,
# person_heat_multiplier_step=person_heat_multiplier_step,
# target_ground_heat_min=target_ground_heat_min,
# target_ground_heat_max=target_ground_heat_max,
# target_ground_heat_step=target_ground_heat_step,
# tree_correction_strength_min=tree_correction_strength_min,
# tree_correction_strength_max=tree_correction_strength_max,
# tree_correction_strength_step=tree_correction_strength_step,
# target_tree_heat_min=target_tree_heat_min,
# target_tree_heat_max=target_tree_heat_max,
# target_tree_heat_step=target_tree_heat_step,
# vehicle_heat_multiplier_min=vehicle_heat_multiplier_min,
# vehicle_heat_multiplier_max=vehicle_heat_multiplier_max,
# vehicle_heat_multiplier_step=vehicle_heat_multiplier_step
# ).all_parameter_combinations()
# elif(TEST_MODE==2):
# #START OF TEST MODE 2------------------------------------------------------------------------------------------------------------------
# if(SEARCH_MODE=="LOW_FIDELITY"):
# #Set the parameters
# blend_weight_min=0
# blend_weight_max=100
# blend_weight_step=2
# brightness_min=0
# brightness_max=100
# brightness_step=2
# contrast_min=0
# contrast_max=100
# contrast_step=5
# cold_brightness_multiplier_min=0
# cold_brightness_multiplier_max=200
# cold_brightness_multiplier_step=10
# cold_power_min=-2
# cold_power_max=2
# cold_power_step=0.2
# hot_brightness_multiplier_min=0
# hot_brightness_multiplier_max=200
# hot_brightness_multiplier_step=10
# hot_power_min=-2
# hot_power_max=2
# hot_power_step=0.2
# light_bulb_heat_multiplier_min=0
# light_bulb_heat_multiplier_max=1
# light_bulb_heat_multiplier_step=0.1
# elif(SEARCH_MODE=="HIGH_FIDELITY"):
# #Set the parameters
# blend_weight_min=30
# blend_weight_max=100
# blend_weight_step=0.5
# brightness_min=40
# brightness_max=100
# brightness_step=1
# contrast_min=0
# contrast_max=100
# contrast_step=1
# cold_brightness_multiplier_min=0
# cold_brightness_multiplier_max=200
# cold_brightness_multiplier_step=1
# cold_power_min=-2
# cold_power_max=2
# cold_power_step=0.1
# hot_brightness_multiplier_min=0
# hot_brightness_multiplier_max=10
# hot_brightness_multiplier_step=0.2
# hot_power_min=-2
# hot_power_max=2
# hot_power_step=0.1
# light_bulb_heat_multiplier_min=0
# light_bulb_heat_multiplier_max=1
# light_bulb_heat_multiplier_step=0.01
# parameter_combinations = pc.Parameters(
# test_mode=TEST_MODE,
# blend_weight_min=blend_weight_min,
# blend_weight_max=blend_weight_max,
# blend_weight_step=blend_weight_step,
# brightness_min=brightness_min,
# brightness_max=brightness_max,
# brightness_step=brightness_step,
# contrast_min=contrast_min,
# contrast_max=contrast_max,
# contrast_step=contrast_step,
# cold_brightness_multiplier_min=cold_brightness_multiplier_min,
# cold_brightness_multiplier_max=cold_brightness_multiplier_max,
# cold_brightness_multiplier_step=cold_brightness_multiplier_step,
# cold_power_min=cold_power_min,
# cold_power_max=cold_power_max,
# cold_power_step=cold_power_step,
# hot_brightness_multiplier_min=hot_brightness_multiplier_min,
# hot_brightness_multiplier_max=hot_brightness_multiplier_max,
# hot_brightness_multiplier_step=hot_brightness_multiplier_step,
# hot_power_min=hot_power_min,
# hot_power_max=hot_power_max,
# hot_power_step=hot_power_step,
# light_bulb_heat_multiplier_min=light_bulb_heat_multiplier_min,
# light_bulb_heat_multiplier_max=light_bulb_heat_multiplier_max,
# light_bulb_heat_multiplier_step=light_bulb_heat_multiplier_step
# ).all_parameter_combinations()
class capture(object):
def __init__(self, batch_num):
unreal.EditorLevelLibrary.editor_set_game_view(True)
self.parameter_combinations = parameter_combinations
self.count = 0
self.batch_num = batch_num
self.on_pre_tick = unreal.register_slate_pre_tick_callback(self.__pretick__)
def finish_collection(self):
pd.display(df)
for file in df.filename:
if(os.path.exists(SCREENSHOTS_DIR + "\\" + file)):
os.rename(SCREENSHOTS_DIR + "\\" + file, RESULTS_FILE_PATH + "\\images\\" + file)
# #Saves file information to excel file
df.to_excel(RESULTS_FILE_PATH + "\\" + pc.test_name(TEST_MODE) + "_batch" + str(self.batch_num) + "raw_data.xlsx")
def get_next_params(self):
params = self.parameter_combinations[self.count]
if(self.count >= len(self.parameter_combinations)):
self.finish_collection()
exit()
self.count += 1
return params
def __pretick__(self, deltatime):
try:
self.count += 1
print(self.count)
# params = self.get_next_params()
filename = pc.test_name(TEST_MODE) + "-" + str(self.count) + ".png"
# row = pc.create_row(TEST_MODE, self.count, params, filename)
# print(row)
# blend_weight = row["blend"].item()
# brightness = row["brightness"].item()
# contrast = row["contrast"].item()
# cold_brightness_multiplier = row["cold_brightness_multiplier"].item()
# cold_power = row["cold_power"].item()
# hot_brightness_multiplier = row["hot_brightness_multiplier"].item()
# hot_power = row["hot_power"].item()
# light_bulb_heat_multiplier = row["light_bulb_heat_multiplier"].item()
# blend_weight = 0
# brightness = 0
# contrast = 0
# cold_brightness_multiplier = 0
# cold_power = 0
# hot_brightness_multiplier = 0
# hot_power = 0
# light_bulb_heat_multiplier = 0
# unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"blend_weight", blend_weight)
# unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"Brightness", brightness)
# unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"Contrast", contrast)
# unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"cold_brightness_multiplier", cold_brightness_multiplier)
# unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"cold_power", cold_power)
# unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"hot_brightness_multiplier", hot_brightness_multiplier)
# unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"hot_power", hot_power)
# unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"light_bulb_heat_multiplier", light_bulb_heat_multiplier)
# df.loc[len(df.index)] = row
unreal.AutomationLibrary.take_high_res_screenshot(1920, 1080, filename, camera = camera_actor)
unreal.register_slate_pre_tick_callback(self.on_pre_tick)
print("attempted to take screenshot")
if(self.count == 5): #TODO Delete later: For testing purposes
print(error)
print(df.to_string())
unreal.register_slate_pre_tick_callback(self.on_pre_tick)
except Exception as error:
print(error)
print(df.to_string())
unreal.register_slate_pre_tick_callback(self.on_pre_tick)
unreal.EditorLevelLibrary.pilot_level_actor(camera_actor)
print("capured?")
instance = capture(0)
print("Yes!")
|
import unreal
actorSubsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
gl_level_actors = actorSubsystem.get_all_level_actors()
def getActor(actorName):
filtered_list = unreal.EditorFilterLibrary.by_actor_label(
gl_level_actors,
actorName,
unreal.EditorScriptingStringMatchType.EXACT_MATCH
)
if len(filtered_list) == 0:
unreal.log_warning('Did not find any actor with label: "{}"'.format(actorName))
if len(filtered_list) > 1:
unreal.log_warning('More then one actor with label: "{}"'.format(actorName))
return filtered_list
myActor = getActor('TPhotometricLight_UniforDiffuse')[0]
my_light_component = myActor.light_component
# Usual Python assert
assert my_light_component.intensity_units.name == 'LUMENS', 'Wrong light intensity units'
# or use unreal log error msgs
if not my_light_component.intensity_units.name == 'LUMENS':
unreal.log_error('Wrong light intensity units')
|
import socket
import unreal # Unreal Engine Python API (requires Unreal Engine to be running)
# Simulated RTX API placeholder (can be replaced with actual RTX integrations)
class RTXGraphics:
@staticmethod
def initialize():
print("Initializing RTX Graphics...")
@staticmethod
def render_scene():
print("Rendering scene with RTX graphics...")
# Unreal Engine Integration
class UnrealEngineIntegration:
@staticmethod
def create_actor(actor_name, location):
"""
Create an actor in the Unreal Engine scene.
"""
world = unreal.EditorLevelLibrary.get_editor_world()
actor_class = unreal.EditorAssetLibrary.load_blueprint_class("/project/") # Update the path
actor_location = unreal.Vector(location[0], location[1], location[2])
actor = unreal.EditorLevelLibrary.spawn_actor_from_class(actor_class, actor_location)
actor.set_actor_label(actor_name)
print(f"Actor '{actor_name}' created at {location}.")
# Server Code
def server():
host = "127.0.0.1" # Localhost
port = 65432 # Port to listen on
# Initialize RTX Graphics
RTXGraphics.initialize()
# Create a TCP/IP socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
server_socket.bind((host, port))
server_socket.listen()
print(f"Server listening on {host}:{port}")
while True:
# Wait for a connection
client_socket, client_address = server_socket.accept()
with client_socket:
print(f"Connected by {client_address}")
# Send source data
source_data = "Graphics Source Data"
client_socket.sendall(source_data.encode())
# Receive response from client
response = client_socket.recv(1024).decode()
print(f"Received from client: {response}")
if response == "run_graphics":
print("Running graphics inside the game...")
# Render with RTX
RTXGraphics.render_scene()
# Integrate with Unreal Engine
UnrealEngineIntegration.create_actor("RTXActor", [0, 0, 100])
# Client Code
def client():
host = "127.0.0.1" # Server's hostname or IP address
port = 65432 # Server's port
# Create a TCP/IP socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
client_socket.connect((host, port))
# Receive source data from server
source_data = client_socket.recv(1024).decode()
print(f"Received from server: {source_data}")
# Process the data and send a response
if source_data == "Graphics Source Data":
response = "run_graphics"
client_socket.sendall(response.encode())
# Entry Point
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
print("Usage: python script.py [server|client]")
sys.exit(1)
mode = sys.argv[1]
if mode == "server":
server()
elif mode == "client":
client()
else:
print("Invalid mode. Use 'server' or 'client'.")
|
# /project/
# @CBgameDev Optimisation Script - Log Skel Mesh Missing Physics Asset
# /project/
import unreal
import os
EditAssetLib = unreal.EditorAssetLibrary()
SystemsLib = unreal.SystemLibrary
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()
if _assetClassName == "SkeletalMesh":
#asset_obj = EditAssetLib.load_asset(asset)
_SkeletalMeshAsset = unreal.SkeletalMesh.cast(EditAssetLib.load_asset(asset))
_PhysicsAsset = unreal.SkeletalMesh.cast(_SkeletalMeshAsset).physics_asset
# unreal.log(SkelMeshLib.get_lod_count(_SkeletalMeshAsset))
# unreal.log(_SkeletalMeshAsset)
# StringToCheck = _assetData.get_asset().get_editor_property("phys_material") # asset_obj.get_editor_property("phys_material")
# unreal.log("Used Phys Mat = %s" % StringToCheck)
if not SystemsLib.is_valid(_PhysicsAsset):
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 Skeletal Meshes Missing Physics Assets"
DescOfOptimisation = "Searches the entire project for Skeletal Meshes With No Physics Asset Plugged In"
SummaryMessageIntro = "-- Skeletal Meshes Without Physics Assets Plugged In --"
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
|
# This file is based on templates provided and copyrighted by Autodesk, Inc.
# This file has been modified by Epic Games, Inc. and is subject to the license
# file included in this repository.
from collections import namedtuple, defaultdict
import copy
import os
import unreal
import sgtk
# A named tuple to store LevelSequence edits: the sequence/project/
# the edit is in.
SequenceEdit = namedtuple("SequenceEdit", ["sequence", "track", "section"])
HookBaseClass = sgtk.get_hook_baseclass()
class UnrealSessionCollector(HookBaseClass):
"""
Collector that operates on the Unreal session. Should inherit from the basic
collector hook.
You can read more about collectors here:
http://developer.shotgunsoftware.com/tk-multi-publish2/collector.html
Here's Maya's implementation for reference:
https://github.com/project/-maya/project/-multi-publish2/project/.py
"""
@property
def settings(self):
"""
Dictionary defining the settings that this collector expects to receive
through the settings parameter in the process_current_session and
process_file methods.
A dictionary on the following form::
{
"Settings Name": {
"type": "settings_type",
"default": "default_value",
"description": "One line description of the setting"
}
The type string should be one of the data types that toolkit accepts as
part of its environment configuration.
"""
# grab any base class settings
collector_settings = super(UnrealSessionCollector, self).settings or {}
# Add setting specific to this collector.
work_template_setting = {
"Work Template": {
"type": "template",
"default": None,
"description": "Template path for artist work files. Should "
"correspond to a template defined in "
"templates.yml. If configured, is made available"
"to publish plugins via the collected item's "
"properties. ",
},
}
collector_settings.update(work_template_setting)
return collector_settings
def process_current_session(self, settings, parent_item):
"""
Analyzes the current session in Unreal and parents a subtree of
items under the parent_item passed in.
:param dict settings: Configured settings for this collector
:param parent_item: Root item instance
"""
# Create an item representing the current Unreal session
parent_item = self.collect_current_session(settings, parent_item)
# Collect assets selected in Unreal
self.collect_selected_assets(parent_item)
def collect_current_session(self, settings, parent_item):
"""
Creates an item that represents the current Unreal session.
:param dict settings: Configured settings for this collector
:param parent_item: Parent Item instance
:returns: Item of type unreal.session
"""
# Create the session item for the publish hierarchy
# In Unreal, the current session can be defined as the current level/map (.umap)
# Don't create a session item for now since the .umap does not need to be published
session_item = parent_item
# Get the icon path to display for this item
icon_path = os.path.join(
self.disk_location,
os.pardir,
"icons",
"unreal.png"
)
# Set the icon for the session item
# Will also be used for the children items parented to the session item
session_item.set_icon_from_path(icon_path)
# Set the project root
unreal_sg = sgtk.platform.current_engine().unreal_sg_engine
project_root = unreal_sg.get_shotgun_work_dir()
# Important to convert "/" in path returned by Unreal to "\" for templates to work
project_root = project_root.replace("/", "\\")
session_item.properties["project_root"] = project_root
self.logger.info("Current Unreal project folder is: %s." % (project_root))
# If a work template is defined, add it to the item properties so
# that it can be used by publish plugins
work_template_setting = settings.get("Work Template")
if work_template_setting:
publisher = self.parent
work_template = publisher.get_template_by_name(work_template_setting.value)
if work_template:
# Override the work template to use the project root from Unreal and not the default root for templates
work_template = sgtk.TemplatePath(work_template.definition, work_template.keys, project_root)
session_item.properties["work_template"] = work_template
self.logger.debug("Work template defined for Unreal collection.")
self.logger.info("Collected current Unreal session")
return session_item
def create_asset_item(self, parent_item, asset_path, asset_type, asset_name, display_name=None):
"""
Create an unreal item under the given parent item.
:param asset_path: The unreal asset path, as a string.
:param asset_type: The unreal asset type, as a string.
:param asset_name: The unreal asset name, as a string.
:param display_name: Optional display name for the item.
:returns: The created item.
"""
item_type = "unreal.asset.%s" % asset_type
asset_item = parent_item.create_item(
item_type, # Include the asset type for the publish plugin to use
asset_type, # Display type
display_name or asset_name, # Display name of item instance
)
# Set asset properties which can be used by publish plugins
asset_item.properties["asset_path"] = asset_path
asset_item.properties["asset_name"] = asset_name
asset_item.properties["asset_type"] = asset_type
return asset_item
def collect_selected_assets(self, parent_item):
"""
Creates items for assets selected in Unreal.
:param parent_item: Parent Item instance
"""
unreal_sg = sgtk.platform.current_engine().unreal_sg_engine
sequence_edits = None
# 선택된 에셋 로깅 추가
self.logger.debug("Selected assets: %s", unreal_sg.selected_assets)
self.logger.debug("Selected assets count: %s", len(unreal_sg.selected_assets))
# Iterate through the selected assets and get their info and add them as items to be published
for asset in unreal_sg.selected_assets:
self.logger.debug("Asset: %s", asset)
if asset.asset_class_path.asset_name == "LevelSequence":
if sequence_edits is None:
sequence_edits = self.retrieve_sequence_edits()
self.collect_level_sequence(parent_item, asset, sequence_edits)
else:
self.create_asset_item(
parent_item,
# :class:`Name` instances, we cast them to strings otherwise
# string operations fail down the line..
"%s" % unreal_sg.object_path(asset),
"%s" % asset.asset_class_path.asset_name,
"%s" % asset.asset_name,
)
def get_all_paths_from_sequence(self, level_sequence, sequence_edits, visited=None):
"""
Retrieve all edit paths from the given Level Sequence to top Level Sequences.
Recursively explore the sequence edits, stop the recursion when a Level
Sequence which is not a sub-sequence of another is reached.
Lists of Level Sequences are returned, where each list contains all the
the Level Sequences to traverse to reach the top Level Sequence from the
starting Level Sequence.
For example if a master Level Sequence contains some `Seq_<seq number>`
sequences and each of them contains shots like `Shot_<seq number>_<shot number>`,
a path for Shot_001_010 would be `[Shot_001_010, Seq_001, Master sequence]`.
If an alternate Cut is maintained with another master level Sequence, both
paths would be detected and returned by this method, e.g.
`[[Shot_001_010, Seq_001, Master sequence], [Shot_001_010, Seq_001, Master sequence 2]]`
Maintain a list of visited Level Sequences to detect cycles.
:param level_sequence: A :class:`unreal.LevelSequence` instance.
:param sequence_edits: A dictionary with :class:`unreal.LevelSequence as keys and
lists of :class:`SequenceEdit` as values.
:param visited: A list of :class:`unreal.LevelSequence` instances, populated
as nodes are visited.
:returns: A list of lists of Level Sequences.
"""
if not visited:
visited = []
visited.append(level_sequence)
self.logger.info("Treating %s" % level_sequence.get_name())
if not sequence_edits[level_sequence]:
# No parent, return a list with a single entry with the current
# sequence
return [[level_sequence]]
all_paths = []
# Loop over parents get all paths starting from them
for edit in sequence_edits[level_sequence]:
if edit.sequence in visited:
self.logger.warning(
"Detected a cycle in edits path %s to %s" % (
"->".join(visited), edit.sequence
)
)
else:
# Get paths from the parent and prepend the current sequence
# to them.
for edit_path in self.get_all_paths_from_sequence(
edit.sequence,
sequence_edits,
copy.copy(visited), # Each visit needs its own stack
):
self.logger.info("Got %s from %s" % (edit_path, edit.sequence.get_name()))
all_paths.append([level_sequence] + edit_path)
return all_paths
def collect_level_sequence(self, parent_item, asset, sequence_edits):
"""
Collect the items for the given Level Sequence asset.
Multiple items can be collected for a given Level Sequence if it appears
in multiple edits.
:param parent_item: Parent Item instance.
:param asset: An Unreal LevelSequence asset.
:param sequence_edits: A dictionary with :class:`unreal.LevelSequence as keys and
lists of :class:`SequenceEdit` as values.
"""
unreal_sg = sgtk.platform.current_engine().unreal_sg_engine
level_sequence = unreal.load_asset(unreal_sg.object_path(asset))
for edits_path in self.get_all_paths_from_sequence(level_sequence, sequence_edits):
# Reverse the path to have it from top master sequence to the shot.
edits_path.reverse()
self.logger.info("Collected %s" % [x.get_name() for x in edits_path])
if len(edits_path) > 1:
display_name = "%s (%s)" % (edits_path[0].get_name(), edits_path[-1].get_name())
else:
display_name = edits_path[0].get_name()
item = self.create_asset_item(
parent_item,
edits_path[0].get_path_name(),
"LevelSequence",
edits_path[0].get_name(),
display_name,
)
# Store the edits on the item so we can leverage them later when
# publishing.
item.properties["edits_path"] = edits_path
def retrieve_sequence_edits(self):
"""
Build a dictionary for all Level Sequences where keys are Level Sequences
and values the list of edits they are in.
:returns: A dictionary of :class:`unreal.LevelSequence` where values are
lists of :class:`SequenceEdit`.
"""
sequence_edits = defaultdict(list)
unreal_sg = sgtk.platform.current_engine().unreal_sg_engine
level_sequence_class = unreal.TopLevelAssetPath("/project/", "LevelSequence")
asset_helper = unreal.AssetRegistryHelpers.get_asset_registry()
# Retrieve all Level Sequence assets
all_level_sequences = asset_helper.get_assets_by_class(level_sequence_class)
for lvseq_asset in all_level_sequences:
lvseq = unreal.load_asset(unreal_sg.object_path(lvseq_asset), unreal.LevelSequence)
# Check shots
for track in lvseq.find_master_tracks_by_type(unreal.MovieSceneCinematicShotTrack):
for section in track.get_sections():
# Not sure if you can have anything else than a MovieSceneSubSection
# in a MovieSceneCinematicShotTrack, but let's be cautious here.
try:
# Get the Sequence attached to the section and check if
# it is the one we're looking for.
section_seq = section.get_sequence()
sequence_edits[section_seq].append(
SequenceEdit(lvseq, track, section)
)
except AttributeError:
pass
return sequence_edits
|
import os
import subprocess
CRY_ENGINE_OUTPUT_FOLDER_ROOT = "D:/project/"
LEVEL_ROOT_FOLDER = "data/levels" # Removed leading slash for consistency
LEVEL_LAYERS_FOLDER = "layers"
LEVEL_EDITOR_XML = "level.editor_xml"
PREFAB_ROOT_FOLDER = 'prefabs'
LEVEL_NAME = "rataje"
def convert_meshes_from_list(file_path):
"""
Reads a list of mesh paths from a file and converts each using the cgf-converter tool.
"""
script_dir = os.path.dirname(os.path.abspath(__file__))
converter_exe = os.path.join(script_dir, "../cgf-converter.exe")
with open(file_path, 'r') as file:
for line in file:
mesh_path = line.strip()
if not mesh_path:
continue
full_mesh_path = os.path.join(CRY_ENGINE_OUTPUT_FOLDER_ROOT, mesh_path.replace("/", os.sep))
command = [converter_exe, full_mesh_path, "-dae", "-group"]
try:
print(f"Executing: {' '.join(command)}")
subprocess.run(command, check=True)
except subprocess.CalledProcessError as e:
print(f"Error converting {mesh_path}: {e}")
def import_meshes_to_unreal(file_path):
import unreal
import asset_import_utils
import importlib
importlib.reload(asset_import_utils)
with open(file_path, 'r') as file:
tasks = []
for line in file:
mesh_path = line.strip()
if not mesh_path:
continue
mesh_path = mesh_path.replace(".cgf", ".fbx")
fbx_path = os.path.join(CRY_ENGINE_OUTPUT_FOLDER_ROOT, mesh_path.replace("/", os.sep))
package_name = f"/project/{mesh_path.replace('.fbx', '')}"
package_path = package_name[:package_name.rfind("/")]
name = package_name.split("/")[-1]
if os.path.exists(fbx_path):
option = asset_import_utils.build_staticmesh_import_options()
task = asset_import_utils.build_input_task_simple(fbx_path, package_path, name, option)
tasks.append(task)
else:
unreal.log_error("File not found: {}".format(fbx_path))
asset_import_utils.execute_import_tasks(tasks)
def batch_change_mesh_build_setting():
import unreal
editor_util_lib = unreal.EditorUtilityLibrary
selected_assets = editor_util_lib.get_selected_asset_data()
sm_edit_sub = unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem)
with unreal.ScopedSlowTask(len(selected_assets), "Change mesh build setting..") as slow_task:
# display the dialog
slow_task.make_dialog(True)
for selected_asset in selected_assets:
if slow_task.should_cancel():
break
slow_task.enter_progress_frame(1, "Change mesh build setting for {}".format(selected_asset.asset_name))
static_mesh = unreal.load_asset(selected_asset.package_name)
build_setting = sm_edit_sub.get_lod_build_settings(static_mesh, 0)
build_setting.set_editor_property('recompute_normals', True)
sm_edit_sub.set_lod_build_settings(static_mesh, 0, build_setting)
nanite_setting = sm_edit_sub.get_nanite_settings(static_mesh)
nanite_setting.set_editor_property('enabled', True)
sm_edit_sub.set_nanite_settings(static_mesh, nanite_setting, True)
unreal.EditorAssetLibrary.save_loaded_asset(static_mesh)
if __name__ == "__main__":
script_dir = os.path.dirname(os.path.abspath(__file__))
mesh_list_file = os.path.join(script_dir, "convert_mesh_list.txt")
# convert_meshes_from_list(mesh_list_file)
# import_meshes_to_unreal(mesh_list_file)
batch_change_mesh_build_setting()
|
import unreal
# Instances of Unreal classes
editor_asset_lib = unreal.EditorAssetLibrary()
# Set source dir and options
source_dir = "/project/"
include_subfolders = True
deleted = 0
# Get all assets in source dir
assets = editor_asset_lib.list_assets(source_dir, recursive=include_subfolders, include_folder=True)
folders = [asset for asset in assets if editor_asset_lib.does_directory_exist(asset)]
for folder in folders:
# Check if folder has assets
has_assets = editor_asset_lib.does_directory_have_assets(folder)
if not has_assets:
# Delete folder
editor_asset_lib.delete_directory(folder)
deleted += 1
unreal.log(f"Folder {folder} without assets was deleted.")
unreal.log(f"Deleted {deleted} folders without assets.")
|
import unreal
import os
import scripts.utils.popUp as popUp
#########################################################################################################
# UEFileManager #
#########################################################################################################
class UEFileFunctionalities:
"""
Class for Unreal Engine file functionalities.
This class provides methods to interact with files and directories within an Unreal Engine project.
Methods:
- get_all_files_in_directory(self, directory): Get all files from a single directory (non-recursively).
- get_project_path(self): Get the project path.
- fetch_files_from_dir_in_project(self, dir, project_path): Fetch files from a directory in the project.
"""
def __init__(self):
pass
def get_all_files_in_directory(self, directory):
"""
Get all files from a single directory (non-recursively).
Args:
- directory (str): The directory path.
Returns:
- files_list (list): A list of file names in the directory.
"""
files_list = []
# Check if the directory exists
if os.path.exists(directory) and os.path.isdir(directory):
# List all files in the directory
files_list = [
f
for f in os.listdir(directory)
if os.path.isfile(os.path.join(directory, f))
]
else:
popUp.show_popup_message("UEFileManager", "Not a valid dir")
return files_list
def get_project_path(self):
"""
Get the project path.
Returns:
- project_path (str): The project path in normal Windows path form.
"""
project_path = unreal.Paths.project_dir().rstrip("/")
return project_path.split("../")[-1]
def fetch_files_from_dir_in_project(self, dir, project_path, mode="windows"):
"""
Fetch files from a directory in the project.
Args:
- dir (str): The directory path within the project.
- project_path (str): The project path.
Returns:
- files_list (list): A list of file names in the directory.
"""
# Check if the UE path exists in the project
if unreal.EditorAssetLibrary.does_directory_exist(dir + "/"):
if "/Game" in dir:
# Get the complete path in windows form
complete_path = (
"C:/" + project_path + "/Content" + dir.split("/Game")[1]
)
else:
complete_path = "C:/" + project_path + "/Content" + dir
if mode == "windows":
files = [
complete_path + "/" + file
for file in self.get_all_files_in_directory(complete_path)
]
else:
files = [
dir + file
for file in self.get_all_files_in_directory(complete_path)
]
return files
return []
|
import unreal
from Lib import __lib_topaz__ as topaz
desired_triangle_percentage : float # UI Binded Value
assets = topaz.get_selected_assets()
## execution here ##
for each in assets :
if each.__class__ == unreal.Blueprint :
comps = topaz.get_component_by_class(each, unreal.StaticMeshComponent)
for comp in comps :
static_mesh = comp.static_mesh
blendModes = topaz.get_materials_from_staticmesh(static_mesh, True)
is_translucent_exist = topaz.is_translucent_exist(blendModes)
if static_mesh is not None and not is_translucent_exist:
nanite_settings : unreal.MeshNaniteSettings = static_mesh.get_editor_property('nanite_settings')
nanite_settings.enabled = True
nanite_settings.keep_percent_triangles = desired_triangle_percentage
static_mesh.set_editor_property('nanite_settings', nanite_settings)
#print(nanite_settings.keep_percent_triangles)
if each.__class__ == unreal.StaticMesh :
blendModes = topaz.get_materials_from_staticmesh(static_mesh, True)
is_translucent_exist = topaz.is_translucent_exist(blendModes)
if each is not None and not is_translucent_exist:
nanite_settings : unreal.MeshNaniteSettings = each.get_editor_property('nanite_settings')
nanite_settings.enabled = True
nanite_settings.set_editor_property('keep_percent_triangles', desired_triangle_percentage)
each.set_editor_property('nanite_settings', nanite_settings)
print('OK')
|
import unreal
from pathlib import Path
import sys
# import os
# import shutil
# sys.path.append(str(Path(__file__).parent.parent.parent.parent.parent.resolve()))
# from importlib import *
# reloads = []
# for k, v in sys.modules.items():
# if k.startswith("pamux_unreal_tools"):
# reloads.append(v)
# for module in reloads:
# reload(module)
from pamux_unreal_tools.generated.material_expression_wrappers import *
from pamux_unreal_tools.utils.types import *
from pamux_unreal_tools.builders.material_function_builder import MaterialFunctionBuilder
from pamux_unreal_tools.base.material_function.material_function_outputs_base import MaterialFunctionOutputs
from pamux_unreal_tools.base.material_expression.material_expression_container_builder_base import MaterialExpressionContainerBuilderBase
from pamux_unreal_tools.interfaces.IHeightLerpWithTwoHeightMaps import IHeightLerpWithTwoHeightMaps
from pamux_unreal_tools.examples.M_Landscape_Master.interfaces.IBlendTwoMaterialsViaHighOpacityMap import IBlendTwoMaterialsViaHighOpacityMap
from pamux_unreal_tools.factories.material_function_factory import MaterialFunctionFactory
class MF_BlendTwoMaterialsViaHighOpacityMap:
@staticmethod
def load_MF(builder):
return builder.load_MF("/project/",
["Alpha", "MaterialA", "MaterialB"],
["Result"])
class Dependencies:
def __init__(self, builder: MaterialExpressionContainerBuilderBase) -> None:
self.heightLerpWithTwoHeightMaps = builder.load_MF(
"/project/",
[ "Transistion Phase", "Height Texture 1", "Height Texture 2" ],
[ "Alpha" ])
class Inputs:
def __init__(self, builder: MaterialExpressionContainerBuilderBase) -> None:
# No Preview
self.materialA = builder.build_FunctionInput("MaterialA", 0, TMaterialAttributes(), False, False)
self.materialB = builder.build_FunctionInput("MaterialB", 1, TMaterialAttributes(), False, False)
self.alpha = builder.build_FunctionInput("Alpha", 2, 0.0, False, False)
class Builder(MaterialFunctionBuilder):
def __init__(self) -> None:
super().__init__(
"/project/",
MF_BlendTwoMaterialsViaHighOpacityMap.Dependencies,
MF_BlendTwoMaterialsViaHighOpacityMap.Inputs,
MaterialFunctionOutputs.Result)
def build(self):
breakMaterialAttributesA = BreakMaterialAttributes(self.inputs.materialA)
breakMaterialAttributesA.opacity.add_rt()
breakMaterialAttributesB = BreakMaterialAttributes(self.inputs.materialB)
breakMaterialAttributesB.opacity.add_rt()
lerp = self.dependencies.heightLerpWithTwoHeightMaps.call()
lerp.inputs.transistionPhase.comesFrom(self.inputs.alpha) # Transistion is misspelled in the built in function
lerp.inputs.heightTexture1.comesFrom(breakMaterialAttributesA.opacity)
lerp.inputs.heightTexture2.comesFrom(breakMaterialAttributesB.opacity)
blendMaterialAttributes = BlendMaterialAttributes(self.inputs.materialA, self.inputs.materialB, lerp.outputs.alpha)
blendMaterialAttributes.connectTo(self.outputs.result)
# MF_BlendTwoMaterialsViaHighOpacityMap.Builder().get()
|
# AdvancedSkeleton To ControlRig
# Copyright (C) Animation Studios
# email: user@example.com
# 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')
ControlRigBlueprint = selectedAsset
HierarchyModifier = ControlRigBlueprint.get_hierarchy_modifier()
try:
RigVMController = ControlRigBlueprint.get_editor_property('controller') #UE4
except:
RigVMController = ControlRigBlueprint.get_controller() #UE5
PreviousArrayInfo = dict()
global ASCtrlNr
global PreviousEndPlug
global PreviousEndPlugInv
global PreviousYInv
global sp
global nonTransformFaceCtrlNr
ASCtrlNr = 0
PreviousYInv = 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 PreviousArrayInfo
global ctrlBoxSize
global ASCtrlNr
global nonTransformFaceCtrlNr
endPlug = name+'_CON.ExecuteContext'
RigVMGraph = ControlRigBlueprint.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 = HierarchyModifier.get_elements()
for key in RigElementKeys:
if (key.name == 'Root_M'):
RootScale = HierarchyModifier.get_bone (key).get_editor_property('global_transform').scale3d
if (key.name == ParentRigBoneName):
if (key.type == 1):#Bone
ParentRigBone = HierarchyModifier.get_bone (key)
RigControl = asAddController (name, parent, joint, type, gizmoName, ws, size, offT, color)
if name=='Main':
return
#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)
if name=='RootX_M':
#CON
CON = asAddNode (sp+'TransformConstraintPerItem','Execute',node_name=name+'_CON')
RigVMController.set_node_position (CON, [100, y-90])
RigVMController.set_pin_default_value(name+'_CON.Item.Type','Bone')
RigVMController.set_pin_default_value(name+'_CON.Item.Name',joint)
RigVMController.add_array_pin(name+'_CON.Targets')
RigVMController.add_link(name+'_GT.Transform' , name+'_CON.Targets.0.Transform')
RigVMController.add_link(PreviousEndPlug , name+'_CON.ExecuteContext')
endPlug = name+'_CON.ExecuteContext'
else:
#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(PreviousEndPlug , name+'_ST.ExecuteContext')
endPlug = name+'_ST.ExecuteContext'
if type=='FK':
if "twistJoints" in PreviousArrayInfo:
inbetweenJoints = int (PreviousArrayInfo["twistJoints"])
key = HierarchyModifier.add_bone ('UnTwist'+ParentRigBoneName,parent_name=joint)
UnTwistBone = HierarchyModifier.get_bone (key)
UnTwistBone.set_editor_property('local_transform', unreal.Transform())
asParent ('UnTwist'+ParentRigBoneName,'TwistSystem')
asAlign (ParentRigBoneName,'UnTwist'+ParentRigBoneName)
#GTParent
constraintTo = str(ParentRigBone.get_editor_property('parent_name'))
x = re.search("Part", constraintTo)
if x:
constraintTo = ParentRigBoneName
GTParent = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTParent')
RigVMController.set_node_position (GTParent, [600, y])
RigVMController.set_pin_default_value(name+'_GTParent.Item.Type','Bone')
RigVMController.set_pin_default_value(name+'_GTParent.Item.Name',constraintTo)
#CONUnTwist
CONUnTwist = asAddNode (sp+'TransformConstraintPerItem','Execute',node_name=name+'_CONUnTwist')
RigVMController.set_node_position (CONUnTwist, [1000, y])
RigVMController.set_pin_default_value(name+'_CONUnTwist.Item.Type','Bone')
RigVMController.set_pin_default_value(name+'_CONUnTwist.Item.Name','UnTwist'+ParentRigBoneName)
RigVMController.add_array_pin(name+'_CONUnTwist.Targets')
RigVMController.add_link(name+'_GTParent.Transform' , name+'_CONUnTwist.Targets.0.Transform')
RigVMController.add_link(endPlug , name+'_CONUnTwist.ExecuteContext')
Items = asAddNode (sp+'CollectionItems','Execute',node_name=name+'_Items')
RigVMController.set_node_position (Items, [1450, y])
RigVMController.set_pin_default_value(name+'_Items.Items.0.Name','UnTwist'+ParentRigBoneName)
for x in range(1,inbetweenJoints+3):
RigVMController.add_array_pin(name+'_Items.Items')
RigVMController.set_pin_default_value(name+'_Items.Items.'+str(x)+'.Name',ParentRigBoneBaseName+'Part'+str((x-1))+side)
RigVMController.set_pin_default_value(name+'_Items.Items.'+str(x)+'.Type','Bone')
RigVMController.set_pin_default_value(name+'_Items.Items.1.Name',ParentRigBoneName)
RigVMController.set_pin_default_value(name+'_Items.Items.'+str((inbetweenJoints+2))+'.Name',joint)
Twist = asAddNode (sp+'TwistBonesPerItem','Execute',node_name=name+'_Twist')
RigVMController.set_node_position (Twist, [1750, y])
RigVMController.add_link(name+'_Items.Collection' , name+'_Twist.Items')
RigVMController.add_link(name+'_CONUnTwist.ExecuteContext' , name+'_Twist.ExecuteContext')
endPlug = name+'_Twist.ExecuteContext'
if "inbetweenJoints" in arrayInfo:
inbetweenJoints = int (arrayInfo["inbetweenJoints"])
Chain = asAddNode (sp+'CollectionChain','Execute',node_name=name+'_Chain')
RigVMController.set_node_position (Chain, [1350, y])
RigVMController.set_pin_default_value(name+'_Chain.FirstItem.Name',baseName+'Part1'+side)
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, [1700, 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+'DistributeRotationForCollection','Execute',node_name=name+'_Distr')
RigVMController.set_node_position (Distr, [2100, y])
weight = (1.0 / inbetweenJoints)
RigVMController.set_pin_default_value(name+'_Distr.Weight',str(weight))
RigVMController.add_link(name+'_Chain.Collection' , 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(PreviousEndPlug , name+'_Distr.ExecuteContext')
endPlug = name+'_Distr.ExecuteContext'
if "inbetweenJoints" in PreviousArrayInfo:
Transform = RigControl.get_editor_property('offset_transform')
SpaceKey = HierarchyModifier.add_space ('Space'+joint)
Space = HierarchyModifier.get_space (SpaceKey)
Space.set_editor_property('initial_transform', Transform)
HierarchyModifier.set_space (Space)
RigControl.set_editor_property('offset_transform', unreal.Transform())
HierarchyModifier.set_control (RigControl)
asParent (name,'Space'+joint)
asParent ('Space'+joint,parent)
#GTSpace
GTSpace = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTSpace')
RigVMController.set_node_position (GTSpace, [600, y])
RigVMController.set_pin_default_value(name+'_GTSpace.Item.Type','Bone')
RigVMController.set_pin_default_value(name+'_GTSpace.Item.Name',joint)
#STSpace
STSpace = asAddNode (sp+'SetTransform','Execute',node_name=name+'_STSpace')
RigVMController.set_node_position (STSpace, [950, y])
RigVMController.set_pin_default_value(name+'_STSpace.Item.Type','Space')
RigVMController.set_pin_default_value(name+'_STSpace.Item.Name','Space'+joint)
RigVMController.add_link(name+'_GTSpace.Transform' , name+'_STSpace.Transform')
RigVMController.set_pin_default_value(name+'_STSpace.bPropagateToChildren','True')
RigVMController.add_link(PreviousEndPlug , name+'_STSpace.ExecuteContext')
if not "inbetweenJoints" in arrayInfo:
RigVMController.add_link(name+'_STSpace.ExecuteContext' , name+'_ST.ExecuteContext')
else:
RigVMController.add_link(name+'_STSpace.ExecuteContext' , name+'_Distr.ExecuteContext')
if "global" in arrayInfo and float(arrayInfo["global"])==10:
SpaceKey = HierarchyModifier.add_space ('Global'+name)
SpaceObj = HierarchyModifier.get_space (SpaceKey)
asParent ('Global'+name, parent)
asAlign (name,'Global'+name)
RigControl.set_editor_property('offset_transform', unreal.Transform())
HierarchyModifier.set_control (RigControl)
asParent (name,'Global'+name)
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','Space')
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')
#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','Space')
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 = HierarchyModifier.get_initial_transform(SpaceKey)
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')
# RigVMController.add_link(name+'_STGlobal.ExecuteContext' , endPlug)
RigVMController.add_link(name+'_STGlobal.ExecuteContext' , name+'_ST.ExecuteContext')
if type=='IK':
RigControl = asAddController ('Pole'+name, parent, joint, type, 'Box_Solid', ws, size/5.0, offT, color)
RigControl.set_editor_property('offset_transform', unreal.Transform(location=[float(arrayInfo["ppX"])*RootScale.x,float(arrayInfo["ppZ"])*RootScale.y,float(arrayInfo["ppY"])*RootScale.z],scale=RootScale))
HierarchyModifier.set_control (RigControl)
#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(PreviousEndPlug , name+'_IK.ExecuteContext')
endPlug = name+'_IK.ExecuteContext'
#GTSpace
GTSpace = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTSpace')
RigVMController.set_node_position (GTSpace, [1000, y])
RigVMController.set_pin_default_value(name+'_GTSpace.Item.Type','Bone')
RigVMController.set_pin_default_value(name+'_GTSpace.Item.Name',arrayInfo["endJoint"])
#modify _GT to use a local-oriented child of ws controller
key = HierarchyModifier.add_control (name+'LS',parent_name=name)
RigControl = HierarchyModifier.get_control (key)
RigControl.set_editor_property('gizmo_enabled',False)
HierarchyModifier.set_control (RigControl)
RigVMController.set_pin_default_value(name+'_GT.Item.Name',name+'LS')
for key in RigElementKeys:
if (key.name == arrayInfo["endJoint"]):
endJointObject = HierarchyModifier.get_bone (key)
EndJointTransform = endJointObject.get_editor_property('global_transform')
Rotation = EndJointTransform.rotation.rotator()
Transform = unreal.Transform(location=[0,0,0],rotation=Rotation,scale=[1,1,1])
RigControl.set_editor_property('offset_transform', Transform)
HierarchyModifier.set_control (RigControl)
#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.add_link(name+'_GTSpace.Transform' , name+'_STinvIK.Transform')
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.add_link(name+'_GTSpace.Transform' , name+'_STinvPole.Transform')
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
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':
Transform = RigControl.get_editor_property('gizmo_transform')
if name=='ctrlBox':
RigControl.offset_transform.translation = [Transform.translation.z,(Transform.translation.y*-1),Transform.translation.x]
ctrlBoxSize = float (arrayInfo["ctrlBoxSize"])
Scale = [0.07,0.15,0.1]
ctrlBoxScale = [ctrlBoxSize,ctrlBoxSize,ctrlBoxSize]
RigControl.offset_transform.scale3d = ctrlBoxScale
RigControl.gizmo_transform.scale3d = Scale
RigControl.gizmo_transform.translation = [0,0,-1.5] #guestimate
HierarchyModifier.set_control (RigControl)
return
nonTransformFaceCtrl = False
if name=='ctrlEmotions_M' or name=='ctrlPhonemes_M' or name=='ctrlARKit_M' or name=='ctrlBoxRobloxHead_M':
nonTransformFaceCtrl = True
nonTransformFaceCtrlNr = nonTransformFaceCtrlNr+1
RigControl.set_editor_property('gizmo_enabled',False)
HierarchyModifier.set_control (RigControl)
if type=='ctrlBox':
RigVMController.remove_node(RigVMGraph.find_node_by_name(name+'_GT'))
RigVMController.remove_node(RigVMGraph.find_node_by_name(name+'_ST'))
RigControl.set_editor_property('control_type',unreal.RigControlType.VECTOR2D)
RigControl.set_editor_property('primary_axis',unreal.RigControlAxis.Y)
RigControl.offset_transform.translation = Transform.translation * (1.0/ctrlBoxSize)
RigControl.gizmo_transform.scale3d = [0.05,0.05,0.05]
RigControl.limit_translation = True
value = unreal.RigControlValue()
RigControl.maximum_value = value
RigControl.gizmo_transform.translation = [0,0,0]
HierarchyModifier.set_control (RigControl)
maxXform = unreal.Transform(location=[1,1,1])
minXform = unreal.Transform(location=[-1,-1,-1])
if name=='ctrlMouth_M':
maxXform = unreal.Transform(location=[1,1,0])
if re.search("^ctrlCheek_", name) or re.search("^ctrlNose_", name):
minXform = unreal.Transform(location=[-1,-1,0])
RigElementKeys = HierarchyModifier.get_elements()
for key in RigElementKeys:
if (key.name == name):
RigControlKey = key
HierarchyModifier.set_control_value_transform (RigControlKey, maxXform, value_type=unreal.RigControlValueType.MAXIMUM)
HierarchyModifier.set_control_value_transform (RigControlKey, minXform, value_type=unreal.RigControlValueType.MINIMUM)
HierarchyModifier.set_control (HierarchyModifier.get_control (RigControlKey))
endPlug = PreviousEndPlug
if type=='ctrlBox':
AttrGrpkey = HierarchyModifier.add_control (name+"_Attributes",parent_name=parent)
else:
AttrGrpkey = HierarchyModifier.add_control (name+"_Attributes",parent_name=name)
AttrGrpRigControl = HierarchyModifier.get_control (AttrGrpkey)
AttrGrpRigControl.set_editor_property('gizmo_transform', unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[0,0,0]))
Transform = RigControl.get_editor_property('offset_transform').copy()
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]
AttrGrpRigControl.set_editor_property('offset_transform', Transform)
HierarchyModifier.set_control (AttrGrpRigControl)
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])
minXform = unreal.Transform(location=[min,min,min])
RigElementKeys = HierarchyModifier.get_elements()
for key in RigElementKeys:
if key.name == name+"_"+Attr.replace("-setLimits", ""):
HierarchyModifier.set_control_value_transform (key, minXform, value_type=unreal.RigControlValueType.MINIMUM)
HierarchyModifier.set_control (HierarchyModifier.get_control (key))
continue
transformAttrDriver = True
if not re.search("translate", Attr) or re.search("rotate", Attr) or re.search("scale", Attr):
key = HierarchyModifier.add_control (name+"_"+Attr,parent_name=parent)
AttrRigControl = HierarchyModifier.get_control (key)
AttrRigControl = asParent (name+"_"+Attr, name+"_Attributes")
AttrRigControl.set_editor_property('control_type',unreal.RigControlType.FLOAT)
AttrRigControl.set_editor_property('gizmo_color', unreal.LinearColor(r=1.0, g=0.0, b=0.0, a=0.0))
AttrRigControl.set_editor_property('gizmo_transform', unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[0.035,0.035,0.035]))
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):
AttrRigControl.set_editor_property('primary_axis',unreal.RigControlAxis.Z)
Transform.translation = [attrNr,0,0]
attrNr = attrNr+1
AttrRigControl.set_editor_property('offset_transform', Transform)
AttrRigControl.limit_translation = True
HierarchyModifier.set_control (AttrRigControl)
maxXform = unreal.Transform(location=[1,1,1])
RigElementKeys = HierarchyModifier.get_elements()
for key in RigElementKeys:
if (key.name == name+"_"+Attr):
RigControlKey = key
HierarchyModifier.set_control_value_transform (RigControlKey, maxXform, value_type=unreal.RigControlValueType.MAXIMUM)
HierarchyModifier.set_control (HierarchyModifier.get_control (RigControlKey))
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 = HierarchyModifier.get_elements()
for key in RigElementKeys:
if key.name == obj:
objObject = HierarchyModifier.get_control(key)
if not asObjExists ('Offset'+obj):
SpaceKey = HierarchyModifier.add_space ('Offset'+obj)
SpaceObj = HierarchyModifier.get_space (SpaceKey)
objParent = str(objObject.get_editor_property('parent_name'))
asParent ('Offset'+obj, objParent)
asAlign (obj,'Offset'+obj)
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)
SpaceKey = HierarchyModifier.add_space (sdk)
asParent (sdk,parentTo)
objObject.set_editor_property('offset_transform', unreal.Transform())
HierarchyModifier.set_control (objObject)
asParent (obj,sdk)
#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','Space')
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)
HierarchyModifier.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)
HierarchyModifier.set_control (RigControl)
PreviousEndPlug = endPlug
def asObjExists (obj):
RigElementKeys = HierarchyModifier.get_elements()
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):
x = re.search("^Space.*", parent)
if x:
key = HierarchyModifier.add_control (name,space_name=parent)
else:
key = HierarchyModifier.add_control (name,parent_name=parent)
RigControl = HierarchyModifier.get_control (key)
RigElementKeys = HierarchyModifier.get_elements()
LocObject = None
jointIsBone = False
for key in RigElementKeys:
if key.name == joint:
if key.type == 1: #BONE
jointObject = HierarchyModifier.get_bone(key)
jointIsBone = True
if key.name == 'Loc'+name:
LocObject = HierarchyModifier.get_bone(key)
OffsetTransform = unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[1,1,1])
GizmoLocation = [offT[0],offT[2],offT[1]]
GizmoRotation = [0,0,0]
if ws is 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]
RigControl.set_editor_property('gizmo_visible',False)
x = re.search("^Pole.*", name)
if x:
GizmoLocation = [0,0,0]
s = 0.01*size
Scale = [s,s,s]
if LocObject==None:
LocKey = HierarchyModifier.add_bone ('Loc'+name,'LocBones')
LocObject = HierarchyModifier.get_bone (LocKey)
if jointIsBone:
jointTransform = jointObject.get_editor_property('global_transform')
if ws is 1:
jointTransform.rotation = [0,0,0]
OffsetTransform = jointTransform
if name!='Main':
LocObject.set_editor_property('initial_transform', jointTransform)
HierarchyModifier.set_bone (LocObject)
if parent!='':
for key in RigElementKeys:
if key.name == 'Loc'+parent:
ParentLocObject = HierarchyModifier.get_bone(key)
LocTransform = ParentLocObject.get_editor_property('global_transform')
if jointIsBone:
OffsetTransform = jointTransform.make_relative(LocTransform)
RigControl.set_editor_property('offset_transform', OffsetTransform)
RigControl.set_editor_property('gizmo_name',gizmoName)
RigControl.set_editor_property('gizmo_transform', unreal.Transform(location=GizmoLocation,rotation=GizmoRotation,scale=Scale))
Color = unreal.Color(b=color[2]*255, g=color[1]*255, r=color[0]*255, a=0)
LinearColor = unreal.LinearColor()
LinearColor.set_from_srgb(Color)
RigControl.set_editor_property('gizmo_color',LinearColor)
HierarchyModifier.set_control (RigControl)
return RigControl
def asParent (child,parent):
RigElementKeys = HierarchyModifier.get_elements()
for key in RigElementKeys:
if (key.name == child):
childKey = key
for key in RigElementKeys:
if (key.name == parent):
parentKey = key
if not HierarchyModifier.reparent_element (childKey, parentKey):
#bug in UE4.27: n`th Space, can not be child of n`th Ctrl, making a new space
HierarchyModifier.rename_element (childKey, child+'SpaceParentX')
childKey = HierarchyModifier.add_space (child)
if not HierarchyModifier.reparent_element (childKey, parentKey):
raise Exception('Failed to parent:'+child+' to '+parent)
asParent (child+'SpaceParentX','Spaces')
return asGetRigElement(child)
def asGetRigElement (elementName):
RigElementKeys = HierarchyModifier.get_elements()
for key in RigElementKeys:
if key.name == elementName:
if key.type == 1: #BONE
element = HierarchyModifier.get_bone(key)
if key.type == 2: #SPACE
element = HierarchyModifier.get_space(key)
if key.type == 4: #CONTROL
element = HierarchyModifier.get_control(key)
return element
def asAlign (source,dest):
RigElementKeys = HierarchyModifier.get_elements()
for key in RigElementKeys:
if (key.name == source):
if key.type == 1: #BONE
sourceObject = HierarchyModifier.get_bone(key)
sourceType = 'Bone'
if key.type == 2: #SPACE
sourceObject = HierarchyModifier.get_space(key)
sourceType = 'Space'
if key.type == 4: #CONTROL
sourceObject = HierarchyModifier.get_control(key)
sourceType = 'Control'
if (key.name == dest):
if key.type == 1: #BONE
destObject = HierarchyModifier.get_bone(key)
destType = 'Bone'
if key.type == 2: #SPACE
destObject = HierarchyModifier.get_space(key)
destType = 'Space'
if key.type == 4: #CONTROL
destObject = HierarchyModifier.get_control(key)
destType = 'Control'
if sourceType != 'Bone':
for key in RigElementKeys:
if key.name == 'Loc'+source:
source = 'Loc'+source
sourceObject = HierarchyModifier.get_bone(key)
sourceType = 'Bone'
Transform = sourceObject.get_editor_property('global_transform')
#Relative to parent
LocDestParent = None
DestParent = destObject.get_editor_property('parent_name')
for key in RigElementKeys:
if key.name == 'Loc'+str(DestParent):
LocDestParent = HierarchyModifier.get_bone(key)
LocDestParentTransform = LocDestParent.get_editor_property('global_transform')
Transform = Transform.make_relative(LocDestParentTransform)
destObject.set_editor_property('initial_transform', Transform)
if destType == 'Bone':
HierarchyModifier.set_bone (destObject)
if destType == 'Space':
HierarchyModifier.set_space (destObject)
if destType == 'Control':
HierarchyModifier.set_control (destObject)
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 main ():
global PreviousEndPlugInv
RigElementKeys = HierarchyModifier.get_elements()
RigVMGraph = ControlRigBlueprint.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':
HierarchyModifier.remove_element(key)
if not (key.type==1 or key.type==8): #BONE
try:
HierarchyModifier.remove_element(key)
except:
pass
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])
#Backwards solve nodes
GTinvRoot = asAddNode (sp+'GetTransform','Execute',node_name='Root_M_GTinvRoot')
RigVMController.set_node_position (GTinvRoot, [-2100, 400])
RigVMController.set_pin_default_value('Root_M_GTinvRoot.Item.Type','Bone')
RigVMController.set_pin_default_value('Root_M_GTinvRoot.Item.Name','Root_M')
CONinvRoot = asAddNode (sp+'TransformConstraintPerItem','Execute',node_name='Root_M_CONinvRoot')
RigVMController.set_node_position (CONinvRoot, [-1500, 400-90])
RigVMController.set_pin_default_value('Root_M_CONinvRoot.Item.Type','Control')
RigVMController.set_pin_default_value('Root_M_CONinvRoot.Item.Name','RootX_M')
RigVMController.add_array_pin('Root_M_CONinvRoot.Targets')
RigVMController.add_link('Root_M_GTinvRoot.Transform' , 'Root_M_CONinvRoot.Targets.0.Transform')
RigVMController.add_link('RigUnit_InverseExecution.ExecuteContext' , 'Root_M_CONinvRoot.ExecuteContext')
CCinv = asAddNode (sp+'CollectionChildren','Execute',node_name='CCinv')
RigVMController.set_node_position (CCinv, [-2600, 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, 1000])
RigVMController.add_link('Root_M_CONinvRoot.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, 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, 1000])
RigVMController.add_link('CLinv.Item.Name' , 'GTinv.Item.Name')
IEinv = asAddNode (sp+'ItemExists','Execute',node_name='IEinv')
RigVMController.set_node_position (IEinv, [-1700, 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, 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, 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')
HierarchyModifier.add_bone ('MotionSystem')
HierarchyModifier.add_bone ('TwistSystem')
HierarchyModifier.add_bone ('LocBones')
HierarchyModifier.add_bone ('DrivingSystem')
HierarchyModifier.add_bone ('Spaces')
asParent ('TwistSystem','MotionSystem')
asParent ('LocBones','MotionSystem')
asParent ('DrivingSystem','MotionSystem')
asParent ('Spaces','MotionSystem')
selectedAsset.get_class().modify(True)#tag dirty
#//-- ASControllers Starts Here --//
#//-- ASControllers Ends Here --//
# selectedAsset.get_class().modify(True)#tag dirty
# Unreal un-sets `dirty` flag upon opening of ControlRigEditor, causing non-prompt for save upon exit and loss of ControlRig, therefor just save
# unreal.EditorAssetLibrary.save_asset(selectedAsset.get_path_name()) #Removed since this requires "Editor Scripting Utilities" plugin
selectedAsset.get_class().modify(False)
print ("ControlRig created")
if __name__ == "__main__":
main()
|
# 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 math
import unreal
@unreal.uclass()
class CurveInputExample(unreal.PlacedEditorUtilityBase):
# Use a FProperty to hold the reference to the API wrapper we create in
# run_curve_input_example
_asset_wrapper = unreal.uproperty(unreal.HoudiniPublicAPIAssetWrapper)
@unreal.ufunction(meta=dict(BlueprintCallable=True, CallInEditor=True))
def run_curve_input_example(self):
# Get the API instance
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
# Ensure we have a running session
if not api.is_session_valid():
api.create_session()
# Load our HDA uasset
example_hda = unreal.load_object(None, '/project/.copy_to_curve_1_0')
# Create an API wrapper instance for instantiating the HDA and interacting with it
wrapper = api.instantiate_asset(example_hda, instantiate_at=unreal.Transform())
if wrapper:
# Pre-instantiation is the earliest point where we can set parameter values
wrapper.on_pre_instantiation_delegate.add_function(self, '_set_initial_parameter_values')
# Jumping ahead a bit: we also want to configure inputs, but inputs are only available after instantiation
wrapper.on_post_instantiation_delegate.add_function(self, '_set_inputs')
# Jumping ahead a bit: we also want to print the outputs after the node has cook and the plug-in has processed the output
wrapper.on_post_processing_delegate.add_function(self, '_print_outputs')
self.set_editor_property('_asset_wrapper', wrapper)
@unreal.ufunction(params=[unreal.HoudiniPublicAPIAssetWrapper], meta=dict(CallInEditor=True))
def _set_initial_parameter_values(self, in_wrapper):
""" Set our initial parameter values: disable upvectorstart and set the scale to 0.2. """
# Uncheck the upvectoratstart parameter
in_wrapper.set_bool_parameter_value('upvectoratstart', False)
# Set the scale to 0.2
in_wrapper.set_float_parameter_value('scale', 0.2)
# Since we are done with setting the initial values, we can unbind from the delegate
in_wrapper.on_pre_instantiation_delegate.remove_function(self, '_set_initial_parameter_values')
@unreal.ufunction(params=[unreal.HoudiniPublicAPIAssetWrapper], meta=dict(CallInEditor=True))
def _set_inputs(self, in_wrapper):
""" Configure our inputs: input 0 is a cube and input 1 a helix. """
# Create an empty geometry input
geo_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPIGeoInput)
# Load the cube static mesh asset
cube = unreal.load_object(None, '/project/.Cube')
# Set the input object array for our geometry input, in this case containing only the cube
geo_input.set_input_objects((cube, ))
# Set the input on the instantiated HDA via the wrapper
in_wrapper.set_input_at_index(0, geo_input)
# 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)
# 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)
# unbind from the delegate, since we are done with setting inputs
in_wrapper.on_post_instantiation_delegate.remove_function(self, '_set_inputs')
@unreal.ufunction(params=[unreal.HoudiniPublicAPIAssetWrapper], meta=dict(CallInEditor=True))
def _print_outputs(self, in_wrapper):
""" Print the outputs that were generated by the HDA (after a cook) """
num_outputs = in_wrapper.get_num_outputs()
print('num_outputs: {}'.format(num_outputs))
if num_outputs > 0:
for output_idx in range(num_outputs):
identifiers = in_wrapper.get_output_identifiers_at(output_idx)
print('\toutput index: {}'.format(output_idx))
print('\toutput type: {}'.format(in_wrapper.get_output_type_at(output_idx)))
print('\tnum_output_objects: {}'.format(len(identifiers)))
if identifiers:
for identifier in identifiers:
output_object = in_wrapper.get_output_object_at(output_idx, identifier)
output_component = in_wrapper.get_output_component_at(output_idx, identifier)
is_proxy = in_wrapper.is_output_current_proxy_at(output_idx, identifier)
print('\t\tidentifier: {}'.format(identifier))
print('\t\toutput_object: {}'.format(output_object.get_name() if output_object else 'None'))
print('\t\toutput_component: {}'.format(output_component.get_name() if output_component else 'None'))
print('\t\tis_proxy: {}'.format(is_proxy))
print('')
def run():
# Spawn CurveInputExample and call run_curve_input_example
curve_input_example_actor = unreal.EditorLevelLibrary.spawn_actor_from_class(CurveInputExample.static_class(), unreal.Vector.ZERO, unreal.Rotator())
curve_input_example_actor.run_curve_input_example()
if __name__ == '__main__':
run()
|
#! /project/ python
# -*- coding: utf-8 -*-
"""
Initialization module for mca-package
"""
# mca python imports
# software specific imports
import unreal
# mca python imports
from mca.common import log
from mca.ue.utils import asset_utils
logger = log.MCA_LOGGER
def import_asset(filename, game_path, asset_name, import_options=None, replace_existing=True, save=False):
"""
Imports an asset into Unreal
:param str filename: full file name path to the FBX.
:param str game_path: Folder path to the asset. This does not include the asset name.
:param str asset_name: Name of the asset.
:param unreal.FbxImportUI import_options: This sets the options on the import window.
:param bool replace_existing: If True, the asset will be overwritten.
:param bool save: If True, the asset will be saved.
:return: Returns the unreal.Object instance
:rtype: unreal.Object
"""
# Create an import task
import_task = unreal.AssetImportTask()
# Set base properties on the import task
import_task.filename = filename
import_task.destination_path = game_path
import_task.destination_name = asset_name
import_task.automated = True # Suppress UI
import_task.set_editor_property('replace_existing', replace_existing)
import_task.set_editor_property('save', save)
if import_options:
import_task.options = import_options
unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks([import_task])
imported_assets = import_task.get_editor_property('imported_object_paths')
if not imported_assets:
logger.warning(f'{asset_name}: was not imported!')
return
# Return the instance of the imported asset
asset = imported_assets[0]
asset = unreal.EditorAssetLibrary.find_asset_data(asset).get_asset()
asset_utils.save_asset(asset)
return unreal.load_asset(imported_assets[0])
def texture_2d_import_options():
"""
Returns the import options for the texture 2d import window.
:return: Returns the import options for the texture 2d import window.
:rtype: unreal.FbxImportUI
"""
options = unreal.FbxImportUI()
options.import_textures = True
return options
|
# 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_object_transform_offset(
geo_asset,
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_object_transform_offset(
geo_asset,
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_object_transform_offset'):
print('\t\t\tObject Transform Offset: {0}'.format(in_input.get_object_transform_offset(input_object)))
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()
|
import unreal
from neo4j import GraphDatabase
class MazePopulator:
def __init__(self, uri, user, password):
self.driver = GraphDatabase.driver(uri, auth=(user, password), database="world")
def close(self):
self.driver.close()
def create_cube(self, name, location, scale):
# Load the cube asset
actor_class = unreal.EditorAssetLibrary.load_asset("/project/")
# Ensure the actor class is valid
if actor_class is None:
raise RuntimeError('Failed to load cube asset.')
# Set the actor location and scale
actor_location = unreal.Vector(location[0], location[1], location[2])
actor_scale = unreal.Vector(scale[0], scale[1], scale[2])
# Spawn the cube in the level
actor = unreal.EditorLevelLibrary.spawn_actor_from_object(actor_class, actor_location)
actor.set_actor_scale3d(actor_scale)
actor.set_actor_label(name)
def populate_maze(self):
with self.driver.session() as session:
# Populate sectors
sectors = session.run("MATCH (s:Sector) RETURN s")
for record in sectors:
sector = record["s"]
if sector["center_x"] is not None and sector["center_y"] is not None:
self.create_cube(
f"Sector_{sector['name']}",
(sector["center_x"] * 100, sector["center_y"] * 100, 0),
(sector["width"], sector["height"], 100)
)
else:
unreal.log_error(f"Sector {sector['name']} has invalid center coordinates.")
# Populate arenas
arenas = session.run("MATCH (a:Arena) RETURN a")
for record in arenas:
arena = record["a"]
if arena["center_x"] is not None and arena["center_y"] is not None:
self.create_cube(
f"Arena_{arena['name']}",
(arena["center_x"] * 100, arena["center_y"] * 100, 100),
(arena["width"], arena["height"], 100)
)
else:
unreal.log_error(f"Arena {arena['name']} has invalid center coordinates.")
# Populate game objects
game_objects = session.run("MATCH (g:GameObject) RETURN g")
for record in game_objects:
game_object = record["g"]
if game_object["center_x"] is not None and game_object["center_y"] is not None:
self.create_cube(
f"GameObject_{game_object['name']}",
(game_object["center_x"] * 100, game_object["center_y"] * 100, 200),
(game_object["width"], game_object["height"], 100)
)
else:
unreal.log_error(f"GameObject {game_object['name']} has invalid center coordinates.")
# Populate spawning locations
spawning_locations = session.run("MATCH (sl:SpawningLocation) RETURN sl")
for record in spawning_locations:
spawning_location = record["sl"]
if spawning_location["center_x"] is not None and spawning_location["center_y"] is not None:
self.create_cube(
f"SpawningLocation_{spawning_location['name']}",
(spawning_location["center_x"] * 100, spawning_location["center_y"] * 100, 300),
(spawning_location["width"], spawning_location["height"], 100)
)
else:
unreal.log_error(f"SpawningLocation {spawning_location['name']} has invalid center coordinates.")
# Usage example
maze_populator = MazePopulator("bolt://localhost:7687", "neo4j", "ABhijeet55")
maze_populator.populate_maze()
maze_populator.close()
|
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
import yaml
import unreal
from typing import Any
from deadline.unreal_submitter.unreal_open_job.unreal_open_job import (
UnrealOpenJobParameterDefinition,
)
from deadline.unreal_submitter.unreal_open_job.unreal_open_job_step import (
UnrealOpenJobStepParameterDefinition,
)
from deadline.unreal_submitter.unreal_open_job.unreal_open_job_parameters_consistency import (
ParametersConsistencyChecker,
ParametersConsistencyCheckResult,
)
@unreal.uclass()
class PythonYamlLibraryImplementation(unreal.PythonYamlLibrary):
"""
Implementation of the C++ PythonYamlLibrary for working with YAML template files.
Do real execution of calls from C++
"""
@staticmethod
def job_parameter_to_u_parameter_definition(
job_parameter: dict[str, Any],
) -> unreal.ParameterDefinition:
"""
Convert given Job Parameter definition dictionary to unreal.ParameterDefinition.
:param job_parameter: Job Parameter definition dictionary.
:type job_parameter: dict[str, Any]
:return: unreal.ParameterDefinition
"""
u_parameter_definition = unreal.ParameterDefinition()
u_parameter_definition.name = job_parameter["name"]
u_parameter_definition.type = getattr(unreal.ValueType, job_parameter["type"])
if job_parameter.get("value") is not None:
u_parameter_definition.value = str(job_parameter["value"])
elif job_parameter.get("default") is not None:
u_parameter_definition.value = str(job_parameter["default"])
# Map userInterface.control to UserInterfaceControl enum
if "userInterface" in job_parameter and "control" in job_parameter["userInterface"]:
control_value = job_parameter["userInterface"]["control"]
# Map YAML control values to Unreal enum values
control_mapping = {
"LINE_EDIT": unreal.UserInterfaceControl.LINE_EDIT,
"MULTILINE_EDIT": unreal.UserInterfaceControl.MULTILINE_EDIT,
"DROPDOWN_LIST": unreal.UserInterfaceControl.DROPDOWN_LIST,
"CHECK_BOX": unreal.UserInterfaceControl.CHECK_BOX,
"HIDDEN": unreal.UserInterfaceControl.HIDDEN,
"CHOOSE_INPUT_FILE": unreal.UserInterfaceControl.CHOOSE_INPUT_FILE,
"CHOOSE_OUTPUT_FILE": unreal.UserInterfaceControl.CHOOSE_OUTPUT_FILE,
"CHOOSE_DIRECTORY": unreal.UserInterfaceControl.CHOOSE_DIRECTORY,
"SPIN_BOX": unreal.UserInterfaceControl.SPIN_BOX,
}
if control_value in control_mapping:
u_parameter_definition.user_interface_control = control_mapping[control_value]
else:
# Default to LINE_EDIT if unknown control type
u_parameter_definition.user_interface_control = (
unreal.UserInterfaceControl.LINE_EDIT
)
return u_parameter_definition
@staticmethod
def step_parameter_to_u_step_task_parameter(
step_parameter: dict[str, str],
) -> unreal.StepTaskParameterDefinition:
"""
Convert given Step Parameter definition dictionary to unreal.StepTaskParameterDefinition.
:param step_parameter: Step Parameter definition dictionary.
:type step_parameter: dict[str, Any]
:return: unreal.StepTaskParameterDefinition
"""
u_step_task_parameter_definition = unreal.StepTaskParameterDefinition()
u_step_task_parameter_definition.name = step_parameter["name"]
u_step_task_parameter_definition.type = getattr(unreal.ValueType, step_parameter["type"])
u_step_task_parameter_definition.range = [str(v) for v in step_parameter.get("range", [])]
return u_step_task_parameter_definition
@staticmethod
def environment_to_u_environment(environment: dict[str, Any]) -> unreal.EnvironmentStruct:
"""
Convert given Environment dictionary to unreal.EnvironmentStruct.
Use only name, descriptions and variables
:param environment: Environment dictionary.
:type environment: dict[str, Any]
:return: unreal.EnvironmentStruct
"""
u_environment = unreal.EnvironmentStruct()
u_environment.name = environment["name"]
u_environment.description = environment.get("description", "")
u_variables: list[unreal.EnvVariable] = []
for k, v in environment.get("variables", {}).items():
u_variable = unreal.EnvVariable()
u_variable.name = k
u_variable.value = v
u_variables.append(u_variable.copy())
u_environment.variables = u_variables
return u_environment
@unreal.ufunction(override=True)
def open_job_file(self, path: str) -> list[unreal.ParameterDefinition]:
"""
Open given job template file and build the list of unreal.ParameterDefinition from its data
:param path: Path to the job template file.
:type path: str
:return: list of unreal.ParameterDefinition
"""
with open(path, "r") as f:
job_template = yaml.safe_load(f)
u_parameter_definitions: list[unreal.ParameterDefinition] = []
for parameter_definition in job_template["parameterDefinitions"]:
u_param = PythonYamlLibraryImplementation.job_parameter_to_u_parameter_definition(
parameter_definition
)
u_parameter_definitions.append(u_param.copy())
return u_parameter_definitions
@unreal.ufunction(override=True)
def open_step_file(self, path: str) -> unreal.StepStruct:
"""
Open given step template file and build the unreal.StepStruct from its data
:param path: Path to the step template file.
:type path: str
:return: unreal.StepStruct
"""
with open(path, "r") as f:
step_template = yaml.safe_load(f)
u_step_task_parameter_definitions: list[unreal.StepTaskParameterDefinition] = []
for param_definition in step_template["parameterSpace"]["taskParameterDefinitions"]:
u_param = PythonYamlLibraryImplementation.step_parameter_to_u_step_task_parameter(
param_definition
)
u_step_task_parameter_definitions.append(u_param.copy())
u_step_struct = unreal.StepStruct()
u_step_struct.name = step_template["name"]
u_step_struct.parameters = u_step_task_parameter_definitions
return u_step_struct
@unreal.ufunction(override=True)
def open_env_file(self, path: str) -> unreal.EnvironmentStruct:
"""
Open given environment template file and build the unreal.EnvironmentStruct from its data
:param path: Path to the environment template file.
:type path: str
:return: unreal.EnvironmentStruct
"""
with open(path, "r") as f:
environment_template = yaml.safe_load(f)
u_environment = PythonYamlLibraryImplementation.environment_to_u_environment(
environment_template
)
return u_environment
@unreal.uclass()
class ParametersConsistencyCheckerImplementation(unreal.PythonParametersConsistencyChecker):
"""
Implementation of the C++ PythonParametersConsistencyChecker
for checking/fixing parameters consistency.
Do real execution of calls from C++
"""
@staticmethod
def check_result_to_u_check_result(
consistency_check_result: ParametersConsistencyCheckResult,
) -> unreal.ParametersConsistencyCheckResult:
"""
Convert python's ParametersConsistencyCheckResult to unreal.ParametersConsistencyCheckResult.
:param consistency_check_result: ParametersConsistencyCheckResult instance
:type consistency_check_result: ParametersConsistencyCheckResult
:return: unreal.ParametersConsistencyCheckResult
"""
result = unreal.ParametersConsistencyCheckResult()
result.passed = consistency_check_result.passed
result.reason = consistency_check_result.reason
return result
@unreal.ufunction(override=True)
def check_job_parameters_consistency(
self, open_job: unreal.DeadlineCloudJob
) -> unreal.ParametersConsistencyCheckResult:
"""
Check parameters consistency of the given job.
:param open_job: unreal.DeadlineCloudJob instance
:return: unreal.ParametersConsistencyCheckResult
"""
result = ParametersConsistencyChecker.check_job_parameters_consistency(
job_template_path=open_job.path_to_template.file_path,
job_parameters=[
UnrealOpenJobParameterDefinition.from_unreal_param_definition(param).to_dict()
for param in open_job.get_job_parameters()
],
)
return ParametersConsistencyCheckerImplementation.check_result_to_u_check_result(result)
@unreal.ufunction(override=True)
def fix_job_parameters_consistency(self, open_job: unreal.DeadlineCloudJob):
"""
Fix parameters consistency of the given job.
:param open_job: unreal.DeadlineCloudJob instance
"""
fixed_parameters = ParametersConsistencyChecker.fix_job_parameters_consistency(
job_template_path=open_job.path_to_template.file_path,
job_parameters=[
UnrealOpenJobParameterDefinition.from_unreal_param_definition(param).to_dict()
for param in open_job.get_job_parameters()
],
)
if fixed_parameters:
open_job.set_job_parameters(
[
PythonYamlLibraryImplementation.job_parameter_to_u_parameter_definition(fixed)
for fixed in fixed_parameters
]
)
@unreal.ufunction(override=True)
def check_step_parameters_consistency(
self, open_job_step: unreal.DeadlineCloudStep
) -> unreal.ParametersConsistencyCheckResult:
"""
Check parameters consistency of the given step.
:param open_job_step: unreal.DeadlineCloudStep instance
:return: unreal.ParametersConsistencyCheckResult
"""
result = ParametersConsistencyChecker.check_step_parameters_consistency(
step_template_path=open_job_step.path_to_template.file_path,
step_parameters=[
UnrealOpenJobStepParameterDefinition.from_unreal_param_definition(param).to_dict()
for param in open_job_step.get_step_parameters()
],
)
return ParametersConsistencyCheckerImplementation.check_result_to_u_check_result(result)
@unreal.ufunction(override=True)
def fix_step_parameters_consistency(self, open_job_step: unreal.DeadlineCloudStep):
"""
Fix parameters consistency of the given step.
:param open_job_step: unreal.DeadlineCloudStep instance
"""
fixed_parameters = ParametersConsistencyChecker.fix_step_parameters_consistency(
step_template_path=open_job_step.path_to_template.file_path,
step_parameters=[
UnrealOpenJobStepParameterDefinition.from_unreal_param_definition(param).to_dict()
for param in open_job_step.get_step_parameters()
],
)
if fixed_parameters:
open_job_step.set_step_parameters(
[
PythonYamlLibraryImplementation.step_parameter_to_u_step_task_parameter(fixed)
for fixed in fixed_parameters
]
)
@unreal.ufunction(override=True)
def check_environment_variables_consistency(
self, open_job_environment: unreal.DeadlineCloudEnvironment
) -> unreal.ParametersConsistencyCheckResult:
"""
Check variables consistency of the given environment.
:param open_job_environment: unreal.DeadlineCloudEnvironment instance
:return: unreal.ParametersConsistencyCheckResult
"""
result = ParametersConsistencyChecker.check_environment_variables_consistency(
environment_template_path=open_job_environment.path_to_template.file_path,
environment_variables=open_job_environment.variables.get_editor_property("variables"),
)
return ParametersConsistencyCheckerImplementation.check_result_to_u_check_result(result)
@unreal.ufunction(override=True)
def fix_environment_variables_consistency(
self, open_job_environment: unreal.DeadlineCloudEnvironment
):
"""
Fix variables consistency of the given environment.
:param open_job_environment: unreal.DeadlineCloudEnvironment instance
"""
fixed_variables = ParametersConsistencyChecker.fix_environment_variables_consistency(
environment_template_path=open_job_environment.path_to_template.file_path,
environment_variables=open_job_environment.variables.get_editor_property("variables"),
)
if fixed_variables:
open_job_environment.variables.set_editor_property("variables", fixed_variables)
|
import unreal
import json
import os
proj_path = os.path.dirname(__file__)
with open(proj_path + r"/project/.json") as f:
data = json.load(f)
unreal.get_editor_subsystem(unreal.LevelEditorSubsystem).load_level("/project/")
unreal.log("Headlessly Running file")
for info in data["Scene_Data"]:
asset_name = info["WorldName"]
usd_file_path = info["FilePath"]
usd_file_path = str(usd_file_path)
spawn_location = unreal.Vector(0,0,0)
spawn_rotation = unreal.Rotator(0,0,0)
cache_name = "USDCahce"
cache_path = r"/project/"
if (unreal.EditorAssetLibrary.does_asset_exist(f"{cache_path}/{cache_name}") != True):
usd_asset_cache = unreal.AssetToolsHelpers.get_asset_tools().create_asset(
cache_name,
cache_path,
unreal.UsdAssetCache,
unreal.UsdAssetCacheFactory()
)
else:
usd_asset_cache = unreal.EditorAssetLibrary.load_asset(f"{cache_path}/{cache_name}")
unreal.EditorAssetLibrary.save_loaded_asset(usd_asset_cache)
actor = unreal.EditorLevelLibrary.spawn_actor_from_class(
unreal.UsdStageActor,
spawn_location,
spawn_rotation
)
unreal_usd_file = unreal.FilePath(usd_file_path)
actor.set_editor_property("root_layer", unreal_usd_file)
actor.set_editor_property("initial_load_set", unreal.UsdInitialLoadSet.LOAD_ALL)
usd_asset_cache.add_asset_reference(actor,actor)
usd_asset_cache.refresh_storage()
unreal.EditorAssetLibrary.save_loaded_asset(usd_asset_cache)
unreal.get_editor_subsystem(unreal.LevelEditorSubsystem).save_current_level()
|
# 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)
|
# -*- coding: utf-8 -*-
import os
import sys
import subprocess
import unreal
from Utilities.Utils import Singleton
import random
import re
if sys.platform == "darwin":
import webbrowser
class ChameleonGallery(metaclass=Singleton):
def __init__(self, jsonPath):
self.jsonPath = jsonPath
self.data = unreal.PythonBPLib.get_chameleon_data(self.jsonPath)
self.ui_scrollbox = "ScrollBox"
self.ui_crumbname = "SBreadcrumbTrailA"
self.ui_image = "SImageA"
self.ui_image_local = "SImage_ImageFromRelativePath"
self.ui_imageB = "SImage_ImageFromPath"
self.ui_progressBar = "ProgressBarA"
self.ui_drop_target_text_box = "DropResultBox"
self.ui_python_not_ready = "IsPythonReadyImg"
self.ui_python_is_ready = "IsPythonReadyImgB"
self.ui_is_python_ready_text = "IsPythonReadyText"
self.ui_details_view = "DetailsView"
self.ui_color_block = "ColorBlock"
self.ui_button_expand_color_picker = "ButtonExpandColorPicker"
self.ui_color_picker = "ColorPicker"
self.ui_dpi_scaler = "DPIScaler"
self.imageFlagA = 0
self.imageFlagB = 0
# set data in init
self.set_random_image_data()
self.data.set_combo_box_items('CombBoxA', ['1', '3', '5'])
self.data.set_object(self.ui_details_view, self.data)
self.is_color_picker_shown = self.data.get_visibility(self.ui_color_picker) == "Visible"
self.linearColor_re = re.compile(r"\(R=([-\d.]+),G=([-\d.]+),B=([-\d.]+),A=([-\d.]+)\)")
self.tapython_version = dict(unreal.PythonBPLib.get_ta_python_version())
print("ChameleonGallery.Init")
def mark_python_ready(self):
print("mark_python_ready call")
self.data.set_visibility(self.ui_python_not_ready, "Collapsed")
self.data.set_visibility(self.ui_python_is_ready, "Visible")
self.data.set_text(self.ui_is_python_ready_text, "Python Path Ready.")
def push_breadcrumb(self):
count = self.data.get_breadcrumbs_count_string(self.ui_crumbname)
strs = "is breadcrumb tail from alice in wonder world"
label = strs.split()[count % len(strs.split())]
self.data.push_breadcrumb_string(self.ui_crumbname, label, label)
def set_random_image_data(self):
width = 64
height = 64
colors = [unreal.LinearColor(1, 1, 1, 1) if random.randint(0, 1) else unreal.LinearColor(0, 0, 0, 1) for _ in range(width * height)]
self.data.set_image_pixels(self.ui_image, colors, width, height)
def set_random_progress_bar_value(self):
self.data.set_progress_bar_percent(self.ui_progressBar,random.random())
def change_local_image(self):
self.data.set_image_from(self.ui_image_local, ["Images/ChameleonLogo_c.png", "Images/ChameleonLogo_b.png"][self.imageFlagA])
self.imageFlagA = (self.imageFlagA + 1) % 2
def change_image(self):
self.data.set_image_from_path(self.ui_imageB, ["PythonChameleonIcon_128x.png", "Icon128.png"][self.imageFlagB])
self.imageFlagB = (self.imageFlagB + 1) % 2
def change_comboBox_items(self):
offset = random.randint(1, 10)
items = [str(v+offset) for v in range(random.randint(1, 10))]
self.data.set_combo_box_items("CombBoxA", items)
def launch_other_galleries(self):
if not os.path.exists(os.path.join(os.path.dirname(__file__), 'auto_gen/border_brushes_Gallery.json')):
unreal.PythonBPLib.notification("auto-generated Galleries not exists", info_level=1)
return
gallery_paths = ['ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json'
]
bLaunch = unreal.PythonBPLib.confirm_dialog(f'Open Other {len(gallery_paths)} Galleries? You can close them with the "Close all Gallery" Button' , "Open Other Galleries", with_cancel_button=False)
if bLaunch:
with unreal.ScopedSlowTask(len(gallery_paths), "Spawn Actors") as slow_task:
slow_task.make_dialog(True)
for i, p in enumerate(gallery_paths):
slow_task.enter_progress_frame(1, f"Launch Gallery: {p}")
unreal.ChameleonData.launch_chameleon_tool(p)
def request_close_other_galleries(self):
if not os.path.exists(os.path.join(os.path.dirname(__file__), 'auto_gen/border_brushes_Gallery.json')):
unreal.PythonBPLib.notification("auto-generated Galleries not exists", info_level=1)
return
gallery_paths = ['ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json'
]
for i, p in enumerate(gallery_paths):
unreal.ChameleonData.request_close(p)
# unreal.ChameleonData.request_close('/project/.json')
exists_tools_var = [globals()[x] for x in globals() if "Utilities.Utils.Singleton" in str(type(type(globals()[x])))]
def on_drop(self, assets, assets_folders, actors):
str_for_show = ""
for items, name in zip([assets, assets_folders, actors], ["Assets:", "Assets Folders:", "Actors:"]):
if items:
str_for_show += f"{name}\n"
for item in items:
str_for_show += f"\t{item}\n"
self.data.set_text(self.ui_drop_target_text_box, str_for_show)
print(f"str_for_show: {str_for_show}")
def on_drop_func(self, *args, **kwargs):
print(f"args: {args}")
print(f"kwargs: {kwargs}")
str_for_show = ""
for name, items in kwargs.items():
if items:
str_for_show += f"{name}:\n"
for item in items:
str_for_show += f"\t{item}\n"
self.data.set_text(self.ui_drop_target_text_box, str_for_show)
def get_full_size_of_this_chameleon(self):
current_size = unreal.ChameleonData.get_chameleon_window_size(self.jsonPath)
scrollbox_offsets = self.data.get_scroll_box_offsets(self.ui_scrollbox)
height_full = scrollbox_offsets["ScrollOffsetOfEnd"] / (1.0-scrollbox_offsets["viewFraction"])
height_full += 48
print(f"delta: {height_full} - {round(height_full)}")
return current_size.x, round(height_full)
def on_button_ChangeTabSize_click(self, offset_pixel):
current_size = unreal.ChameleonData.get_chameleon_window_size(self.jsonPath)
print(f"currentSize: {current_size}")
offsets = self.data.get_scroll_box_offsets(self.ui_scrollbox)
print(offsets)
if current_size:
current_size.x += offset_pixel
unreal.ChameleonData.set_chameleon_window_size("ChameleonGallery/ChameleonGallery.json", current_size)
def on_button_FlashWindow_click(self):
unreal.ChameleonData.flash_chameleon_window("ChameleonGallery/ChameleonGallery.json")
def on_button_Snapshot_click(self):
full_size = self.get_full_size_of_this_chameleon()
print(f"try save snapshot @ {full_size}")
saved_file_path = unreal.ChameleonData.snapshot_chameleon_window(self.jsonPath, unreal.Vector2D(*full_size))
if saved_file_path:
unreal.PythonBPLib.notification(f"UI Snapshot Saved:", hyperlink_text = saved_file_path
, on_hyperlink_click_command = f'chameleon_gallery.explorer("{saved_file_path}")')
else:
unreal.PythonBPLib.notification(f"Save UI snapshot failed.", info_level = 1)
def explorer(self, file_path):
if sys.platform == "darwin":
webbrowser.open(os.path.dirname(file_path))
else:
file_path = file_path.replace("/", "\\")
subprocess.call('explorer "{}" '.format(os.path.dirname(file_path)))
def set_selected_actor_to_details_view(self):
selected = unreal.get_editor_subsystem(unreal.EditorActorSubsystem).get_selected_level_actors()
if selected:
self.data.set_object(self.ui_details_view, selected[0])
else:
print("Selected None")
def on_expand_color_picker_click(self):
self.data.set_visibility(self.ui_color_picker, "Collapsed" if self.is_color_picker_shown else "Visible")
self.data.set_text(self.ui_button_expand_color_picker, "Expand ColorPicker" if self.is_color_picker_shown else "Collapse ColorPicker")
self.is_color_picker_shown = not self.is_color_picker_shown
current_size = unreal.ChameleonData.get_chameleon_window_size(self.jsonPath)
if current_size.x < 650:
current_size.x = 650
unreal.ChameleonData.set_chameleon_window_size("ChameleonGallery/ChameleonGallery.json", current_size)
def on_color_picker_commit(self, color_str):
v = [float(a) for a in self.linearColor_re.match(color_str).groups()]
self.data.set_color(self.ui_color_block, unreal.LinearColor(*v))
def change_dpi_scaler_value(self, value):
if self.tapython_version["Minor"] < 2 or(
self.tapython_version["Minor"] == 2 and self.tapython_version["Patch"] < 1
):
print("Need TAPython version >= 1.2.1")
return
self.data.set_dpi_scale(self.ui_dpi_scaler, value + 0.5)
|
from tqdm import tqdm
import json
import os
import random
import numpy as np
import math
import time
import unreal
import re
# for name in list(globals().keys()):
# if not name.startswith('_'):
# del globals()[name]
# import unreal
def natural_sort_key(s):
return [int(text) if text.isdigit() else text.lower() for text in re.split('([0-9]+)', s)]
def get_candidate_blocks(bool_map, block_size):
candidate_blocks = []
for i in range(bool_map.shape[0] - block_size):
for j in range(bool_map.shape[1] - block_size):
sub_map = bool_map[int(i - block_size / 2):int(i + block_size / 2), int(j - block_size / 2):int(j + block_size / 2)]
if sub_map.shape[0] != 0 and sub_map.shape[1] != 0 and np.all(sub_map):
candidate_blocks.append((i, j))
# print(f"Found empty space at ({i},{j})")
return candidate_blocks
def update_bool_map(bool_map, block_size, block_position, width=None, height=None):
i, j = block_position
assert bool_map[int(i - block_size / 2):int(i + block_size / 2), int(j - block_size / 2):int(j + block_size / 2)].all()
bool_map[int(i - 2 * block_size / 2):int(i + 2 * block_size / 2), int(j - 2 * block_size / 2):int(j + 2 * block_size / 2)] = False
return bool_map
def main():
'''
tuple_template_scene=(camera_name,component,render_target)
assume all the objects are already in the scene
'''
save_path = "/project/"
obj_rest_point = unreal.Vector(500, 500, 0)
obj_rest_rotator = unreal.Rotator(0, 0, 0)
editor_subsystem = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem)
world = editor_subsystem.get_editor_world()
# 0. retrieve all the actors
editor_actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
actors = editor_actor_subsystem.get_all_level_actors()
camera_location_list = [
[-165, 0, 190],
[165, 0, 190],
[0, -61, 220],
[0, 61, 220],
[-120, -60, 190],
[120, 60, 190],
[-120, 60, 190],
[120, -60, 190]
]
camera_rotation_list = [
[0, -35, 0],
[0, -35, 180],
[0, -60, 90],
[0, -60, -90],
[0, -50, 30],
[0, -50, -150],
[0, -50, -30],
[0, -50, 150]
]
camera_actors = {}
apple = []
coffee_mug = []
note_book = []
iphone4s = []
RTs = []
capture_component = []
for actor in actors:
if "camera" in actor.get_actor_label():
camera_actors[actor.get_actor_label()] = actor
if "apple" in actor.get_actor_label():
apple.append(actor)
if "coffee_mug" in actor.get_actor_label():
coffee_mug.append(actor)
if "notebook" in actor.get_actor_label():
note_book.append(actor)
if "iphone4s" in actor.get_actor_label():
iphone4s.append(actor)
for i in range(8):
this_cc = camera_actors[f'camera{i+1}'].get_component_by_class(unreal.SceneCaptureComponent2D)
this_cc.set_editor_property("bCaptureEveryFrame", True)
# this_cc.set_editor_property("b_enable_post_processing", True)
pp_settings = this_cc.get_editor_property("post_process_settings")
pp_settings.override_dynamic_global_illumination_method = True
pp_settings.override_reflection_method = True
# bloom
pp_settings.override_bloom_method = True
pp_settings.override_tone_curve_amount = True
this_cc.set_editor_property("post_process_settings", pp_settings)
capture_component.append(this_cc)
RTs.append(capture_component[i].texture_target)
import os
existed_episodes = sorted(os.listdir(save_path), key=natural_sort_key)
episodes = 10000
counter = 0
for episode in range(episodes):
if episode < len(existed_episodes):
continue
if counter > 800:
break
# 1. initialize the camera actors
camera_actors['camera1'].set_actor_location_and_rotation(unreal.Vector(*camera_location_list[0]), unreal.Rotator(*camera_rotation_list[0]), False, False)
camera_actors['camera2'].set_actor_location_and_rotation(unreal.Vector(*camera_location_list[1]), unreal.Rotator(*camera_rotation_list[1]), False, False)
camera_actors['camera3'].set_actor_location_and_rotation(unreal.Vector(*camera_location_list[2]), unreal.Rotator(*camera_rotation_list[2]), False, False)
camera_actors['camera4'].set_actor_location_and_rotation(unreal.Vector(*camera_location_list[3]), unreal.Rotator(*camera_rotation_list[3]), False, False)
camera_actors['camera5'].set_actor_location_and_rotation(unreal.Vector(*camera_location_list[4]), unreal.Rotator(*camera_rotation_list[4]), False, False)
camera_actors['camera6'].set_actor_location_and_rotation(unreal.Vector(*camera_location_list[5]), unreal.Rotator(*camera_rotation_list[5]), False, False)
camera_actors['camera7'].set_actor_location_and_rotation(unreal.Vector(*camera_location_list[6]), unreal.Rotator(*camera_rotation_list[6]), False, False)
camera_actors['camera8'].set_actor_location_and_rotation(unreal.Vector(*camera_location_list[7]), unreal.Rotator(*camera_rotation_list[7]), False, False)
# 2. initialize the scene
num_apple = len(apple)
num_coffee_mug = len(coffee_mug)
num_note_book = len(note_book)
num_iphone4s = len(iphone4s)
for i in range(num_apple):
apple[i].set_actor_location_and_rotation(obj_rest_point, obj_rest_rotator, False, False)
# print(f"Object {i} has width {width}, length {length}, height {height}")
for i in range(num_coffee_mug):
coffee_mug[i].set_actor_location_and_rotation(obj_rest_point, obj_rest_rotator, False, False)
# print(f"Object {i} has width {width}, length {length}, height {height}")
for i in range(num_note_book):
note_book[i].set_actor_location_and_rotation(obj_rest_point, obj_rest_rotator, False, False)
# print(f"Object {i} has width {width}, length {length}, height {height}")
for i in range(num_iphone4s):
iphone4s[i].set_actor_location_and_rotation(obj_rest_point, obj_rest_rotator, False, False)
# print(f"Object {i} has width {width}, length {length}, height {height}")
# place the scene
limits = [[-90, 90], [-40, 40]]
height = 77
bool_map = np.bool_(np.ones((180, 80)))
bool_map[:25, :] = False
bool_map[-25:, :] = False
bool_map[:, :10] = False
bool_map[:, -10:] = False
block_size = 15
choose_apple = np.random.choice([0, num_apple])
choose_coffee_mug = np.random.choice([0, num_coffee_mug])
choose_note_book = np.random.choice([0, num_note_book])
choose_iphone4s = np.random.choice([0, num_iphone4s])
counter_apple = 0
counter_coffee_mug = 0
counter_note_book = 0
counter_iphone4s = 0
for i in range(choose_apple):
candidate_blocks = get_candidate_blocks(bool_map, block_size)
if candidate_blocks:
block_position = random.choice(candidate_blocks)
bool_map = update_bool_map(bool_map, block_size, block_position)
x = block_position[0] + limits[0][0]
y = block_position[1] + limits[1][0]
random_angle = np.random.randint(0, 360)
apple[i].set_actor_location_and_rotation(unreal.Vector(x, y, 51), unreal.Rotator(0, 0, random_angle), False, False)
counter_apple += 1
for i in range(choose_coffee_mug):
candidate_blocks = get_candidate_blocks(bool_map, block_size)
if candidate_blocks:
block_position = random.choice(candidate_blocks)
bool_map = update_bool_map(bool_map, block_size, block_position)
x = block_position[0] + limits[0][0]
y = block_position[1] + limits[1][0]
random_angle = np.random.randint(0, 360)
coffee_mug[i].set_actor_location_and_rotation(unreal.Vector(x, y, height), unreal.Rotator(0, 0, random_angle), False, False)
counter_coffee_mug += 1
for i in range(choose_note_book):
candidate_blocks = get_candidate_blocks(bool_map, block_size)
if candidate_blocks:
block_position = random.choice(candidate_blocks)
bool_map = update_bool_map(bool_map, block_size, block_position)
x = block_position[0] + limits[0][0]
y = block_position[1] + limits[1][0] - 7
random_angle = np.random.randint(0, 360)
note_book[i].set_actor_location_and_rotation(unreal.Vector(x, y, height), unreal.Rotator(0, 0, random_angle), False, False)
counter_note_book += 1
for i in range(choose_iphone4s):
candidate_blocks = get_candidate_blocks(bool_map, block_size)
if candidate_blocks:
block_position = random.choice(candidate_blocks)
bool_map = update_bool_map(bool_map, block_size, block_position)
x = block_position[0] + limits[0][0]
y = block_position[1] + limits[1][0]
random_angle = np.random.randint(0, 360)
iphone4s[i].set_actor_location_and_rotation(unreal.Vector(x, y, height), unreal.Rotator(0, 90, random_angle), False, False)
counter_iphone4s += 1
scene_info = {
'apple': int(counter_apple),
'coffee_mug': int(counter_coffee_mug),
'note_book': int(counter_note_book),
'iphone4s': int(counter_iphone4s),
}
folder_path = os.path.join(save_path, f'episode{episode}')
for i, RT in enumerate(RTs):
capture_component[i].capture_scene()
unreal.RenderingLibrary.export_render_target(world, RT, folder_path, f'camera_{i}.png')
with open(os.path.join(folder_path, 'info.json'), 'w') as f:
json.dump(scene_info, f)
counter += 1
main()
|
import unreal
from Lib import __lib_topaz__ as topaz
assets = unreal.EditorUtilityLibrary.get_selected_assets()
## execution here ##
for each in assets :
if each.__class__ == unreal.Blueprint :
comps = topaz.get_component_by_class(each, unreal.StaticMeshComponent)
for comp in comps :
static_mesh : unreal.StaticMesh = comp.static_mesh
if static_mesh is not None :
__desired_triangle_percentage__ = 0.05
nanite_settings : unreal.MeshNaniteSettings = static_mesh.get_editor_property('nanite_settings')
nanite_settings.enabled = True
nanite_settings.keep_percent_triangles = __desired_triangle_percentage__
static_mesh.set_editor_property('nanite_settings', nanite_settings)
#print(nanite_settings.keep_percent_triangles)
if each.__class__ == unreal.StaticMesh :
if each is not None :
__desired_triangle_percentage__ = 0.05
nanite_settings : unreal.MeshNaniteSettings = each.get_editor_property('nanite_settings')
nanite_settings.enabled = True
nanite_settings.set_editor_property('keep_percent_triangles', __desired_triangle_percentage__)
each.set_editor_property('nanite_settings', nanite_settings)
print('OK')
|
import unreal
def get_selected_assets():
"""Get selected assets from the Content Browser."""
editor_utility = unreal.EditorUtilityLibrary()
return editor_utility.get_selected_assets()
def get_selected_actors():
"""Get selected actors in the level."""
editor_level_library = unreal.EditorLevelLibrary()
return editor_level_library.get_selected_level_actors()
def assign_material_to_static_mesh(static_mesh, material, material_index=0):
"""Assign a material to a static mesh."""
static_mesh_editor_subsystem = unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem)
static_mesh_editor_subsystem.set_material(static_mesh, material_index, material)
def assign_material_to_actor(actor, material, material_index=0):
"""Assign a material to an actor's static mesh component."""
static_mesh_component = actor.get_component_by_class(unreal.StaticMeshComponent)
if static_mesh_component:
static_mesh_component.set_material(material_index, material)
def run():
"""Main function to assign material or material instance."""
unreal.log("Assigning Material to Selected Objects...")
# Get selected assets and actors
selected_assets = get_selected_assets()
selected_actors = get_selected_actors()
# Find the first material or material instance in the selected assets
material = next((asset for asset in selected_assets if isinstance(asset, (unreal.Material, unreal.MaterialInstance))), None)
if not material:
unreal.log_error("No material or material instance selected.")
return
unreal.log(f"Selected material: {material.get_name()}")
# Assign material to selected static meshes in the Content Browser
for asset in selected_assets:
if isinstance(asset, unreal.StaticMesh):
assign_material_to_static_mesh(asset, material)
unreal.log(f"Assigned material {material.get_name()} to static mesh {asset.get_name()}")
# Assign material to selected actors in the level
for actor in selected_actors:
assign_material_to_actor(actor, material)
unreal.log(f"Assigned material {material.get_name()} to actor {actor.get_name()}")
unreal.log("Material assignment completed.")
# Run the script
run()
|
import unreal
from Utilities.Utils import Singleton
import json
import os
from .DataObject import DataObject, DataSubscriber
class BaseWizard(DataSubscriber):
def __init__(self, jsonPath, config_path):
self.jsonPath = jsonPath
self.data = unreal.PythonBPLib.get_chameleon_data(self.jsonPath)
self.asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
self.config = {}
self.base_asset = None
self.name = None
self.objectDatas : dict[str, DataObject] = {}
self.config_path = None
self.load_config_file(config_path)
content = self.create_json_content_from_data()
self.data.set_content_from_json("main-content", content)
self.hide_rename()
self.hide_properties()
def on_value_changed(self, id):
try:
self.data.set_text(id + "-text", self._get_asset_data(id).get_name())
self.data.set_color_and_opacity(id + "-text", self._get_asset_data(id).get_text_color())
except:
pass
if self.base_asset:
unreal.EditorAssetLibrary.save_asset(self.base_asset, True)
def load_config_file(self, config_path):
path = os.path.abspath(os.path.join(os.path.dirname(__file__), config_path))
self.config_path = path
try:
with open(path, 'r') as f:
config = json.load(f)
self.CONFIG = config.get("assetRefs")
self.BASE_CLASS = config.get("baseClass").get("assetPath")
self.DEFAULT_DIR = config.get("baseClass").get("defaultDirectory")
except FileNotFoundError:
unreal.log_error(f"Config file not found: {config_path}")
except json.JSONDecodeError as e:
unreal.log_error(f"Invalid JSON in config: {e}")
def rename_asset(self, aka):
asset = self._get_asset_data(aka)
new_name = self.data.get_text(aka + "new-name")
result = asset.rename(new_name)
if not result:
self.data.set_text(aka + "new-name", "")
def on_request_create_base_asset(self):
name = self.data.get_text("enemy-name")
print(name)
if not name:
unreal.EditorDialog.show_message("Error", "Name is empty!", unreal.AppMsgType.OK)
return
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
parent_class = unreal.EditorAssetLibrary.load_blueprint_class(self.BASE_CLASS)
factory = unreal.BlueprintFactory()
factory.set_editor_property('parent_class', parent_class)
created_asset = asset_tools.create_asset(
"BP_Enemy_" + name,
self.DEFAULT_DIR,
unreal.Blueprint,
factory
)
if created_asset:
asset_path = created_asset.get_path_name()
unreal.EditorDialog.show_message("Error", "Created " + asset_path, unreal.AppMsgType.OK)
unreal.EditorAssetLibrary.save_asset(asset_path, True)
else:
unreal.EditorDialog.show_message("Error", "Failed", unreal.AppMsgType.OK)
self.load_base_class(created_asset.get_path_name())
def on_request_create_default_asset(self, aka):
property = self._get_asset_data(aka)
name = self.data.get_text("enemy-name")
property.create_default_value(name)
def duplicate_asset(self, name, save_path, source_asset_path):
source_asset = unreal.EditorAssetLibrary.load_asset(source_asset_path)
new_asset = self.asset_tools.duplicate_asset(name, save_path, source_asset)
unreal.EditorAssetLibrary.save_loaded_asset(new_asset, True)
return new_asset
def load_base_class(self, asset_path):
# DOTO: handle C++ because currently only load blueprint class
if not asset_path:
unreal.EditorDialog.show_message("Error", "Please provide valid base class!", unreal.AppMsgType.OK)
return
self.data.set_text("base-class-text", asset_path)
for key in self.CONFIG:
self.objectDatas[key] = DataObject(key, asset_path, self.config_path)
self.objectDatas[key].register_subscriber(self)
self.on_value_changed(key)
self.show_properties()
self.show_rename()
self.update_asset_color()
self.base_asset = asset_path
def _get_asset_from_property(self, property_name):
return unreal.load_asset(self.CONFIG.get(property_name).get("assetPath"))
def on_drop_base_class(self, *args, **kwargs):
assets = kwargs.get("assets", None)
if assets:
self.load_base_class(assets[0])
def on_asset_clicked(self, aka):
asset = self._get_asset_data(aka)
asset.edit_asset()
def on_drop_asset(self, aka, **kwargs):
assets = kwargs.get("assets", None)
if assets:
new_asset = unreal.load_asset(assets[0])
dataObject = self._get_asset_data(aka)
if dataObject:
dataObject.set_property(new_asset)
def _get_asset_data(self, key) -> DataObject:
if key:
return self.objectDatas[key]
def create_json_content_from_data(self):
slots = []
for key, value in self.CONFIG.items():
slots.append(
{
"Aka": key,
"AutoHeight": True,
"SHorizontalBox": {
"Slots": [
{
"AutoHeight": True,
"SHorizontalBox": {
"Slots": [
{
"AutoWidth": True,
"AutoHeight": True,
"SColorBlock": {
"Aka": key + "-color",
"Size": [10, 30],
"Color": [1, 0, 0, 1],
"ColorIsHSV": False
}
},
{
"SButton": {
"Content": {
"SDropTarget": {
"Content": {
"STextBlock":
{
"Aka": key + "-text",
"Text": key,
}
},
# TODO hard-coded
"OnDrop": f"boss_wizard.on_drop_asset('{key}', %**kwargs)"
}
},
# TODO hard-coded for now
"OnClick": f"boss_wizard.on_asset_clicked('{key}')"
}
},
{
"AutoHeight": True,
"AutoWidth": True,
"SButton": {
"ButtonColorAndOpacity": [0, 0.5, 1.5, 1],
"Content": {
"SImage": {
"Image": {
"Style": "FEditorStyle",
"Brush": "SystemWideCommands.FindInContentBrowser.Small"
},
"DesiredSizeOverride": [23, 10]
}
},
"ToolTipText": "Browse to asset",
"OnClick": f"boss_wizard.sync_to_editor('{key}')"
}
}
]
}
},
{
"AutoHeight": True,
"SHorizontalBox": {
"Slots": [
{
"AutoWidth": True,
"SBox": {
"WidthOverride": 100,
"Content": {
"SButton": {
"HAlign": "Center",
"VAlign": "Center",
"Text": "Create",
"ButtonColorAndOpacity": [0, 3, 0, 1],
"ToolTipText": "Create new asset based on template",
"OnClick": f"boss_wizard.on_request_create_default_asset('{key}')"
}
}
}
},
{
"AutoHeight": True,
"SHorizontalBox": {
"Aka": key + "-rename",
"Slots": [
{
"Padding": [10, 0, 0, 0],
"VAlign": "Center",
"AutoHeight": True,
"SEditableText": {
"Aka": key + "new-name",
"HAlign": "Center",
"HintText": "New name, don't add prefix"
}
},
{
"AutoWidth": True,
"SBox": {
"WidthOverride": 100,
"Content": {
"SButton": {
"AutoHeight": True,
"HAlign": "Center",
"VAlign": "Center",
"Text": "Rename 🤓",
"ButtonColorAndOpacity": [3, 2.8, 0, 1],
#TODO hard-coded
"OnClick": f"boss_wizard.rename_asset('{key}')",
}
}
}
},
]
}
},
]
}
},
]
}})
structure = {
"SVerticalBox": {
"Slots": slots
}
}
json_string = json.dumps(structure, indent=4)
return json_string
def hide_rename(self):
for key in self.CONFIG:
self.data.set_visibility(key + "-rename", "Collapsed")
def show_rename(self):
for key in self.CONFIG:
self.data.set_visibility(key + "-rename", "Visible")
def hide_properties(self):
for key in self.CONFIG:
self.data.set_visibility(key, "Collapsed")
def show_properties(self):
for key in self.CONFIG:
self.data.set_visibility(key, "Visible")
self.data.set_visibility("browse-to-base-asset", "Visible")
# for quick test random logics
def sync_to_editor(self, aka):
asset_path = self._get_asset_data(aka).get_path()
if asset_path:
unreal.EditorAssetLibrary.sync_browser_to_objects([asset_path])
def update_asset_color(self):
for key in self.CONFIG:
data = self._get_asset_data(key)
self.data.set_color(key + "-color", data.get_asset_color())
def sync_browser_to_base(self):
unreal.EditorAssetLibrary.sync_browser_to_objects([self.base_asset])
|
import time
import unreal
from Utilities.Utils import Singleton
from Utilities.ChameleonTaskExecutor import ChameleonTaskExecutor
class MinimalAsyncTaskExample(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.executor = ChameleonTaskExecutor(self)
self.ui_text_block = "TextBlock"
self.ui_throbber = "Throbber"
def slow_async_task(self, seconds:float) -> float:
# This slow asynchronous task may involve operations such as file I/O, web requests, or other time-consuming activities.
# Operations involving Unreal Engine assets must be executed on the main thread, NOT within this function. Use unreal.ScopedSlowTask(seconds) and we can have a progress bar.
#
# DON'T modify any Slate widget in this function, as it's running in a different thread.
# The Unreal Engine enforces restrictions on accessing Slate widgets from threads other than the main game thread.
# Refer to SlateGlobals.h: #define SLATE_CROSS_THREAD_CHECK() checkf(IsInGameThread() || IsInSlateThread(), TEXT("Access to Slate is restricted to the GameThread or the SlateLoadingThread!"));
print(f"instance_fake_task started, it will cost {seconds} second(s).")
time.sleep(seconds)
print(f"instance_fake_task finished., {seconds}s")
return seconds
def show_busy_icon(self, b_busy:bool):
if b_busy:
self.data.set_text(self.ui_text_block, f"Running Task.")
self.data.set_visibility(self.ui_throbber, "Visible")
else:
self.data.set_text(self.ui_text_block, f"All tasks finished.")
self.data.set_visibility(self.ui_throbber, "Collapsed")
def add_slow_task(self, seconds:float):
# modify Slate widget in this function, as it's running in the main thread.
self.show_busy_icon(True)
self.executor.submit_task(self.slow_async_task, args=[seconds], on_finish_callback=self.on_task_finish)
def on_task_finish(self, future_id:int):
# This function will be called in the main thread. so it's safe to modify Slate widget here.
future = self.executor.get_future(future_id)
if future is None:
unreal.log_warning(f"Can't find future: {future_id}")
else:
self.data.set_text(self.ui_text_block, f"Task done, result: {future.result()}")
if not self.executor.is_any_task_running():
self.show_busy_icon(False)
print(f"on_task_finish. Future: {future_id}, result: {future.result()}")
def some_slow_tasks(self):
self.show_busy_icon(True)
self.executor.submit_task(self.slow_async_task, args=[2], on_finish_callback=self.on_task_finish)
self.executor.submit_task(self.slow_async_task, args=[3], on_finish_callback=self.on_task_finish)
|
# 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()
|
#!/project/ python3
"""
Fix Script for Animations and Level Issues
- Recreates corrupted flipbook animations
- Fixes level lighting
- Ensures character blueprint works
"""
import unreal
import sys
def log_message(message, error=False):
"""Print and log message"""
print(message)
if error:
unreal.log_error(message)
else:
unreal.log(message)
def delete_corrupted_animations():
"""Delete corrupted animation assets"""
log_message("=== DELETING CORRUPTED ANIMATIONS ===")
animation_paths = [
"/project/",
"/project/",
"/project/",
"/project/",
"/project/",
"/project/",
"/project/",
"/project/"
]
for anim_path in animation_paths:
try:
if unreal.EditorAssetLibrary.does_asset_exist(anim_path):
unreal.EditorAssetLibrary.delete_asset(anim_path)
log_message(f"✓ Deleted corrupted animation: {anim_path}")
except Exception as e:
log_message(f"Error deleting {anim_path}: {str(e)}", error=True)
def create_flipbook_animations():
"""Create proper flipbook animations from sprites"""
log_message("=== CREATING FLIPBOOK ANIMATIONS ===")
# Animation definitions: [name, row, start_col, end_col, fps]
animation_defs = [
["Idle", 0, 0, 5, 8.0],
["Move", 1, 0, 5, 12.0],
["AttackUpwards", 2, 0, 5, 12.0],
["AttackDownwards", 3, 0, 5, 12.0],
["AttackSideways", 4, 0, 5, 12.0],
["AttackUpwards2", 5, 0, 5, 12.0],
["AttackDownwards2", 6, 0, 5, 12.0],
["AttackSideways2", 7, 0, 5, 12.0]
]
for anim_name, row, start_col, end_col, fps in animation_defs:
log_message(f"Creating animation: {anim_name}")
# Collect sprites for this animation
sprites = []
for col in range(start_col, end_col + 1):
sprite_path = f"/project/{row}_C{col}"
if unreal.EditorAssetLibrary.does_asset_exist(sprite_path):
sprite = unreal.EditorAssetLibrary.load_asset(sprite_path)
if sprite and isinstance(sprite, unreal.PaperSprite):
sprites.append(sprite)
log_message(f" Added sprite: R{row}_C{col}")
else:
log_message(f" ✗ Invalid sprite: {sprite_path}", error=True)
else:
log_message(f" ✗ Missing sprite: {sprite_path}", error=True)
if sprites:
try:
# Create flipbook using asset tools
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
flipbook_factory = unreal.PaperFlipbookFactory()
# Create the flipbook asset
flipbook = asset_tools.create_asset(
anim_name,
"/project/",
unreal.PaperFlipbook,
flipbook_factory
)
if flipbook:
# Set basic properties
flipbook.set_frames_per_second(fps)
# Add sprites as keyframes
for i, sprite in enumerate(sprites):
flipbook.set_key_frame(i, unreal.PaperFlipbookKeyFrame(sprite=sprite, frame_run=1))
# Set default material
default_material = unreal.EditorAssetLibrary.load_asset("/project/")
if default_material:
flipbook.set_default_material(default_material)
# Save the asset
anim_path = f"/project/{anim_name}"
unreal.EditorAssetLibrary.save_asset(anim_path)
log_message(f"✓ Created {anim_name} with {len(sprites)} frames at {fps} fps")
else:
log_message(f"✗ Failed to create flipbook for {anim_name}", error=True)
except Exception as e:
log_message(f"✗ Error creating {anim_name}: {str(e)}", error=True)
else:
log_message(f"✗ No valid sprites found for {anim_name}", error=True)
def fix_character_blueprint():
"""Fix character blueprint to ensure it has proper sprite component"""
log_message("=== FIXING CHARACTER BLUEPRINT ===")
try:
bp_path = "/project/"
# Load the blueprint
bp_asset = unreal.EditorAssetLibrary.load_asset(bp_path)
if not bp_asset:
log_message(f"✗ Could not load character blueprint: {bp_path}", error=True)
return False
log_message(f"✓ Loaded character blueprint")
# Get the blueprint's default object
bp_class = bp_asset.generated_class()
if bp_class:
default_object = bp_class.get_default_object()
if default_object:
log_message("✓ Character blueprint has default object")
# Try to get sprite component - this should work for PaperCharacter
if hasattr(default_object, 'sprite'):
sprite_comp = default_object.sprite
if sprite_comp:
log_message("✓ Character has sprite component")
# Try to set an idle animation if available
idle_anim = unreal.EditorAssetLibrary.load_asset("/project/")
if idle_anim:
sprite_comp.set_flipbook(idle_anim)
log_message("✓ Set idle animation on sprite component")
return True
else:
log_message("✗ Sprite component is None", error=True)
else:
log_message("✗ Default object has no sprite attribute", error=True)
else:
log_message("✗ Blueprint has no default object", error=True)
else:
log_message("✗ Blueprint has no generated class", error=True)
return False
except Exception as e:
log_message(f"✗ Error fixing character blueprint: {str(e)}", error=True)
return False
def fix_level_lighting():
"""Fix level lighting and add essential actors"""
log_message("=== FIXING LEVEL LIGHTING ===")
try:
# Load the test level
level_path = "/project/"
success = unreal.EditorLevelLibrary.load_level(level_path)
if not success:
log_message(f"✗ Could not load level: {level_path}", error=True)
return False
log_message("✓ Loaded TestLevel")
# Get all actors in the level
all_actors = unreal.EditorLevelLibrary.get_all_level_actors()
log_message(f"Found {len(all_actors)} actors in level")
# Check what we have
has_directional_light = False
has_sky_light = False
has_floor = False
has_player_start = False
for actor in all_actors:
actor_class = actor.get_class().get_name()
if "DirectionalLight" in actor_class:
has_directional_light = True
# Make sure it's bright enough
light_comp = actor.get_component_by_class(unreal.DirectionalLightComponent)
if light_comp:
light_comp.set_intensity(3.0)
light_comp.set_light_color(unreal.LinearColor(1.0, 0.95, 0.8, 1.0))
log_message(f"✓ Found and configured DirectionalLight")
elif "SkyLight" in actor_class:
has_sky_light = True
# Configure sky light
light_comp = actor.get_component_by_class(unreal.SkyLightComponent)
if light_comp:
light_comp.set_intensity(1.0)
log_message(f"✓ Found and configured SkyLight")
elif "StaticMeshActor" in actor_class:
has_floor = True
log_message(f"✓ Found StaticMeshActor (floor)")
elif "PlayerStart" in actor_class:
has_player_start = True
log_message(f"✓ Found PlayerStart")
# Create missing lighting
if not has_directional_light:
log_message("Creating DirectionalLight...")
directional_light = unreal.EditorLevelLibrary.spawn_actor_from_class(
unreal.DirectionalLight,
unreal.Vector(0, 0, 300),
unreal.Rotator(-45, 45, 0)
)
if directional_light:
light_comp = directional_light.get_component_by_class(unreal.DirectionalLightComponent)
if light_comp:
light_comp.set_intensity(3.0)
light_comp.set_light_color(unreal.LinearColor(1.0, 0.95, 0.8, 1.0))
log_message("✓ Created DirectionalLight")
if not has_sky_light:
log_message("Creating SkyLight...")
sky_light = unreal.EditorLevelLibrary.spawn_actor_from_class(
unreal.SkyLight,
unreal.Vector(0, 0, 200)
)
if sky_light:
light_comp = sky_light.get_component_by_class(unreal.SkyLightComponent)
if light_comp:
light_comp.set_intensity(1.0)
log_message("✓ Created SkyLight")
if not has_floor:
log_message("Creating Floor...")
cube_mesh = unreal.EditorAssetLibrary.load_asset("/project/")
if cube_mesh:
floor_actor = unreal.EditorLevelLibrary.spawn_actor_from_class(
unreal.StaticMeshActor,
unreal.Vector(0, 0, -100)
)
if floor_actor:
mesh_comp = floor_actor.get_component_by_class(unreal.StaticMeshComponent)
if mesh_comp:
mesh_comp.set_static_mesh(cube_mesh)
floor_actor.set_actor_scale3d(unreal.Vector(50, 50, 1))
log_message("✓ Created Floor")
if not has_player_start:
log_message("Creating PlayerStart...")
player_start = unreal.EditorLevelLibrary.spawn_actor_from_class(
unreal.PlayerStart,
unreal.Vector(0, 0, 50)
)
if player_start:
log_message("✓ Created PlayerStart")
# Save level
unreal.EditorLevelLibrary.save_current_level()
log_message("✓ Saved level changes")
return True
except Exception as e:
log_message(f"✗ Error fixing level: {str(e)}", error=True)
return False
def test_final_state():
"""Test that everything works"""
log_message("=== TESTING FINAL STATE ===")
# Test animations
animation_paths = [
"/project/",
"/project/",
"/project/",
"/project/",
"/project/"
]
animations_working = 0
for anim_path in animation_paths:
try:
anim = unreal.EditorAssetLibrary.load_asset(anim_path)
if anim and isinstance(anim, unreal.PaperFlipbook):
frames = anim.get_num_frames()
log_message(f"✓ {anim_path}: {frames} frames")
animations_working += 1
else:
log_message(f"✗ {anim_path}: Invalid or None", error=True)
except Exception as e:
log_message(f"✗ {anim_path}: Error - {str(e)}", error=True)
# Test character blueprint
try:
bp = unreal.EditorAssetLibrary.load_asset("/project/")
if bp:
log_message("✓ Character blueprint loads")
else:
log_message("✗ Character blueprint failed to load", error=True)
except Exception as e:
log_message(f"✗ Character blueprint error: {str(e)}", error=True)
log_message(f"FINAL RESULT: {animations_working}/5 animations working")
return animations_working >= 3 # At least 3 basic animations should work
def main():
"""Main fix function"""
log_message("=" * 60)
log_message("COMPREHENSIVE ANIMATION AND LEVEL FIX")
log_message("=" * 60)
try:
# Step 1: Delete corrupted animations
delete_corrupted_animations()
# Step 2: Create proper flipbook animations
create_flipbook_animations()
# Step 3: Fix character blueprint
fix_character_blueprint()
# Step 4: Fix level lighting
fix_level_lighting()
# Step 5: Test final state
success = test_final_state()
log_message("=" * 60)
if success:
log_message("✓ FIX COMPLETED SUCCESSFULLY!")
log_message("The character should now have working animations and the level should be properly lit.")
log_message("Test by opening TestLevel and clicking Play.")
else:
log_message("✗ FIX PARTIALLY COMPLETED", error=True)
log_message("Some issues remain. Check the errors above.")
log_message("=" * 60)
except Exception as e:
log_message(f"CRITICAL ERROR: {str(e)}", error=True)
if __name__ == "__main__":
main()
|
import unreal
import csv
def get_static_mesh_data(asset):
if isinstance(asset, unreal.StaticMesh):
name = asset.get_name()
path = "StaticMesh\'" + asset.get_path_name() + "\'"
bound = asset.get_bounding_box()
box = bound.max - bound.min
height = max( box.z / 100.0, 0.01 )
radius = max( max(box.x, box.y) / 100.0, 0.01)
return name, path, radius, height
return None, None, None, None
def write_to_csv(data, path, write_mode):
if len(data) == 0 :
unreal.log_warning("The data is empty!")
return False
if not path.endswith('/') and not path.endswith('\\'):
unreal.log_warning("add / at end")
path += '/'
file_path = path + 'foliage.csv'
mode = "wb+" if write_mode == 'Replace' else "ab+"
with open(file_path, mode) as f:
writer = csv.writer(f)
writer.writerow(["name", "path", "radius", "height"])
writer.writerows(data)
f.close()
return True
def fill_data_list(asset, data, name):
if isinstance(asset, unreal.FoliageType):
f_path = "FoliageType_InstancedStaticMesh\'" + asset.get_path_name() + "\'"
sm_asset = asset.get_editor_property('mesh')
f_name, _, f_radius, f_height = get_static_mesh_data(sm_asset)
if f_name is not None:
data.append((f_name, f_path, f_radius, f_height))
name.append(f_name)
elif isinstance(asset, unreal.StaticMesh):
s_name, s_path, s_radius, s_height = get_static_mesh_data(asset)
if s_name not in name and s_name is not None:
data.append((s_name, s_path, s_radius, s_height))
name.append(s_name)
assets = unreal.EditorUtilityLibrary.get_selected_assets()
data = []
name = []
for asset in assets:
if isinstance(asset, unreal.DataTable):
columns = unreal.DataTableFunctionLibrary.get_data_table_column_as_string(asset, unreal.Name("Foliage"))
for column in columns:
if column is "None":
continue
c_asset = unreal.load_asset(column)
fill_data_list(c_asset, data, name)
else:
fill_data_list(asset, data, name)
# input parameters: filepath, write_m
if write_to_csv(data, filepath, write_m) :
output_log = "Export Foliage Number : " + str(len(data)) + "\nFile Path: " + filepath + 'foliage.csv'
unreal.log(output_log)
else:
unreal.log_warning("write to csv fail!")
|
#!/project/
# -*- coding: utf-8 -*-
import unreal
file = open('/project/.txt')
lines = file.readlines()
locatorClass = unreal.EditorAssetLibrary.load_blueprint_class('/project/')
tree = unreal.EditorAssetLibrary.load_blueprint_class('/project/')
treelittle = unreal.EditorAssetLibrary.load_blueprint_class('/project/')
treemidsize = unreal.EditorAssetLibrary.load_blueprint_class('/project/')
treemidleaf = unreal.EditorAssetLibrary.load_blueprint_class('/project/')
treetwiggy = unreal.EditorAssetLibrary.load_blueprint_class('/project/')
leafyplant = unreal.EditorAssetLibrary.load_blueprint_class('/project/')
treewall = unreal.EditorAssetLibrary.load_blueprint_class('/project/')
for line in lines:
if line.startswith('@locator'):
arr = line.split(' ')
locName = arr[1]
c = None
quatX = float(arr[2].replace(',', '.')) * -1
quatY = float(arr[3].replace(',', '.'))
quatZ = float(arr[4].replace(',', '.')) * -1
quatW = float(arr[5].replace(',', '.'))
posX = float(arr[6].replace(',', '.')) * 100
posY = float(arr[7].replace(',', '.')) * -100
posZ = float(arr[8].replace(',', '.')) * 100
flag = int(arr[9])
quat = unreal.Quat(quatX, quatY, quatZ, quatW).rotator()
if locName.startswith("tree"):
c = tree
if locName.startswith("treelittle"):
c = treelittle
elif locName.startswith("treemidleaf"):
c = treemidleaf
elif locName.startswith("treemidsize"):
c = treemidsize
elif locName.startswith("treetwiggy"):
c = treetwiggy
if locName.startswith("treewall"):
c = treewall
elif (locName.startswith("bullrush")) or (locName.startswith("fnc")) or (locName.startswith("rockpeb")) or (locName.startswith("rock")) or (locName.startswith("busha")) or (locName.startswith("sandypeb")) or (locName.startswith("reeds")) or (locName.startswith("flwrs")):
c = unreal.EditorAssetLibrary.load_blueprint_class('/project/' + locName)
elif locName.startswith("leafyplant"):
c = leafyplant
elif (locName.startswith("mush_")):
c = unreal.EditorAssetLibrary.load_blueprint_class('/project/' + locName.split("_")[0] + "_" + locName.split("_")[1])
if c == None:
try:
c = unreal.EditorAssetLibrary.load_blueprint_class('/project/' + locName.split("_")[0])
except:
continue
if c == None:
continue
asset = unreal.EditorLevelLibrary.spawn_actor_from_class(c, unreal.Vector(posX, posY, posZ), quat)
asset.tags = [locName]
asset.set_actor_label(locName)
asset.set_folder_path("Locators")
|
# -*- 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))
|
from typing import Dict, Any, Optional
import unreal
import json
def create_object(
object_class: str,
object_name: str,
location: Optional[Dict[str, float]] = None,
rotation: Optional[Dict[str, float]] = None,
scale: Optional[Dict[str, float]] = None,
properties: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
try:
world = unreal.get_editor_subsystem(
unreal.UnrealEditorSubsystem
).get_editor_world()
if not world:
return {"error": "No world loaded"}
actor_class = None
class_mappings = {
"StaticMeshActor": unreal.StaticMeshActor,
"SkeletalMeshActor": unreal.SkeletalMeshActor,
"DirectionalLight": unreal.DirectionalLight,
"PointLight": unreal.PointLight,
"SpotLight": unreal.SpotLight,
"Camera": unreal.CameraActor,
"CameraActor": unreal.CameraActor,
"Pawn": unreal.Pawn,
"Character": unreal.Character,
"PlayerStart": unreal.PlayerStart,
}
actor_class = class_mappings.get(object_class)
# If not found, try loading as native class
if not actor_class:
try:
actor_class = unreal.load_class(None, object_class)
except Exception:
pass
# If still not found, try finding by name
if not actor_class:
try:
actor_class = unreal.find_class(object_class)
except Exception:
pass
# If still not found, try loading as blueprint class last
if not actor_class:
try:
actor_class = unreal.EditorAssetLibrary.load_blueprint_class(
object_class
)
except Exception:
pass
if not actor_class:
return {"error": f"Could not find class: {object_class}"}
spawn_location = unreal.Vector(
x=location.get("x", 0.0) if location else 0.0,
y=location.get("y", 0.0) if location else 0.0,
z=location.get("z", 0.0) if location else 0.0,
)
spawn_rotation = unreal.Rotator(
pitch=rotation.get("pitch", 0.0) if rotation else 0.0,
yaw=rotation.get("yaw", 0.0) if rotation else 0.0,
roll=rotation.get("roll", 0.0) if rotation else 0.0,
)
spawn_scale = unreal.Vector(
x=scale.get("x", 1.0) if scale else 1.0,
y=scale.get("y", 1.0) if scale else 1.0,
z=scale.get("z", 1.0) if scale else 1.0,
)
actor = unreal.EditorLevelLibrary.spawn_actor_from_class(
actor_class, spawn_location, spawn_rotation
)
if not actor:
return {"error": "Failed to spawn actor"}
if object_name:
actor.set_actor_label(object_name)
actor.set_actor_scale3d(spawn_scale)
# Apply default mesh and material for StaticMeshActor if no properties provided
if actor.get_class().get_name() == "StaticMeshActor" and not properties:
mesh_component = actor.get_component_by_class(unreal.StaticMeshComponent)
if mesh_component:
name_lower = object_name.lower()
mesh_path = "/project/" # Default fallback
if "sphere" in name_lower or "ball" in name_lower:
mesh_path = "/project/"
elif "cylinder" in name_lower:
mesh_path = "/project/"
elif "cone" in name_lower:
mesh_path = "/project/"
elif "plane" in name_lower:
mesh_path = "/project/"
mesh = unreal.EditorAssetLibrary.load_asset(mesh_path)
if mesh:
mesh_component.set_static_mesh(mesh)
# Apply default material
default_material = unreal.EditorAssetLibrary.load_asset(
"/project/"
)
if default_material:
mesh_component.set_material(0, default_material)
if properties:
for prop_name, prop_value in properties.items():
try:
if (
prop_name == "StaticMesh"
and actor.get_class().get_name() == "StaticMeshActor"
):
static_mesh = unreal.EditorAssetLibrary.load_asset(prop_value)
if static_mesh:
mesh_component = actor.get_component_by_class(
unreal.StaticMeshComponent
)
if mesh_component:
mesh_component.set_static_mesh(static_mesh)
elif (
prop_name == "Material"
and actor.get_class().get_name() == "StaticMeshActor"
):
material = unreal.EditorAssetLibrary.load_asset(prop_value)
if material:
mesh_component = actor.get_component_by_class(
unreal.StaticMeshComponent
)
if mesh_component:
mesh_component.set_material(0, material)
elif (
prop_name == "Materials"
and actor.get_class().get_name() == "StaticMeshActor"
and isinstance(prop_value, list)
):
mesh_component = actor.get_component_by_class(
unreal.StaticMeshComponent
)
if mesh_component:
for i, material_path in enumerate(prop_value):
if material_path:
material = unreal.EditorAssetLibrary.load_asset(
material_path
)
if material:
mesh_component.set_material(i, material)
elif hasattr(actor, prop_name):
setattr(actor, prop_name, prop_value)
except Exception as e:
continue
return {
"success": True,
"actor_name": actor.get_name(),
"actor_label": actor.get_actor_label(),
"class": actor.get_class().get_name(),
"location": {
"x": actor.get_actor_location().x,
"y": actor.get_actor_location().y,
"z": actor.get_actor_location().z,
},
"rotation": {
"pitch": actor.get_actor_rotation().pitch,
"yaw": actor.get_actor_rotation().yaw,
"roll": actor.get_actor_rotation().roll,
},
"scale": {
"x": actor.get_actor_scale3d().x,
"y": actor.get_actor_scale3d().y,
"z": actor.get_actor_scale3d().z,
},
}
except Exception as e:
return {"error": f"Failed to create object: {str(e)}"}
def parse_value(value_str):
import json as parse_json
if value_str and value_str != "null" and value_str.strip():
try:
return parse_json.loads(value_str)
except Exception:
return None
return None
def main():
# These are template variables from the js side
object_class = "${object_class}"
object_name = "${object_name}"
location_str = """${location}"""
rotation_str = """${rotation}"""
scale_str = """${scale}"""
properties_str = """${properties}"""
location = parse_value(location_str)
rotation = parse_value(rotation_str)
scale = parse_value(scale_str)
properties = parse_value(properties_str)
result = create_object(
object_class=object_class,
object_name=object_name,
location=location,
rotation=rotation,
scale=scale,
properties=properties,
)
print(json.dumps(result, indent=2))
if __name__ == "__main__":
main()
|
# Copyright Epic Games, Inc. All Rights Reserved.
import unreal
import random
#
# USAGE:
# - Requires the "Python Editor Script Plugin" to be enabled in your project.
#
# Open the Python interactive console and use:
# import MoviePipelineMiscExamples
# MoviePipelineMiscExamples.ExampleResolveOutputPath()
# or:
# MoviePipelineMiscExamples.ExampleResolveVersionNumber()
'''
Summary:
This example shows how you can partially determine what filename or output
folder a Queue may render to, ie: it lets you resolve the Output Directory
into an actual filepath taking into account shot names, etc.
For things not determined by the job, they are pulled from the Params struct
which must be filled out.
'''
def ExampleResolveOutputPath():
subsystem = unreal.get_editor_subsystem(unreal.MoviePipelineQueueSubsystem)
pipelineQueue = subsystem.get_queue()
if(len(pipelineQueue.get_jobs()) == 0):
unreal.log_error("Open the Window > Movie Render Queue and add at least one job to use this example.")
return
# Get the output settings
job = pipelineQueue.get_jobs()[0]
outputSetting = job.get_configuration().find_or_add_setting_by_class(unreal.MoviePipelineOutputSetting)
outputSetting.output_directory.set_editor_property("path", "C:/TestFolder")
outputSetting.file_name_format = "{shot_name}.{frame_number}"
combinedPath = unreal.Paths.combine([outputSetting.output_directory.path, outputSetting.file_name_format])
# Create the params struct
params = unreal.MoviePipelineFilenameResolveParams()
params.frame_number = 55
params.frame_number_shot = 23
params.frame_number_rel = 12
params.frame_number_shot_rel = 3
params.camera_name_override = job.shot_info[0].inner_name
params.shot_name_override = job.shot_info[0].outer_name
params.zero_pad_frame_number_count = 3
params.force_relative_frame_numbers = False
params.file_name_format_overrides["ext"] = "jpg"
params.initialization_time = unreal.MathLibrary.utc_now()
params.initialization_version = 3
params.job = job
params.shot_override = job.shot_info[0]
(resolvedPath, mergedFormatArgs) = unreal.MoviePipelineLibrary.resolve_filename_format_arguments(combinedPath, params)
unreal.log("Resolved Path: " + resolvedPath)
'''
Summary:
This example shows how you can partially determine what filename or output
folder a Queue may render to, ie: it lets you resolve the Output Directory
into an actual filepath taking into account shot names, etc.
For things not determined by the job, they are pulled from the Params struct
which must be filled out.
'''
def ExampleResolveVersionNumber():
subsystem = unreal.get_editor_subsystem(unreal.MoviePipelineQueueSubsystem)
pipelineQueue = subsystem.get_queue()
if(len(pipelineQueue.get_jobs()) == 0):
unreal.log_error("Open the Window > Movie Render Queue and add at least one job to use this example.")
return
# Get the output settings
job = pipelineQueue.get_jobs()[0]
outputSetting = job.get_configuration().find_or_add_setting_by_class(unreal.MoviePipelineOutputSetting)
outputSetting.auto_version = True
outputSetting.file_name_format = "{version}/{shot_name}.{frame_number}"
combinedPath = unreal.Paths.combine([outputSetting.output_directory.path, outputSetting.file_name_format])
# Create the params struct
params = unreal.MoviePipelineFilenameResolveParams()
params.frame_number = 55
params.frame_number_shot = 23
params.frame_number_rel = 12
params.frame_number_shot_rel = 3
params.camera_name_override = job.shot_info[0].inner_name # Only need these if shot_override isn't specified, but listed here for examples sake
params.shot_name_override = job.shot_info[0].outer_name
params.zero_pad_frame_number_count = 3
params.force_relative_frame_numbers = False
params.file_name_format_overrides["ext"] = "jpg"
params.initialization_time = unreal.MathLibrary.utc_now()
params.job = job
params.shot_override = job.shot_info[0]
unreal.log("Looking for a folder with version formatting (vXXX) at path: " + combinedPath)
versionNumberFoundOnDisk = unreal.MoviePipelineLibrary.resolve_version_number(params)
if versionNumberFoundOnDisk == 0:
unreal.log("Either didn't find a folder with pattern 'v000' or no folder found on disk, version number is 0.")
else:
unreal.log("Found a version folder, new version would be: " + str(versionNumberFoundOnDisk))
|
import unreal
accepted_classes = []
exclude_folders = []
combo_box = unreal.ComboBoxString()
file_paths = []
def FillCombo(combo_box, excluded_folders, excluded_classes, excluded_names) -> list[str]:
combo_box.clear_options()
assetReg = unreal.AssetRegistryHelpers.get_asset_registry()
allAssetsData = assetReg.get_assets_by_path("/Game/", True)
for asset in allAssetsData:
assetString = unreal.AssetRegistryHelpers.get_full_name(asset)
filepathStartPos = assetString.index(' ') + 1
filepathEndPos = assetString.index('.', filepathStartPos)
filepath = assetString[filepathStartPos : filepathEndPos]
assetClassStartPos = assetString.index('.') + 1
assetClassEndPos = assetString.index(' ')
assetClass = assetString[assetClassStartPos : assetClassEndPos]
assetName = assetString[assetString.index('.', assetClassEndPos + 1) + 1 : ]
flag = False
for folderName in excluded_folders:
if "/" + folderName + "/" in filepath:
flag = True
if not flag:
for classFilter in excluded_classes:
if classFilter in assetClass:
flag = True
if not flag:
for nameFilter in excluded_names:
if nameFilter in assetName:
flag = True
if not flag:
combo_box.add_option(assetName)
file_paths.append(filepath)
return file_paths
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.