text
stringlengths 15
267k
|
|---|
import unreal
selected_assets = unreal.EditorUtilityLibrary.get_selected_assets()
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
loaded_subsystem = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem)
for asset in selected_assets:
# Get the asset's package path
package_path = asset.get_path_name()
# Get the asset's references
references = loaded_subsystem.find_package_referencers_for_asset(package_path)
for reference in references:
path_to_check = "/project/"
if reference.startswith(path_to_check):
print(f"Asset: {package_path}")
print(f"Reference found in {path_to_check}: {reference}")
|
from pathlib import Path
import shutil
import unreal
from ayon_core.pipeline import publish
class ExtractUAsset(publish.Extractor):
"""Extract a UAsset."""
label = "Extract UAsset"
hosts = ["unreal"]
families = ["uasset", "umap"]
optional = True
def process(self, instance):
extension = (
"umap" if "umap" in instance.data.get("families") else "uasset")
ar = unreal.AssetRegistryHelpers.get_asset_registry()
self.log.debug("Performing extraction..")
staging_dir = self.staging_dir(instance)
members = instance.data.get("members", [])
if not members:
raise RuntimeError("No members found in instance.")
# UAsset publishing supports only one member
obj = members[0]
asset = ar.get_asset_by_object_path(obj).get_asset()
sys_path = unreal.SystemLibrary.get_system_path(asset)
filename = Path(sys_path).name
shutil.copy(sys_path, staging_dir)
self.log.info(f"instance.data: {instance.data}")
if "representations" not in instance.data:
instance.data["representations"] = []
representation = {
"name": extension,
"ext": extension,
"files": filename,
"stagingDir": staging_dir,
}
instance.data["representations"].append(representation)
|
import pyvfx_boilerplate.boilerplate_ui as bpui
try:
import maya.cmds as cmds
import maya.mel as mel
MAYA = True
except ImportError:
MAYA = False
try:
import nuke
NUKE = True
except ImportError:
NUKE = False
try:
import hou # noqa
HOUDINI = True
except ImportError:
HOUDINI = False
try:
import MaxPlus
THREEDSMAX = True
except ImportError:
THREEDSMAX = False
try:
import bpy
BLENDER = True
except ImportError:
BLENDER = False
try:
import unreal # noqa
UNREAL = True
except ImportError:
UNREAL = False
rootMenuName = "pyvfx"
def activate(dockable=False):
bpr = bpui.BoilerplateRunner(bpui.Boilerplate)
kwargs = {}
kwargs["dockable"] = dockable
bpr.run_main(**kwargs)
mcmd = "import pyvfx_boilerplate.menu\npyvfx_boilerplate.menu.activate({})"
if NUKE:
m = nuke.menu("Nuke")
menuname = "{}/boilerplate UI".format(rootMenuName)
m.addCommand("{}/boilerplate UI".format(rootMenuName), mcmd.format(""))
m.addCommand("{} dockable".format(menuname), mcmd.format("True"))
elif MAYA:
MainMayaWindow = mel.eval("$temp = $gMainWindow")
if not cmds.menu("pyvfxMenuItemRoot", exists=True):
cmds.menu(
"pyvfxMenuItemRoot",
label=rootMenuName,
parent=MainMayaWindow,
tearOff=True,
allowOptionBoxes=True,
)
cmds.menuItem(
label="boilerplate UI",
parent="pyvfxMenuItemRoot",
ec=True,
command=mcmd.format(""),
)
cmds.menuItem(
label="boilerplate UI dockable",
parent="pyvfxMenuItemRoot",
ec=True,
command=mcmd.format("True"),
)
elif HOUDINI:
print("add menu code here for Houdini")
activate()
elif UNREAL:
# http://golaem.com/project/-crowd-documentation/rendering-unreal-engine
# https://github.com/project/
print("add menu code here for Unreal")
activate()
elif THREEDSMAX:
def activate_dockable():
activate(True)
MaxPlus.MenuManager.UnregisterMenu(rootMenuName)
mb = MaxPlus.MenuBuilder(rootMenuName)
menuitem = "boilerplate UI"
menuitemD = "{} dockable".format(menuitem)
menulist = [
(menuitem, menuitem, activate),
(menuitemD, menuitemD, activate_dockable),
]
for item in menulist:
action = MaxPlus.ActionFactory.Create(item[0], item[1], item[2])
mb.AddItem(action)
menu = mb.Create(MaxPlus.MenuManager.GetMainMenu())
elif BLENDER:
# a little of This
# https://blender.stackexchange.com/project/-ht-upper-bar-append-add-menus-in-two-places
# and a little of this
# https://blenderartists.org/project/-a-custom-menu-option/project/
class PyvfxBoilerplateActivateOperator(bpy.types.Operator):
""" start the pyvfx_boilerplate ui"""
bl_idname = "pyvfx_boilerplate_activate"
bl_label = "boilerplate UI"
def execute(self, context):
activate()
return {"FINISHED"}
class TOPBAR_MT_pyvfx_menu(bpy.types.Menu):
""" create the pyvfx top menu and pyvfx menu item"""
bl_label = rootMenuName
def draw(self, context):
""" create the pyvfx menu item"""
layout = self.layout
layout.operator("pyvfx_boilerplate_activate")
def menu_draw(self, context):
""" create the pyvfx top menu"""
self.layout.menu("TOPBAR_MT_pyvfx_menu")
def register():
bpy.utils.register_class(PyvfxBoilerplateActivateOperator)
bpy.utils.register_class(TOPBAR_MT_pyvfx_menu)
bpy.types.TOPBAR_MT_editor_menus.append(TOPBAR_MT_pyvfx_menu.menu_draw)
def unregister():
bpy.utils.unregister_class(PyvfxBoilerplateActivateOperator)
bpy.types.TOPBAR_MT_editor_menus.remove(TOPBAR_MT_pyvfx_menu.menu_draw)
bpy.utils.unregister_class(TOPBAR_MT_pyvfx_menu)
register()
else:
activate()
|
# Copyright (c) <2021> Side Effects Software Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. The name of Side Effects Software may not be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
""" An example script that uses the API to instantiate two HDAs. The first HDA
will be used as an input to the second HDA. For the second HDA we set 2 inputs:
an asset input (the first instantiated HDA) and a curve input (a helix). The
inputs are set during post instantiation (before the first cook). After the
first cook and output creation (post processing) the input structure is fetched
and logged.
"""
import math
import unreal
_g_wrapper1 = None
_g_wrapper2 = None
def get_copy_curve_hda_path():
return '/project/.copy_to_curve_1_0'
def get_copy_curve_hda():
return unreal.load_object(None, get_copy_curve_hda_path())
def get_pig_head_hda_path():
return '/project/.pig_head_subdivider_v01'
def get_pig_head_hda():
return unreal.load_object(None, get_pig_head_hda_path())
def configure_inputs(in_wrapper):
print('configure_inputs')
# Unbind from the delegate
in_wrapper.on_post_instantiation_delegate.remove_callable(configure_inputs)
# Create a geo input
asset_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPIAssetInput)
# Set the input objects/assets for this input
# asset_input.set_input_objects((_g_wrapper1.get_houdini_asset_actor().houdini_asset_component, ))
asset_input.set_input_objects((_g_wrapper1, ))
# copy the input data to the HDA as node input 0
in_wrapper.set_input_at_index(0, asset_input)
# We can now discard the API input object
asset_input = None
# Create a curve input
curve_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPICurveInput)
# Create a curve wrapper/helper
curve_object = unreal.HoudiniPublicAPICurveInputObject(curve_input)
# Make it a Nurbs curve
curve_object.set_curve_type(unreal.HoudiniPublicAPICurveType.NURBS)
# Set the points of the curve, for this example we create a helix
# consisting of 100 points
curve_points = []
for i in range(10):
t = i / 10.0 * math.pi * 2.0
x = 100.0 * math.cos(t)
y = 100.0 * math.sin(t)
z = i * 10.0
curve_points.append(unreal.Transform([x, y, z], [0, 0, 0], [1, 1, 1]))
curve_object.set_curve_points(curve_points)
# Set the curve wrapper as an input object
curve_input.set_input_objects((curve_object, ))
# Copy the input data to the HDA as node input 1
in_wrapper.set_input_at_index(1, curve_input)
# We can now discard the API input object
curve_input = None
def print_api_input(in_input):
print('\t\tInput type: {0}'.format(in_input.__class__))
print('\t\tbKeepWorldTransform: {0}'.format(in_input.keep_world_transform))
print('\t\tbImportAsReference: {0}'.format(in_input.import_as_reference))
if isinstance(in_input, unreal.HoudiniPublicAPICurveInput):
print('\t\tbCookOnCurveChanged: {0}'.format(in_input.cook_on_curve_changed))
print('\t\tbAddRotAndScaleAttributesOnCurves: {0}'.format(in_input.add_rot_and_scale_attributes_on_curves))
input_objects = in_input.get_input_objects()
if not input_objects:
print('\t\tEmpty input!')
else:
print('\t\tNumber of objects in input: {0}'.format(len(input_objects)))
for idx, input_object in enumerate(input_objects):
print('\t\t\tInput object #{0}: {1}'.format(idx, input_object))
if isinstance(input_object, unreal.HoudiniPublicAPICurveInputObject):
print('\t\t\tbClosed: {0}'.format(input_object.is_closed()))
print('\t\t\tCurveMethod: {0}'.format(input_object.get_curve_method()))
print('\t\t\tCurveType: {0}'.format(input_object.get_curve_type()))
print('\t\t\tReversed: {0}'.format(input_object.is_reversed()))
print('\t\t\tCurvePoints: {0}'.format(input_object.get_curve_points()))
def print_inputs(in_wrapper):
print('print_inputs')
# Unbind from the delegate
in_wrapper.on_post_processing_delegate.remove_callable(print_inputs)
# Fetch inputs, iterate over it and log
node_inputs = in_wrapper.get_inputs_at_indices()
parm_inputs = in_wrapper.get_input_parameters()
if not node_inputs:
print('No node inputs found!')
else:
print('Number of node inputs: {0}'.format(len(node_inputs)))
for input_index, input_wrapper in node_inputs.items():
print('\tInput index: {0}'.format(input_index))
print_api_input(input_wrapper)
if not parm_inputs:
print('No parameter inputs found!')
else:
print('Number of parameter inputs: {0}'.format(len(parm_inputs)))
for parm_name, input_wrapper in parm_inputs.items():
print('\tInput parameter name: {0}'.format(parm_name))
print_api_input(input_wrapper)
def run():
# get the API singleton
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
global _g_wrapper1, _g_wrapper2
# instantiate the input HDA with auto-cook enabled
_g_wrapper1 = api.instantiate_asset(get_pig_head_hda(), unreal.Transform())
# instantiate the copy curve HDA
_g_wrapper2 = api.instantiate_asset(get_copy_curve_hda(), unreal.Transform())
# Configure inputs on_post_instantiation, after instantiation, but before first cook
_g_wrapper2.on_post_instantiation_delegate.add_callable(configure_inputs)
# Print the input state after the cook and output creation.
_g_wrapper2.on_post_processing_delegate.add_callable(print_inputs)
if __name__ == '__main__':
run()
|
import json
import unreal
with open("C:/project/ Projects/project/"
"MaterialAutoAssign/project/.json", "r") as f:
material_references_data = json.load(f)
with open("C:/project/ Projects/project/"
"MaterialAutoAssign/project/.json", "r") as f:
material_rename_data = json.load(f)
missing_material_paths = []
for mesh_path, mesh_material_data in material_references_data.items():
for slot_name, material_path in mesh_material_data.items():
material_path = material_rename_data.get(material_path, material_path)
if not unreal.EditorAssetLibrary.does_asset_exist(
material_path) and material_path not in missing_material_paths:
missing_material_paths.append(material_path)
for missing_material_path in missing_material_paths:
print(missing_material_path)
|
import unreal
# import os
# plugin_path = r"/project/-5.6.2-vc9hc26998b_12\Library\plugins\platforms"
# os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path
import sys
sys.path.append('/project/-packages')
# from PySide2 import QtGui
# from PySide2 import QtCore
# from PySide2 import QtWidgets
# from PySide2 import QtUiTools
from PyQt5 import QtGui
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from PyQt5 import uic
# This function will receive the tick from Unreal
def __QtAppTick__(delta_seconds):
for window in opened_windows:
window.eventTick(delta_seconds)
# This function will be called when the application is closing.
def __QtAppQuit__():
unreal.unregister_slate_post_tick_callback(tick_handle)
# This function is called by the windows when they are closing. (Only if the connection is properly made.)
def __QtWindowClosed__(window=None):
if window in opened_windows:
opened_windows.remove(window)
# This part is for the initial setup. Need to run once to spawn the application.
unreal_app = QtWidgets.QApplication.instance()
if not unreal_app:
unreal_app = QtWidgets.QApplication(sys.argv)
tick_handle = unreal.register_slate_post_tick_callback(__QtAppTick__)
unreal_app.aboutToQuit.connect(__QtAppQuit__)
existing_windows = {}
opened_windows = []
# desired_window_class: class QtGui.QWidget : The window class you want to spawn
# return: The new or existing window
def spawnQtWindow(desired_window_class=None):
window = existing_windows.get(desired_window_class, None)
if not window:
window = desired_window_class()
existing_windows[desired_window_class] = window
window.aboutToClose = __QtWindowClosed__
if window not in opened_windows:
opened_windows.append(window)
window.show()
window.activateWindow()
return window
def run():
spawnQtWindow(QtWindowOne)
WINDOW_NAME = 'Qt Window One'
UI_FILE_FULLNAME = __file__.replace('.py', '.ui')
class QtWindowOne(QtGui.QWidget):
def __init__(self, parent=None):
super(QtWindowOne, 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 = uic.loadUi(UI_FILE_FULLNAME)
self.widget.setParent(self)
self.setWindowTitle(WINDOW_NAME)
self.setGeometry(100, 100, self.widget.width(), self.widget.height())
self.initialiseWidget()
def closeEvent(self, event):
if self.aboutToClose:
self.aboutToClose(self)
event.accept()
def eventTick(self, delta_seconds):
self.myTick(delta_seconds)
##########################################
def initialiseWidget(self):
self.time_while_this_window_is_open = 0.0
self.random_actor = None
self.random_actor_is_going_up = True
self.widget.button_MoveRandom.clicked.connect(self.moveRandomActorInScene)
def moveRandomActorInScene(self):
import random
import WorldFunctions
all_actors = WorldFunctions.getAllActors(use_selection = False, actor_class = unreal.StaticMeshActor, actor_tag = None)
rand = random.randrange(0, len(all_actors))
self.random_actor = all_actors[rand]
def myTick(self, delta_seconds):
# Set Time
self.time_while_this_window_is_open += delta_seconds
self.widget.lbl_Seconds.setText("%.1f Seconds" % self.time_while_this_window_is_open)
# Affect Actor
if self.random_actor:
actor_location = self.random_actor.get_actor_location()
speed = 300.0 * delta_seconds
if self.random_actor_is_going_up:
if actor_location.z > 1000.0:
self.random_actor_is_going_up = False
else:
speed = -speed
if actor_location.z < 0.0:
self.random_actor_is_going_up = True
self.random_actor.add_actor_world_offset(unreal.Vector(0.0, 0.0, speed), False, False)
if __name__ == '__main__':
run()
# import sys
# PATH = r"/project/"
# if PATH not in sys.path:
# sys.path.append(PATH)
# import qtWindow
# reload(qtWindow)
|
# 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 instantiates an HDA that contains a TOP network.
After the HDA itself has cooked (in on_post_process) we iterate over all
TOP networks in the HDA and print their paths. Auto-bake is then enabled for
PDG and the TOP networks are cooked.
"""
import os
import unreal
_g_wrapper = None
def get_test_hda_path():
return '/project/.pdg_pighead_grid_2_0'
def get_test_hda():
return unreal.load_object(None, get_test_hda_path())
def get_hda_directory():
""" Attempt to get the directory containing the .hda files. This is
/project/. In newer versions of UE we can use
``unreal.SystemLibrary.get_system_path(asset)``, in older versions
we manually construct the path to the plugin.
Returns:
(str): the path to the example hda directory or ``None``.
"""
if hasattr(unreal.SystemLibrary, 'get_system_path'):
return os.path.dirname(os.path.normpath(
unreal.SystemLibrary.get_system_path(get_test_hda())))
else:
plugin_dir = os.path.join(
os.path.normpath(unreal.Paths.project_plugins_dir()),
'Runtime', 'HoudiniEngine', 'Content', 'Examples', 'hda'
)
if not os.path.exists(plugin_dir):
plugin_dir = os.path.join(
os.path.normpath(unreal.Paths.engine_plugins_dir()),
'Runtime', 'HoudiniEngine', 'Content', 'Examples', 'hda'
)
if not os.path.exists(plugin_dir):
return None
return plugin_dir
def delete_instantiated_asset():
global _g_wrapper
if _g_wrapper:
result = _g_wrapper.delete_instantiated_asset()
_g_wrapper = None
return result
else:
return False
def on_pre_instantiation(in_wrapper):
print('on_pre_instantiation')
# Set the hda_directory parameter to the directory that contains the
# example .hda files
hda_directory = get_hda_directory()
print('Setting "hda_directory" to {0}'.format(hda_directory))
in_wrapper.set_string_parameter_value('hda_directory', hda_directory)
# Cook the HDA (not PDG yet)
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'))
def on_post_process(in_wrapper):
print('on_post_process')
# in_wrapper.on_post_processing_delegate.remove_callable(on_post_process)
# Iterate over all PDG/TOP networks and nodes and log them
print('TOP networks:')
for network_path in in_wrapper.get_pdgtop_network_paths():
print('\t{}'.format(network_path))
for node_path in in_wrapper.get_pdgtop_node_paths(network_path):
print('\t\t{}'.format(node_path))
# Enable PDG auto-bake (auto bake TOP nodes after they are cooked)
in_wrapper.set_pdg_auto_bake_enabled(True)
# Bind to PDG post bake delegate (called after all baking is complete)
in_wrapper.on_post_pdg_bake_delegate.add_callable(on_post_bake)
# Cook the specified TOP node
in_wrapper.pdg_cook_node('topnet1', 'HE_OUT_PIGHEAD_GRID')
def run():
# get the API singleton
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
global _g_wrapper
# instantiate an asset, disabling auto-cook of the asset
_g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform(), enable_auto_cook=False)
# Bind to the on pre instantiation delegate (before the first cook) and
# set parameters
_g_wrapper.on_pre_instantiation_delegate.add_callable(on_pre_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 sys
sys.path.append('C:/project/-packages')
from PySide import QtGui, QtUiTools
WINDOW_NAME = 'Qt Window One'
UI_FILE_FULLNAME = __file__.replace('.py', '.ui')
class QtWindowOne(QtGui.QWidget):
def __init__(self, parent=None):
super(QtWindowOne, 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.initialiseWidget()
def closeEvent(self, event):
if self.aboutToClose:
self.aboutToClose(self)
event.accept()
def eventTick(self, delta_seconds):
self.myTick(delta_seconds)
##########################################
def initialiseWidget(self):
self.time_while_this_window_is_open = 0.0
self.random_actor = None
self.random_actor_is_going_up = True
self.widget.button_MoveRandom.clicked.connect(self.moveRandomActorInScene)
def moveRandomActorInScene(self):
import random
import WorldFunctions
all_actors = WorldFunctions.getAllActors(use_selection = False, actor_class = unreal.StaticMeshActor, actor_tag = None)
rand = random.randrange(0, len(all_actors))
self.random_actor = all_actors[rand]
def myTick(self, delta_seconds):
# Set Time
self.time_while_this_window_is_open += delta_seconds
self.widget.lbl_Seconds.setText("%.1f Seconds" % self.time_while_this_window_is_open)
# Affect Actor
if self.random_actor:
actor_location = self.random_actor.get_actor_location()
speed = 300.0 * delta_seconds
if self.random_actor_is_going_up:
if actor_location.z > 1000.0:
self.random_actor_is_going_up = False
else:
speed = -speed
if actor_location.z < 0.0:
self.random_actor_is_going_up = True
self.random_actor.add_actor_world_offset(unreal.Vector(0.0, 0.0, speed), False, False)
|
import unreal
import glob
import os
class fbxImport():
def __init__(self, relative_fbx_path="../DCC"):
# Unreal Engineใใญใธใงใฏใใฎใใฃใฌใฏใใชใๅๅพ
self.proj_dir = unreal.SystemLibrary.get_project_directory()
# FBXใใกใคใซใๆ ผ็ดใใใฆใใ็ธๅฏพใใน
self.relative_fbx_path = relative_fbx_path
# FBXใใกใคใซใฎใซใผใใใฃใฌใฏใใชใฎใใซใในใ็ๆ
self.fbx_root_dir = os.path.join(self.proj_dir, self.relative_fbx_path)
def get_fbx_paths(self):
# FBXใใกใคใซใๆค็ดขใใใใใฎใในใ็ๆ
match_path = os.path.join(self.fbx_root_dir, "**/*.fbx")
# ๆๅฎใใใใในไปฅไธใฎFBXใใกใคใซใๅ
จใฆๅๅพ
self.fbx_paths = glob.glob(match_path, recursive=True)
# ใในๅ
ใฎใใใฏในใฉใใทใฅใในใฉใใทใฅใซ็ฝฎๆใใ็นๅฎใฎๆกไปถใซๅ่ดใใใใกใคใซใฎใฟใใชในใใซ่ฟฝๅ
self.fbx_paths = [
s.replace('\\', '/')
for s in self.fbx_paths
if "_high" not in s
]
def debug_fbx_info(self):
# FBXใใกใคใซใฎใในๆ
ๅ ฑใๅๅพใใใใใใฐๆ
ๅ ฑใจใใฆๅบๅ
self.get_fbx_paths()
print(self.fbx_paths)
for file_path in self.fbx_paths:
# ๆๅใฎFBXใใกใคใซใฎใในใๅๅพใใฆใใใใฐๅบๅ
file_path = self.fbx_paths[0]
dir = file_path.split("../DCC/")[1]
name = file_path.split('/')[-1].split('.')[0]
dir = os.path.join("/Game", dir.split(name)[0], "Mesh")
print(dir)
print(name)
print(file_path)
def make_option(self):
# FBXใคใณใใผใใชใใทใงใณใฎ่จญๅฎ
op = unreal.FbxImportUI()
# ใใใชใขใซใฎใคใณใใผใใ็กๅนๅ
op.import_materials = False
# ่ชๅ็ๆใฎ่ก็ชๅฆ็ใ็กๅนๅ
op.static_mesh_import_data.auto_generate_collision = False
# ใกใใทใฅใฎ็ตๅใๆๅนๅ
op.static_mesh_import_data.combine_meshes = True
self.op = op
def make_task(self, fbx_path, destination_path, object_name):
# FBXใใกใคใซใฎใคใณใใผใใฟในใฏใไฝๆ
# ใคใณใใผใใฟในใฏใฎ่จญๅฎ
task = unreal.AssetImportTask()
task.automated = True
task.destination_name = object_name
task.destination_path = destination_path
task.filename = fbx_path
task.replace_existing = True
return task
def execute_tasks(self):
"""
ๆๅฎใใใในไปฅไธใฎfbxใใกใคใซใในใๅ้ใใใใใใซๅฏพใใฆๅฏพๅฟใใContentsใใฉใซใๅ
ใในใไฝๆใใใๆฐ่ฆไฝๆใฎใขใปใใใซๅฏพใใฆใคใณใใผใใ่กใ
"""
self.get_fbx_paths()
self.make_option()
tasks = []
import_list = []
# ใใกใคใซใใจใซๅฎๅ
ใในใไฝๆใFBXใคใณใใผใใฟในใฏใ่ฟฝๅ
for fbx_path in self.fbx_paths:
#fbx_pathใEnvironment/project/ใๆกๅผตๅญใชใใฎใใกใคใซๅใซๅ่งฃใใฆContentsใใฉใซใ็จใซๅ็ตๅใใ
name = fbx_path.split('/')[-1].split('.')[0]
dir = fbx_path.split("../DCC/")[1]
destination_path = os.path.join("/Game", dir.split(name)[0], "Mesh")
# destination_pathใ้ธๆใใใฆใใใใฉใซใไปฅไธใงใใๅ ดๅใฎใฟใฟในใฏใไฝๆ
destination_asset = os.path.join(destination_path,name)
if not unreal.EditorAssetLibrary.does_asset_exist(destination_asset):
# if selected_folder in destination_path:
task = self.make_task(fbx_path,destination_path,name)
tasks.append(task)
import_list.append(destination_asset)
print(f"{destination_asset}is creating...")
else:
print(f"{destination_asset} is already created. skip")
confirmation=unreal.EditorDialog.show_message(
"ไปฅไธใฎใในใซFBXใใคใณใใผใใใพใใ็ถ่กใใพใใ๏ผ",
"\n".join(import_list),
unreal.AppMsgType.YES_NO
)
# ใฆใผใถใผใYESใ้ธๆใใๅ ดๅใฎใฟใฟในใฏใๅฎ่ก
if confirmation == unreal.AppReturnType.YES:
# Unreal Engineใฎใขใปใใใใผใซใไฝฟ็จใใฆใฟในใฏใๅฎ่ก
atool = unreal.AssetToolsHelpers.get_asset_tools()
atool.import_asset_tasks(tasks)
def main():
# ใคใณใใผใๅฆ็ใฎๅฎ่ก
fbx = fbxImport("../project/")
fbx.execute_tasks()
main()
|
import unreal
from CommonFunctions import get_asset_dir
selected_assets = unreal.EditorUtilityLibrary.get_selected_assets()
editor_lib = unreal.EditorAssetLibrary
asset_subsys = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem)
new_dir_path = "/project/"
def replace_ref(assets):
for asset in assets:
if isinstance(asset,unreal.Object):
asset_path = asset.get_path_name()
asset_old = editor_lib.load_asset(asset_path)
asset_name = asset.get_name()
print("Asset")
print([asset_old])
asset_new_path = new_dir_path + asset_name + "." + asset_name
if editor_lib.does_asset_exist(asset_new_path):
print("Asset exists in the new directory")
asset_new = editor_lib.load_asset(asset_new_path)
print("New Asset")
print(asset_new)
# replace=asset_subsys.consolidate_assets(assets_to_consolidate=[asset_new],asset_to_consolidate_to=asset)
replace = editor_lib.consolidate_assets(asset_to_consolidate_to=asset_new,assets_to_consolidate=[asset_old])
print("done")
print(replace)
else:
print("no target asset")
def check_ref(asset):
if isinstance(asset,unreal.Object):
asset_path = asset.get_path_name()
asset_ref = editor_lib.find_package_referencers_for_asset(asset_path)
print("Asset_Reference")
print(asset_ref)
|
๏ปฟ# coding: utf-8
import unreal
import argparse
print("VRM4U python begin")
print (__file__)
parser = argparse.ArgumentParser()
parser.add_argument("-vrm")
parser.add_argument("-rig")
args = parser.parse_args()
print(args.vrm)
#print(dummy[3])
humanoidBoneList = [
"hips",
"leftUpperLeg",
"rightUpperLeg",
"leftLowerLeg",
"rightLowerLeg",
"leftFoot",
"rightFoot",
"spine",
"chest",
"upperChest", # 9 optional
"neck",
"head",
"leftShoulder",
"rightShoulder",
"leftUpperArm",
"rightUpperArm",
"leftLowerArm",
"rightLowerArm",
"leftHand",
"rightHand",
"leftToes",
"rightToes",
"leftEye",
"rightEye",
"jaw",
"leftThumbProximal", # 24
"leftThumbIntermediate",
"leftThumbDistal",
"leftIndexProximal",
"leftIndexIntermediate",
"leftIndexDistal",
"leftMiddleProximal",
"leftMiddleIntermediate",
"leftMiddleDistal",
"leftRingProximal",
"leftRingIntermediate",
"leftRingDistal",
"leftLittleProximal",
"leftLittleIntermediate",
"leftLittleDistal",
"rightThumbProximal",
"rightThumbIntermediate",
"rightThumbDistal",
"rightIndexProximal",
"rightIndexIntermediate",
"rightIndexDistal",
"rightMiddleProximal",
"rightMiddleIntermediate",
"rightMiddleDistal",
"rightRingProximal",
"rightRingIntermediate",
"rightRingDistal",
"rightLittleProximal",
"rightLittleIntermediate",
"rightLittleDistal", #54
]
humanoidBoneParentList = [
"", #"hips",
"hips",#"leftUpperLeg",
"hips",#"rightUpperLeg",
"leftUpperLeg",#"leftLowerLeg",
"rightUpperLeg",#"rightLowerLeg",
"leftLowerLeg",#"leftFoot",
"rightLowerLeg",#"rightFoot",
"hips",#"spine",
"spine",#"chest",
"chest",#"upperChest" 9 optional
"chest",#"neck",
"neck",#"head",
"chest",#"leftShoulder", # <-- upper..
"chest",#"rightShoulder",
"leftShoulder",#"leftUpperArm",
"rightShoulder",#"rightUpperArm",
"leftUpperArm",#"leftLowerArm",
"rightUpperArm",#"rightLowerArm",
"leftLowerArm",#"leftHand",
"rightLowerArm",#"rightHand",
"leftFoot",#"leftToes",
"rightFoot",#"rightToes",
"head",#"leftEye",
"head",#"rightEye",
"head",#"jaw",
"leftHand",#"leftThumbProximal",
"leftThumbProximal",#"leftThumbIntermediate",
"leftThumbIntermediate",#"leftThumbDistal",
"leftHand",#"leftIndexProximal",
"leftIndexProximal",#"leftIndexIntermediate",
"leftIndexIntermediate",#"leftIndexDistal",
"leftHand",#"leftMiddleProximal",
"leftMiddleProximal",#"leftMiddleIntermediate",
"leftMiddleIntermediate",#"leftMiddleDistal",
"leftHand",#"leftRingProximal",
"leftRingProximal",#"leftRingIntermediate",
"leftRingIntermediate",#"leftRingDistal",
"leftHand",#"leftLittleProximal",
"leftLittleProximal",#"leftLittleIntermediate",
"leftLittleIntermediate",#"leftLittleDistal",
"rightHand",#"rightThumbProximal",
"rightThumbProximal",#"rightThumbIntermediate",
"rightThumbIntermediate",#"rightThumbDistal",
"rightHand",#"rightIndexProximal",
"rightIndexProximal",#"rightIndexIntermediate",
"rightIndexIntermediate",#"rightIndexDistal",
"rightHand",#"rightMiddleProximal",
"rightMiddleProximal",#"rightMiddleIntermediate",
"rightMiddleIntermediate",#"rightMiddleDistal",
"rightHand",#"rightRingProximal",
"rightRingProximal",#"rightRingIntermediate",
"rightRingIntermediate",#"rightRingDistal",
"rightHand",#"rightLittleProximal",
"rightLittleProximal",#"rightLittleIntermediate",
"rightLittleIntermediate",#"rightLittleDistal",
]
for i in range(len(humanoidBoneList)):
humanoidBoneList[i] = humanoidBoneList[i].lower()
for i in range(len(humanoidBoneParentList)):
humanoidBoneParentList[i] = humanoidBoneParentList[i].lower()
######
reg = unreal.AssetRegistryHelpers.get_asset_registry();
## meta ๅๅพ
a = reg.get_all_assets();
for aa in a:
if (aa.get_editor_property("object_path") == args.vrm):
v:unreal.VrmAssetListObject = aa
vv = v.get_asset().vrm_meta_object
print(vv)
meta = vv
##
rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints()
print(rigs)
for r in rigs:
s:str = r.get_path_name()
ss:str = args.rig
if (s.find(ss) < 0):
print("no rig")
else:
rig = r
#rig = rigs[10]
h_mod = rig.get_hierarchy_modifier()
#elements = h_mod.get_selection()
#sk = rig.get_preview_mesh()
#k = sk.skeleton
#print(k)
### ๅ
จใฆใฎ้ชจ
modelBoneListAll = []
modelBoneNameList = []
for e in reversed(h_mod.get_elements()):
if (e.type != unreal.RigElementType.BONE):
h_mod.remove_element(e)
name_to_control = {"dummy_for_table" : None}
gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.2, 0.2, 0.2])
for e in h_mod.get_elements():
print(e.name)
if (e.type != unreal.RigElementType.BONE):
continue
bone = h_mod.get_bone(e)
parentName = "{}".format(bone.get_editor_property('parent_name'))
#print("parent==")
#print(parentName)
cur_parentName = parentName + "_c"
name_s = "{}".format(e.name) + "_s"
name_c = "{}".format(e.name) + "_c"
space = h_mod.add_space(name_s, parent_name=cur_parentName, space_type=unreal.RigSpaceType.CONTROL)
control = h_mod.add_control(name_c,
space_name=space.name,
gizmo_color=[0.1, 0.1, 1.0, 1.0],
)
h_mod.set_initial_global_transform(space, h_mod.get_global_transform(e))
cc = h_mod.get_control(control)
cc.set_editor_property('gizmo_transform', gizmo_trans)
#cc.set_editor_property('control_type', unreal.RigControlType.ROTATOR)
h_mod.set_control(cc)
name_to_control[name_c] = cc
c = None
try:
i = list(name_to_control.keys()).index(cur_parentName)
except:
i = -1
if (i >= 0):
c = name_to_control[cur_parentName]
if (cc != None):
if ("{}".format(e.name) in meta.humanoid_bone_table.values() ):
cc.set_editor_property('gizmo_color', unreal.LinearColor(0.1, 0.1, 1.0, 1.0))
h_mod.set_control(cc)
else:
cc.set_editor_property('gizmo_color', unreal.LinearColor(1.0, 0.1, 0.1, 1.0))
h_mod.set_control(cc)
c = rig.controller
g = c.get_graph()
n = g.get_nodes()
# ้
ๅใใผใ่ฟฝๅ
collectionItem_forControl:unreal.RigVMStructNode = None
collectionItem_forBone:unreal.RigVMStructNode = None
for node in n:
if (node.get_node_title() == 'Items'):
#print(node.get_node_title())
#node = unreal.RigUnit_CollectionItems.cast(node)
pin = node.find_pin('Items')
print(pin.get_array_size())
print(pin.get_default_value())
if (pin.get_array_size() < 40):
continue
if 'Type=Control' in pin.get_default_value():
collectionItem_forControl = node
if 'Type=Bone' in pin.get_default_value():
collectionItem_forBone = node
#nn = unreal.EditorFilterLibrary.by_class(n,unreal.RigUnit_CollectionItems.static_class())
# controller array
if (collectionItem_forControl == None):
collectionItem_forControl = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute')
items_forControl = collectionItem_forControl.find_pin('Items')
c.clear_array_pin(items_forControl.get_pin_path())
if (collectionItem_forBone != None):
items_forBone = collectionItem_forBone.find_pin('Items')
c.clear_array_pin(items_forBone.get_pin_path())
for bone_h in meta.humanoid_bone_table:
bone_m = meta.humanoid_bone_table[bone_h]
try:
i = humanoidBoneList.index(bone_h.lower())
except:
i = -1
if (i >= 0):
tmp = '(Type=Bone,Name='
tmp += "{}".format(bone_m).lower()
tmp += ')'
c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp)
for e in h_mod.get_elements():
print(e.name)
if (e.type == unreal.RigElementType.CONTROL):
tmp = '(Type=Control,Name='
tmp += "{}".format(e.name)
tmp += ')'
c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp)
|
import unreal
actors = unreal.EditorLevelLibrary.get_all_level_actors()
for actor in actors:
if not isinstance(actor,unreal.StaticMeshActor):
continue
comp = actor.static_mesh_component
mesh = comp.static_mesh
path = mesh.get_path_name()
if path.startswith("/project/"):
path = path.replace("/project/","/project/")
comp.set_editor_property("static_mesh",unreal.load_asset(path))
material_list = []
print(comp.get_editor_property("override_materials"))
for material in comp.get_editor_property("override_materials"):
print(unicode(actor))
path = material.get_path_name()
path = path.replace("/project/","/project/")
material_list.append(unreal.load_asset(path))
if material_list:
comp.set_editor_property("override_materials",material_list)
|
import unreal
MEL = unreal.MaterialEditingLibrary
MP = unreal.MaterialProperty
MST = unreal.MaterialSamplerType
BM = unreal.BlendMode
M = unreal.Material
T = unreal.Texture
ATH = unreal.AssetToolsHelpers
EAL = unreal.EditorAssetLibrary
EUL = unreal.EditorUtilityLibrary
##
# Actions to be performed on a per-texture basis
##
# A base class for actions
class Action:
def execute(self, material, expression):
pass
# Adds a sampler and connects the desired output to the desired material property pin
class CreateConnection(Action):
def __init__(self, output_name, material_property):
self.output_name = output_name
self.material_property = material_property
def execute(self, material, expression, y_pos):
MEL.connect_material_property(expression, self.output_name, self.material_property)
# Same as CreateConnection, but a Multiply node is also generated so the color value is scaled by the given factor
class CreateConnectionScaled(CreateConnection):
def __init__(self, output_name, material_property, scale):
self.output_name = output_name
self.material_property = material_property
self.scale = scale
def execute(self, material, expression, y_pos):
multiply_node = MEL.create_material_expression(material, unreal.MaterialExpressionMultiply, -250, y_pos)
multiply_node.set_editor_property('ConstB', self.scale)
MEL.connect_material_expressions(expression, self.output_name, multiply_node, 'A')
MEL.connect_material_property(multiply_node, '', self.material_property)
# Sets any available property on the material asset
class SetProperty(Action):
def __init__(self, properti, value):
self.property = properti
self.value = value
def execute(self, material, expression, y_pos):
material.set_editor_property(self.property, self.value)
# Sets the sampler type for the texture sample
class SetSamplerType(Action):
def __init__(self, sampler_type):
self.sampler_type = sampler_type
def execute(self, material, expression, y_pos):
expression.set_editor_property('sampler_type', self.sampler_type)
##
# This dictionary assigns the given texture type names (found in suffixes, for ex. T_TextureName_D - D means it's a
# Diffuse texture) to the different actions that should be performed to properly set it up in the material.
##
actions = {
'DA': [
CreateConnection('RGB', MP.MP_BASE_COLOR),
CreateConnection('A', MP.MP_OPACITY),
SetProperty('blend_mode', BM.BLEND_TRANSLUCENT)
],
'D': [
CreateConnection('RGB', MP.MP_BASE_COLOR)
],
'AO': [
CreateConnection('R', MP.MP_AMBIENT_OCCLUSION),
SetSamplerType(MST.SAMPLERTYPE_MASKS)
],
'A': [
CreateConnection('R', MP.MP_OPACITY),
SetSamplerType(MST.SAMPLERTYPE_GRAYSCALE),
SetProperty('blend_mode', BM.BLEND_TRANSLUCENT)
],
'N': [
CreateConnection('RGB', MP.MP_NORMAL),
SetSamplerType(MST.SAMPLERTYPE_NORMAL)
],
'M': [
CreateConnection('R', MP.MP_METALLIC),
SetSamplerType(MST.SAMPLERTYPE_MASKS)
],
'R': [
CreateConnection('G', MP.MP_ROUGHNESS),
SetSamplerType(MST.SAMPLERTYPE_MASKS)
],
'S': [
CreateConnection('B', MP.MP_SPECULAR),
SetSamplerType(MST.SAMPLERTYPE_MASKS)
],
'E': [
CreateConnectionScaled('RGB', MP.MP_EMISSIVE_COLOR, 15)
],
}
##
# Helper functions
##
# Create a material at a given path
def create_empty_material(name) -> M:
asset_tools = ATH.get_asset_tools()
package_name, asset_name = asset_tools.create_unique_asset_name(name, '')
if not EAL.does_asset_exist(package_name):
path = package_name.rsplit('/', 1)[0]
name = package_name.rsplit('/', 1)[1]
return asset_tools.create_asset(name, path, M, unreal.MaterialFactoryNew())
return unreal.load_asset(package_name)
# Perform actions defined in the 'actions' dictionary. This should result in textures being added properly with respect
# for required or desired settings for certain texture types
def apply_texture(material, texture_name, y_pos):
sampler = MEL.create_material_expression(material, unreal.MaterialExpressionTextureSample, -500, y_pos)
sampler.texture = unreal.load_asset(texture_name)
texture_suffix = texture_name.rsplit('_', 1)[1]
for key in actions:
if key in texture_suffix:
texture_suffix = texture_suffix.replace(key, '')
for action in actions[key]:
action.execute(material, sampler, y_pos)
##
# Create material from selected textures
##
def create_material_from_textures(name):
material = create_empty_material(name)
selected_assets = EUL.get_selected_assets()
y_pos = 0
for asset in selected_assets:
if isinstance(asset, T):
apply_texture(material, asset.get_path_name(), y_pos)
y_pos += 250
MEL.recompile_material(material)
EAL.save_asset(material.get_path_name(), only_if_is_dirty=True)
asset_tools = ATH.get_asset_tools()
asset_tools.open_editor_for_assets([material])
|
import unreal
def get_component_handles(blueprint_asset_path): ## ์ฌ์ฉ์ํด๋๋จ, ๋ค์ ํจ์์์ ํธ์ถํด์ ์ฌ์ฉํ๋ ํจ์, ํธ๋ค๋ฌ ์ง์ ๋ฌผ๊ณ ์ถ์ผ๋ฉด ์ฐ์
subsystem = unreal.get_engine_subsystem(unreal.SubobjectDataSubsystem)
blueprint_asset = unreal.load_asset(blueprint_asset_path)
subobject_data_handles = subsystem.k2_gather_subobject_data_for_blueprint(blueprint_asset)
return subobject_data_handles
def get_component_objects(blueprint_asset_path : str): ## ์ปดํฌ๋ํธ ๋ฌด์ํ๊ฒ ๋ค ๊ธ์ด์ค
objects = []
handles = get_component_handles(blueprint_asset_path)
for handle in handles:
data = unreal.SubobjectDataBlueprintFunctionLibrary.get_data(handle)
object = unreal.SubobjectDataBlueprintFunctionLibrary.get_object(data)
objects.append(object)
return objects
def get_component_by_class(blueprint_to_find_components : unreal.Blueprint, component_class_to_find : unreal.Class): ## ์ปดํฌ๋ํธ์ค์ ํด๋์ค ๋ง๋๊ฒ๋ง ๋ฆฌํดํด์ค
components = []
asset_path = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(blueprint_to_find_components)
component_objects = get_component_objects(asset_path)
for each in component_objects:
compare_class = (each.__class__ == component_class_to_find)
if compare_class :
components.append(each)
return components
def get_component_by_var_name(blueprint_to_find_components : unreal.Blueprint, component_name_to_find : str) : ##์ปดํฌ๋ํธ ์ด๋ฆ์ผ๋ก ์ฐพ์
components = []
asset_path = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(blueprint_to_find_components)
component_objects = get_component_objects(asset_path)
for each in component_objects:
compare_name = (each.get_name()) == ( component_name_to_find + '_GEN_VARIABLE' )
if compare_name :
components.append(each)
return components
assets = unreal.EditorUtilityLibrary.get_selected_assets()
for each in assets :
comps = get_component_by_class(each, unreal.StaticMeshComponent)
for comp in comps :
if not comp.visible :
comp.visible = True
|
# Copyright Epic Games, Inc. All Rights Reserved.
import unreal
import flow.cmd
import unrealcmd
#-------------------------------------------------------------------------------
def _write(key, value):
value = str(value)
if value.startswith("?"): value = flow.cmd.text.light_yellow(value[1:])
elif value.startswith("!"): value = flow.cmd.text.light_red(value[1:])
dots = max(23 - len(str(key)), 3)
dots = flow.cmd.text.grey(("." * dots) if dots > 0 else "")
print(key, dots, value)
#-------------------------------------------------------------------------------
class InfoBase(unrealcmd.Cmd):
json = unrealcmd.Opt(False, "Print the output as JSON")
def _print_pretty(self, info):
def print_dict(name, subject):
if isinstance(subject, dict):
it = subject.items()
elif isinstance(subject, list):
it = enumerate(subject)
for key, value in it:
if isinstance(value, dict|list):
print_dict(key, value)
continue
if name and name != "env":
print(end=self._end)
self._end = "\n"
self.print_info(name.title().replace("_", " "))
name = None
_write(key, value)
print_dict("", info)
def _print_json(self, info):
import sys
import json
def represent(subject):
if hasattr(subject, "get_inner"):
return subject.get_inner()
return repr(subject)
json.dump(info, sys.stdout, indent=2, default=represent)
def main(self):
self._end = ""
info = self._get_info()
if self.args.json:
self._print_json(info)
else:
self._print_pretty(info)
#-------------------------------------------------------------------------------
class Info(InfoBase):
""" Displays info about the current session. """
def _get_engine_info(self):
context = self.get_unreal_context()
engine = context.get_engine()
info = {
"path" : str(engine.get_dir()),
"version" : "",
"version_full" : "",
"branch" : "",
"changelist" : "0",
}
version = engine.get_info()
if version:
info["branch"] = version["BranchName"]
info["changelist"] = str(version["Changelist"])
info["version"] = str(engine.get_version_major())
info["version_full"] = "{}.{}.{}".format(
version["MajorVersion"],
version["MinorVersion"],
version["PatchVersion"])
return info
def _get_project_info(self):
context = self.get_unreal_context()
project = context.get_project()
info = {
"name" : "?no active project"
}
if not project:
return info
info["name"] = project.get_name()
info["path"] = str(project.get_path())
info["dir"] = str(project.get_dir())
targets_info = {}
known_targets = (
("editor", unreal.TargetType.EDITOR),
("game", unreal.TargetType.GAME),
("client", unreal.TargetType.CLIENT),
("server", unreal.TargetType.SERVER),
)
for target_name, target_type in known_targets:
target = context.get_target_by_type(target_type)
output = target.get_name() if target else "!unknown"
targets_info[target_name] = output
info["targets"] = targets_info
return info
def _get_platforms_info(self):
info = {}
for platform_name in sorted(self.read_platforms()):
inner = info.setdefault(platform_name.lower(), {})
platform = self.get_platform(platform_name)
inner["name"] = platform.get_name()
inner["version"] = platform.get_version() or "!unknown"
inner["env"] = {}
for item in platform.read_env():
try: value = item.validate()
except EnvironmentError: value = "!" + item.get()
inner["env"][item.key] = value
return info
def _get_info(self):
return {
"engine" : self._get_engine_info(),
"project" : self._get_project_info(),
"platforms" : self._get_platforms_info(),
}
#-------------------------------------------------------------------------------
class Projects(InfoBase):
""" Displays the branch's synced .uprojects """
def _get_info(self):
context = self.get_unreal_context()
branch = context.get_branch(must_exist=True)
return { "branch_projects" : list(str(x) for x in branch.read_projects()) }
#-------------------------------------------------------------------------------
class Config(InfoBase):
""" Evaluates currect context's config for a particular category. The 'override'
option can be used to enumerate platform-specific config sets."""
category = unrealcmd.Arg(str, "The ini category to load")
override = unrealcmd.Opt("", "Alternative config set to enumerate (e.g. 'WinGDK')")
def complete_category(self, prefix):
return ("Engine", "Game", "Input", "DeviceProfiles", "GameUserSettings",
"Scalability", "RuntimeOptions", "InstallBundle", "Hardware", "GameplayTags")
def _get_info(self):
context = self.get_unreal_context()
config = context.get_config()
ini = config.get(self.args.category, override=self.args.override)
ret = {}
for s_name, section in ini:
ret[s_name] = {k:v for k,v in section}
return ret
|
# Copyright (c) <2021> Side Effects Software Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. The name of Side Effects Software may not be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
""" An example script that uses the API and
HoudiniEngineV2.asyncprocessor.ProcessHDA. ProcessHDA is configured with the
asset to instantiate, as well as 2 inputs: a geometry input (a cube) and a
curve input (a helix).
ProcessHDA is then activiated upon which the asset will be instantiated,
inputs set, and cooked. The ProcessHDA class's on_post_processing() function is
overridden to fetch the input structure and logged. The other state/phase
functions (on_pre_instantiate(), on_post_instantiate() etc) are overridden to
simply log the function name, in order to observe progress in the log.
"""
import math
import unreal
from HoudiniEngineV2.asyncprocessor import ProcessHDA
_g_processor = None
class ProcessHDAExample(ProcessHDA):
@staticmethod
def _print_api_input(in_input):
print('\t\tInput type: {0}'.format(in_input.__class__))
print('\t\tbKeepWorldTransform: {0}'.format(in_input.keep_world_transform))
print('\t\tbImportAsReference: {0}'.format(in_input.import_as_reference))
if isinstance(in_input, unreal.HoudiniPublicAPIGeoInput):
print('\t\tbPackBeforeMerge: {0}'.format(in_input.pack_before_merge))
print('\t\tbExportLODs: {0}'.format(in_input.export_lo_ds))
print('\t\tbExportSockets: {0}'.format(in_input.export_sockets))
print('\t\tbExportColliders: {0}'.format(in_input.export_colliders))
elif isinstance(in_input, unreal.HoudiniPublicAPICurveInput):
print('\t\tbCookOnCurveChanged: {0}'.format(in_input.cook_on_curve_changed))
print('\t\tbAddRotAndScaleAttributesOnCurves: {0}'.format(in_input.add_rot_and_scale_attributes_on_curves))
input_objects = in_input.get_input_objects()
if not input_objects:
print('\t\tEmpty input!')
else:
print('\t\tNumber of objects in input: {0}'.format(len(input_objects)))
for idx, input_object in enumerate(input_objects):
print('\t\t\tInput object #{0}: {1}'.format(idx, input_object))
if hasattr(in_input, 'supports_transform_offset') and in_input.supports_transform_offset():
print('\t\t\tObject Transform Offset: {0}'.format(in_input.get_input_object_transform_offset(idx)))
if isinstance(input_object, unreal.HoudiniPublicAPICurveInputObject):
print('\t\t\tbClosed: {0}'.format(input_object.is_closed()))
print('\t\t\tCurveMethod: {0}'.format(input_object.get_curve_method()))
print('\t\t\tCurveType: {0}'.format(input_object.get_curve_type()))
print('\t\t\tReversed: {0}'.format(input_object.is_reversed()))
print('\t\t\tCurvePoints: {0}'.format(input_object.get_curve_points()))
def on_failure(self):
print('on_failure')
global _g_processor
_g_processor = None
def on_complete(self):
print('on_complete')
global _g_processor
_g_processor = None
def on_pre_instantiation(self):
print('on_pre_instantiation')
def on_post_instantiation(self):
print('on_post_instantiation')
def on_post_auto_cook(self, cook_success):
print('on_post_auto_cook, success = {0}'.format(cook_success))
def on_pre_process(self):
print('on_pre_process')
def on_post_processing(self):
print('on_post_processing')
# Fetch inputs, iterate over it and log
node_inputs = self.asset_wrapper.get_inputs_at_indices()
parm_inputs = self.asset_wrapper.get_input_parameters()
if not node_inputs:
print('No node inputs found!')
else:
print('Number of node inputs: {0}'.format(len(node_inputs)))
for input_index, input_wrapper in node_inputs.items():
print('\tInput index: {0}'.format(input_index))
self._print_api_input(input_wrapper)
if not parm_inputs:
print('No parameter inputs found!')
else:
print('Number of parameter inputs: {0}'.format(len(parm_inputs)))
for parm_name, input_wrapper in parm_inputs.items():
print('\tInput parameter name: {0}'.format(parm_name))
self._print_api_input(input_wrapper)
def on_post_auto_bake(self, bake_success):
print('on_post_auto_bake, succes = {0}'.format(bake_success))
def get_test_hda_path():
return '/project/.copy_to_curve_1_0'
def get_test_hda():
return unreal.load_object(None, get_test_hda_path())
def get_geo_asset_path():
return '/project/.Cube'
def get_geo_asset():
return unreal.load_object(None, get_geo_asset_path())
def build_inputs():
print('configure_inputs')
# get the API singleton
houdini_api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
node_inputs = {}
# Create a geo input
geo_input = houdini_api.create_empty_input(unreal.HoudiniPublicAPIGeoInput)
# Set the input objects/assets for this input
geo_object = get_geo_asset()
geo_input.set_input_objects((geo_object, ))
# store the input data to the HDA as node input 0
node_inputs[0] = geo_input
# Create a curve input
curve_input = houdini_api.create_empty_input(unreal.HoudiniPublicAPICurveInput)
# Create a curve wrapper/helper
curve_object = unreal.HoudiniPublicAPICurveInputObject(curve_input)
# Make it a Nurbs curve
curve_object.set_curve_type(unreal.HoudiniPublicAPICurveType.NURBS)
# Set the points of the curve, for this example we create a helix
# consisting of 100 points
curve_points = []
for i in range(100):
t = i / 20.0 * math.pi * 2.0
x = 100.0 * math.cos(t)
y = 100.0 * math.sin(t)
z = i
curve_points.append(unreal.Transform([x, y, z], [0, 0, 0], [1, 1, 1]))
curve_object.set_curve_points(curve_points)
# Set the curve wrapper as an input object
curve_input.set_input_objects((curve_object, ))
# Store the input data to the HDA as node input 1
node_inputs[1] = curve_input
return node_inputs
def run():
# Create the processor with preconfigured inputs
global _g_processor
_g_processor = ProcessHDAExample(
get_test_hda(), node_inputs=build_inputs())
# Activate the processor, this will starts instantiation, and then cook
if not _g_processor.activate():
unreal.log_warning('Activation failed.')
else:
unreal.log('Activated!')
if __name__ == '__main__':
run()
|
import unreal
# define actor location
actorLocation = unreal.Vector(0, 0, 0)
actorRotation = unreal.Rotator(0, 0, 0)
levelSubsys = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem)
# create new atmospheric actors
dirLight = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.DirectionalLight, actorLocation, actorRotation, False)
skyLight = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.SkyLight, actorLocation, actorRotation, False)
sky = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.SkyAtmosphere, actorLocation, actorRotation, False)
fog = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.ExponentialHeightFog, actorLocation, actorRotation, False)
clouds = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.VolumetricCloud, actorLocation, actorRotation, False)
# save level
levelSubsys.save_current_level()
|
import unreal
import os
def add_camera_position_to_txt(name, all_cams):
t, r = unreal.EditorLevelLibrary.get_level_viewport_camera_info()
path = unreal.Paths.project_config_dir()
abs_path = unreal.Paths.convert_relative_path_to_full(path) + "ViewportTransform/"
filename = abs_path + name + '.txt'
if not os.path.exists(abs_path):
os.makedirs(abs_path)
tf = str(t.x) + ',' + str(t.y) + ',' + str(t.z) + ',' + str(r.roll) + ',' + str(r.pitch) + ',' + str(r.yaw) + '\n'
unreal.log(all_cams)
unreal.log(tf)
if tf not in all_cams:
with open(filename, 'a+') as txt:
txt.writelines(tf)
txt.close()
def read_camera_position_from_txt(name):
path = unreal.Paths.project_config_dir() + "ViewportTransform/"
filename = path + name + '.txt'
with open(filename, "r") as txt:
readline = txt.readlines()
txt.close()
return readline
def set_camera(index, all_cams):
tf = all_cams[index].split(',')
t = unreal.Vector(float(tf[0]), float(tf[1]), float(tf[2]))
r = unreal.Rotator(float(tf[3]), float(tf[4]), float(tf[5]))
unreal.EditorLevelLibrary.set_level_viewport_camera_info(t, r)
def process_camera(mode, all_cams, current):
if mode == 1:
current += 1
else:
current -= 1
now = current % len(all_cams)
set_camera(now, all_cams)
return now
def remove_current_camera(name, all_cams, current):
if len(all_cams) == 0:
return current
path = unreal.Paths.project_config_dir() + "ViewportTransform/"
filename = path + name + '.txt'
with open(filename, "w") as txt_w:
for line_no, line in enumerate(all_cams, 0):
if line_no == current:
continue
txt_w.write(line)
txt_w.close()
if current > 1:
return current - 1
else:
return current
def load_viewport():
path = unreal.Paths.project_config_dir() + "ViewportTransform/"
abs_path = unreal.Paths.convert_relative_path_to_full(path)
if not os.path.exists(abs_path):
return ['default']
files = os.listdir(abs_path)
if len(files) == 0:
return ['default']
filename = []
for f in files:
filename.append(os.path.splitext(f)[0])
return filename
def create_seq():
path = unreal.Paths.project_config_dir() + "ViewportTransform/"
abs_path = unreal.Paths.convert_relative_path_to_full(path)
filename = 'viewport_default.txt'
if not os.path.exists(abs_path):
os.makedirs(abs_path)
txt_path = abs_path + filename
f = open(txt_path, "w+")
f.close()
elif not os.path.exists(abs_path+filename):
txt_path = abs_path + filename
f = open(txt_path, "w+")
f.close()
else:
files = os.listdir(abs_path)
num = []
for f in files:
fn = os.path.splitext(f)[0]
# unreal.log(fn[-2:])
try:
num.append(int(fn[-2:]))
except Exception:
pass
new_one = 1
while new_one in num:
new_one += 1
b = len(str(new_one))
if b > 3:
filename = 'viewport_seq%05d.txt' % new_one
filename = 'viewport_seq%02d.txt' % new_one
txt_path = abs_path + filename
f = open(txt_path, "w+")
f.close()
return filename.replace(".txt","")
def remove_seq(name):
if name == 'viewport_default':
return
path = unreal.Paths.project_config_dir() + "ViewportTransform/"
filename = name+".txt"
file_path = path + filename
if not os.path.exists(file_path):
return
os.remove(file_path)
def screen_snapshot(seq_name, camera_index):
image_index = 1
file_name = "{}_{:d}_{:d}".format(seq_name, camera_index, image_index)
path = unreal.Paths().screen_shot_dir() + file_name + ".png"
while os.path.exists(path):
image_index += 1
file_name = "{}_{:d}_{:d}".format(seq_name, camera_index, image_index)
path = unreal.Paths().screen_shot_dir() + file_name + ".png"
unreal.AutomationLibrary().take_high_res_screenshot(1920, 1080, file_name)
def screen_stats_save(seq_name,camera_index,export_path):
image_index = 1
file_name = "{}_{:d}_{:d}.csv".format(seq_name, camera_index, image_index)
save_path = unreal.Paths().convert_relative_path_to_full(export_path) + "/"
path = save_path + file_name
unreal.log_warning("csv file path : {}".format(path))
while os.path.exists(path):
image_index += 1
file_name = "{}_{:d}_{:d}.csv".format(seq_name, camera_index, image_index)
path = save_path + file_name
out = file_name
|
# Copyright (c) <2021> Side Effects Software Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. The name of Side Effects Software may not be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unreal
class ProcessHDA(object):
""" An object that wraps async processing of an HDA (instantiating,
cooking/project/ an HDA), with functions that are called at the
various stages of the process, that can be overridden by subclasses for
custom funtionality:
- on_failure()
- on_complete(): upon successful completion (could be PostInstantiation
if auto cook is disabled, PostProcessing if auto bake is disabled, or
after PostAutoBake if auto bake is enabled.
- on_pre_instantiation(): before the HDA is instantiated, a good place
to set parameter values before the first cook.
- on_post_instantiation(): after the HDA is instantiated, a good place
to set/configure inputs before the first cook.
- on_post_auto_cook(): right after a cook
- on_pre_process(): after a cook but before output objects have been
created/processed
- on_post_processing(): after output objects have been created
- on_post_auto_bake(): after outputs have been baked
Instantiate the processor via the constructor and then call the activate()
function to start the asynchronous process.
"""
def __init__(
self,
houdini_asset,
instantiate_at=unreal.Transform(),
parameters=None,
node_inputs=None,
parameter_inputs=None,
world_context_object=None,
spawn_in_level_override=None,
enable_auto_cook=True,
enable_auto_bake=False,
bake_directory_path="",
bake_method=unreal.HoudiniEngineBakeOption.TO_ACTOR,
remove_output_after_bake=False,
recenter_baked_actors=False,
replace_previous_bake=False,
delete_instantiated_asset_on_completion_or_failure=False):
""" Instantiates an HDA in the specified world/level. Sets parameters
and inputs supplied in InParameters, InNodeInputs and parameter_inputs.
If bInEnableAutoCook is true, cooks the HDA. If bInEnableAutoBake is
true, bakes the cooked outputs according to the supplied baking
parameters.
This all happens asynchronously, with the various output pins firing at
the various points in the process:
- PreInstantiation: before the HDA is instantiated, a good place
to set parameter values before the first cook (parameter values
from ``parameters`` are automatically applied at this point)
- PostInstantiation: after the HDA is instantiated, a good place
to set/configure inputs before the first cook (inputs from
``node_inputs`` and ``parameter_inputs`` are automatically applied
at this point)
- PostAutoCook: right after a cook
- PreProcess: after a cook but before output objects have been
created/processed
- PostProcessing: after output objects have been created
- PostAutoBake: after outputs have been baked
- Completed: upon successful completion (could be PostInstantiation
if auto cook is disabled, PostProcessing if auto bake is disabled,
or after PostAutoBake if auto bake is enabled).
- Failed: If the process failed at any point.
Args:
houdini_asset (HoudiniAsset): The HDA to instantiate.
instantiate_at (Transform): The Transform to instantiate the HDA with.
parameters (Map(Name, HoudiniParameterTuple)): The parameters to set before cooking the instantiated HDA.
node_inputs (Map(int32, HoudiniPublicAPIInput)): The node inputs to set before cooking the instantiated HDA.
parameter_inputs (Map(Name, HoudiniPublicAPIInput)): The parameter-based inputs to set before cooking the instantiated HDA.
world_context_object (Object): A world context object for identifying the world to spawn in, if spawn_in_level_override is null.
spawn_in_level_override (Level): If not nullptr, then the HoudiniAssetActor is spawned in that level. If both spawn_in_level_override and world_context_object are null, then the actor is spawned in the current editor context world's current level.
enable_auto_cook (bool): If true (the default) the HDA will cook automatically after instantiation and after parameter, transform and input changes.
enable_auto_bake (bool): If true, the HDA output is automatically baked after a cook. Defaults to false.
bake_directory_path (str): The directory to bake to if the bake path is not set via attributes on the HDA output.
bake_method (HoudiniEngineBakeOption): The bake target (to actor vs blueprint). @see HoudiniEngineBakeOption.
remove_output_after_bake (bool): If true, HDA temporary outputs are removed after a bake. Defaults to false.
recenter_baked_actors (bool): Recenter the baked actors to their bounding box center. Defaults to false.
replace_previous_bake (bool): If true, on every bake replace the previous bake's output (assets + actors) with the new bake's output. Defaults to false.
delete_instantiated_asset_on_completion_or_failure (bool): If true, deletes the instantiated asset actor on completion or failure. Defaults to false.
"""
super(ProcessHDA, self).__init__()
self._houdini_asset = houdini_asset
self._instantiate_at = instantiate_at
self._parameters = parameters
self._node_inputs = node_inputs
self._parameter_inputs = parameter_inputs
self._world_context_object = world_context_object
self._spawn_in_level_override = spawn_in_level_override
self._enable_auto_cook = enable_auto_cook
self._enable_auto_bake = enable_auto_bake
self._bake_directory_path = bake_directory_path
self._bake_method = bake_method
self._remove_output_after_bake = remove_output_after_bake
self._recenter_baked_actors = recenter_baked_actors
self._replace_previous_bake = replace_previous_bake
self._delete_instantiated_asset_on_completion_or_failure = delete_instantiated_asset_on_completion_or_failure
self._asset_wrapper = None
self._cook_success = False
self._bake_success = False
@property
def asset_wrapper(self):
""" The asset wrapper for the instantiated HDA processed by this node. """
return self._asset_wrapper
@property
def cook_success(self):
""" True if the last cook was successful. """
return self._cook_success
@property
def bake_success(self):
""" True if the last bake was successful. """
return self._bake_success
@property
def houdini_asset(self):
""" The HDA to instantiate. """
return self._houdini_asset
@property
def instantiate_at(self):
""" The transform the instantiate the asset with. """
return self._instantiate_at
@property
def parameters(self):
""" The parameters to set on on_pre_instantiation """
return self._parameters
@property
def node_inputs(self):
""" The node inputs to set on on_post_instantiation """
return self._node_inputs
@property
def parameter_inputs(self):
""" The object path parameter inputs to set on on_post_instantiation """
return self._parameter_inputs
@property
def world_context_object(self):
""" The world context object: spawn in this world if spawn_in_level_override is not set. """
return self._world_context_object
@property
def spawn_in_level_override(self):
""" The level to spawn in. If both this and world_context_object is not set, spawn in the editor context's level. """
return self._spawn_in_level_override
@property
def enable_auto_cook(self):
""" Whether to set the instantiated asset to auto cook. """
return self._enable_auto_cook
@property
def enable_auto_bake(self):
""" Whether to set the instantiated asset to auto bake after a cook. """
return self._enable_auto_bake
@property
def bake_directory_path(self):
""" Set the fallback bake directory, for if output attributes do not specify it. """
return self._bake_directory_path
@property
def bake_method(self):
""" The bake method/target: for example, to actors vs to blueprints. """
return self._bake_method
@property
def remove_output_after_bake(self):
""" Remove temporary HDA output after a bake. """
return self._remove_output_after_bake
@property
def recenter_baked_actors(self):
""" Recenter the baked actors at their bounding box center. """
return self._recenter_baked_actors
@property
def replace_previous_bake(self):
""" Replace previous bake output on each bake. For the purposes of this
node, this would mostly apply to .uassets and not actors.
"""
return self._replace_previous_bake
@property
def delete_instantiated_asset_on_completion_or_failure(self):
""" Whether or not to delete the instantiated asset after Complete is called. """
return self._delete_instantiated_asset_on_completion_or_failure
def activate(self):
""" Activate the process. This will:
- instantiate houdini_asset and wrap it as asset_wrapper
- call on_failure() for any immediate failures
- otherwise bind to delegates from asset_wrapper so that the
various self.on_*() functions are called as appropriate
Returns immediately (does not block until cooking/processing is
complete).
Returns:
(bool): False if activation failed.
"""
# Get the API instance
houdini_api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
if not houdini_api:
# Handle failures: this will unbind delegates and call on_failure()
self._handle_on_failure()
return False
# Create an empty API asset wrapper
self._asset_wrapper = unreal.HoudiniPublicAPIAssetWrapper.create_empty_wrapper(houdini_api)
if not self._asset_wrapper:
# Handle failures: this will unbind delegates and call on_failure()
self._handle_on_failure()
return False
# Bind to the wrapper's delegates for instantiation, cooking, baking
# etc events
self._asset_wrapper.on_pre_instantiation_delegate.add_callable(
self._handle_on_pre_instantiation)
self._asset_wrapper.on_post_instantiation_delegate.add_callable(
self._handle_on_post_instantiation)
self._asset_wrapper.on_post_cook_delegate.add_callable(
self._handle_on_post_auto_cook)
self._asset_wrapper.on_pre_process_state_exited_delegate.add_callable(
self._handle_on_pre_process)
self._asset_wrapper.on_post_processing_delegate.add_callable(
self._handle_on_post_processing)
self._asset_wrapper.on_post_bake_delegate.add_callable(
self._handle_on_post_auto_bake)
# Begin the instantiation process of houdini_asset and wrap it with
# self.asset_wrapper
if not houdini_api.instantiate_asset_with_existing_wrapper(
self.asset_wrapper,
self.houdini_asset,
self.instantiate_at,
self.world_context_object,
self.spawn_in_level_override,
self.enable_auto_cook,
self.enable_auto_bake,
self.bake_directory_path,
self.bake_method,
self.remove_output_after_bake,
self.recenter_baked_actors,
self.replace_previous_bake):
# Handle failures: this will unbind delegates and call on_failure()
self._handle_on_failure()
return False
return True
def _unbind_delegates(self):
""" Unbinds from self.asset_wrapper's delegates (if valid). """
if not self._asset_wrapper:
return
self._asset_wrapper.on_pre_instantiation_delegate.add_callable(
self._handle_on_pre_instantiation)
self._asset_wrapper.on_post_instantiation_delegate.add_callable(
self._handle_on_post_instantiation)
self._asset_wrapper.on_post_cook_delegate.add_callable(
self._handle_on_post_auto_cook)
self._asset_wrapper.on_pre_process_state_exited_delegate.add_callable(
self._handle_on_pre_process)
self._asset_wrapper.on_post_processing_delegate.add_callable(
self._handle_on_post_processing)
self._asset_wrapper.on_post_bake_delegate.add_callable(
self._handle_on_post_auto_bake)
def _check_wrapper(self, wrapper):
""" Checks that wrapper matches self.asset_wrapper. Logs a warning if
it does not.
Args:
wrapper (HoudiniPublicAPIAssetWrapper): the wrapper to check
against self.asset_wrapper
Returns:
(bool): True if the wrappers match.
"""
if wrapper != self._asset_wrapper:
unreal.log_warning(
'[UHoudiniPublicAPIProcessHDANode] Received delegate event '
'from unexpected asset wrapper ({0} vs {1})!'.format(
self._asset_wrapper.get_name() if self._asset_wrapper else '',
wrapper.get_name() if wrapper else ''
)
)
return False
return True
def _handle_on_failure(self):
""" Handle any failures during the lifecycle of the process. Calls
self.on_failure() and then unbinds from self.asset_wrapper and
optionally deletes the instantiated asset.
"""
self.on_failure()
self._unbind_delegates()
if self.delete_instantiated_asset_on_completion_or_failure and self.asset_wrapper:
self.asset_wrapper.delete_instantiated_asset()
def _handle_on_complete(self):
""" Handles completion of the process. This can happen at one of
three stages:
- After on_post_instantiate(), if enable_auto_cook is False.
- After on_post_auto_cook(), if enable_auto_cook is True but
enable_auto_bake is False.
- After on_post_auto_bake(), if both enable_auto_cook and
enable_auto_bake are True.
Calls self.on_complete() and then unbinds from self.asset_wrapper's
delegates and optionally deletes the instantiated asset.
"""
self.on_complete()
self._unbind_delegates()
if self.delete_instantiated_asset_on_completion_or_failure and self.asset_wrapper:
self.asset_wrapper.delete_instantiated_asset()
def _handle_on_pre_instantiation(self, wrapper):
""" Called during pre_instantiation. Sets ``parameters`` on the HDA
and calls self.on_pre_instantiation().
"""
if not self._check_wrapper(wrapper):
return
# Set any parameters specified for the HDA
if self.asset_wrapper and self.parameters:
self.asset_wrapper.set_parameter_tuples(self.parameters)
self.on_pre_instantiation()
def _handle_on_post_instantiation(self, wrapper):
""" Called during post_instantiation. Sets inputs (``node_inputs`` and
``parameter_inputs``) on the HDA and calls self.on_post_instantiation().
Completes execution if enable_auto_cook is False.
"""
if not self._check_wrapper(wrapper):
return
# Set any inputs specified when the node was created
if self.asset_wrapper:
if self.node_inputs:
self.asset_wrapper.set_inputs_at_indices(self.node_inputs)
if self.parameter_inputs:
self.asset_wrapper.set_input_parameters(self.parameter_inputs)
self.on_post_instantiation()
# If not set to auto cook, complete execution now
if not self.enable_auto_cook:
self._handle_on_complete()
def _handle_on_post_auto_cook(self, wrapper, cook_success):
""" Called during post_cook. Sets self.cook_success and calls
self.on_post_auto_cook().
Args:
cook_success (bool): True if the cook was successful.
"""
if not self._check_wrapper(wrapper):
return
self._cook_success = cook_success
self.on_post_auto_cook(cook_success)
def _handle_on_pre_process(self, wrapper):
""" Called during pre_process. Calls self.on_pre_process().
"""
if not self._check_wrapper(wrapper):
return
self.on_pre_process()
def _handle_on_post_processing(self, wrapper):
""" Called during post_processing. Calls self.on_post_processing().
Completes execution if enable_auto_bake is False.
"""
if not self._check_wrapper(wrapper):
return
self.on_post_processing()
# If not set to auto bake, complete execution now
if not self.enable_auto_bake:
self._handle_on_complete()
def _handle_on_post_auto_bake(self, wrapper, bake_success):
""" Called during post_bake. Sets self.bake_success and calls
self.on_post_auto_bake().
Args:
bake_success (bool): True if the bake was successful.
"""
if not self._check_wrapper(wrapper):
return
self._bake_success = bake_success
self.on_post_auto_bake(bake_success)
self._handle_on_complete()
def on_failure(self):
""" Called if the process fails to instantiate or fails to start
a cook.
Subclasses can override this function implement custom functionality.
"""
pass
def on_complete(self):
""" Called if the process completes instantiation, cook and/or baking,
depending on enable_auto_cook and enable_auto_bake.
Subclasses can override this function implement custom functionality.
"""
pass
def on_pre_instantiation(self):
""" Called during pre_instantiation.
Subclasses can override this function implement custom functionality.
"""
pass
def on_post_instantiation(self):
""" Called during post_instantiation.
Subclasses can override this function implement custom functionality.
"""
pass
def on_post_auto_cook(self, cook_success):
""" Called during post_cook.
Subclasses can override this function implement custom functionality.
Args:
cook_success (bool): True if the cook was successful.
"""
pass
def on_pre_process(self):
""" Called during pre_process.
Subclasses can override this function implement custom functionality.
"""
pass
def on_post_processing(self):
""" Called during post_processing.
Subclasses can override this function implement custom functionality.
"""
pass
def on_post_auto_bake(self, bake_success):
""" Called during post_bake.
Subclasses can override this function implement custom functionality.
Args:
bake_success (bool): True if the bake was successful.
"""
pass
|
#Discription
##Python 3.7 with UE4.26 Python Module by Minomi
###ํจ์ ์ฌ์ฉ์ import ๋ฐฉ์์ด ์๋ ๋ณต์ฌํด์ ์ฌ์ฉํ๋๊ฒ ๋ ์ ์ ๊ฑด๊ฐ์ ์ด๋กญ์ต๋๋ค.
#######################################import modules from here#######################################
import unreal
#######################################import modules end#######################################
#######################################functions from here#######################################
def get_selected_asset_dir() -> str :
ar_asset_lists = unreal.EditorUtilityLibrary.get_selected_assets()
if len(ar_asset_lists) > 0 :
str_selected_asset = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(ar_asset_lists[0])
path = str_selected_asset.rsplit('/', 1)[0]
else :
path = ''
return path
def get_anim_list (__path: str) -> list :
seq_list = unreal.EditorAssetLibrary.list_assets(__path, True, False)
return seq_list
def check_animseq_by_name_in_list (__anim_name: str, __list: list ) -> str :
for each in __list :
name = each.rsplit('.', 1)[1]
found_name = name.find(__anim_name)
if found_name != -1 :
break
return each
def set_bs_sample (__animation, __axis_x: float, __axis_y: float) : # returns [BlendSample] unreal native type
bs_sample = unreal.BlendSample()
vec_sample = unreal.Vector(__axis_x, __axis_y, 0.0) #do not use 3D BlendSampleVector
bs_sample.set_editor_property('animation', __animation)
bs_sample.set_editor_property('sample_value', vec_sample)
bs_sample.set_editor_property('rate_scale', 1.0)
bs_sample.set_editor_property('snap_to_grid', True)
return bs_sample
def set_blendSample_to_bs (__blendspace, __blendsample) : #returns [BlendSpace] unreal loaded asset
__blendspace.set_editor_property('sample_data', __blendsample)
return 0
def get_bp_c_by_name(__bp_dir:str):
__bp_c = __bp_dir + '_C'
return __bp_c
def get_bp_mesh_comp_by_name (__bp_c:str, __seek_comp_name:str) :
loaded_bp_c = unreal.EditorAssetLibrary.load_blueprint_class(__bp_c)
bp_c_obj = unreal.get_default_object(loaded_bp_c)
loaded_comp = bp_c_obj.get_editor_property(__seek_comp_name)
return loaded_comp
#์ธํ์ผ๋ก ๋ฐ๋ __bp_c ์๊ท๋จผํธ '/direc/*_Bluperint.*_Blueprint_c' << ์ ๊ฐ์ ํฌ๋งท์ผ๋ก ๋ฐ์์ผํจ
##asset_path๋ฅผ str๋ก ๋์ด์์ ๊ฒฝ์ฐ ์๋จ์ get_bp_c_by_name ํจ์ ์ด์ฉํ์ฌ class๋ก ํ๋ฒ ๋ ๋ํํด์ฃผ์ธ์.
###__seek_comp_name ์๊ท๋จผํธ ๋์ ์ํ๋ฉด ์๋์ ํจ์๋ฅผ ์ฌ์ฉํ์ธ์.
def get_bp_instance (__bp_c:str) :
loaded_bp_c = unreal.EditorAssetLibrary.load_blueprint_class(__bp_c)
bp_c_obj = unreal.get_default_object(loaded_bp_c)
return bp_c_obj
#Objectํ๋ Blueprint instance๋ฅผ ๋ฐํ
#์ปดํฌ๋ํธ๋ ๋ฐํ๋ bp_c_obj.get_editor_property('์ฐพ๊ณ ์ ํ๋ ์ปดํฌ๋ํธ ์ด๋ฆ')์ผ๋ก ๋์ด๋ค ์ฐ์ธ์.
# BP ์ปดํฌ๋ํธ ์ ๊ทผ ์์
## ๋ธ๋ฃจํ๋ฆฐํธ ํด๋์ค ๋ก๋
### ๋ํดํธ ์ค๋ธ์ ํธ ๋ก๋
#### ์ปดํฌ๋ํธ ๋ก๋ (get_editor_property)
#######################################functions end#######################################
#######################################class from here######################################
class wrapedBlendSpaceSetting:
bs_dir: str = '/project/' #blend space relative path
post_fix: str = '' #edit this if variation
pre_fix: str = '' #edit this if variation
custom_input: str = pre_fix + '/Animation' + post_fix
bs_names: list = [
"IdleRun_BS_Peaceful",
"IdleRun_BS_Battle",
"Down_BS",
"Groggy_BS",
"Airborne_BS",
"LockOn_BS"
]
seq_names: list = [
'_Idle01',
'_Walk_L',
'_BattleIdle01',
'_Run_L',
'_KnockDown_L',
'_Groggy_L',
'_Airborne_L',
'_Caution_Cw',
'_Caution_Fw',
'_Caution_Bw',
'_Caution_Lw',
'_Caution_Rw'
]
|
# 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 an
individual output object.
"""
_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_process(in_wrapper):
print('on_post_process')
# Print details about the outputs and record the first static mesh we find
sm_index = None
sm_identifier = None
# in_wrapper.on_post_processing_delegate.remove_callable(on_post_process)
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)
output_type = in_wrapper.get_output_type_at(output_idx)
print('\toutput index: {}'.format(output_idx))
print('\toutput type: {}'.format(output_type))
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('')
if (output_type == unreal.HoudiniOutputType.MESH and
isinstance(output_object, unreal.StaticMesh)):
sm_index = output_idx
sm_identifier = identifier
# Bake the first static mesh we found to the CB
if sm_index is not None and sm_identifier is not None:
print('baking {}'.format(sm_identifier))
success = in_wrapper.bake_output_object_at(sm_index, sm_identifier)
print('success' if success else 'failed')
# Delete the instantiated asset
in_wrapper.delete_instantiated_asset()
global _g_wrapper
_g_wrapper = None
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 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()
|
from Tkinter import *
import unreal
class UnrealApp:
def __init__(self):
self.root = Tk()
# Example text area
textarea = Text(self.root)
textarea.pack(expand=True, fill="both")
textarea.insert(END, "Heya!")
def run(max_tick_time=0.16):
# Don't use this; it'll block the UE4's Slate UI ticks
# root.mainloop()
# Instead, do the below:
self.tick_handle = None
self.tick_time = 0
def tick(delta_seconds):
self.tick_time += delta_seconds
# TODO: Use FPS instead of a hardcoded number to delay ticks
if self.tick_time > max_tick_time:
try:
self.root.update_idletasks()
self.root.update()
except Exception:
pass
self.tick_time = 0
# Setup our app to handle Unreal ticks to update the UI
self.tick_handle = unreal.register_slate_post_tick_callback(tick)
if __name__ == "__main__":
app = UnrealApp()
app.run()
|
# -*- 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.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
|
"""
this startup code is used to add a script editor button to the unreal tool bar.
ignore this file when using this script editor widget outside Unreal
"""
import os
import sys
import unreal
MODULE_PATH = os.path.dirname(os.path.abspath(__file__))
UPPER_PATH = os.path.join(MODULE_PATH, '..')
sys.path.append(UPPER_PATH)
def create_script_editor_button():
"""
Start up script to add script editor button to tool bar
"""
section_name = 'Plugins'
se_command = (
'from unreal_script_editor import main;'
'global editor;'
'editor = main.show()'
)
menus = unreal.ToolMenus.get()
level_menu_bar = menus.find_menu('LevelEditor.LevelEditorToolBar.PlayToolBar')
level_menu_bar.add_section(section_name=section_name, label=section_name)
entry = unreal.ToolMenuEntry(type=unreal.MultiBlockType.TOOL_BAR_BUTTON)
entry.set_label('Script Editor')
entry.set_tool_tip('Unreal Python Script Editor')
entry.set_icon('EditorStyle', 'DebugConsole.Icon')
entry.set_string_command(
type=unreal.ToolMenuStringCommandType.PYTHON,
custom_type=unreal.Name(''),
string=se_command
)
level_menu_bar.add_menu_entry(section_name, entry)
menus.refresh_all_widgets()
if __name__ == "__main__":
create_script_editor_button()
|
import unreal
import argparse
import sys
import os
import json
import tkinter as tk
from tkinter import filedialog
def create_performance_asset(path_to_identity : str, path_to_capture_data : str, save_performance_location : str) -> unreal.MetaHumanPerformance:
capture_data_asset = unreal.load_asset(path_to_capture_data)
identity_asset = unreal.load_asset(path_to_identity)
performance_asset_name = "{0}_Performance".format(capture_data_asset.get_name())
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
performance_asset = asset_tools.create_asset(asset_name=performance_asset_name, package_path=save_performance_location,
asset_class=unreal.MetaHumanPerformance, factory=unreal.MetaHumanPerformanceFactoryNew())
performance_asset.set_editor_property("identity", identity_asset)# load into the identity setting
performance_asset.set_editor_property("footage_capture_data", capture_data_asset)# load into the capture footage setting
return performance_asset
def run_animation_export(output_order, performance_asset : unreal.MetaHumanPerformance):
performance_asset_name = "AS"+str(output_order)# this is the name of the animation sequence, can be changed
unreal.log("Exporting animation sequence for Performance '{0}'".format(performance_asset_name))
export_settings = unreal.MetaHumanPerformanceExportAnimationSettings()
export_settings.enable_head_movement = False# Enable or disable to export the head rotation
export_settings.show_export_dialog = False
export_settings.export_range = unreal.PerformanceExportRange.PROCESSING_RANGE
anim_sequence: unreal.AnimSequence = unreal.MetaHumanPerformanceExportUtils.export_animation_sequence(performance_asset, export_settings)
unreal.log("Exported Anim Sequence {0}".format(performance_asset_name))
def process_shot(output_order, performance_asset : unreal.MetaHumanPerformance, export_level_sequence : bool, export_sequence_location : str,
path_to_meta_human_target : str, start_frame : int = None, end_frame : int = None):
performance_asset_name = "AS"+str(output_order)# this is the name of the animation sequence, can be changed
if start_frame is not None:
performance_asset.set_editor_property("start_frame_to_process", start_frame)
if end_frame is not None:
performance_asset.set_editor_property("end_frame_to_process", end_frame)
#Setting process to blocking will make sure the action is executed on the main thread, blocking it until processing is finished
process_blocking = True
performance_asset.set_blocking_processing(process_blocking)
unreal.log("Starting MH pipeline for '{0}'".format(performance_asset_name))
startPipelineError = performance_asset.start_pipeline()
if startPipelineError is unreal.StartPipelineErrorType.NONE:
unreal.log("Finished MH pipeline for '{0}'".format(performance_asset_name))
elif startPipelineError is unreal.StartPipelineErrorType.TOO_MANY_FRAMES:
unreal.log("Too many frames when starting MH pipeline for '{0}'".format(performance_asset_name))
else:
unreal.log("Unknown error starting MH pipeline for '{0}'".format(performance_asset_name))
#export the animation sequence
run_animation_export(output_order, performance_asset)
def run(output_order, number, end_frame):
#load into the metahuman identity and capture footage, then output a metahuman performance
performance_asset = create_performance_asset(
path_to_identity="/project/", # can be changed
path_to_capture_data="/project/"+str(number)+"_Ingested/006Vasilisa_"+str(number), # can be changed
save_performance_location="/project/") # can be changed
#process the metahuman performance and export the animation sequence
process_shot(
output_order=output_order,
performance_asset=performance_asset,
export_level_sequence=True,
export_sequence_location="/project/", # can be changed
path_to_meta_human_target="/project/", # can be changed
start_frame=0,
end_frame=end_frame)
# function to get the current level sequence and the sequencer objects
def get_sequencer_objects(level_sequence):
world = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem).get_editor_world()
#sequence_asset = unreal.LevelSequenceEditorBlueprintLibrary.get_current_level_sequence()
sequence_asset = level_sequence
range = sequence_asset.get_playback_range()
sequencer_objects_list = []
sequencer_names_list = []
bound_objects = []
sequencer_objects_list_temp = unreal.SequencerTools.get_bound_objects(world, sequence_asset, sequence_asset.get_bindings(), range)
for obj in sequencer_objects_list_temp:
bound_objects = obj.bound_objects
if len(bound_objects)>0:
if type(bound_objects[0]) == unreal.Actor:
sequencer_objects_list.append(bound_objects[0])
sequencer_names_list.append(bound_objects[0].get_actor_label())
return sequence_asset, sequencer_objects_list, sequencer_names_list
# function to export the face animation keys to a json file
def mgMetaHuman_face_keys_export(level_sequence, output_path):
system_lib = unreal.SystemLibrary()
root = tk.Tk()
root.withdraw()
face_anim = {}
world = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem).get_editor_world()
sequence_asset, sequencer_objects_list,sequencer_names_list = get_sequencer_objects(level_sequence)
face_possessable = None
editor_asset_name = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(sequence_asset).split('.')[-1]
for num in range(0, len(sequencer_names_list)):
actor = sequencer_objects_list[num]
asset_name = actor.get_actor_label()
bp_possessable = sequence_asset.add_possessable(actor)
child_possessable_list = bp_possessable.get_child_possessables()
character_name = ''
for current_child in child_possessable_list:
if 'Face' in current_child.get_name():
face_possessable = current_child
if face_possessable:
character_name = (face_possessable.get_parent().get_display_name())
face_possessable_track_list = face_possessable.get_tracks()
face_control_rig_track = face_possessable_track_list[len(face_possessable_track_list)-1]
face_control_channel_list = unreal.MovieSceneSectionExtensions.get_all_channels(face_control_rig_track.get_sections()[0])
face_control_name_list = []
for channel in face_control_channel_list:
channel_name = str(channel.get_name())
channel_string_list = channel_name.split('_')
channel_name = channel_name.replace('_' + channel_string_list[-1], '')
face_control_name_list.append(channel_name)
for ctrl_num in range(0, len(face_control_channel_list)):
control_name = face_control_name_list[ctrl_num]
try:
numKeys = face_control_channel_list[ctrl_num].get_num_keys()
key_list = [None] * numKeys
keys = face_control_channel_list[ctrl_num].get_keys()
for key in range(0, numKeys):
key_value = keys[key].get_value()
key_time = keys[key].get_time(time_unit=unreal.SequenceTimeUnit.DISPLAY_RATE).frame_number.value
key_list[key]=([key_value, key_time])
face_anim[control_name] = key_list
except:
face_anim[control_name] = []
character_name = str(character_name)
if 'BP_' in character_name:
character_name = character_name.replace('BP_', '')
if 'BP ' in character_name:
character_name = character_name.replace('BP ', '')
character_name = character_name.lower()
print('character_name is ' + character_name)
folder_path = output_path
os.makedirs(folder_path, exist_ok=True)
file_path = os.path.join(folder_path, f'{editor_asset_name}_face_anim.json')
with open(file_path, 'w') as keys_file:
keys_file.write('anim_keys_dict = ')
keys_file.write(json.dumps(face_anim))
print('Face Animation Keys output to: ' + str(keys_file.name))
else:
print(editor_asset_name)
print('is not a level sequence. Skipping.')
#path that contains video data, start to process performance
path = "/project/" #can be changed
output_order = 1
for i in os.listdir(path):
set_path = os.path.join(path, i)
if os.path.isdir(set_path):
#get the current folder number
folder_number = int(i.split("_")[-1])
json_file_path = os.path.join(set_path, "take.json")
if os.path.isfile(json_file_path):
with open(json_file_path, "r") as file:
data = json.load(file)
end_frame = data["frames"]
end_frame = end_frame // 2 + 1
run(output_order, folder_number, end_frame)
print("The performance process is done!")
output_order += 1
# The start the second part: create the level sequence and export the sequence
# add a new actor into the world
actor_path = "/project/" # the path of the actor, can be changed
actor_class = unreal.EditorAssetLibrary.load_blueprint_class(actor_path)
coordinate = unreal.Vector(-25200.0, -25200.0, 100.0) # randomly put it on a coordinate of the world
editor_subsystem = unreal.EditorActorSubsystem()
new_actor = editor_subsystem.spawn_actor_from_class(actor_class, coordinate)
animation_sequence = dict()
#assume the dataset is only 50 folders !!! Important, need to be changed base on real dataset number!! And number order should be 1, 2, 3, 4, ... ...
for i in range(1,50):
animation_sequence[i] = False
path = "/project/" #folder that contain all the character folders, need to be changed base on the real path, can be changed
#for every character folder, start to do the work:
for i in os.listdir(path):
set_path = os.path.join(path, i) #the path of each specific character folder
if os.path.isdir(set_path):
#if it is indeed a directory
json_file_path = os.path.join(set_path, "take.json")
if os.path.isfile(json_file_path):
#if the json file exists -> create a new level sequence -> set the playback range
with open(json_file_path) as file:
data = json.load(file)
frames_value = data["frames"]
value = frames_value // 2 + 1 #this is the upper bound of the frame range
#create a new level sequence
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
asset_name = set_path.split("\\")[-1] #get the last part of the path
level_sequence = unreal.AssetTools.create_asset(asset_tools, asset_name, package_path = "/Game/", asset_class = unreal.LevelSequence, factory = unreal.LevelSequenceFactoryNew())
level_sequence.set_playback_start(0) #starting frame will always be 0
level_sequence.set_playback_end(value) #end
#start to load into the animation to the current face track:
#Need to be changed base on the real name
face_anim_path = "/project/"
#then from low to high to load the animation sequence into the current face track (if the sequenced is loaded before, it will not be loaded again, then go the next)
for i in range(26,50):#And number order of the animation file should be continueing!!!
final_face_anim_path = face_anim_path + str(i) + "_Performance"
if final_face_anim_path:#if the path exists
if animation_sequence[i] == False:#if the animation sequence is not used before
animation_sequence[i] = True
anim_asset = unreal.EditorAssetLibrary.load_asset(final_face_anim_path)
print("animation sequence:" + str(anim_asset))
break
else:
continue
anim_asset = unreal.AnimSequence.cast(anim_asset)
params = unreal.MovieSceneSkeletalAnimationParams()
params.set_editor_property("Animation", anim_asset)
#add the actor into the level sequence
actor_binding = level_sequence.add_possessable(new_actor)
transform_track = actor_binding.add_track(unreal.MovieScene3DTransformTrack)
anim_track = actor_binding.add_track(unreal.MovieSceneSkeletalAnimationTrack)
# Add section to track to be able to manipulate range, parameters, or properties
transform_section = transform_track.add_section()
anim_section = anim_track.add_section()
# Get level sequence start and end frame
start_frame = level_sequence.get_playback_start()
end_frame = level_sequence.get_playback_end()
# Set section range to level sequence start and end frame
transform_section.set_range(start_frame, end_frame)
anim_section.set_range(start_frame, end_frame)
#add face animation track
components = new_actor.get_components_by_class(unreal.SkeletalMeshComponent)
print("Components of Cooper: ")
print(components)
face_component = None
for component in components:
if component.get_name() == "Face":
face_component = component
break
print(face_component)
#get the face track (same technique as above):
face_binding = level_sequence.add_possessable(face_component)
print(face_binding)
transform_track2 = face_binding.add_track(unreal.MovieScene3DTransformTrack)
anim_track2 = face_binding.add_track(unreal.MovieSceneSkeletalAnimationTrack)
transform_section2 = transform_track2.add_section()
anim_section2 = anim_track2.add_section()
anim_section2.set_editor_property("Params", params)#add animation
transform_section2.set_range(start_frame, end_frame)
anim_section2.set_range(start_frame, end_frame)
# bake to control rig to the face
print("level sequence: " + str(level_sequence))
editor_subsystem = unreal.UnrealEditorSubsystem()
world = editor_subsystem.get_editor_world()
print("world: " + str(world))
anim_seq_export_options = unreal.AnimSeqExportOption()
print("anim_seq_export_options: " + str(anim_seq_export_options))
control_rig = unreal.load_object(name = '/project/', outer = None)# can be changed
control_rig_class = control_rig.get_control_rig_class()# use class type in the under argument
print("control rig class: " + str(control_rig_class))
unreal.ControlRigSequencerLibrary.bake_to_control_rig(world, level_sequence, control_rig_class = control_rig_class, export_options = anim_seq_export_options, tolerance = 0.01, reduce_keys = False, binding = face_binding)
# Refresh to visually see the new level sequence
unreal.LevelSequenceEditorBlueprintLibrary.refresh_current_level_sequence()
# Export the current face animation keys to a json file
output_path = "/project/" # can be changed
mgMetaHuman_face_keys_export(level_sequence, output_path)
unreal.LevelSequenceEditorBlueprintLibrary.refresh_current_level_sequence()
print("Well Done! Jerry!")
|
# 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 instantiates an HDA that contains a TOP network.
After the HDA itself has cooked (in on_post_process) we iterate over all
TOP networks in the HDA and print their paths. Auto-bake is then enabled for
PDG and the TOP networks are cooked.
"""
import os
import unreal
_g_wrapper = None
def get_test_hda_path():
return '/project/.pdg_pighead_grid_2_0'
def get_test_hda():
return unreal.load_object(None, get_test_hda_path())
def get_hda_directory():
""" Attempt to get the directory containing the .hda files. This is
/project/. In newer versions of UE we can use
``unreal.SystemLibrary.get_system_path(asset)``, in older versions
we manually construct the path to the plugin.
Returns:
(str): the path to the example hda directory or ``None``.
"""
if hasattr(unreal.SystemLibrary, 'get_system_path'):
return os.path.dirname(os.path.normpath(
unreal.SystemLibrary.get_system_path(get_test_hda())))
else:
plugin_dir = os.path.join(
os.path.normpath(unreal.Paths.project_plugins_dir()),
'Runtime', 'HoudiniEngine', 'Content', 'Examples', 'hda'
)
if not os.path.exists(plugin_dir):
plugin_dir = os.path.join(
os.path.normpath(unreal.Paths.engine_plugins_dir()),
'Runtime', 'HoudiniEngine', 'Content', 'Examples', 'hda'
)
if not os.path.exists(plugin_dir):
return None
return plugin_dir
def delete_instantiated_asset():
global _g_wrapper
if _g_wrapper:
result = _g_wrapper.delete_instantiated_asset()
_g_wrapper = None
return result
else:
return False
def on_pre_instantiation(in_wrapper):
print('on_pre_instantiation')
# Set the hda_directory parameter to the directory that contains the
# example .hda files
hda_directory = get_hda_directory()
print('Setting "hda_directory" to {0}'.format(hda_directory))
in_wrapper.set_string_parameter_value('hda_directory', hda_directory)
# Cook the HDA (not PDG yet)
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'))
def on_post_process(in_wrapper):
print('on_post_process')
# in_wrapper.on_post_processing_delegate.remove_callable(on_post_process)
# Iterate over all PDG/TOP networks and nodes and log them
print('TOP networks:')
for network_path in in_wrapper.get_pdgtop_network_paths():
print('\t{}'.format(network_path))
for node_path in in_wrapper.get_pdgtop_node_paths(network_path):
print('\t\t{}'.format(node_path))
# Enable PDG auto-bake (auto bake TOP nodes after they are cooked)
in_wrapper.set_pdg_auto_bake_enabled(True)
# Bind to PDG post bake delegate (called after all baking is complete)
in_wrapper.on_post_pdg_bake_delegate.add_callable(on_post_bake)
# Cook the specified TOP node
in_wrapper.pdg_cook_node('topnet1', 'HE_OUT_PIGHEAD_GRID')
def run():
# get the API singleton
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
global _g_wrapper
# instantiate an asset, disabling auto-cook of the asset
_g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform(), enable_auto_cook=False)
# Bind to the on pre instantiation delegate (before the first cook) and
# set parameters
_g_wrapper.on_pre_instantiation_delegate.add_callable(on_pre_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()
|
# Copyright (c) <2021> Side Effects Software Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. The name of Side Effects Software may not be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
""" An example script that uses the API to instantiate an HDA and then
set 2 inputs: a geometry input (a cube) and a curve input (a helix). The
inputs are set during post instantiation (before the first cook). After the
first cook and output creation (post processing) the input structure is fetched
and logged.
"""
import math
import unreal
_g_wrapper = None
def get_test_hda_path():
return '/project/.copy_to_curve_1_0'
def get_test_hda():
return unreal.load_object(None, get_test_hda_path())
def get_geo_asset_path():
return '/project/.Cube'
def get_geo_asset():
return unreal.load_object(None, get_geo_asset_path())
def configure_inputs(in_wrapper):
print('configure_inputs')
# Unbind from the delegate
in_wrapper.on_post_instantiation_delegate.remove_callable(configure_inputs)
# Create a geo input
geo_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPIGeoInput)
# Set the input objects/assets for this input
geo_object = get_geo_asset()
if not geo_input.set_input_objects((geo_object, )):
# If any errors occurred, get the last error message
print('Error on geo_input: {0}'.format(geo_input.get_last_error_message()))
# copy the input data to the HDA as node input 0
in_wrapper.set_input_at_index(0, geo_input)
# We can now discard the API input object
geo_input = None
# Create a curve input
curve_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPICurveInput)
# Create a curve wrapper/helper
curve_object = unreal.HoudiniPublicAPICurveInputObject(curve_input)
# Make it a Nurbs curve
curve_object.set_curve_type(unreal.HoudiniPublicAPICurveType.NURBS)
# Set the points of the curve, for this example we create a helix
# consisting of 100 points
curve_points = []
for i in range(100):
t = i / 20.0 * math.pi * 2.0
x = 100.0 * math.cos(t)
y = 100.0 * math.sin(t)
z = i
curve_points.append(unreal.Transform([x, y, z], [0, 0, 0], [1, 1, 1]))
curve_object.set_curve_points(curve_points)
# Error handling/message example: try to set geo_object on curve input
if not curve_input.set_input_objects((geo_object, )):
print('Error (example) while setting \'{0}\' on curve input: {1}'.format(
geo_object.get_name(), curve_input.get_last_error_message()
))
# Set the curve wrapper as an input object
curve_input.set_input_objects((curve_object, ))
# Copy the input data to the HDA as node input 1
in_wrapper.set_input_at_index(1, curve_input)
# We can now discard the API input object
curve_input = None
# Check for errors on the wrapper
last_error = in_wrapper.get_last_error_message()
if last_error:
print('Error on wrapper during input configuration: {0}'.format(last_error))
def print_api_input(in_input):
print('\t\tInput type: {0}'.format(in_input.__class__))
print('\t\tbKeepWorldTransform: {0}'.format(in_input.keep_world_transform))
print('\t\tbImportAsReference: {0}'.format(in_input.import_as_reference))
if isinstance(in_input, unreal.HoudiniPublicAPIGeoInput):
print('\t\tbPackBeforeMerge: {0}'.format(in_input.pack_before_merge))
print('\t\tbExportLODs: {0}'.format(in_input.export_lo_ds))
print('\t\tbExportSockets: {0}'.format(in_input.export_sockets))
print('\t\tbExportColliders: {0}'.format(in_input.export_colliders))
elif isinstance(in_input, unreal.HoudiniPublicAPICurveInput):
print('\t\tbCookOnCurveChanged: {0}'.format(in_input.cook_on_curve_changed))
print('\t\tbAddRotAndScaleAttributesOnCurves: {0}'.format(in_input.add_rot_and_scale_attributes_on_curves))
input_objects = in_input.get_input_objects()
if not input_objects:
print('\t\tEmpty input!')
else:
print('\t\tNumber of objects in input: {0}'.format(len(input_objects)))
for idx, input_object in enumerate(input_objects):
print('\t\t\tInput object #{0}: {1}'.format(idx, input_object))
if isinstance(input_object, unreal.HoudiniPublicAPICurveInputObject):
print('\t\t\tbClosed: {0}'.format(input_object.is_closed()))
print('\t\t\tCurveMethod: {0}'.format(input_object.get_curve_method()))
print('\t\t\tCurveType: {0}'.format(input_object.get_curve_type()))
print('\t\t\tReversed: {0}'.format(input_object.is_reversed()))
print('\t\t\tCurvePoints: {0}'.format(input_object.get_curve_points()))
def print_inputs(in_wrapper):
print('print_inputs')
# Unbind from the delegate
in_wrapper.on_post_processing_delegate.remove_callable(print_inputs)
# Fetch inputs, iterate over it and log
node_inputs = in_wrapper.get_inputs_at_indices()
parm_inputs = in_wrapper.get_input_parameters()
if not node_inputs:
print('No node inputs found!')
else:
print('Number of node inputs: {0}'.format(len(node_inputs)))
for input_index, input_wrapper in node_inputs.items():
print('\tInput index: {0}'.format(input_index))
print_api_input(input_wrapper)
if not parm_inputs:
print('No parameter inputs found!')
else:
print('Number of parameter inputs: {0}'.format(len(parm_inputs)))
for parm_name, input_wrapper in parm_inputs.items():
print('\tInput parameter name: {0}'.format(parm_name))
print_api_input(input_wrapper)
def run():
# get the API singleton
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
global _g_wrapper
# instantiate an asset with auto-cook enabled
_g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform())
# Configure inputs on_post_instantiation, after instantiation, but before first cook
_g_wrapper.on_post_instantiation_delegate.add_callable(configure_inputs)
# Print the input state after the cook and output creation.
_g_wrapper.on_post_processing_delegate.add_callable(print_inputs)
if __name__ == '__main__':
run()
|
import os
import re
import subprocess
import time
from pathlib import Path
import unreal
import winsound
from mods.liana.helpers import *
from mods.liana.valorant import *
# BigSets
all_textures = []
all_blueprints = {}
object_types = []
all_level_paths = []
AssetTools = unreal.AssetToolsHelpers.get_asset_tools()
## Returns a array with all OverrideMaterials
def create_override_material(data):
material_array = []
for mat in data["Properties"]["OverrideMaterials"]:
if not mat:
material_array.append(None)
continue
object_name = return_object_name(mat["ObjectName"])
if object_name == "Stone_M2_Steps_MI1":
object_name = "Stone_M2_Steps_MI"
if "MaterialInstanceDynamic" in object_name:
material_array.append(None)
continue
material_array.append(unreal.load_asset(
f'/project/{object_name}'))
return material_array
def extract_assets(settings: Settings):
## Extracting Assets on umodel
asset_objects = settings.selected_map.folder_path.joinpath("all_assets.txt")
args = [settings.umodel.__str__(),
f"-path={settings.paks_path.__str__()}",
f"-game=valorant",
f"-aes={settings.aes}",
f"-files={asset_objects}",
"-export",
f"-{settings.texture_format.replace('.', '')}",
f"-out={settings.assets_path.__str__()}"]
subprocess.call(args, stderr=subprocess.DEVNULL)
def extract_data(
settings: Settings,
export_directory: str,
asset_list_txt: str = ""):
## Extracts the data from CUE4Parse (Json's)
args = [settings.cue4extractor.__str__(),
"--game-directory", settings.paks_path.__str__(),
"--aes-key", settings.aes,
"--export-directory", export_directory.__str__(),
"--map-name", settings.selected_map.name,
"--file-list", asset_list_txt,
"--game-umaps", settings.umap_list_path.__str__()
]
subprocess.call(args)
def get_map_assets(settings: Settings):
## Handles the extraction of the assets and filters them by type
umaps = []
if check_export(settings):
extract_data(
settings, export_directory=settings.selected_map.umaps_path)
extract_assets(settings)
umaps = get_files(
path=settings.selected_map.umaps_path.__str__(), extension=".json")
umap: Path
object_list = list()
actor_list = list()
materials_ovr_list = list()
materials_list = list()
for umap in umaps:
umap_json, asd = filter_umap(read_json(umap))
object_types.append(asd)
# save json
save_json(umap.__str__(), umap_json)
# get objects
umap_objects, umap_materials, umap_actors = get_objects(umap_json, umap)
actor_list.append(umap_actors)
object_list.append(umap_objects)
materials_ovr_list.append(umap_materials)
# ACTORS
actor_txt = save_list(filepath=settings.selected_map.folder_path.joinpath(
f"_assets_actors.txt"), lines=actor_list)
extract_data(
settings,
export_directory=settings.selected_map.actors_path,
asset_list_txt=actor_txt)
actors = get_files(
path=settings.selected_map.actors_path.__str__(),
extension=".json")
for ac in actors:
actor_json = read_json(ac)
actor_objects, actor_materials, local4list = get_objects(actor_json, umap)
object_list.append(actor_objects)
materials_ovr_list.append(actor_materials)
# next
object_txt = save_list(filepath=settings.selected_map.folder_path.joinpath(
f"_assets_objects.txt"), lines=object_list)
mats_ovr_txt = save_list(filepath=settings.selected_map.folder_path.joinpath(
f"_assets_materials_ovr.txt"), lines=materials_ovr_list)
extract_data(
settings,
export_directory=settings.selected_map.objects_path,
asset_list_txt=object_txt)
extract_data(
settings,
export_directory=settings.selected_map.materials_ovr_path,
asset_list_txt=mats_ovr_txt)
# ---------------------------------------------------------------------------------------
models = get_files(
path=settings.selected_map.objects_path.__str__(),
extension=".json")
model: Path
for model in models:
model_json = read_json(model)
# save json
save_json(model.__str__(), model_json)
# get object materials
model_materials = get_object_materials(model_json)
# get object textures
# ...
materials_list.append(model_materials)
save_list(filepath=settings.selected_map.folder_path.joinpath("all_assets.txt"), lines=[
[
path_convert(path) for path in _list
] for _list in object_list + materials_list + materials_ovr_list
])
mats_txt = save_list(filepath=settings.selected_map.folder_path.joinpath(
f"_assets_materials.txt"), lines=materials_list)
extract_data(
settings,
export_directory=settings.selected_map.materials_path,
asset_list_txt=mats_txt)
extract_assets(settings)
with open(settings.selected_map.folder_path.joinpath('exported.yo').__str__(), 'w') as out_file:
out_file.write(write_export_file())
with open(settings.assets_path.joinpath('exported.yo').__str__(), 'w') as out_file:
out_file.write(write_export_file())
else:
umaps = get_files(
path=settings.selected_map.umaps_path.__str__(), extension=".json")
return umaps
def set_material(
ue_material,
settings: Settings,
mat_data: actor_defs, ):
## Sets the material parameters to the material
if not mat_data.props:
return
mat_props = mat_data.props
set_textures(mat_props, ue_material, settings=settings)
set_all_settings(mat_props, ue_material)
# fix this
if "BasePropertyOverrides" in mat_props:
base_prop_override = set_all_settings(mat_props["BasePropertyOverrides"],
unreal.MaterialInstanceBasePropertyOverrides())
set_unreal_prop(ue_material, "BasePropertyOverrides", base_prop_override)
unreal.MaterialEditingLibrary.update_material_instance(ue_material)
if "StaticParameters" in mat_props:
if "StaticSwitchParameters" in mat_props["StaticParameters"]:
for param in mat_props["StaticParameters"]["StaticSwitchParameters"]:
param_name = param["ParameterInfo"]["Name"].lower()
param_value = param["Value"]
unreal.MaterialEditingLibrary.set_material_instance_static_switch_parameter_value(
ue_material, param_name, bool(param_value))
## Unreal doesn't support mask parameters switch lolz so have to do this
if "StaticComponentMaskParameters" in mat_props["StaticParameters"]:
for param in mat_props["StaticParameters"]["StaticComponentMaskParameters"]:
mask_list = ["R", "G", "B"]
for mask in mask_list:
value = param[mask]
unreal.MaterialEditingLibrary.set_material_instance_static_switch_parameter_value(
ue_material, mask, bool(value))
if "ScalarParameterValues" in mat_props:
for param in mat_props["ScalarParameterValues"]:
param_name = param['ParameterInfo']['Name'].lower()
param_value = param["ParameterValue"]
set_material_scalar_value(ue_material, param_name, param_value)
if "VectorParameterValues" in mat_props:
for param in mat_props["VectorParameterValues"]:
param_name = param['ParameterInfo']['Name'].lower()
param_value = param["ParameterValue"]
set_material_vector_value(ue_material, param_name, get_rgb(param_value))
def set_textures(mat_props: dict, material_reference, settings: Settings):
## Sets the textures to the material
set_texture_param = unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value
if not has_key("TextureParameterValues", mat_props):
return
for tex_param in mat_props["TextureParameterValues"]:
tex_game_path = get_texture_path(s=tex_param, f=settings.texture_format)
if not tex_game_path:
continue
tex_local_path = settings.assets_path.joinpath(tex_game_path).__str__()
param_name = tex_param['ParameterInfo']['Name'].lower()
tex_name = Path(tex_local_path).stem
if Path(tex_local_path).exists():
loaded_texture = unreal.load_asset(
f'/project/{tex_name}')
if not loaded_texture:
continue
set_texture_param(material_reference, param_name, loaded_texture)
unreal.MaterialEditingLibrary.update_material_instance(material_reference)
def settings_create_ovr_material(mat_dict: list):
## No clue (?) but not gonna bother rn no idea why i didnt use the first ovr material func
material_array = []
loaded = None
for mat in mat_dict:
if not mat:
material_array.append(None)
continue
object_name = return_object_name(mat["ObjectName"])
if "MaterialInstanceDynamic" in object_name:
material_array.append(None)
continue
loaded = unreal.load_asset(f'/project/{object_name}')
if loaded == None:
loaded = unreal.load_asset(f'/project/{object_name}')
material_array.append(loaded)
return material_array
def set_all_settings(asset_props: dict, component_reference):
## Sets all the settings to the component (material, mesh, etc) from "Properties" using some weird black magic
if not asset_props:
return
for setting in asset_props:
value_setting = asset_props[setting]
try:
editor_property = component_reference.get_editor_property(setting)
except:
continue
class_name = type(editor_property).__name__
type_value = type(value_setting).__name__
if type_value == "int" or type_value == "float" or type_value == "bool":
if setting == "InfluenceRadius" and value_setting == 0:
set_unreal_prop(component_reference, setting, 14680)
continue
set_unreal_prop(component_reference, setting, value_setting)
continue
if "::" in value_setting:
value_setting = value_setting.split("::")[1]
# Try to make these automatic? with 'unreal.classname.value"?
if class_name == "LinearColor":
set_unreal_prop(component_reference, setting, unreal.LinearColor(r=value_setting['R'], g=value_setting['G'],
b=value_setting['B']))
continue
if class_name == "Vector4":
set_unreal_prop(component_reference, setting, unreal.Vector4(x=value_setting['X'], y=value_setting['Y'],
z=value_setting['Z'], w=value_setting['W']))
continue
if "Color" in class_name:
set_unreal_prop(component_reference, setting, unreal.Color(r=value_setting['R'], g=value_setting['G'],
b=value_setting['B'], a=value_setting['A']))
continue
if type_value == "dict":
if setting == "IESTexture":
set_unreal_prop(component_reference, setting, get_ies_texture(value_setting))
continue
if setting == "Cubemap":
set_unreal_prop(component_reference, setting, get_cubemap_texture(value_setting))
continue
if setting == "DecalMaterial":
component_reference.set_decal_material(get_mat(value_setting))
continue
if setting == "DecalSize":
set_unreal_prop(component_reference, setting,
unreal.Vector(value_setting["X"], value_setting["Y"], value_setting["Z"]))
continue
if setting == "StaticMesh":
##mesh_loaded = unreal.BPFL.set_mesh_reference(value_setting["ObjectName"],"Meshes")
mesh_loaded = mesh_to_asset(value_setting, "StaticMesh ", "Meshes")
set_unreal_prop(component_reference, setting, mesh_loaded)
continue
if setting == "BoxExtent":
set_unreal_prop(component_reference, 'box_extent',
unreal.Vector(x=value_setting['X'], y=value_setting['Y'], z=value_setting['Z'])),
continue
if setting == "LightmassSettings":
set_unreal_prop(component_reference, 'lightmass_settings', get_light_mass(value_setting,
component_reference.get_editor_property(
'lightmass_settings')))
continue
continue
if type_value == "list":
if setting == "OverrideMaterials":
mat_override = settings_create_ovr_material(value_setting)
set_unreal_prop(component_reference, setting, mat_override)
continue
continue
python_unreal_value = return_python_unreal_enum(value_setting)
try:
value = eval(f'unreal.{class_name}.{python_unreal_value}')
except:
continue
set_unreal_prop(component_reference, setting, value)
return component_reference
def get_light_mass(light_mass: dict, light_mass_reference):
blacklist_lmass = ['bLightAsBackFace', 'bUseTwoSidedLighting']
## Sets the lightmass settings to the component
for l_mass in light_mass:
if l_mass in blacklist_lmass:
continue
value_setting = light_mass[l_mass]
first_name = l_mass
if l_mass[0] == "b":
l_mass = l_mass[1:]
value = re.sub(r'(?<!^)(?=[A-Z])', '_', l_mass)
set_unreal_prop(light_mass_reference, value, value_setting)
return light_mass_reference
def import_light(light_data: actor_defs, all_objs: list):
## Imports the light actors to the World
light_type_replace = light_data.type.replace("Component", "")
if not light_data.transform:
light_data.transform = get_scene_transform(light_data.scene_props)
# light_data.transform = get_scene_parent(light_data.data,light_data.outer,all_objs)
if not light_data.transform:
return
light = unreal.EditorLevelLibrary.spawn_actor_from_class(eval(f'unreal.{light_type_replace}'),
light_data.transform.translation,
light_data.transform.rotation.rotator())
light.set_folder_path(f'Lights/{light_type_replace}')
light.set_actor_label(light_data.name)
light.set_actor_scale3d(light_data.transform.scale3d)
light_component = unreal.BPFL.get_component(light)
if type(light_component) == unreal.BrushComponent:
light_component = light
if hasattr(light_component, "settings"):
set_unreal_prop(light_component, "Unbound", True)
set_unreal_prop(light_component, "Priority", 1.0)
set_all_settings(light_data.props["Settings"], light_component.settings)
set_all_settings(light_data.props, light_component)
def import_decal(decal_data: actor_defs):
## Imports the decal actors to the World
if not decal_data.transform or has_key("Template", decal_data.data):
return
decal = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.DecalActor, decal_data.transform.translation,
decal_data.transform.rotation.rotator())
decal.set_folder_path(f'Decals')
decal.set_actor_label(decal_data.name)
decal.set_actor_scale3d(decal_data.transform.scale3d)
decal_component = decal.decal
if type(decal_data) == dict:
decal_component.set_decal_material(get_mat(actor_def=decal_data["DecalMaterial"]))
set_all_settings(decal_data.props, decal_component)
## fix this so it stops returning #some bps are not spawning because of attachparent ig fix it later
def fix_actor_bp(actor_data: actor_defs, settings: Settings):
## Fixes spawned blueprints with runtime-changed components
try:
component = unreal.BPFL.get_component_by_name(all_blueprints[actor_data.outer], actor_data.name)
except:
return
if not component:
return
if has_key("StaticMesh", actor_data.props):
loaded = mesh_to_asset(actor_data.props["StaticMesh"], "StaticMesh ", "Meshes")
#loaded = unreal.BPFL.set_mesh_reference(actor_data.props["StaticMesh"]["Name"],"Meshes")
component.set_editor_property('static_mesh', loaded)
if has_key("OverrideMaterials", actor_data.props):
if settings.import_materials:
mat_override = create_override_material(actor_data.data)
if mat_override and "Barrier" not in actor_data.name:
unreal.BPFL.set_override_material(all_blueprints[actor_data.outer], actor_data.name, mat_override)
if not has_key("AttachParent", actor_data.props):
return
transform = has_transform(actor_data.props)
if type(transform) != bool:
if has_key("RelativeScale3D", actor_data.props):
component = unreal.BPFL.get_component_by_name(all_blueprints[actor_data.outer], actor_data.name)
set_unreal_prop(component, "relative_scale3d", transform.scale3d)
if has_key("RelativeLocation", actor_data.props):
component = unreal.BPFL.get_component_by_name(all_blueprints[actor_data.outer], actor_data.name)
set_unreal_prop(component, "relative_location", transform.translation)
if has_key("RelativeRotation", actor_data.props):
component = unreal.BPFL.get_component_by_name(all_blueprints[actor_data.outer], actor_data.name)
set_unreal_prop(component, "relative_rotation", transform.rotation.rotator())
def import_mesh(mesh_data: actor_defs, settings: Settings, map_obj: MapObject):
## Imports the mesh actor to the world
override_vertex_colors = []
if has_key("Template", mesh_data.data):
fix_actor_bp(mesh_data, settings)
return
if not has_key("StaticMesh", mesh_data.props):
return
transform = get_transform(mesh_data.props)
if not transform:
return
unreal_mesh_type = unreal.StaticMeshActor
if map_obj.is_instanced():
unreal_mesh_type = unreal.HismActor
mesh_actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal_mesh_type, location=unreal.Vector(),
rotation=unreal.Rotator())
mesh_actor.set_actor_label(mesh_data.outer)
if has_key("LODData", mesh_data.data):
override_vertex_colors = get_override_vertex_color(mesh_data.data)
if map_obj.is_instanced():
component = mesh_actor.hism_component
mesh_actor.set_folder_path('Meshes/Instanced')
for inst_index in mesh_data.data["PerInstanceSMData"]:
component.add_instance(get_transform(inst_index))
else:
component = mesh_actor.static_mesh_component
folder_name = 'Meshes/Static'
if map_obj.umap.endswith('_VFX'):
folder_name = 'Meshes/VFX'
mesh_actor.set_folder_path(folder_name)
set_all_settings(mesh_data.props, component)
component.set_world_transform(transform, False, False)
if len(override_vertex_colors) > 0:
unreal.BPFL.paint_sm_vertices(component, override_vertex_colors, map_obj.model_path)
if has_key("OverrideMaterials", mesh_data.props):
if not settings.import_materials:
return
mat_override = create_override_material(mesh_data.data)
if mat_override:
set_unreal_prop(component, "override_materials", mat_override)
def set_mesh_build_settings(settings: Settings):
## Sets the build settings for the mesh since umodel exports it with wrong LMapCoordinateIndex and LMapResolution and Collision obviously
light_res_multiplier = settings.manual_lmres_mult
objects_path = settings.selected_map.objects_path
list_objects = objects_path
for m_object in os.listdir(list_objects):
object_json = read_json(objects_path.joinpath(m_object))
for o_object in object_json:
key = actor_defs(o_object)
if key.type == "StaticMesh":
light_map_res = round(256 * light_res_multiplier / 4) * 4
light_map_coord = 1
if has_key("LightMapCoordinateIndex", key.props):
light_map_coord = key.props["LightMapCoordinateIndex"]
if has_key("LightMapResolution", key.props):
light_map_res = round(key.props["LightMapResolution"] * light_res_multiplier / 4) * 4
mesh_load = unreal.load_asset(f"/project/{key.name}")
if mesh_load:
cast_mesh = unreal.StaticMesh.cast(mesh_load)
actual_coord = cast_mesh.get_editor_property("light_map_coordinate_index")
actual_resolution = cast_mesh.get_editor_property("light_map_resolution")
if actual_coord != light_map_coord:
set_unreal_prop(cast_mesh, "light_map_coordinate_index", light_map_coord)
if actual_resolution != light_map_res:
set_unreal_prop(cast_mesh, "light_map_resolution", light_map_res)
if key.type == "BodySetup":
if has_key("CollisionTraceFlag", key.props):
col_trace = re.sub('([A-Z])', r'_\1', key.props["CollisionTraceFlag"])
mesh_load = unreal.load_asset(f"/project/{key.outer}")
if mesh_load:
cast_mesh = unreal.StaticMesh.cast(mesh_load)
body_setup = cast_mesh.get_editor_property("body_setup")
str_collision = 'CTF_' + col_trace[8:len(col_trace)].upper()
set_unreal_prop(body_setup, "collision_trace_flag",
eval(f'unreal.CollisionTraceFlag.{str_collision}'))
set_unreal_prop(cast_mesh, "body_setup", body_setup)
def import_umap(settings: Settings, umap_data: dict, umap_name: str):
## Imports a umap according to filters and settings selected // at the moment i don't like it since
## it's a bit messy and i don't like the way i'm doing it but it works
## Looping before the main_import just for blueprints to be spawned first, no idea how to fix it lets stay like this atm
objects_to_import = filter_objects(umap_data, umap_name)
if settings.import_blueprints:
for objectIndex, object_data in enumerate(objects_to_import):
object_type = get_object_type(object_data)
if object_type == "blueprint":
import_blueprint(actor_defs(object_data), objects_to_import)
for objectIndex, object_data in enumerate(objects_to_import):
object_type = get_object_type(object_data)
actor_data_definition = actor_defs(object_data)
if object_type == "mesh" and settings.import_Mesh:
map_object = MapObject(settings=settings, data=object_data, umap_name=umap_name, umap_data=umap_data)
import_mesh(mesh_data=actor_data_definition, settings=settings, map_obj=map_object)
if object_type == "decal" and settings.import_decals:
import_decal(actor_data_definition)
if object_type == "light" and settings.import_lights:
import_light(actor_data_definition, objects_to_import)
def level_streaming_setup():
## Sets up the level streaming for the map if using the streaming option
world = unreal.EditorLevelLibrary.get_editor_world()
for level_path in all_level_paths:
unreal.EditorLevelUtils.add_level_to_world(world, level_path, unreal.LevelStreamingAlwaysLoaded)
def import_blueprint(bp_actor: actor_defs, umap_data: list):
## Imports a blueprint actor from the umap
transform = bp_actor.transform
if not transform:
transform = get_scene_transform(bp_actor.scene_props)
if type(transform) == bool:
transform = get_transform(bp_actor.props)
if not transform:
return
bp_name = bp_actor.type[0:len(bp_actor.type) - 2]
loaded_bp = unreal.load_asset(f"/project/{bp_name}.{bp_name}")
actor = unreal.EditorLevelLibrary.spawn_actor_from_object(loaded_bp, transform.translation,
transform.rotation.rotator())
if not actor:
return
all_blueprints[bp_actor.name] = actor
actor.set_actor_label(bp_actor.name)
actor.set_actor_scale3d(transform.scale3d)
def create_new_level(map_name):
## Creates a new level with the map name
new_map = map_name.split('_')[0]
map_path = (f"/project/{new_map}/{map_name}")
loaded_map = unreal.load_asset(map_path)
sub_system_editor = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem)
unreal.LevelEditorSubsystem.new_level(sub_system_editor, map_path)
all_level_paths.append(map_path)
def get_override_vertex_color(mesh_data: dict):
## Gets the override vertex color from the mesh data
lod_data = mesh_data["LODData"]
vtx_array = []
for lod in lod_data:
if has_key("OverrideVertexColors", lod):
vertex_to_convert = lod["OverrideVertexColors"]["Data"]
for rgba_hex in vertex_to_convert:
vtx_array.append(unreal.BPFL.return_from_hex(rgba_hex))
return vtx_array
def import_all_textures_from_material(material_data: dict, settings: Settings):
## Imports all the textures from a material json first
mat_info = actor_defs(material_data[0])
if mat_info.props:
if has_key("TextureParameterValues", mat_info.props):
tx_parameters = mat_info.props["TextureParameterValues"]
for tx_param in tx_parameters:
tex_game_path = get_texture_path(s=tx_param, f=settings.texture_format)
if not tex_game_path:
continue
tex_local_path = settings.assets_path.joinpath(tex_game_path).__str__()
if tex_local_path not in all_textures:
all_textures.append(tex_local_path)
def create_material(material_data: list, settings: Settings):
## Creates a material from the material data
mat_data = material_data[0]
mat_data = actor_defs(mat_data)
parent = "BaseEnv_MAT_V4"
if "Blend" in mat_data.name and "BaseEnv_Blend_MAT_V4_V3Compatibility" not in mat_data.name:
parent = "BaseEnv_Blend_MAT_V4"
if not mat_data.props:
return
loaded_material = unreal.load_asset(f"/project/{mat_data.name}.{mat_data.name}")
if not loaded_material:
loaded_material = AssetTools.create_asset(mat_data.name, '/project/',
unreal.MaterialInstanceConstant,
unreal.MaterialInstanceConstantFactoryNew())
if has_key("Parent", mat_data.props):
parent = return_parent(mat_data.props["Parent"]["ObjectName"])
material_instance = unreal.MaterialInstanceConstant.cast(loaded_material)
set_unreal_prop(material_instance, "parent", import_shader(parent))
set_material(settings=settings, mat_data=mat_data, ue_material=loaded_material)
def import_all_meshes(settings: Settings):
## Imports all the meshes from the map first accordingly.
all_meshes = []
obj_path = settings.selected_map.folder_path.joinpath("_assets_objects.txt")
with open(obj_path, 'r') as file:
lines = file.read().splitlines()
exp_path = str(settings.assets_path)
for line in lines:
if is_blacklisted(line.split('\\')[-1]):
continue
line_arr = line.split('\\')
if line_arr[0] == "Engine":
continue
else:
line_arr.pop(0)
line_arr.pop(0)
joined_lines_back = "\\".join(line_arr)
full_path = exp_path + '\\Game\\' + joined_lines_back + ".pskx"
if full_path not in all_meshes:
all_meshes.append(full_path)
# import
unreal.BPFL.import_meshes(all_meshes, str(settings.selected_map.objects_path))
def imports_all_textures(settings: Settings):
## Imports all the texture from materials.
mat_path = settings.selected_map.materials_path
mat_ovr_path = settings.selected_map.materials_ovr_path
for path_mat in os.listdir(mat_path):
mat_json = read_json(mat_path.joinpath(path_mat))
import_all_textures_from_material(mat_json, settings)
for path_ovr_mat in os.listdir(mat_ovr_path):
mat_ovr_json = read_json(mat_ovr_path.joinpath(path_ovr_mat))
import_all_textures_from_material(mat_ovr_json, settings)
unreal.BPFL.import_textures(all_textures)
def create_bp(full_data: dict, bp_name: str, settings: Settings):
## Creates a blueprint from the json data
BlacklistBP = ["SoundBarrier", "SpawnBarrierProjectile", "BP_UnwalkableBlockingVolumeCylinder",
'BP_StuckPickupVolume', "BP_BlockingVolume", "TargetingBlockingVolume_Box", "directional_look_up"]
# BlacklistBP = ['SpawnBarrier','SoundBarrier','SpawnBarrierProjectile','Gumshoe_CameraBlockingVolumeParent_Box','DomeBuyMarker','BP_StuckPickupVolume','BP_LevelBlockingVolume','BP_TargetingLandmark','BombSpawnLocation']
bp_name = bp_name.split('.')[0]
bp_actor = unreal.load_asset(f'/project/{bp_name}')
if not bp_actor and bp_name not in BlacklistBP:
bp_actor = AssetTools.create_asset(bp_name, '/project/', unreal.Blueprint,
unreal.BlueprintFactory())
else:
return
data = full_data["Nodes"]
if len(data) == 0:
return
root_scene = full_data["SceneRoot"]
default_scene_root = root_scene[0].split('.')[-1]
game_objects = full_data["GameObjects"]
nodes_root = full_data["ChildNodes"]
for idx, bpc in enumerate(data):
if bpc["Name"] == default_scene_root:
del data[idx]
data.insert(len(data), bpc)
break
data.reverse()
nodes_array = []
for bp_node in data:
if bp_node["Name"] in nodes_root:
continue
component_name = bp_node["Properties"]["ComponentClass"]["ObjectName"].replace(
"Class ", "")
try:
unreal_class = eval(f'unreal.{component_name}')
except:
continue
properties = bp_node["Properties"]
if has_key("ChildNodes", properties):
nodes_array = handle_child_nodes(properties["ChildNodes"], data, bp_actor)
comp_internal_name = properties["InternalVariableName"]
component = unreal.BPFL.create_bp_comp(
bp_actor, unreal_class, comp_internal_name, nodes_array)
if has_key("CompProps", properties):
properties = properties["CompProps"]
set_mesh_settings(properties, component)
set_all_settings(properties, component)
for game_object in game_objects:
if bp_name == "SpawnBarrier":
continue
component = unreal.BPFL.create_bp_comp(bp_actor, unreal.StaticMeshComponent, "GameObjectMesh", nodes_array)
set_all_settings(game_object["Properties"], component)
set_mesh_settings(game_object["Properties"], component)
def set_mesh_settings(mesh_properties: dict, component):
set_all_settings(mesh_properties, component)
transform = get_transform(mesh_properties)
if has_key("RelativeRotation", mesh_properties):
set_unreal_prop(component, "relative_rotation", transform.rotation.rotator())
if has_key("RelativeLocation", mesh_properties):
set_unreal_prop(component, "relative_location", transform.translation)
if has_key("RelativeScale3D", mesh_properties):
set_unreal_prop(component, "relative_scale3d", transform.scale3d)
def handle_child_nodes(child_nodes_array: dict, entire_data: list, bp_actor):
## Handles the child nodes of the blueprint since they are not in order.
local_child_array = []
for child_node in child_nodes_array:
child_obj_name = child_node["ObjectName"]
child_name = child_obj_name.split('.')[-1]
for c_node in entire_data:
component_name = c_node["Properties"]["ComponentClass"]["ObjectName"].replace(
"Class ", "")
try:
unreal_class = eval(f'unreal.{component_name}')
except:
continue
internal_name = c_node["Properties"]["InternalVariableName"]
if "TargetViewMode" in internal_name or "Decal1" in internal_name or "SM_Barrier_Back_VisionBlocker" in internal_name:
continue
if c_node["Name"] == child_name:
u_node, comp_node = unreal.BPFL.create_node(
bp_actor, unreal_class, internal_name)
local_child_array.append(u_node)
set_all_settings(c_node["Properties"]["CompProps"], comp_node)
transform = has_transform(c_node["Properties"]["CompProps"])
if type(transform) != bool:
comp_node.set_editor_property("relative_location", transform.translation)
comp_node.set_editor_property("relative_rotation", transform.rotation.rotator())
comp_node.set_editor_property("relative_scale3d", transform.scale3d)
break
return local_child_array
def import_all_blueprints(settings: Settings):
## Imports all the blueprints from the actors folder.
bp_path = settings.selected_map.actors_path
for bp in os.listdir(bp_path):
bp_json = reduce_bp_json(read_json(settings.selected_map.actors_path.joinpath(bp)))
create_bp(bp_json, bp, settings)
def import_all_materials(settings: Settings):
## Imports all the materials from the materials folder.
mat_path = settings.selected_map.materials_path
mat_ovr_path = settings.selected_map.materials_ovr_path
for path_mat in os.listdir(mat_path):
mat_json = read_json(mat_path.joinpath(path_mat))
create_material(mat_json, settings)
for path_ovr_mat in os.listdir(mat_ovr_path):
mat_ovr_json = read_json(mat_ovr_path.joinpath(path_ovr_mat))
create_material(mat_ovr_json, settings)
def import_map(setting):
## Main function first it sets some lighting settings ( have to revisit it for people who don't want the script to change their lighting settings)
## then it imports all meshes / textures / blueprints first and create materials from them.
## then each umap from the /maps folder is imported and the actors spawned accordingly.
unreal.BPFL.change_project_settings()
unreal.BPFL.execute_console_command('r.DefaultFeature.LightUnits 0')
unreal.BPFL.execute_console_command('r.DynamicGlobalIlluminationMethod 0')
all_level_paths.clear()
settings = Settings(setting)
umap_json_paths = get_map_assets(settings)
if not settings.import_sublevel:
create_new_level(settings.selected_map.name)
clear_level()
if settings.import_materials:
txt_time = time.time()
imports_all_textures(settings)
print(f'Exported all textures in {time.time() - txt_time} seconds')
mat_time = time.time()
import_all_materials(settings)
print(f'Exported all materials in {time.time() - mat_time} seconds')
m_start_time = time.time()
if settings.import_Mesh:
import_all_meshes(settings)
print(f'Exported all meshes in {time.time() - m_start_time} seconds')
bp_start_time = time.time()
if settings.import_blueprints:
import_all_blueprints(settings)
print(f'Exported all blueprints in {time.time() - bp_start_time} seconds')
umap_json_path: Path
actor_start_time = time.time()
with unreal.ScopedSlowTask(len(umap_json_paths), "Importing levels") as slow_task:
slow_task.make_dialog(True)
idx = 0
for index, umap_json_path in reversed(
list(enumerate(umap_json_paths))):
umap_data = read_json(umap_json_path)
umap_name = umap_json_path.stem
slow_task.enter_progress_frame(
work=1, desc=f"Importing level:{umap_name} {idx}/{len(umap_json_paths)} ")
if settings.import_sublevel:
create_new_level(umap_name)
import_umap(settings=settings, umap_data=umap_data, umap_name=umap_name)
if settings.import_sublevel:
unreal.EditorLevelLibrary.save_current_level()
idx = idx + 1
print("--- %s seconds to spawn actors ---" % (time.time() - actor_start_time))
if settings.import_sublevel:
level_streaming_setup()
if settings.import_Mesh:
set_mesh_build_settings(settings=settings)
# winsound.Beep(7500, 983)
|
import unreal
import sys
import os
import socket
import magic
EAL = unreal.EditorAssetLibrary
# EUL = unreal.EditorUtilityLibrary
EAS = unreal.EditorActorSubsystem
# ESML = unreal.EditorStaticMeshLibrary
PML = unreal.ProceduralMeshLibrary
world = unreal.World
hostname = socket.gethostname()
ipaddress = socket.gethostbyname(hostname)
# Description: This function is used to print a warning in unreal log
def warning(text):
return unreal.log_warning(text)
# Description: This function is used to print an error in unreal log
def error(text):
return unreal.log_error(text)
# Description: This function is used to print in unreal log
def log(text):
return unreal.log(text)
# Description: This function is used to process all unreal paths
def process_paths():
unrealpaths = []
for p in sys.path:
unrealpaths.append(p)
return unrealpaths
gamePaths = process_paths()
# Description: This function is used to print any list (mainly paths)
def show(x):
for path in range(len(x)):
print(x[path])
# Description: Returns the paths of all assets under project root directory
def process_asset_paths():
assets = []
gamepath = '/Game'
assetpaths = EAL.list_assets(gamepath)
for assetpath in assetpaths:
assets.append(assetpath)
return assets
assetPaths = process_asset_paths()
# Description: Returns a list of all game actors
def get_all_actors():
actors = []
allactors = unreal.get_editor_subsystem(EAS).get_all_level_actors()
for actor in allactors:
actors.append(actor)
return actors
allActorsPath = get_all_actors()
# Description: Returns the class of the asset
def get_asset_class(classtype):
assets = []
gamepath = '/Game'
assetpaths = EAL.list_assets(gamepath)
for assetpath in assetpaths:
assetdata = EAL.find_asset_data(assetpath)
assetclass = assetdata.asset_class
if classtype == assetclass:
assets.append(assetdata.get_asset())
return assets
# assetClasses = ["SoundWave", "Material", "MaterialInstanceConstant", "MaterialFunction", "Texture2D", "StaticMesh",
# "SkeletalMesh", "ObjectRedirector", "PhysicsAsset", "Skeleton", "UserDefinedEnum", "TextureRenderTarget2D",
# "Blueprint", "SoundCue", "WidgetBlueprint", "HapticFeedbackEffect_Curve", "MapBuildDataRegistry",
# "NiagaraParameterCollection", "NiagaraSystem"]
soundWaveActors = get_asset_class("SoundWave")
materialActors = get_asset_class("Material")
materialInstanceConstantActors = get_asset_class("MaterialInstanceConstant")
materialFunctionActors = get_asset_class("MaterialFunction")
texture2DActors = get_asset_class("Texture2D")
skeletalMeshActors = get_asset_class("SkeletalMesh")
objectRedirectorActors = get_asset_class("ObjectRedirector")
physicsAssetActors = get_asset_class("PhysicsAsset")
skeletonActors = get_asset_class("Skeleton")
userDefinedEnumActors = get_asset_class("UserDefinedEnum")
textureRenderTarget2DActors = get_asset_class("TextureRenderTarget2D")
blueprintActors = get_asset_class("Blueprint")
soundCueActors = get_asset_class("SoundCue")
widgetBlueprintActors = get_asset_class("WidgetBlueprint")
hapticFeedbackEffect_CurveActors = get_asset_class("HapticFeedbackEffect_Curve")
mapBuildDataRegistryActors = get_asset_class("MapBuildDataRegistry")
niagaraParameterCollectionActors = get_asset_class("NiagaraParameterCollection")
niagaraSystemActors = get_asset_class("NiagaraSystem")
staticMeshActors = get_asset_class("StaticMesh")
# Description: Returns asset import data of the staticMesh actors
def get_staticmesh_data():
assetsimportdata = []
for staticMesh in staticMeshActors:
assetimportdata = staticMesh.get_editor_property("asset_import_data")
assetsimportdata.append(assetimportdata)
return assetsimportdata
staticMeshData = get_staticmesh_data()
# Level Of Detail (LOD)
lod_groups = ["LevelArchitecture", "SmallProp", "LargeProp", "Deco", "Vista", "Foliage", "HighDetail"]
# Description: This function is used to print the LOD (Level of Detail) of the staticMesh actors
def check_staticmesh_lod():
for staticMesh in staticMeshActors:
assetimportdata = staticMesh.get_editor_property("asset_import_data")
lodgroupinfo = staticMesh.get_editor_property("lod_group")
if lodgroupinfo == "None":
warning("No LOD group (" + str(staticMesh.get_num_lods()) + ") assigned to " + str(staticMesh.get_name()))
log("PAT/project/" + str(assetimportdata))
# Description: Returns the LOD (Level of Detail) of the staticMesh actors
def get_staticmesh_lod_data():
for staticMesh in staticMeshActors:
staticmeshtricount = []
numlods = staticMesh.get_num_lods()
staticmeshlod = []
for i in range(numlods):
lodtricount = 0
numsections = staticMesh.get_num_sections(i)
for j in range(numsections):
sectiondata = PML.get_section_from_static_mesh(staticMesh, i, j)
# print(str(staticMesh.get_name()) + " has " + str(len(sectiondata[0])) + " vertices, ",
# str(int(len(sectiondata[1])/3)) + " triangles in LOD (" + str(i) + ")" )
lodtricount += len(sectiondata[1])/3
staticmeshtricount.append(int(lodtricount))
staticmeshreductions = [100]
for k in range(1, len(staticmeshtricount)):
staticmeshreductions.append(int(staticmeshtricount[k] / staticmeshtricount[0] * 100))
# Level of Detail 1
try:
loddata = staticMesh.get_name(), staticmeshtricount[1]
except:
warning("No LOD assigned to " + str(staticMesh.get_name()) + " using LOD 0")
loddata = staticMesh.get_name(), staticmeshtricount[0]
staticmeshlod.append(loddata)
# print(str(staticMesh.get_name()) + " LOD triangle/project/" + str(staticmeshtricount),
# " with " + str(staticmeshreductions) + "% reductions")
return staticmeshlod
lodsdata = get_staticmesh_lod_data()
# Description: Returns the number of repetitions of staticMesh actors
def get_staticmesh_instance_counts():
staticmeshinstanceactors = []
staticmeshactorcounts = []
for levelActor in allActorsPath:
if levelActor.get_class().get_name() == "StaticMeshActor":
staticmeshcomponent = levelActor.static_mesh_component
staticmesh = staticmeshcomponent.static_mesh
staticmeshinstanceactors.append(staticmesh.get_name())
processedactors = []
for staticmeshactor in staticmeshinstanceactors:
if staticmeshactor not in processedactors:
actorcounts = staticmeshactor, staticmeshinstanceactors.count(staticmeshactor)
staticmeshactorcounts.append(actorcounts)
processedactors.append(staticmeshactor)
staticmeshactorcounts.sort(key=lambda a: a[1], reverse=True)
aggregatetricounts = []
for i in range(len(staticmeshactorcounts)):
for j in range(len(lodsdata)):
if staticmeshactorcounts[i][0] == lodsdata[j][0]:
aggregatetricount = staticmeshactorcounts[i][0], staticmeshactorcounts[i][0] * lodsdata[j][1]
aggregatetricounts.append(aggregatetricount)
aggregatetricounts.sort(key=lambda a: a[1], reverse=True)
return aggregatetricounts
staticMeshInstanceCounts = get_staticmesh_instance_counts()
# Description: This function is used to print the materials and textures associated to the staticMesh actors
def check_material_information_smc():
for levelActor in allActorsPath:
if levelActor.get_class().get_name() == "StaticMeshActor":
staticmeshcomponent = levelActor.static_mesh_component
print("Acto/project/" + levelActor.get_name())
materials = staticmeshcomponent.get_materials()
for material in materials:
print(material.get_name())
try:
for item in material.texture_parameter_values:
print(item)
except:
pass
print("_____")
# Description: This function is used to print the materials and textures associated to the staticMesh actors
def get_all_properties(unrealclass=None):
return unreal.get_all_properties(unrealclass)
# Description: Returns a list with all staticMesh components
def show_staticmesh_components():
staticmeshcomponents = []
for component in dir(unreal.StaticMeshComponent):
staticmeshcomponents.append(component)
return staticmeshcomponents
allComponentsStaticMesh = show_staticmesh_components()
# Description: Returns a list with all fbx
def process_fbx_paths():
fbxfilepaths = []
for staticMesh in staticMeshActors:
assetimportdata = staticMesh.get_editor_property("asset_import_data")
if assetimportdata.extract_filenames():
fbxfilepaths.append(assetimportdata.extract_filenames())
return fbxfilepaths
fbxPaths = process_fbx_paths()
# Description: Is used to cast objects into a certain class
# object_to_cast: obj unreal.Object : The object you want to cast
# object_class: obj unreal.Class : The class you want to cast the object into
def cast(objecttocast=None, objectclass=None):
try:
return objectclass.cast(objecttocast)
except:
return None
# For mimetypes we use python-magic-bin
mime = magic.Magic(mime=True)
def build_import_task(filename, destination_path, destination_name, options=None):
task = unreal.AssetImportTask()
task.set_editor_property('automated', False)
task.set_editor_property('destination_name', destination_name)
task.set_editor_property('destination_path', destination_path)
task.set_editor_property('filename', filename)
task.set_editor_property('replace_existing', False)
task.set_editor_property('save', False)
task.set_editor_property('options', options)
return task
def build_staticmesh_import_options():
options = unreal.FbxImportUI()
options.set_editor_property("import_mesh", True)
options.set_editor_property("import_textures", False)
options.set_editor_property("import_materials", True)
options.set_editor_property("import_as_skeletal", False) # StaticMesh
options.static_mesh_import_data.set_editor_property("import_translation", unreal.Vector(0.0, 0.0, 0.0))
options.static_mesh_import_data.set_editor_property("import_rotation", unreal.Rotator(0.0, 0.0, 0.0))
options.static_mesh_import_data.set_editor_property("import_uniform_scale", 1.0)
options.static_mesh_import_data.set_editor_property("combine_meshes", True)
options.static_mesh_import_data.set_editor_property("generate_lightmap_u_vs", True)
options.static_mesh_import_data.set_editor_property("auto_generate_collision", True)
return options
def build_skeletalmesh_import_options():
options = unreal.FbxImportUI()
options.set_editor_property("import_mesh", True)
options.set_editor_property("import_textures", True)
options.set_editor_property("import_materials", True)
options.set_editor_property("import_as_skeletal", True) # SkeletalMesh
options.skeletal_mesh_import_data.set_editor_property("import_translation", unreal.Vector(0.0, 0.0, 0.0))
options.skeletal_mesh_import_data.set_editor_property("import_rotation", unreal.Rotator(0.0, 0.0, 0.0))
options.skeletal_mesh_import_data.set_editor_property("import_uniform_scale", 1.0)
options.skeletal_mesh_import_data.set_editor_property("import_morph_targets", True)
options.skeletal_mesh_import_data.set_editor_property("update_skeleton_reference_pose", False)
return options
def build_animation_import_options(skeletonpath):
options = unreal.FbxImportUI()
options.set_editor_property("import_animations", True)
options.skeleton = unreal.load_asset(skeletonpath)
options.anim_sequence_import_data.set_editor_property("import_translation", unreal.Vector(0.0, 0.0, 0.0))
options.anim_sequence_import_data.set_editor_property("import_rotation", unreal.Rotator(0.0, 0.0, 0.0))
options.anim_sequence_import_data.set_editor_property("import_uniform_scale", 1.0)
options.anim_sequence_import_data.set_editor_property("animation_length",
unreal.FBXAnimationLengthImportType.FBXALIT_EXPORTED_TIME)
options.anim_sequence_import_data.set_editor_property("remove_redundant_keys", False)
return options
def execute_import_tasks(tasks):
unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks(tasks)
for task in tasks:
for path in task.get_editor_property("imported_object_paths"):
print("Importe/project/" + str(path))
currentGameImportsDir = unreal.Paths.game_source_dir().replace("../../../../../../",
"/project/").replace("Source", "Content/Imports")
fontsPath = unreal.Paths.game_source_dir().replace("../../../../../../",
"/project/").replace("Source", "Content/Fonts")
soundPath = unreal.Paths.game_source_dir().replace("../../../../../../",
"/project/").replace("Source", "Content/Sound")
texturesPath = unreal.Paths.game_source_dir().replace("../../../../../../",
"/project/").replace("Source", "Content/Textures")
videosPath = unreal.Paths.game_source_dir().replace("../../../../../../",
"/project/").replace("Source", "Content/Videos")
wordsPath = unreal.Paths.game_source_dir().replace("../../../../../../",
"/project/").replace("Source", "Content/Words")
skeletalmeshPath = unreal.Paths.game_source_dir().replace("../../../../../../",
"/project/").replace("Source", "Content/SkeletalMeshes")
staticmeshPath = unreal.Paths.game_source_dir().replace("../../../../../../",
"/project/").replace("Source", "Content/StaticMeshes")
animationsPath = unreal.Paths.game_source_dir().replace("../../../../../../",
"/project/").replace("Source", "Content/Animations")
def import_animation(skeleton):
mytask = []
for file in os.listdir(currentGameImportsDir):
fileextension = file.split(".")[1]
filepath = (currentGameImportsDir + file).replace("\\\\", "/")
if fileextension == "fbx":
prefix = file.split("_")[0]
if prefix == "AN":
# Input a path to a skeleton to import the animation
mytask.append(build_import_task(filepath, soundPath, file, build_animation_import_options(skeleton)))
execute_import_tasks(mytask)
def import_assets():
mytasks = []
for file in os.listdir(currentGameImportsDir):
fileextension = file.split(".")[1]
filepath = (currentGameImportsDir + file).replace("\\\\", "/")
mimefile = mime.from_file(filepath)
mimetype = mimefile.split("/")[0]
prefix = file.split("_")[0]
# We assume files are correctly named as SK_ or SM_ (SkeletalMesh or StaticMesh) inside Imports
if fileextension == "fbx":
if prefix == "SK":
mytasks.append(build_import_task(filepath, soundPath, file, build_skeletalmesh_import_options()))
elif prefix == "SM":
mytasks.append(build_import_task(filepath, soundPath, file, build_staticmesh_import_options()))
else:
if mimetype == "audio":
mytasks.append(build_import_task(filepath, soundPath, file))
elif mimetype == "font":
mytasks.append(build_import_task(filepath, fontsPath, file))
elif mimetype == "image":
mytasks.append(build_import_task(filepath, texturesPath, file))
elif mimetype == "text":
mytasks.append(build_import_task(filepath, wordsPath, file))
elif mimetype == "video":
mytasks.append(build_import_task(filepath, videosPath, file))
execute_import_tasks(mytasks)
# unreal.Package
def get_package_from_path(packagepath):
return unreal.load_asset(packagepath)
def get_all_dirty_packages():
packages = unreal.Array(unreal.Package)
for x in unreal.EditorLoadingAndSavingUtils.get_dirty_content_packages():
packages.append(x)
for x in unreal.EditorLoadingAndSavingUtils.get_dirty_map_packages():
packages.append(x)
return packages
def save_all_dirty_packages(showdialog=False):
if showdialog:
unreal.EditorLoadingAndSavingUtils.save_dirty_packages_with_dialog(save_map_packages=True,
save_content_packages=True)
else:
unreal.EditorLoadingAndSavingUtils.save_dirty_packages(save_map_packages=True, save_content_packages=True)
def save_packages(packages=[], showdialog=False):
if showdialog:
unreal.EditorLoadingAndSavingUtils.save_dirty_packages_with_dialog(packages, only_dirty=False) # May not work.
else:
unreal.EditorLoadingAndSavingUtils.save_packages(packages, only_dirty=False)
def save_asset(assetpath):
EAL.save_asset(assetpath, only_if_is_dirty=False)
def save_directory(directorypath):
EAL.save_directory(directorypath, only_if_is_dirty=False, recursive=True)
def create_directory(directorypath):
EAL.make_directory(directorypath)
def duplicate_directory(directorypath, duplicateddirectorypath):
return EAL.duplicate_directory(directorypath, duplicateddirectorypath)
def delete_directory(directorypath):
EAL.delete_directory(directorypath)
def directory_exists(directorypath):
return EAL.does_directory_exist(directorypath)
def rename_directory(directorypath, renameddirectorypath):
EAL.rename_directory(directorypath, renameddirectorypath)
def duplicate_asset(assetpath, duplicatedassetpath):
return EAL.duplicate_asset(assetpath, duplicatedassetpath)
def delete_asset(assetpath):
EAL.delete_asset(assetpath)
def asset_exists(assetpath):
return EAL.does_asset_exist(assetpath)
def rename_asset(assetpath, renamedassetpath):
EAL.rename_asset(assetpath, renamedassetpath)
def main():
# showPaths(gamePaths)
pass
main()
|
# -*- coding: utf-8 -*-
import logging
import unreal
import inspect
import types
import Utilities
from collections import Counter
class attr_detail(object):
def __init__(self, obj, name:str):
self.name = name
attr = None
self.bCallable = None
self.bCallable_builtin = None
try:
if hasattr(obj, name):
attr = getattr(obj, name)
self.bCallable = callable(attr)
self.bCallable_builtin = inspect.isbuiltin(attr)
except Exception as e:
unreal.log(str(e))
self.bProperty = not self.bCallable
self.result = None
self.param_str = None
self.bEditorProperty = None
self.return_type_str = None
self.doc_str = None
self.property_rw = None
if self.bCallable:
self.return_type_str = ""
if self.bCallable_builtin:
if hasattr(attr, '__doc__'):
docForDisplay, paramStr = _simplifyDoc(attr.__doc__)
# print(f"~~~~~ attr: {self.name} docForDisplay: {docForDisplay} paramStr: {paramStr}")
# print(attr.__doc__)
try:
sig = inspect.getfullargspec(getattr(obj, self.name))
# print("+++ ", sig)
args = sig.args
argCount = len(args)
if "self" in args:
argCount -= 1
except TypeError:
argCount = -1
if "-> " in docForDisplay:
self.return_type_str = docForDisplay[docForDisplay.find(')') + 1:]
else:
self.doc_str = docForDisplay[docForDisplay.find(')') + 1:]
if argCount == 0 or (argCount == -1 and (paramStr == '' or paramStr == 'self')):
# Method with No params
if '-> None' not in docForDisplay or self.name in ["__reduce__", "_post_init"]:
try:
if name == "get_actor_time_dilation" and isinstance(obj, unreal.Object):
# call get_actor_time_dilation will crash engine if actor is get from CDO and has no world.
if obj.get_world():
# self.result = "{}".format(attr.__call__())
self.result = attr.__call__()
else:
self.result = "skip call, world == None."
else:
# self.result = "{}".format(attr.__call__())
self.result = attr.__call__()
except:
self.result = "skip call.."
else:
print(f"docForDisplay: {docForDisplay}, self.name: {self.name}")
self.result = "skip call."
else:
self.param_str = paramStr
self.result = ""
else:
logging.error("Can't find p")
elif self.bCallable_other:
if hasattr(attr, '__doc__'):
if isinstance(attr.__doc__, str):
docForDisplay, paramStr = _simplifyDoc(attr.__doc__)
if name in ["__str__", "__hash__", "__repr__", "__len__"]:
try:
self.result = "{}".format(attr.__call__())
except:
self.result = "skip call."
else:
# self.result = "{}".format(getattr(obj, name))
self.result = getattr(obj, name)
def post(self, obj):
if self.bOtherProperty and not self.result:
try:
self.result = getattr(obj, self.name)
except:
self.result = "skip call..."
def apply_editor_property(self, obj, type_, rws, descript):
self.bEditorProperty = True
self.property_rw = "[{}]".format(rws)
try:
self.result = eval('obj.get_editor_property("{}")'.format(self.name))
except:
self.result = "Invalid"
def __str__(self):
s = f"Attr: {self.name} paramStr: {self.param_str} desc: {self.return_type_str} result: {self.result}"
if self.bProperty:
s += ", Property"
if self.bEditorProperty:
s += ", Eidtor Property"
if self.bOtherProperty:
s += ", Other Property "
if self.bCallable:
s += ", Callable"
if self.bCallable_builtin:
s += ", Callable_builtin"
if self.bCallable_other:
s += ", bCallable_other"
if self.bHasParamFunction:
s+= ", bHasParamFunction"
return s
def check(self):
counter = Counter([self.bOtherProperty, self.bEditorProperty, self.bCallable_other, self.bCallable_builtin])
# print("counter: {}".format(counter))
if counter[True] == 2:
unreal.log_error(f"{self.name}: {self.bEditorProperty}, {self.bOtherProperty} {self.bCallable_builtin} {self.bCallable_other}")
@property
def bOtherProperty(self):
if self.bProperty and not self.bEditorProperty:
return True
return False
@property
def bCallable_other(self):
if self.bCallable and not self.bCallable_builtin:
return True
return False
@property
def display_name(self, bRichText=True):
if self.bProperty:
return f"\t{self.name}"
else:
# callable
if self.param_str:
return f"\t{self.name}({self.param_str}) {self.return_type_str}"
else:
if self.bCallable_other:
return f"\t{self.name}" # __hash__, __class__, __eq__ ็ญ
else:
return f"\t{self.name}() {self.return_type_str}"
@property
def display_result(self) -> str:
if self.bEditorProperty:
return "{} {}".format(self.result, self.property_rw)
else:
return "{}".format(self.result)
@property
def bHasParamFunction(self):
return self.param_str and len(self.param_str) != 0
def ll(obj):
if not obj:
return None
if inspect.ismodule(obj):
return None
result = []
for x in dir(obj):
attr = attr_detail(obj, x)
result.append(attr)
if hasattr(obj, '__doc__') and isinstance(obj, unreal.Object):
editorPropertiesInfos = _getEditorProperties(obj.__doc__, obj)
for name, type_, rws, descript in editorPropertiesInfos:
# print(f"~~ {name} {type} {rws}, {descript}")
index = -1
for i, v in enumerate(result):
if v.name == name:
index = i
break
if index != -1:
this_attr = result[index]
else:
this_attr = attr_detail(obj, name)
result.append(this_attr)
# unreal.log_warning(f"Can't find editor property: {name}")
this_attr.apply_editor_property(obj, type_, rws, descript)
for i, attr in enumerate(result):
attr.post(obj)
return result
def _simplifyDoc(content):
def next_balanced(content, s="(", e = ")" ):
s_pos = -1
e_pos = -1
balance = 0
for index, c in enumerate(content):
match = c == s or c == e
if not match:
continue
balance += 1 if c == s else -1
if c == s and balance == 1 and s_pos == -1:
s_pos = index
if c == e and balance == 0 and s_pos != -1 and e_pos == -1:
e_pos = index
return s_pos, e_pos
return -1, -1
# bracketS, bracketE = content.find('('), content.find(')')
if not content:
return "", ""
bracketS, bracketE = next_balanced(content, s='(', e = ')')
arrow = content.find('->')
funcDocPos = len(content)
endSign = ['--', '\n', '\r']
for s in endSign:
p = content.find(s)
if p != -1 and p < funcDocPos:
funcDocPos = p
funcDoc = content[:funcDocPos]
if bracketS != -1 and bracketE != -1:
param = content[bracketS + 1: bracketE].strip()
else:
param = ""
return funcDoc, param
def _getEditorProperties(content, obj):
# print("Content: {}".format(content))
lines = content.split('\r')
signFound = False
allInfoFound = False
result = []
for line in lines:
if not signFound and '**Editor Properties:**' in line:
signFound = True
if signFound:
#todo re
# nameS, nameE = line.find('``') + 2, line.find('`` ')
nameS, nameE = line.find('- ``') + 4, line.find('`` ')
if nameS == -1 or nameE == -1:
continue
typeS, typeE = line.find('(') + 1, line.find(')')
if typeS == -1 or typeE == -1:
continue
rwS, rwE = line.find('[') + 1, line.find(']')
if rwS == -1 or rwE == -1:
continue
name = line[nameS: nameE]
type_str = line[typeS: typeE]
rws = line[rwS: rwE]
descript = line[rwE + 2:]
allInfoFound = True
result.append((name, type_str, rws, descript))
# print(name, type, rws)
if signFound:
if not allInfoFound:
unreal.log_warning("not all info found {}".format(obj))
else:
unreal.log_warning("can't find editor properties in {}".format(obj))
return result
def log_classes(obj):
print(obj)
print("\ttype: {}".format(type(obj)))
print("\tget_class: {}".format(obj.get_class()))
if type(obj.get_class()) is unreal.BlueprintGeneratedClass:
generatedClass = obj.get_class()
else:
generatedClass = unreal.PythonBPLib.get_blueprint_generated_class(obj)
print("\tgeneratedClass: {}".format(generatedClass))
print("\tbp_class_hierarchy_package: {}".format(unreal.PythonBPLib.get_bp_class_hierarchy_package(generatedClass)))
def is_selected_asset_type(types):
selectedAssets = Utilities.Utils.get_selected_assets()
for asset in selectedAssets:
if type(asset) in types:
return True;
return False
|
import unreal
class tickHooker:
def __init__(self):
self._delegate_handle = None
self._bound_func = None
def hook(self, func):
if self._delegate_handle is not None:
print("Already hooked, unhooking first.")
self.unhook()
if not callable(func):
raise ValueError("Provided func must be callable")
# Wrap to accept delta_seconds and call your function
def tick_wrapper(delta_seconds):
func(delta_seconds)
self._bound_func = tick_wrapper
self._delegate_handle = unreal.register_slate_post_tick_callback(self._bound_func)
print("Tick hooked.")
def unhook(self):
if self._delegate_handle is not None:
unreal.unregister_slate_post_tick_callback(self._delegate_handle)
print("Tick unhooked.")
self._delegate_handle = None
self._bound_func = None
else:
print("No tick hook to unhook.")
def hook_for_x_ticks(self, func, x, final_func=None):
if not isinstance(x, int) or x <= 0:
raise ValueError("x must be a positive integer")
def tick_wrapper(delta_seconds):
nonlocal x
if x > 0:
func()
x -= 1
if x == 0:
if final_func:
final_func(delta_seconds)
self.unhook()
self.hook(tick_wrapper)
def wait_x_ticks_then_execute(self, func, x):
if not isinstance(x, int) or x <= 0:
raise ValueError("x must be a positive integer")
def tick_wrapper(delta_seconds):
nonlocal x
if x > 0:
x -= 1
if x == 0:
func(delta_seconds)
self.unhook()
self.hook(tick_wrapper)
|
import unreal
import sys
args = sys.argv
def focus_on_component(component_name):
unreal.log(f"{component_name} ใซใใฉใผใซในใใพใใ")
world = unreal.UnrealEditorSubsystem().get_game_world()
if(world == None): # ้PIEๆ
# Editor Actor Subsystem ใๅๅพ
editor_actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
# ็พๅจใฎใฌใใซใซใใใในใฆใฎใขใฏใฟใผใๅๅพ
all_actors = editor_actor_subsystem.get_all_level_actors()
else: # PIEๆ
unreal.log(f"World: {world.get_name()}")
all_actors = unreal.GameplayStatics.get_all_actors_of_class(world, unreal.Actor)
# ๆๅฎใใใใณใณใใผใใณใใๆใคใขใฏใฟใผใๆค็ดข
target_component = None
for actor in all_actors:
# unreal.log(actor.get_name())
# ใขใฏใฟใผใฎใในใฆใฎใณใณใใผใใณใใๅๅพ
components = actor.get_components_by_class(unreal.SceneComponent)
for component in components:
if component.get_name() == component_name:
target_component = component
break
if target_component:
break
if not target_component:
unreal.log_error(f"ใณใณใใผใใณใ '{component_name}' ใ่ฆใคใใใพใใใงใใใ")
return
# ใฟใผใฒใใใณใณใใผใใณใใฎใฏใผใซใไฝ็ฝฎใๅๅพ
target_location = target_component.get_world_location()
# Editor Scripting Subsystem ใๅๅพ
editor_scripting_subsystem = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem)
# ็พๅจใฎใซใกใฉไฝ็ฝฎใจๅ่ปขใๅๅพ
camera_location, camera_rotation = editor_scripting_subsystem.get_level_viewport_camera_info()
# ใใฅใผใใผใใใฟใผใฒใใใซใใฉใผใซใน
editor_scripting_subsystem.set_level_viewport_camera_info(target_location, camera_rotation)
unreal.log(f"่ฆ็นใใณใณใใผใใณใ '{component_name}' ใซใใฉใผใซในใใพใใใ")
# ๅฎ่กไพ: "MyUniqTrigger" ใจใใๅๅใฎใณใณใใผใใณใใซใใฉใผใซใน
focus_on_component(args[1])
|
import unreal
class ControlRigExtension(object):
"""
The primary rig object that we operate on.
"""
@classmethod
def load_rig_from_path(cls, rig_path):
"""
Loads in a ControlRigBlueprint based on its path. Returns the resultant rig object
:param rig_path: The relative Game path to the rig, obtained by right click->Copy Reference
:type rig_path: str
:return: The valid ControlRigBlueprint object
:rtype: unreal.ControlRigBlueprint
"""
loaded_rig = unreal.load_asset(rig_path)
if type(loaded_rig) == unreal.ControlRigBlueprint:
return loaded_rig
return None
@staticmethod
def cast_key_to_type(rig_key, rig):
"""
Given an element key and its parent hierarchy modifier, returns the object of the correct type
:param rig_key: The key to query
:type rig_key: unreal.RigElementKey
:param rig: The rig we are looking at
:type rig: unreal.ControlRigBlueprint
:return: The casted type for the key
:rtype: unreal.RigBone | unreal.RigControl | unreal.RigSpace
"""
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 __init__(self):
"""
Creates a ControlRigExtension object. Through this object we can manipulate the loaded object
"""
self._rig = None
@property
def rig(self):
return self._rig
@rig.setter
def rig(self, value):
self._rig = value
def get_selected_controls(self):
"""
Returns the controls that are selected in the hierarchy panel. These return in a first-in/last-out manner
:return: A list of the selected object
:rtype: list[unreal.RigElementKey]
"""
return self.rig.get_hierarchy_modifier().get_selection()
def get_index_by_name(self, controller_name):
"""
Given a name, returns the associated RigElementKey.
:param controller_name: The path of the key to query
:type controller_name: str
:return: The RigElementKeys with the given name, if any
:rtype: unreal.RigElementKey
"""
hierarchy_mod = self.rig.get_hierarchy_modifier()
indexes = hierarchy_mod.get_elements()
for ind in indexes:
if ind.name == controller_name:
return ind
return None
def paste_global_xform(self):
"""
Given a selection, copy the global transform from the first control into the initial transform of the second
control
:return: Nothing
:rtype: None
"""
hierarchy_mod = self.rig.get_hierarchy_modifier()
selection = self.get_selected_controls()
if not len(selection) == 2:
return
global_xform = hierarchy_mod.get_global_transform(selection[1])
hierarchy_mod.set_initial_global_transform(selection[0], global_xform)
|
import unreal
import unreal_uiutils
from unreal_global import *
from unreal_utils import AssetRegistryPostLoad
unreal.log("""@
####################
Init Start up Script
####################
""")
assetregistry_pretickhandle = None
def assetregistry_postload_handle(deltaTime):
"""
Run callback method after registry run to prevent crashed when create new asset at startupS
"""
unreal.log_warning("..Checking Asset Registy Status...")
if AssetRegistry.is_loading_assets():
unreal.log_warning("..Asset registy still loading...")
else:
unreal.log_warning("Asset registy ready!")
unreal.unregister_slate_post_tick_callback(assetregistry_pretickhandle)
AssetRegistryPostLoad.run_callbacks()
assetregistry_pretickhandle = unreal.register_slate_post_tick_callback(assetregistry_postload_handle)
import BlueprintLibrary
import UserInterfaces
def reload():
import importlib
importlib.reload(BlueprintLibrary)
importlib.reload(UserInterfaces)
unreal_uiutils.refresh()
|
"""Remote functions for unreal."""
import json
from functools import lru_cache
from typing import List, Optional, Tuple, Union
from ...data_structure.constants import Vector, color_type
from ...rpc import remote_unreal
try:
import unreal
from unreal_factory import XRFeitoriaUnrealFactory # defined in src/project/
except ImportError:
pass
# Constants
mask_colors: List[color_type] = []
@remote_unreal()
def get_mask_color_file() -> str:
"""Returns the path of the mask color file.
Returns:
str: The path of the mask color file.
"""
return XRFeitoriaUnrealFactory.constants.MASK_COLOR_FILE.as_posix()
@lru_cache
def get_mask_color(stencil_value: int) -> 'Tuple[int, int, int]':
"""Retrieves the RGB color value associated with the given stencil value.
Args:
stencil_value (int): The stencil value for which to retrieve the color.
Returns:
Tuple[int, int, int]: The RGB color value associated with the stencil value.
"""
global mask_colors
if len(mask_colors) == 0:
with open(get_mask_color_file(), 'r') as f:
mask_colors = json.load(f)
return mask_colors[stencil_value]['rgb']
@lru_cache
@remote_unreal()
def get_skeleton_names(actor_asset_path: str) -> 'List[str]':
"""Retrieves the names of the bones in the skeleton of a SkeletalMeshActor (also can
be child class of it).
Args:
actor_asset_path (str): The asset path of the SkeletalMeshActor.
Returns:
List[str]: The names of the bones in the skeleton.
"""
return XRFeitoriaUnrealFactory.utils_actor.get_skeleton_names(actor_asset_path)
@remote_unreal()
def check_asset_in_engine(path: str, raise_error: bool = False) -> bool:
"""Check if an asset exists in the engine.
Args:
path (str): asset path in unreal, e.g. "/project/"
raise_error (bool): raise error if the asset does not exist
Returns:
bool: True if the asset exists, False otherwise
Raises:
ValueError: if the asset does not exist and raise_error is True
"""
is_exist = unreal.EditorAssetLibrary.does_asset_exist(path)
if not is_exist and raise_error:
raise ValueError(f'Asset `{path}` does not exist')
return is_exist
@remote_unreal()
def open_level(asset_path: str) -> None:
"""Open a level.
Args:
asset_path (str): asset path in unreal, e.g. "/project/"
"""
check_asset_in_engine(asset_path, raise_error=True)
XRFeitoriaUnrealFactory.SubSystem.EditorLevelSub.load_level(asset_path)
@remote_unreal()
def save_current_level(asset_path: 'Optional[str]' = None) -> None:
"""Save the current opened level."""
if asset_path is not None:
# BUG: save_map to a new path does not work
world = XRFeitoriaUnrealFactory.SubSystem.EditorLevelSub.get_world()
unreal.EditorLoadingAndSavingUtils.save_map(world, asset_path)
else:
XRFeitoriaUnrealFactory.SubSystem.EditorLevelSub.save_current_level()
@remote_unreal()
def import_asset(
path: 'Union[str, List[str]]',
dst_dir_in_engine: 'Optional[str]' = None,
replace: bool = True,
with_parent_dir: bool = True,
) -> 'Union[str, List[str]]':
"""Import assets to the default asset path.
Args:
path (Union[str, List[str]]): a file path or a list of file paths to import, e.g. "D:/project/.fbx"
dst_dir_in_engine (Optional[str], optional): destination directory in the engine.
Defaults to None falls back to '/project/'
replace (bool, optional): whether to replace the existing asset. Defaults to True.
with_parent_dir (bool, optional): whether to create a parent directory that contains the imported asset.
If False, the imported asset will be in `dst_dir_in_engine` directly. Defaults to True.
Returns:
Union[str, List[str]]: a path or a list of paths to the imported assets, e.g. "/project/"
"""
paths = XRFeitoriaUnrealFactory.utils.import_asset(
path, dst_dir_in_engine, replace=replace, with_parent_dir=with_parent_dir
)
if len(paths) == 1:
return paths[0]
return paths
@remote_unreal()
def import_anim(path: str, skeleton_path: str, dest_path: 'Optional[str]' = None, replace: bool = True) -> 'List[str]':
"""Import animation to the default asset path.
Args:
path (str): The file path to import, e.g. "D:/project/-Animation.fbx".
skeleton_path (str): The path to the skeleton, e.g. "/project/".
dest_path (str, optional): The destination directory in the engine. Defaults to None, falls back to {skeleton_path.parent}/Animation.
replace (bool, optional): whether to replace the existing asset. Defaults to True.
Returns:
List[str]: A list of paths to the imported animations, e.g. ["/project/-Animation"].
"""
return XRFeitoriaUnrealFactory.utils.import_anim(path, skeleton_path, dest_path, replace=replace)
@remote_unreal()
def duplicate_asset(src_path: str, dst_path: str, replace: bool = False) -> None:
"""Duplicate asset in unreal.
Args:
src_path (str): source asset path in unreal, e.g. "/project/"
dst_path (str): destination asset path in unreal, e.g. "/project/"
"""
check_asset_in_engine(src_path, raise_error=True)
if check_asset_in_engine(dst_path) and replace:
delete_asset(dst_path)
unreal.EditorAssetLibrary.duplicate_asset(
source_asset_path=src_path,
destination_asset_path=dst_path,
)
check_asset_in_engine(dst_path, raise_error=True)
unreal.EditorAssetLibrary.save_asset(dst_path)
@remote_unreal()
def new_seq_data(asset_path: str, sequence_path: str, map_path: str) -> None:
"""Create a new data asset of sequence data.
Args:
asset_path (str): path of the data asset.
sequence_path (str): path of the sequence asset.
map_path (str): path of the map asset.
Returns:
unreal.DataAsset: the created data asset.
Notes:
SequenceData Properties:
- "SequencePath": str
- "MapPath": str
"""
XRFeitoriaUnrealFactory.sequence_data_asset(
asset_path=asset_path,
sequence_path=sequence_path,
map_path=map_path,
)
@remote_unreal()
def delete_asset(asset_path: str) -> None:
"""Delete asset.
Args:
asset_path (str): asset path in unreal, e.g. "/project/"
"""
XRFeitoriaUnrealFactory.utils.delete_asset(asset_path)
@remote_unreal()
def open_asset(asset_path: str) -> None:
"""Open asset.
Args:
asset_path (str): asset path in unreal, e.g. "/project/"
"""
XRFeitoriaUnrealFactory.utils.open_asset(asset_path)
@remote_unreal()
def get_rotation_to_look_at(location: 'Vector', target: 'Vector') -> 'Vector':
"""Get the rotation of an object to look at another object.
Args:
location (Vector): Location of the object.
target (Vector): Location of the target object.
Returns:
Vector: Rotation of the object.
"""
target = unreal.Vector(x=target[0], y=target[1], z=target[2])
forward = target - location
z = unreal.Vector(0, 0, -1)
right = forward.cross(z)
up = forward.cross(right)
rotation = unreal.MathLibrary.make_rotation_from_axes(forward, right, up)
return rotation.to_tuple()
|
import unreal
recompile_targets = [
'/project/'
]
material_editor = unreal.MaterialEditingLibrary
editor_asset = unreal.EditorAssetLibrary
for target in recompile_targets:
loaded_material = editor_asset.load_asset(target)
material_editor.recompile_material(loaded_material)
unreal.EditorDialog.show_message("Recompile Material", "Successfully recompiled.", unreal.AppMsgType.OK)
|
# 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 instantiates an HDA that contains a TOP network.
After the HDA itself has cooked (in on_post_process) we iterate over all
TOP networks in the HDA and print their paths. Auto-bake is then enabled for
PDG and the TOP networks are cooked.
"""
import os
import unreal
_g_wrapper = None
def get_test_hda_path():
return '/project/.pdg_pighead_grid_2_0'
def get_test_hda():
return unreal.load_object(None, get_test_hda_path())
def get_hda_directory():
""" Attempt to get the directory containing the .hda files. This is
/project/. In newer versions of UE we can use
``unreal.SystemLibrary.get_system_path(asset)``, in older versions
we manually construct the path to the plugin.
Returns:
(str): the path to the example hda directory or ``None``.
"""
if hasattr(unreal.SystemLibrary, 'get_system_path'):
return os.path.dirname(os.path.normpath(
unreal.SystemLibrary.get_system_path(get_test_hda())))
else:
plugin_dir = os.path.join(
os.path.normpath(unreal.Paths.project_plugins_dir()),
'Runtime', 'HoudiniEngine', 'Content', 'Examples', 'hda'
)
if not os.path.exists(plugin_dir):
plugin_dir = os.path.join(
os.path.normpath(unreal.Paths.engine_plugins_dir()),
'Runtime', 'HoudiniEngine', 'Content', 'Examples', 'hda'
)
if not os.path.exists(plugin_dir):
return None
return plugin_dir
def delete_instantiated_asset():
global _g_wrapper
if _g_wrapper:
result = _g_wrapper.delete_instantiated_asset()
_g_wrapper = None
return result
else:
return False
def on_pre_instantiation(in_wrapper):
print('on_pre_instantiation')
# Set the hda_directory parameter to the directory that contains the
# example .hda files
hda_directory = get_hda_directory()
print('Setting "hda_directory" to {0}'.format(hda_directory))
in_wrapper.set_string_parameter_value('hda_directory', hda_directory)
# Cook the HDA (not PDG yet)
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'))
def on_post_process(in_wrapper):
print('on_post_process')
# in_wrapper.on_post_processing_delegate.remove_callable(on_post_process)
# Iterate over all PDG/TOP networks and nodes and log them
print('TOP networks:')
for network_path in in_wrapper.get_pdgtop_network_paths():
print('\t{}'.format(network_path))
for node_path in in_wrapper.get_pdgtop_node_paths(network_path):
print('\t\t{}'.format(node_path))
# Enable PDG auto-bake (auto bake TOP nodes after they are cooked)
in_wrapper.set_pdg_auto_bake_enabled(True)
# Bind to PDG post bake delegate (called after all baking is complete)
in_wrapper.on_post_pdg_bake_delegate.add_callable(on_post_bake)
# Cook the specified TOP node
in_wrapper.pdg_cook_node('topnet1', 'HE_OUT_PIGHEAD_GRID')
def run():
# get the API singleton
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
global _g_wrapper
# instantiate an asset, disabling auto-cook of the asset
_g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform(), enable_auto_cook=False)
# Bind to the on pre instantiation delegate (before the first cook) and
# set parameters
_g_wrapper.on_pre_instantiation_delegate.add_callable(on_pre_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()
|
# Copyright (c) <2021> Side Effects Software Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. The name of Side Effects Software may not be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
""" Example script that instantiates an HDA using the API and then
setting some parameter values after instantiation but before the
first cook.
"""
import unreal
_g_wrapper = None
def get_test_hda_path():
return '/project/.pig_head_subdivider_v01'
def get_test_hda():
return unreal.load_object(None, get_test_hda_path())
def on_post_instantiation(in_wrapper):
print('on_post_instantiation')
# in_wrapper.on_post_instantiation_delegate.remove_callable(on_post_instantiation)
# Set some parameters to create instances and enable a material
in_wrapper.set_bool_parameter_value('add_instances', True)
in_wrapper.set_int_parameter_value('num_instances', 8)
in_wrapper.set_bool_parameter_value('addshader', True)
def run():
# get the API singleton
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
global _g_wrapper
# instantiate an asset with auto-cook enabled
_g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform())
# Bind on_post_instantiation (before the first cook) callback to set parameters
_g_wrapper.on_post_instantiation_delegate.add_callable(on_post_instantiation)
if __name__ == '__main__':
run()
|
# Copyright Epic Games, Inc. All Rights Reserved
"""
This script handles processing jobs and shots in the current loaded queue
"""
import unreal
from .utils import (
movie_pipeline_queue,
execute_render,
setup_remote_render_jobs,
update_render_output
)
def setup_render_parser(subparser):
"""
This method adds a custom execution function and args to a render subparser
:param subparser: Subparser for processing custom sequences
"""
# Function to process arguments
subparser.set_defaults(func=_process_args)
def render_jobs(
is_remote=False,
is_cmdline=False,
executor_instance=None,
remote_batch_name=None,
remote_job_preset=None,
output_dir_override=None,
output_filename_override=None
):
"""
This renders the current state of the queue
:param bool is_remote: Is this a remote render
:param bool is_cmdline: Is this a commandline render
:param executor_instance: Movie Pipeline Executor instance
:param str remote_batch_name: Batch name for remote renders
:param str remote_job_preset: Remote render job preset
:param str output_dir_override: Movie Pipeline output directory override
:param str output_filename_override: Movie Pipeline filename format override
:return: MRQ executor
"""
if not movie_pipeline_queue.get_jobs():
# Make sure we have jobs in the queue to work with
raise RuntimeError("There are no jobs in the queue!!")
# Update the job
for job in movie_pipeline_queue.get_jobs():
# If we have output job overrides and filename overrides, update it on
# the job
if output_dir_override or output_filename_override:
update_render_output(
job,
output_dir=output_dir_override,
output_filename=output_filename_override
)
# Get the job output settings
output_setting = job.get_configuration().find_setting_by_class(
unreal.MoviePipelineOutputSetting
)
# Allow flushing flies to disk per shot.
# Required for the OnIndividualShotFinishedCallback to get called.
output_setting.flush_disk_writes_per_shot = True
if is_remote:
setup_remote_render_jobs(
remote_batch_name,
remote_job_preset,
movie_pipeline_queue.get_jobs(),
)
try:
# Execute the render.
# This will execute the render based on whether its remote or local
executor = execute_render(
is_remote,
executor_instance=executor_instance,
is_cmdline=is_cmdline,
)
except Exception as err:
unreal.log_error(
f"An error occurred executing the render.\n\tError: {err}"
)
raise
return executor
def _process_args(args):
"""
Function to process the arguments for the sequence subcommand
:param args: Parsed Arguments from parser
"""
return render_jobs(
is_remote=args.remote,
is_cmdline=args.cmdline,
remote_batch_name=args.batch_name,
remote_job_preset=args.deadline_job_preset,
output_dir_override=args.output_override,
output_filename_override=args.filename_override
)
|
import os
import re
import subprocess
import time
from pathlib import Path
import unreal
import winsound
from mods.liana.helpers import *
from mods.liana.valorant import *
# BigSets
all_textures = []
all_blueprints = {}
object_types = []
all_level_paths = []
AssetTools = unreal.AssetToolsHelpers.get_asset_tools()
## Returns a array with all OverrideMaterials
def create_override_material(data):
material_array = []
for mat in data["Properties"]["OverrideMaterials"]:
if not mat:
material_array.append(None)
continue
object_name = return_object_name(mat["ObjectName"])
if object_name == "Stone_M2_Steps_MI1":
object_name = "Stone_M2_Steps_MI"
if "MaterialInstanceDynamic" in object_name:
material_array.append(None)
continue
material_array.append(unreal.load_asset(
f'/project/{object_name}'))
return material_array
def extract_assets(settings: Settings):
## Extracting Assets on umodel
asset_objects = settings.selected_map.folder_path.joinpath("all_assets.txt")
args = [settings.umodel.__str__(),
f"-path={settings.paks_path.__str__()}",
f"-game=valorant",
f"-aes={settings.aes}",
f"-files={asset_objects}",
"-export",
f"-{settings.texture_format.replace('.', '')}",
f"-out={settings.assets_path.__str__()}"]
subprocess.call(args, stderr=subprocess.DEVNULL)
def extract_data(
settings: Settings,
export_directory: str,
asset_list_txt: str = ""):
## Extracts the data from CUE4Parse (Json's)
args = [settings.cue4extractor.__str__(),
"--game-directory", settings.paks_path.__str__(),
"--aes-key", settings.aes,
"--export-directory", export_directory.__str__(),
"--map-name", settings.selected_map.name,
"--file-list", asset_list_txt,
"--game-umaps", settings.umap_list_path.__str__()
]
subprocess.call(args)
def get_map_assets(settings: Settings):
## Handles the extraction of the assets and filters them by type
umaps = []
if check_export(settings):
extract_data(
settings, export_directory=settings.selected_map.umaps_path)
extract_assets(settings)
umaps = get_files(
path=settings.selected_map.umaps_path.__str__(), extension=".json")
umap: Path
object_list = list()
actor_list = list()
materials_ovr_list = list()
materials_list = list()
for umap in umaps:
umap_json, asd = filter_umap(read_json(umap))
object_types.append(asd)
# save json
save_json(umap.__str__(), umap_json)
# get objects
umap_objects, umap_materials, umap_actors = get_objects(umap_json, umap)
actor_list.append(umap_actors)
object_list.append(umap_objects)
materials_ovr_list.append(umap_materials)
# ACTORS
actor_txt = save_list(filepath=settings.selected_map.folder_path.joinpath(
f"_assets_actors.txt"), lines=actor_list)
extract_data(
settings,
export_directory=settings.selected_map.actors_path,
asset_list_txt=actor_txt)
actors = get_files(
path=settings.selected_map.actors_path.__str__(),
extension=".json")
for ac in actors:
actor_json = read_json(ac)
actor_objects, actor_materials, local4list = get_objects(actor_json, umap)
object_list.append(actor_objects)
materials_ovr_list.append(actor_materials)
# next
object_txt = save_list(filepath=settings.selected_map.folder_path.joinpath(
f"_assets_objects.txt"), lines=object_list)
mats_ovr_txt = save_list(filepath=settings.selected_map.folder_path.joinpath(
f"_assets_materials_ovr.txt"), lines=materials_ovr_list)
extract_data(
settings,
export_directory=settings.selected_map.objects_path,
asset_list_txt=object_txt)
extract_data(
settings,
export_directory=settings.selected_map.materials_ovr_path,
asset_list_txt=mats_ovr_txt)
# ---------------------------------------------------------------------------------------
models = get_files(
path=settings.selected_map.objects_path.__str__(),
extension=".json")
model: Path
for model in models:
model_json = read_json(model)
# save json
save_json(model.__str__(), model_json)
# get object materials
model_materials = get_object_materials(model_json)
# get object textures
# ...
materials_list.append(model_materials)
save_list(filepath=settings.selected_map.folder_path.joinpath("all_assets.txt"), lines=[
[
path_convert(path) for path in _list
] for _list in object_list + materials_list + materials_ovr_list
])
mats_txt = save_list(filepath=settings.selected_map.folder_path.joinpath(
f"_assets_materials.txt"), lines=materials_list)
extract_data(
settings,
export_directory=settings.selected_map.materials_path,
asset_list_txt=mats_txt)
extract_assets(settings)
with open(settings.selected_map.folder_path.joinpath('exported.yo').__str__(), 'w') as out_file:
out_file.write(write_export_file())
with open(settings.assets_path.joinpath('exported.yo').__str__(), 'w') as out_file:
out_file.write(write_export_file())
else:
umaps = get_files(
path=settings.selected_map.umaps_path.__str__(), extension=".json")
return umaps
def set_material(
ue_material,
settings: Settings,
mat_data: actor_defs, ):
## Sets the material parameters to the material
if not mat_data.props:
return
mat_props = mat_data.props
set_textures(mat_props, ue_material, settings=settings)
set_all_settings(mat_props, ue_material)
# fix this
if "BasePropertyOverrides" in mat_props:
base_prop_override = set_all_settings(mat_props["BasePropertyOverrides"],
unreal.MaterialInstanceBasePropertyOverrides())
set_unreal_prop(ue_material, "BasePropertyOverrides", base_prop_override)
unreal.MaterialEditingLibrary.update_material_instance(ue_material)
if "StaticParameters" in mat_props:
if "StaticSwitchParameters" in mat_props["StaticParameters"]:
for param in mat_props["StaticParameters"]["StaticSwitchParameters"]:
param_name = param["ParameterInfo"]["Name"].lower()
param_value = param["Value"]
unreal.MaterialEditingLibrary.set_material_instance_static_switch_parameter_value(
ue_material, param_name, bool(param_value))
## Unreal doesn't support mask parameters switch lolz so have to do this
if "StaticComponentMaskParameters" in mat_props["StaticParameters"]:
for param in mat_props["StaticParameters"]["StaticComponentMaskParameters"]:
mask_list = ["R", "G", "B"]
for mask in mask_list:
value = param[mask]
unreal.MaterialEditingLibrary.set_material_instance_static_switch_parameter_value(
ue_material, mask, bool(value))
if "ScalarParameterValues" in mat_props:
for param in mat_props["ScalarParameterValues"]:
param_name = param['ParameterInfo']['Name'].lower()
param_value = param["ParameterValue"]
set_material_scalar_value(ue_material, param_name, param_value)
if "VectorParameterValues" in mat_props:
for param in mat_props["VectorParameterValues"]:
param_name = param['ParameterInfo']['Name'].lower()
param_value = param["ParameterValue"]
set_material_vector_value(ue_material, param_name, get_rgb(param_value))
def set_textures(mat_props: dict, material_reference, settings: Settings):
## Sets the textures to the material
set_texture_param = unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value
if not has_key("TextureParameterValues", mat_props):
return
for tex_param in mat_props["TextureParameterValues"]:
tex_game_path = get_texture_path(s=tex_param, f=settings.texture_format)
if not tex_game_path:
continue
tex_local_path = settings.assets_path.joinpath(tex_game_path).__str__()
param_name = tex_param['ParameterInfo']['Name'].lower()
tex_name = Path(tex_local_path).stem
if Path(tex_local_path).exists():
loaded_texture = unreal.load_asset(
f'/project/{tex_name}')
if not loaded_texture:
continue
set_texture_param(material_reference, param_name, loaded_texture)
unreal.MaterialEditingLibrary.update_material_instance(material_reference)
def settings_create_ovr_material(mat_dict: list):
## No clue (?) but not gonna bother rn no idea why i didnt use the first ovr material func
material_array = []
loaded = None
for mat in mat_dict:
if not mat:
material_array.append(None)
continue
object_name = return_object_name(mat["ObjectName"])
if "MaterialInstanceDynamic" in object_name:
material_array.append(None)
continue
loaded = unreal.load_asset(f'/project/{object_name}')
if loaded == None:
loaded = unreal.load_asset(f'/project/{object_name}')
material_array.append(loaded)
return material_array
def set_all_settings(asset_props: dict, component_reference):
## Sets all the settings to the component (material, mesh, etc) from "Properties" using some weird black magic
if not asset_props:
return
for setting in asset_props:
value_setting = asset_props[setting]
try:
editor_property = component_reference.get_editor_property(setting)
except:
continue
class_name = type(editor_property).__name__
type_value = type(value_setting).__name__
if type_value == "int" or type_value == "float" or type_value == "bool":
if setting == "InfluenceRadius" and value_setting == 0:
set_unreal_prop(component_reference, setting, 14680)
continue
set_unreal_prop(component_reference, setting, value_setting)
continue
if "::" in value_setting:
value_setting = value_setting.split("::")[1]
# Try to make these automatic? with 'unreal.classname.value"?
if class_name == "LinearColor":
set_unreal_prop(component_reference, setting, unreal.LinearColor(r=value_setting['R'], g=value_setting['G'],
b=value_setting['B']))
continue
if class_name == "Vector4":
set_unreal_prop(component_reference, setting, unreal.Vector4(x=value_setting['X'], y=value_setting['Y'],
z=value_setting['Z'], w=value_setting['W']))
continue
if "Color" in class_name:
set_unreal_prop(component_reference, setting, unreal.Color(r=value_setting['R'], g=value_setting['G'],
b=value_setting['B'], a=value_setting['A']))
continue
if type_value == "dict":
if setting == "IESTexture":
set_unreal_prop(component_reference, setting, get_ies_texture(value_setting))
continue
if setting == "Cubemap":
set_unreal_prop(component_reference, setting, get_cubemap_texture(value_setting))
continue
if setting == "DecalMaterial":
component_reference.set_decal_material(get_mat(value_setting))
continue
if setting == "DecalSize":
set_unreal_prop(component_reference, setting,
unreal.Vector(value_setting["X"], value_setting["Y"], value_setting["Z"]))
continue
if setting == "StaticMesh":
##mesh_loaded = unreal.BPFL.set_mesh_reference(value_setting["ObjectName"],"Meshes")
mesh_loaded = mesh_to_asset(value_setting, "StaticMesh ", "Meshes")
set_unreal_prop(component_reference, setting, mesh_loaded)
continue
if setting == "BoxExtent":
set_unreal_prop(component_reference, 'box_extent',
unreal.Vector(x=value_setting['X'], y=value_setting['Y'], z=value_setting['Z'])),
continue
if setting == "LightmassSettings":
set_unreal_prop(component_reference, 'lightmass_settings', get_light_mass(value_setting,
component_reference.get_editor_property(
'lightmass_settings')))
continue
continue
if type_value == "list":
if setting == "OverrideMaterials":
mat_override = settings_create_ovr_material(value_setting)
set_unreal_prop(component_reference, setting, mat_override)
continue
continue
python_unreal_value = return_python_unreal_enum(value_setting)
try:
value = eval(f'unreal.{class_name}.{python_unreal_value}')
except:
continue
set_unreal_prop(component_reference, setting, value)
return component_reference
def get_light_mass(light_mass: dict, light_mass_reference):
blacklist_lmass = ['bLightAsBackFace', 'bUseTwoSidedLighting']
## Sets the lightmass settings to the component
for l_mass in light_mass:
if l_mass in blacklist_lmass:
continue
value_setting = light_mass[l_mass]
first_name = l_mass
if l_mass[0] == "b":
l_mass = l_mass[1:]
value = re.sub(r'(?<!^)(?=[A-Z])', '_', l_mass)
set_unreal_prop(light_mass_reference, value, value_setting)
return light_mass_reference
def import_light(light_data: actor_defs, all_objs: list):
## Imports the light actors to the World
light_type_replace = light_data.type.replace("Component", "")
if not light_data.transform:
light_data.transform = get_scene_transform(light_data.scene_props)
# light_data.transform = get_scene_parent(light_data.data,light_data.outer,all_objs)
if not light_data.transform:
return
light = unreal.EditorLevelLibrary.spawn_actor_from_class(eval(f'unreal.{light_type_replace}'),
light_data.transform.translation,
light_data.transform.rotation.rotator())
light.set_folder_path(f'Lights/{light_type_replace}')
light.set_actor_label(light_data.name)
light.set_actor_scale3d(light_data.transform.scale3d)
light_component = unreal.BPFL.get_component(light)
if type(light_component) == unreal.BrushComponent:
light_component = light
if hasattr(light_component, "settings"):
set_unreal_prop(light_component, "Unbound", True)
set_unreal_prop(light_component, "Priority", 1.0)
set_all_settings(light_data.props["Settings"], light_component.settings)
set_all_settings(light_data.props, light_component)
def import_decal(decal_data: actor_defs):
## Imports the decal actors to the World
if not decal_data.transform or has_key("Template", decal_data.data):
return
decal = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.DecalActor, decal_data.transform.translation,
decal_data.transform.rotation.rotator())
decal.set_folder_path(f'Decals')
decal.set_actor_label(decal_data.name)
decal.set_actor_scale3d(decal_data.transform.scale3d)
decal_component = decal.decal
if type(decal_data) == dict:
decal_component.set_decal_material(get_mat(actor_def=decal_data["DecalMaterial"]))
set_all_settings(decal_data.props, decal_component)
## fix this so it stops returning #some bps are not spawning because of attachparent ig fix it later
def fix_actor_bp(actor_data: actor_defs, settings: Settings):
## Fixes spawned blueprints with runtime-changed components
try:
component = unreal.BPFL.get_component_by_name(all_blueprints[actor_data.outer], actor_data.name)
except:
return
if not component:
return
if has_key("StaticMesh", actor_data.props):
loaded = mesh_to_asset(actor_data.props["StaticMesh"], "StaticMesh ", "Meshes")
#loaded = unreal.BPFL.set_mesh_reference(actor_data.props["StaticMesh"]["Name"],"Meshes")
component.set_editor_property('static_mesh', loaded)
if has_key("OverrideMaterials", actor_data.props):
if settings.import_materials:
mat_override = create_override_material(actor_data.data)
if mat_override and "Barrier" not in actor_data.name:
unreal.BPFL.set_override_material(all_blueprints[actor_data.outer], actor_data.name, mat_override)
if not has_key("AttachParent", actor_data.props):
return
transform = has_transform(actor_data.props)
if type(transform) != bool:
if has_key("RelativeScale3D", actor_data.props):
component = unreal.BPFL.get_component_by_name(all_blueprints[actor_data.outer], actor_data.name)
set_unreal_prop(component, "relative_scale3d", transform.scale3d)
if has_key("RelativeLocation", actor_data.props):
component = unreal.BPFL.get_component_by_name(all_blueprints[actor_data.outer], actor_data.name)
set_unreal_prop(component, "relative_location", transform.translation)
if has_key("RelativeRotation", actor_data.props):
component = unreal.BPFL.get_component_by_name(all_blueprints[actor_data.outer], actor_data.name)
set_unreal_prop(component, "relative_rotation", transform.rotation.rotator())
def import_mesh(mesh_data: actor_defs, settings: Settings, map_obj: MapObject):
## Imports the mesh actor to the world
override_vertex_colors = []
if has_key("Template", mesh_data.data):
fix_actor_bp(mesh_data, settings)
return
if not has_key("StaticMesh", mesh_data.props):
return
transform = get_transform(mesh_data.props)
if not transform:
return
unreal_mesh_type = unreal.StaticMeshActor
if map_obj.is_instanced():
unreal_mesh_type = unreal.HismActor
mesh_actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal_mesh_type, location=unreal.Vector(),
rotation=unreal.Rotator())
mesh_actor.set_actor_label(mesh_data.outer)
if has_key("LODData", mesh_data.data):
override_vertex_colors = get_override_vertex_color(mesh_data.data)
if map_obj.is_instanced():
component = mesh_actor.hism_component
mesh_actor.set_folder_path('Meshes/Instanced')
for inst_index in mesh_data.data["PerInstanceSMData"]:
component.add_instance(get_transform(inst_index))
else:
component = mesh_actor.static_mesh_component
folder_name = 'Meshes/Static'
if map_obj.umap.endswith('_VFX'):
folder_name = 'Meshes/VFX'
mesh_actor.set_folder_path(folder_name)
set_all_settings(mesh_data.props, component)
component.set_world_transform(transform, False, False)
if len(override_vertex_colors) > 0:
unreal.BPFL.paint_sm_vertices(component, override_vertex_colors, map_obj.model_path)
if has_key("OverrideMaterials", mesh_data.props):
if not settings.import_materials:
return
mat_override = create_override_material(mesh_data.data)
if mat_override:
set_unreal_prop(component, "override_materials", mat_override)
def set_mesh_build_settings(settings: Settings):
## Sets the build settings for the mesh since umodel exports it with wrong LMapCoordinateIndex and LMapResolution and Collision obviously
light_res_multiplier = settings.manual_lmres_mult
objects_path = settings.selected_map.objects_path
list_objects = objects_path
for m_object in os.listdir(list_objects):
object_json = read_json(objects_path.joinpath(m_object))
for o_object in object_json:
key = actor_defs(o_object)
if key.type == "StaticMesh":
light_map_res = round(256 * light_res_multiplier / 4) * 4
light_map_coord = 1
if has_key("LightMapCoordinateIndex", key.props):
light_map_coord = key.props["LightMapCoordinateIndex"]
if has_key("LightMapResolution", key.props):
light_map_res = round(key.props["LightMapResolution"] * light_res_multiplier / 4) * 4
mesh_load = unreal.load_asset(f"/project/{key.name}")
if mesh_load:
cast_mesh = unreal.StaticMesh.cast(mesh_load)
actual_coord = cast_mesh.get_editor_property("light_map_coordinate_index")
actual_resolution = cast_mesh.get_editor_property("light_map_resolution")
if actual_coord != light_map_coord:
set_unreal_prop(cast_mesh, "light_map_coordinate_index", light_map_coord)
if actual_resolution != light_map_res:
set_unreal_prop(cast_mesh, "light_map_resolution", light_map_res)
if key.type == "BodySetup":
if has_key("CollisionTraceFlag", key.props):
col_trace = re.sub('([A-Z])', r'_\1', key.props["CollisionTraceFlag"])
mesh_load = unreal.load_asset(f"/project/{key.outer}")
if mesh_load:
cast_mesh = unreal.StaticMesh.cast(mesh_load)
body_setup = cast_mesh.get_editor_property("body_setup")
str_collision = 'CTF_' + col_trace[8:len(col_trace)].upper()
set_unreal_prop(body_setup, "collision_trace_flag",
eval(f'unreal.CollisionTraceFlag.{str_collision}'))
set_unreal_prop(cast_mesh, "body_setup", body_setup)
def import_umap(settings: Settings, umap_data: dict, umap_name: str):
## Imports a umap according to filters and settings selected // at the moment i don't like it since
## it's a bit messy and i don't like the way i'm doing it but it works
## Looping before the main_import just for blueprints to be spawned first, no idea how to fix it lets stay like this atm
objects_to_import = filter_objects(umap_data, umap_name)
if settings.import_blueprints:
for objectIndex, object_data in enumerate(objects_to_import):
object_type = get_object_type(object_data)
if object_type == "blueprint":
import_blueprint(actor_defs(object_data), objects_to_import)
for objectIndex, object_data in enumerate(objects_to_import):
object_type = get_object_type(object_data)
actor_data_definition = actor_defs(object_data)
if object_type == "mesh" and settings.import_Mesh:
map_object = MapObject(settings=settings, data=object_data, umap_name=umap_name, umap_data=umap_data)
import_mesh(mesh_data=actor_data_definition, settings=settings, map_obj=map_object)
if object_type == "decal" and settings.import_decals:
import_decal(actor_data_definition)
if object_type == "light" and settings.import_lights:
import_light(actor_data_definition, objects_to_import)
def level_streaming_setup():
## Sets up the level streaming for the map if using the streaming option
world = unreal.EditorLevelLibrary.get_editor_world()
for level_path in all_level_paths:
unreal.EditorLevelUtils.add_level_to_world(world, level_path, unreal.LevelStreamingAlwaysLoaded)
def import_blueprint(bp_actor: actor_defs, umap_data: list):
## Imports a blueprint actor from the umap
transform = bp_actor.transform
if not transform:
transform = get_scene_transform(bp_actor.scene_props)
if type(transform) == bool:
transform = get_transform(bp_actor.props)
if not transform:
return
bp_name = bp_actor.type[0:len(bp_actor.type) - 2]
loaded_bp = unreal.load_asset(f"/project/{bp_name}.{bp_name}")
actor = unreal.EditorLevelLibrary.spawn_actor_from_object(loaded_bp, transform.translation,
transform.rotation.rotator())
if not actor:
return
all_blueprints[bp_actor.name] = actor
actor.set_actor_label(bp_actor.name)
actor.set_actor_scale3d(transform.scale3d)
def create_new_level(map_name):
## Creates a new level with the map name
new_map = map_name.split('_')[0]
map_path = (f"/project/{new_map}/{map_name}")
loaded_map = unreal.load_asset(map_path)
sub_system_editor = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem)
unreal.LevelEditorSubsystem.new_level(sub_system_editor, map_path)
all_level_paths.append(map_path)
def get_override_vertex_color(mesh_data: dict):
## Gets the override vertex color from the mesh data
lod_data = mesh_data["LODData"]
vtx_array = []
for lod in lod_data:
if has_key("OverrideVertexColors", lod):
vertex_to_convert = lod["OverrideVertexColors"]["Data"]
for rgba_hex in vertex_to_convert:
vtx_array.append(unreal.BPFL.return_from_hex(rgba_hex))
return vtx_array
def import_all_textures_from_material(material_data: dict, settings: Settings):
## Imports all the textures from a material json first
mat_info = actor_defs(material_data[0])
if mat_info.props:
if has_key("TextureParameterValues", mat_info.props):
tx_parameters = mat_info.props["TextureParameterValues"]
for tx_param in tx_parameters:
tex_game_path = get_texture_path(s=tx_param, f=settings.texture_format)
if not tex_game_path:
continue
tex_local_path = settings.assets_path.joinpath(tex_game_path).__str__()
if tex_local_path not in all_textures:
all_textures.append(tex_local_path)
def create_material(material_data: list, settings: Settings):
## Creates a material from the material data
mat_data = material_data[0]
mat_data = actor_defs(mat_data)
parent = "BaseEnv_MAT_V4"
if "Blend" in mat_data.name and "BaseEnv_Blend_MAT_V4_V3Compatibility" not in mat_data.name:
parent = "BaseEnv_Blend_MAT_V4"
if not mat_data.props:
return
loaded_material = unreal.load_asset(f"/project/{mat_data.name}.{mat_data.name}")
if not loaded_material:
loaded_material = AssetTools.create_asset(mat_data.name, '/project/',
unreal.MaterialInstanceConstant,
unreal.MaterialInstanceConstantFactoryNew())
if has_key("Parent", mat_data.props):
parent = return_parent(mat_data.props["Parent"]["ObjectName"])
material_instance = unreal.MaterialInstanceConstant.cast(loaded_material)
set_unreal_prop(material_instance, "parent", import_shader(parent))
set_material(settings=settings, mat_data=mat_data, ue_material=loaded_material)
def import_all_meshes(settings: Settings):
## Imports all the meshes from the map first accordingly.
all_meshes = []
obj_path = settings.selected_map.folder_path.joinpath("_assets_objects.txt")
with open(obj_path, 'r') as file:
lines = file.read().splitlines()
exp_path = str(settings.assets_path)
for line in lines:
if is_blacklisted(line.split('\\')[-1]):
continue
line_arr = line.split('\\')
if line_arr[0] == "Engine":
continue
else:
line_arr.pop(0)
line_arr.pop(0)
joined_lines_back = "\\".join(line_arr)
full_path = exp_path + '\\Game\\' + joined_lines_back + ".pskx"
if full_path not in all_meshes:
all_meshes.append(full_path)
# import
unreal.BPFL.import_meshes(all_meshes, str(settings.selected_map.objects_path))
def imports_all_textures(settings: Settings):
## Imports all the texture from materials.
mat_path = settings.selected_map.materials_path
mat_ovr_path = settings.selected_map.materials_ovr_path
for path_mat in os.listdir(mat_path):
mat_json = read_json(mat_path.joinpath(path_mat))
import_all_textures_from_material(mat_json, settings)
for path_ovr_mat in os.listdir(mat_ovr_path):
mat_ovr_json = read_json(mat_ovr_path.joinpath(path_ovr_mat))
import_all_textures_from_material(mat_ovr_json, settings)
unreal.BPFL.import_textures(all_textures)
def create_bp(full_data: dict, bp_name: str, settings: Settings):
## Creates a blueprint from the json data
BlacklistBP = ["SoundBarrier", "SpawnBarrierProjectile", "BP_UnwalkableBlockingVolumeCylinder",
'BP_StuckPickupVolume', "BP_BlockingVolume", "TargetingBlockingVolume_Box", "directional_look_up"]
# BlacklistBP = ['SpawnBarrier','SoundBarrier','SpawnBarrierProjectile','Gumshoe_CameraBlockingVolumeParent_Box','DomeBuyMarker','BP_StuckPickupVolume','BP_LevelBlockingVolume','BP_TargetingLandmark','BombSpawnLocation']
bp_name = bp_name.split('.')[0]
bp_actor = unreal.load_asset(f'/project/{bp_name}')
if not bp_actor and bp_name not in BlacklistBP:
bp_actor = AssetTools.create_asset(bp_name, '/project/', unreal.Blueprint,
unreal.BlueprintFactory())
else:
return
data = full_data["Nodes"]
if len(data) == 0:
return
root_scene = full_data["SceneRoot"]
default_scene_root = root_scene[0].split('.')[-1]
game_objects = full_data["GameObjects"]
nodes_root = full_data["ChildNodes"]
for idx, bpc in enumerate(data):
if bpc["Name"] == default_scene_root:
del data[idx]
data.insert(len(data), bpc)
break
data.reverse()
nodes_array = []
for bp_node in data:
if bp_node["Name"] in nodes_root:
continue
component_name = bp_node["Properties"]["ComponentClass"]["ObjectName"].replace(
"Class ", "")
try:
unreal_class = eval(f'unreal.{component_name}')
except:
continue
properties = bp_node["Properties"]
if has_key("ChildNodes", properties):
nodes_array = handle_child_nodes(properties["ChildNodes"], data, bp_actor)
comp_internal_name = properties["InternalVariableName"]
component = unreal.BPFL.create_bp_comp(
bp_actor, unreal_class, comp_internal_name, nodes_array)
if has_key("CompProps", properties):
properties = properties["CompProps"]
set_mesh_settings(properties, component)
set_all_settings(properties, component)
for game_object in game_objects:
if bp_name == "SpawnBarrier":
continue
component = unreal.BPFL.create_bp_comp(bp_actor, unreal.StaticMeshComponent, "GameObjectMesh", nodes_array)
set_all_settings(game_object["Properties"], component)
set_mesh_settings(game_object["Properties"], component)
def set_mesh_settings(mesh_properties: dict, component):
set_all_settings(mesh_properties, component)
transform = get_transform(mesh_properties)
if has_key("RelativeRotation", mesh_properties):
set_unreal_prop(component, "relative_rotation", transform.rotation.rotator())
if has_key("RelativeLocation", mesh_properties):
set_unreal_prop(component, "relative_location", transform.translation)
if has_key("RelativeScale3D", mesh_properties):
set_unreal_prop(component, "relative_scale3d", transform.scale3d)
def handle_child_nodes(child_nodes_array: dict, entire_data: list, bp_actor):
## Handles the child nodes of the blueprint since they are not in order.
local_child_array = []
for child_node in child_nodes_array:
child_obj_name = child_node["ObjectName"]
child_name = child_obj_name.split('.')[-1]
for c_node in entire_data:
component_name = c_node["Properties"]["ComponentClass"]["ObjectName"].replace(
"Class ", "")
try:
unreal_class = eval(f'unreal.{component_name}')
except:
continue
internal_name = c_node["Properties"]["InternalVariableName"]
if "TargetViewMode" in internal_name or "Decal1" in internal_name or "SM_Barrier_Back_VisionBlocker" in internal_name:
continue
if c_node["Name"] == child_name:
u_node, comp_node = unreal.BPFL.create_node(
bp_actor, unreal_class, internal_name)
local_child_array.append(u_node)
set_all_settings(c_node["Properties"]["CompProps"], comp_node)
transform = has_transform(c_node["Properties"]["CompProps"])
if type(transform) != bool:
comp_node.set_editor_property("relative_location", transform.translation)
comp_node.set_editor_property("relative_rotation", transform.rotation.rotator())
comp_node.set_editor_property("relative_scale3d", transform.scale3d)
break
return local_child_array
def import_all_blueprints(settings: Settings):
## Imports all the blueprints from the actors folder.
bp_path = settings.selected_map.actors_path
for bp in os.listdir(bp_path):
bp_json = reduce_bp_json(read_json(settings.selected_map.actors_path.joinpath(bp)))
create_bp(bp_json, bp, settings)
def import_all_materials(settings: Settings):
## Imports all the materials from the materials folder.
mat_path = settings.selected_map.materials_path
mat_ovr_path = settings.selected_map.materials_ovr_path
for path_mat in os.listdir(mat_path):
mat_json = read_json(mat_path.joinpath(path_mat))
create_material(mat_json, settings)
for path_ovr_mat in os.listdir(mat_ovr_path):
mat_ovr_json = read_json(mat_ovr_path.joinpath(path_ovr_mat))
create_material(mat_ovr_json, settings)
def import_map(setting):
## Main function first it sets some lighting settings ( have to revisit it for people who don't want the script to change their lighting settings)
## then it imports all meshes / textures / blueprints first and create materials from them.
## then each umap from the /maps folder is imported and the actors spawned accordingly.
unreal.BPFL.change_project_settings()
unreal.BPFL.execute_console_command('r.DefaultFeature.LightUnits 0')
unreal.BPFL.execute_console_command('r.DynamicGlobalIlluminationMethod 0')
all_level_paths.clear()
settings = Settings(setting)
umap_json_paths = get_map_assets(settings)
if not settings.import_sublevel:
create_new_level(settings.selected_map.name)
clear_level()
if settings.import_materials:
txt_time = time.time()
imports_all_textures(settings)
print(f'Exported all textures in {time.time() - txt_time} seconds')
mat_time = time.time()
import_all_materials(settings)
print(f'Exported all materials in {time.time() - mat_time} seconds')
m_start_time = time.time()
if settings.import_Mesh:
import_all_meshes(settings)
print(f'Exported all meshes in {time.time() - m_start_time} seconds')
bp_start_time = time.time()
if settings.import_blueprints:
import_all_blueprints(settings)
print(f'Exported all blueprints in {time.time() - bp_start_time} seconds')
umap_json_path: Path
actor_start_time = time.time()
with unreal.ScopedSlowTask(len(umap_json_paths), "Importing levels") as slow_task:
slow_task.make_dialog(True)
idx = 0
for index, umap_json_path in reversed(
list(enumerate(umap_json_paths))):
umap_data = read_json(umap_json_path)
umap_name = umap_json_path.stem
slow_task.enter_progress_frame(
work=1, desc=f"Importing level:{umap_name} {idx}/{len(umap_json_paths)} ")
if settings.import_sublevel:
create_new_level(umap_name)
import_umap(settings=settings, umap_data=umap_data, umap_name=umap_name)
if settings.import_sublevel:
unreal.EditorLevelLibrary.save_current_level()
idx = idx + 1
print("--- %s seconds to spawn actors ---" % (time.time() - actor_start_time))
if settings.import_sublevel:
level_streaming_setup()
if settings.import_Mesh:
set_mesh_build_settings(settings=settings)
# winsound.Beep(7500, 983)
|
import os
import unreal
def export_static_mesh_to_obj(static_mesh, export_dir):
static_mesh_name = static_mesh.get_name()
file_name = export_dir + static_mesh_name + ".obj"
print("Exporting static mesh to: {}".format(file_name))
# exportTask
exportTask = unreal.AssetExportTask()
exportTask.object = static_mesh
exportTask.filename = file_name
exportTask.automated = True
exportTask.replace_identical = True
exportTask.prompt = False
objExporter = unreal.StaticMeshExporterOBJ()
exportTask.exporter = objExporter
objExporter.run_asset_export_task(exportTask)
static_mesh_dir = "/project/"
export_dir = "/project/"
# iterate all static meshes in the directory - class should be StaticMesh
for asset_path in unreal.EditorAssetLibrary.list_assets(static_mesh_dir):
static_mesh = unreal.EditorAssetLibrary.load_asset(asset_path)
if isinstance(static_mesh, unreal.StaticMesh):
# print(asset_path)
export_static_mesh_to_obj(static_mesh, export_dir)
# delete all files with UV1 and Internal in the name
for file in os.listdir(export_dir):
if "UV1" in file or "Internal" in file:
os.remove(export_dir + file)
print("Deleted: {}".format(file))
|
import unreal
import sys
MODULE = r'/project/-packages'
if MODULE not in sys.path:
sys.path.append(MODULE)
from PySide import QtGui, QtUiTools
from Qt.QtCompat import loadUi
import os
WINDOW_NAME = 'Qt Window One'
# DIR = os.path.dirname(__file__)
UI_FILE_FULLNAME = __file__.replace(".py",".ui")
# This function will receive the tick from Unreal
def __QtAppTick__(delta_seconds):
for window in opened_windows:
window.eventTick(delta_seconds)
# This function will be called when the application is closing.
def __QtAppQuit__():
unreal.unregister_slate_post_tick_callback(tick_handle)
# This function is called by the windows when they are closing. (Only if the connection is properly made.)
def __QtWindowClosed__(window=None):
if window in opened_windows:
opened_windows.remove(window)
# This part is for the initial setup. Need to run once to spawn the application.
unreal_app = QtGui.QApplication.instance()
if not unreal_app:
unreal_app = QtGui.QApplication(sys.argv)
# tick_handle = unreal.register_slate_post_tick_callback(__QtAppTick__)
# unreal_app.aboutToQuit.connect(__QtAppQuit__)
existing_windows = {}
opened_windows = []
# desired_window_class: class QtGui.QWidget : The window class you want to spawn
# return: The new or existing window
def spawnQtWindow(desired_window_class=None):
window = existing_windows.get(desired_window_class, None)
if not window:
window = desired_window_class()
existing_windows[desired_window_class] = window
# window.aboutToClose = __QtWindowClosed__
if window not in opened_windows:
opened_windows.append(window)
window.show()
window.activateWindow()
return window
def run():
spawnQtWindow(QtWindowOne)
class QtWindowOne(QtGui.QWidget):
def __init__(self, parent=None):
super(QtWindowOne, self).__init__(parent)
layout = QtGui.QVBoxLayout()
self.setLayout(layout)
self.label = QtGui.QLabel("Test")
layout.addWidget(self.label)
self.button = QtGui.QPushButton("click")
self.button.clicked.connect(self.clickEvent)
layout.addWidget(self.label)
layout.addWidget(self.button)
self.setWindowTitle(WINDOW_NAME)
self.setGeometry(100, 100, self.width(), self.height())
unreal.parent_external_window_to_slate(self.winId())
def clickEvent(self):
print "click"
# import sys
# PATH = r"/project/"
# if PATH not in sys.path:
# sys.path.append(PATH)
# import qtWindow2
# reload(qtWindow2)
# qtWindow2.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.
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()
|
# 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()
|
import os
import time
import unreal
if __name__ == "__main__":
case_dir = "/project/"
cnt = 0
pose_file = os.path.join(case_dir, f"uc_placement{cnt}.txt")
while os.path.exists(pose_file):
case_type = f"Uc{cnt}Marker"
prefix = f"tag{case_type}"
holder_prefix = f"holder{case_type}"
print(f"Marker prefix: {prefix}")
# marker poses from IMP
f_stream = open(pose_file, "r")
imp_data = f_stream.readlines()
tag_num = len(imp_data) - 1
print(f"Marker number {tag_num}")
height = 175
decal_scale = [.01, 0.13208, 0.102]
cube_scale = [.01, .67, .52]
player_x, player_y = -272.0, 64.999985
cube_mesh = unreal.EditorAssetLibrary.find_asset_data('/project/').get_asset()
for i in range(tag_num):
line = imp_data[i+1].strip()
print(line)
line = line.split()
# scale 100 converting meters to centimeters
x, y, theta = float(line[1]) * 100 + player_x, -float(line[2]) * 100 + player_y, -float(line[3]) * 180 / 3.14
# get texture file
if i<9:
tex_path = f"/project/-00{i+1}_mat"
else:
tex_path = f"/project/-0{i+1}_mat"
if unreal.EditorAssetLibrary.does_asset_exist(tex_path):
my_tex = unreal.EditorAssetLibrary.find_asset_data(tex_path).get_asset()
my_decal = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.DecalActor,[0,0,0])
my_decal.set_actor_label(f"xxx{prefix}{i}")
my_decal.set_decal_material(my_tex)
my_decal.set_actor_location_and_rotation([x, y, height], unreal.Rotator(-90, 180, theta), False, True)
my_decal.set_actor_scale3d(decal_scale)
my_decal.set_folder_path(f"/{case_type}")
time.sleep(.1)
my_decal.set_actor_label(f"{prefix}{i}")
my_cube = unreal.EditorLevelLibrary.spawn_actor_from_object(cube_mesh, [0, 0, 0])
my_cube.set_actor_label(f"xxx{holder_prefix}{i}")
my_cube.set_actor_location_and_rotation([x, y, height], unreal.Rotator(-90, 180, theta), False, True)
my_cube.set_actor_scale3d(cube_scale)
my_cube.set_folder_path(f"/{case_type}")
my_cube.set_mobility(unreal.ComponentMobility.MOVABLE)
time.sleep(.1)
my_cube.set_actor_label(f"{holder_prefix}{i}")
else:
print(f"cannot find tex {tex_path}")
f_stream.close()
cnt += 1
pose_file = os.path.join(case_dir, f"uc_placement{cnt}.txt")
|
# 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
the ramp points of a float ramp and a color ramp.
"""
import math
import unreal
_g_wrapper = None
def get_test_hda_path():
return '/project/.ramp_example_1_0'
def get_test_hda():
return unreal.load_object(None, get_test_hda_path())
def set_parameters(in_wrapper):
print('set_parameters')
# Unbind from the delegate
in_wrapper.on_post_instantiation_delegate.remove_callable(set_parameters)
# There are two ramps: heightramp and colorramp. The height ramp is a float
# ramp. As an example we'll set the number of ramp points and then set
# each point individually
in_wrapper.set_ramp_parameter_num_points('heightramp', 6)
in_wrapper.set_float_ramp_parameter_point_value('heightramp', 0, 0.0, 0.1)
in_wrapper.set_float_ramp_parameter_point_value('heightramp', 1, 0.2, 0.6)
in_wrapper.set_float_ramp_parameter_point_value('heightramp', 2, 0.4, 1.0)
in_wrapper.set_float_ramp_parameter_point_value('heightramp', 3, 0.6, 1.4)
in_wrapper.set_float_ramp_parameter_point_value('heightramp', 4, 0.8, 1.8)
in_wrapper.set_float_ramp_parameter_point_value('heightramp', 5, 1.0, 2.2)
# For the color ramp, as an example, we can set the all the points via an
# array.
in_wrapper.set_color_ramp_parameter_points('colorramp', (
unreal.HoudiniPublicAPIColorRampPoint(position=0.0, value=unreal.LinearColor.GRAY),
unreal.HoudiniPublicAPIColorRampPoint(position=0.5, value=unreal.LinearColor.GREEN),
unreal.HoudiniPublicAPIColorRampPoint(position=1.0, value=unreal.LinearColor.RED),
))
def print_parameters(in_wrapper):
print('print_parameters')
in_wrapper.on_post_processing_delegate.remove_callable(print_parameters)
# Print the ramp points directly
print('heightramp: num points {0}:'.format(in_wrapper.get_ramp_parameter_num_points('heightramp')))
heightramp_data = in_wrapper.get_float_ramp_parameter_points('heightramp')
if not heightramp_data:
print('\tNone')
else:
for idx, point_data in enumerate(heightramp_data):
print('\t\t{0}: position={1:.6f}; value={2:.6f}; interpoloation={3}'.format(
idx,
point_data.position,
point_data.value,
point_data.interpolation
))
print('colorramp: num points {0}:'.format(in_wrapper.get_ramp_parameter_num_points('colorramp')))
colorramp_data = in_wrapper.get_color_ramp_parameter_points('colorramp')
if not colorramp_data:
print('\tNone')
else:
for idx, point_data in enumerate(colorramp_data):
print('\t\t{0}: position={1:.6f}; value={2}; interpoloation={3}'.format(
idx,
point_data.position,
point_data.value,
point_data.interpolation
))
# 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))
if not param_tuple.float_ramp_points:
print('\tfloat_ramp_points: None')
else:
print('\tfloat_ramp_points:')
for idx, point_data in enumerate(param_tuple.float_ramp_points):
print('\t\t{0}: position={1:.6f}; value={2:.6f}; interpoloation={3}'.format(
idx,
point_data.position,
point_data.value,
point_data.interpolation
))
if not param_tuple.color_ramp_points:
print('\tcolor_ramp_points: None')
else:
print('\tcolor_ramp_points:')
for idx, point_data in enumerate(param_tuple.color_ramp_points):
print('\t\t{0}: position={1:.6f}; value={2}; interpoloation={3}'.format(
idx,
point_data.position,
point_data.value,
point_data.interpolation
))
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())
# Set the float and color ramps on post instantiation, before the first
# cook.
_g_wrapper.on_post_instantiation_delegate.add_callable(set_parameters)
# Print the parameter state after the cook and output creation.
_g_wrapper.on_post_processing_delegate.add_callable(print_parameters)
if __name__ == '__main__':
run()
|
import unreal
def create_menu():
entry_names = []
entry_labels = []
entry_tooltips = []
entry_commands = []
# ---------
entry_names.append( "create_levels")
entry_tooltips.append( "houdini filemarks should be here: Q:/project/")
entry_labels.append( "create levels")
entry_commands.append( "import ue_level; import importlib; importlib.reload(ue_level); ue_level.find_filemarks_to_create_levels()")
# ---------
entry_names.append( "camera_settings")
entry_tooltips.append( "select in outliner: _CAM (Camera) (applies settings from Houdini file)")
entry_labels.append( "update camera settings")
entry_commands.append( "import ue_camera; import importlib; importlib.reload(ue_camera); ue_camera.update_camera_settings('MENU')")
# ---------
entry_names.append( "render_job_settings")
entry_tooltips.append( "select in outliner: _CONFIG (RenderQueueConfig) (applies to: all items in RenderQueue")
entry_labels.append( "apply render job settings")
entry_commands.append( "import ue_render_job; import importlib; importlib.reload(ue_render_job); ue_render_job.apply_selected_RenderQueueConfig()")
# ------------- backup
# custom_menu = ue_main_menu.add_sub_menu("My.Menu", "Python", "My Menu", "This is a IKOON")
# insert_position = unreal.ToolMenuInsert("", unreal.ToolMenuInsertType.FIRST)
# https://docs.unrealengine.com/4.26/en-US/project/.html
ue_menus = unreal.ToolMenus.get()
ue_main_menu = ue_menus.find_menu("LevelEditor.MainMenu")
if not ue_main_menu:
print("Failed to find the 'Main' menu. Something is wrong in the force!")
custom_menu = ue_main_menu.add_sub_menu(ue_main_menu.get_name(), section_name = "ikoon_menu_section_name", name = "ikoon_menu_name", label = "ikoon.py", tool_tip = "Scripts by ikoon")
# --------------- entries ----------------------
for i in range(len(entry_names)):
entry = unreal.ToolMenuEntry(
name = entry_names[i],
type = unreal.MultiBlockType.MENU_ENTRY,
insert_position = unreal.ToolMenuInsert("", unreal.ToolMenuInsertType.FIRST)
# insert_position = [None, unreal.ToolMenuInsertType.DEFAULT],
)
entry.set_label(entry_labels[i])
entry.set_tool_tip(entry_tooltips[i])
entry.set_string_command(
type = unreal.ToolMenuStringCommandType.PYTHON,
custom_type = entry_names[i],
string = entry_commands[i]
)
custom_menu.add_menu_entry(entry_names[i], entry)
# --------------- entries ----------------------
# refresh the UI
ue_menus.refresh_all_widgets()
|
import cv2
import argparse
import tempfile
import os
import numpy as np
import unreal
import pathlib
SCRIPT_PATH = os.path.dirname(__file__)
def parse_arguments():
parser = argparse.ArgumentParser(description='Crop Input Image to square face')
parser.add_argument('--inputImage', required=True, help='Path to the input image')
parser.add_argument('--outputFolderName', required=True, help='Path to the input image')
return parser.parse_args()
def main():
args = parse_arguments()
current_directory = os.path.dirname(SCRIPT_PATH)
contentPath = unreal.Paths.project_content_dir()
pluginsPath = unreal.Paths.make_standard_filename(unreal.Paths.convert_relative_path_to_full(unreal.Paths.project_plugins_dir()))
message = f"Content is at {contentPath}"
image = cv2.imread(args.inputImage)
# Get the path to the temporary directory
temp_dir = tempfile.gettempdir()
file_path = pathlib.Path(args.inputImage)
# Get the filename (stem)
name = file_path.stem
# Get the file extension
extension = file_path.suffix
output_path = os.path.join(temp_dir, f'{name}_crop{extension}')
unreal.log(output_path)
# Save the black and white image to the temporary directory
face = detectFace(image)
cv2.imwrite(output_path, face)
importAssets(output_path, args.outputFolderName+f"/{name}_crop", name)
def detectFace(image, padding = 50):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_alt2.xml')
#
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
#
face = np.zeros(image.shape)
for (x, y, w, h) in faces:
face = image[y - padding:y + h + padding, x - padding:x + w + padding]
return face
def importAssets(fileNames, destinationName , fileName):
if isinstance(fileNames, str):
fileNames = [fileNames]
assetTools = unreal.AssetToolsHelpers.get_asset_tools()
assetImportData = unreal.AutomatedAssetImportData()
assetImportData.destination_path = os.path.join("/Game/", destinationName, "Source")
assetImportData.filenames = fileNames
assetTools.import_assets_automated(assetImportData)
main()
|
import unreal
from Lib import __lib_topaz__ as topaz
import importlib
importlib.reload(topaz)
selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets()
# print(selectedAssets[0])
for asset in selectedAssets:
staticMeshsInBP = topaz.get_component_by_class(asset, unreal.StaticMeshComponent)
directoryPath = asset.get_path_name()
part = directoryPath.split('/')
staticMeshesDirectory = '/'.join(part[:6]) + '/StaticMesh'
print(staticMeshesDirectory)
for staticMesh in staticMeshsInBP:
isStaticMesh = staticMesh.static_mesh
if not isStaticMesh:
continue
arr = staticMesh.static_mesh.get_path_name().split('/')
length = len(arr)
staticMeshFilesName = arr[length-1]
targetPath = staticMeshesDirectory + '/' + staticMeshFilesName
sourcePath = staticMesh.static_mesh.get_path_name()
print(sourcePath, "sourcePath")
print(targetPath, "targetPath")
if(targetPath != sourcePath):
result = unreal.EditorAssetLibrary.rename_asset(sourcePath, targetPath)
print(result)
|
# editor_actions.py
import unreal
import json
import traceback
from typing import List, Dict, Optional, Any # Modified import
def ue_get_selected_assets() -> str:
"""Gets the set of currently selected assets."""
try:
selected_assets = unreal.EditorUtilityLibrary.get_selected_assets()
serialized_assets = []
for asset in selected_assets:
serialized_assets.append({
"asset_name": asset.get_name(),
"asset_path": asset.get_path_name(),
"asset_class": asset.get_class().get_name(),
})
return json.dumps({"success": True, "selected_assets": serialized_assets})
except Exception as e:
return json.dumps({"success": False, "message": str(e)})
# Helper function to load MaterialInterface assets (can be Material or MaterialInstance)
def _load_material_interface(material_path: str):
# Helper implementation (ensure this is robust or use existing if available)
material = unreal.EditorAssetLibrary.load_asset(material_path)
if not material:
raise FileNotFoundError(f"Material asset not found at path: {material_path}")
if not isinstance(material, unreal.MaterialInterface): # Allows Material or MaterialInstance
raise TypeError(f"Asset at {material_path} is not a MaterialInterface, but {type(material).__name__}")
return material
# Helper function to load StaticMesh assets
def _load_static_mesh(mesh_path: str):
# Helper implementation (ensure this is robust or use existing if available)
mesh = unreal.EditorAssetLibrary.load_asset(mesh_path)
if not mesh:
raise FileNotFoundError(f"StaticMesh asset not found at path: {mesh_path}")
if not isinstance(mesh, unreal.StaticMesh):
raise TypeError(f"Asset at {mesh_path} is not a StaticMesh, but {type(mesh).__name__}")
return mesh
# Helper function to get material paths from a mesh component
def _get_component_material_paths(component: unreal.MeshComponent) -> List[str]:
material_paths = []
if component:
for i in range(component.get_num_materials()):
material = component.get_material(i)
if material:
material_paths.append(material.get_path_name())
else:
material_paths.append("") # Represent empty slot
return material_paths
# Helper function to get actors by their paths
def _get_actors_by_paths(actor_paths: List[str]) -> List[unreal.Actor]:
actors = []
all_level_actors = unreal.EditorLevelLibrary.get_all_level_actors()
for path in actor_paths:
actor = next((a for a in all_level_actors if a.get_path_name() == path), None)
if actor:
actors.append(actor)
else:
unreal.log_warning(f"MCP: Actor not found at path: {path}")
return actors
# Helper to create a map of actor paths to their unique material asset paths
def _get_materials_map_for_actors(actors_list: List[unreal.Actor]) -> Dict[str, List[str]]:
materials_map = {}
if not actors_list:
return materials_map
for actor in actors_list:
if not actor: continue
actor_path_name = actor.get_path_name()
actor_material_paths = set()
mesh_components = actor.get_components_by_class(unreal.MeshComponent.static_class())
for comp in mesh_components:
if comp:
for i in range(comp.get_num_materials()):
material = comp.get_material(i)
if material:
actor_material_paths.add(material.get_path_name())
materials_map[actor_path_name] = sorted(list(actor_material_paths))
return materials_map
# Helper to get static mesh path from a static mesh component
def _get_component_mesh_path(component: unreal.StaticMeshComponent) -> str:
if component and hasattr(component, 'static_mesh') and component.static_mesh:
return component.static_mesh.get_path_name()
return ""
# Helper to create a map of actor paths to their unique static mesh asset paths
def _get_meshes_map_for_actors(actors_list: List[unreal.Actor]) -> Dict[str, List[str]]:
meshes_map = {}
if not actors_list:
return meshes_map
for actor in actors_list:
if not actor: continue
actor_path_name = actor.get_path_name()
actor_mesh_paths = set()
sm_components = actor.get_components_by_class(unreal.StaticMeshComponent.static_class())
for comp in sm_components:
mesh_path = _get_component_mesh_path(comp)
if mesh_path:
actor_mesh_paths.add(mesh_path)
meshes_map[actor_path_name] = sorted(list(actor_mesh_paths))
return meshes_map
# Helper to create a map of actor paths to their unique skeletal mesh asset paths
def _get_skeletal_meshes_map_for_actors(actors_list: List[unreal.Actor]) -> Dict[str, List[str]]:
skeletal_meshes_map = {}
if not actors_list:
return skeletal_meshes_map
for actor in actors_list:
if not actor:
continue
actor_path_name = actor.get_path_name()
actor_skel_mesh_paths = set()
skel_components = actor.get_components_by_class(unreal.SkeletalMeshComponent.static_class())
for comp in skel_components:
if hasattr(comp, 'skeletal_mesh') and comp.skeletal_mesh:
actor_skel_mesh_paths.add(comp.skeletal_mesh.get_path_name())
skeletal_meshes_map[actor_path_name] = sorted(list(actor_skel_mesh_paths))
return skeletal_meshes_map
# Base helper for replacing meshes
def _replace_meshes_on_actors_components_base(
actors: List[unreal.Actor],
mesh_to_be_replaced_path: str, # Can be empty/None to replace any mesh
new_mesh_path: str
) -> Dict[str, Any]:
"""Base logic for replacing static meshes on components of given actors."""
mesh_to_replace = None
# Only load if a specific mesh is targeted for replacement
if mesh_to_be_replaced_path and mesh_to_be_replaced_path.lower() not in ["", "none", "any"]:
mesh_to_replace = _load_static_mesh(mesh_to_be_replaced_path) # Uses existing helper
# If _load_static_mesh raises, it will be caught by the calling ue_ function's try-except
new_mesh = _load_static_mesh(new_mesh_path) # Uses existing helper
# If _load_static_mesh raises, it will be caught by the calling ue_ function's try-except
if mesh_to_replace and new_mesh and mesh_to_replace.get_path_name() == new_mesh.get_path_name():
return {"success": True, "message": "Mesh to be replaced is the same as the new mesh. No changes made.", "changed_actors_count": 0, "changed_components_count": 0}
changed_actors_count = 0
changed_components_count = 0
details = {"actors_affected": []}
with unreal.ScopedEditorTransaction("Replace Static Meshes on Components") as trans:
for actor in actors:
if not actor: continue
actor_path = actor.get_path_name()
actor_changed_this_iteration = False
actor_details = {"actor_path": actor_path, "components_changed": []}
static_mesh_components = actor.get_components_by_class(unreal.StaticMeshComponent.static_class())
for component in static_mesh_components:
if not component or component.get_owner() != actor:
continue
component_path = component.get_path_name()
current_mesh = component.static_mesh
should_replace = False
# Case 1: Replace any mesh (mesh_to_be_replaced_path is empty/project/)
if not mesh_to_be_replaced_path or mesh_to_be_replaced_path.lower() in ["", "none", "any"]:
if current_mesh != new_mesh : # Avoid replacing with itself if no specific mesh to replace
should_replace = True
# Case 2: Replace a specific mesh
elif mesh_to_replace and current_mesh and current_mesh.get_path_name() == mesh_to_replace.get_path_name():
if current_mesh.get_path_name() != new_mesh.get_path_name(): # Don't replace if it's already the new mesh
should_replace = True
# Case 3: Component has no mesh, and we want to set one (mesh_to_be_replaced_path is empty/project/)
elif (not mesh_to_be_replaced_path or mesh_to_be_replaced_path.lower() in ["", "none", "any"]) and not current_mesh:
should_replace = True
if should_replace:
if component.set_static_mesh(new_mesh):
changed_components_count += 1
actor_changed_this_iteration = True
actor_details["components_changed"].append({"component_path": component_path, "previous_mesh": current_mesh.get_path_name() if current_mesh else None})
else:
unreal.log_warning(f"MCP: Failed to set static mesh on component {component_path} for actor {actor_path}")
if actor_changed_this_iteration:
changed_actors_count += 1
details["actors_affected"].append(actor_details)
if changed_actors_count > 0:
unreal.EditorLevelLibrary.refresh_all_level_editors()
return {
"success": True,
"message": f"Mesh replacement processed. Actors processed: {len(actors)}.",
"changed_actors_count": changed_actors_count,
"changed_components_count": changed_components_count,
"details": details
}
def ue_replace_materials_on_selected_actors_components(material_to_be_replaced_path: str, new_material_path: str) -> str:
try:
material_to_replace = _load_material_interface(material_to_be_replaced_path)
new_material = _load_material_interface(new_material_path)
selected_actors = unreal.EditorLevelLibrary.get_selected_level_actors()
if not selected_actors:
return json.dumps({"success": False, "message": "No actors selected."})
mesh_components = []
for actor in selected_actors:
components = actor.get_components_by_class(unreal.MeshComponent.static_class())
mesh_components.extend(c for c in components if c)
if not mesh_components:
return json.dumps({"success": False, "message": "No mesh components found on selected actors."})
initial_materials_map = {}
for comp in mesh_components:
initial_materials_map[comp.get_path_name()] = _get_component_material_paths(comp)
unreal.EditorLevelLibrary.replace_mesh_components_materials(
mesh_components,
material_to_replace,
new_material
)
num_components_affected = 0
affected_component_paths = []
for comp in mesh_components:
current_materials = _get_component_material_paths(comp)
original_materials = initial_materials_map.get(comp.get_path_name(), [])
component_changed_here = False
for slot_idx, original_mat_path in enumerate(original_materials):
if original_mat_path == material_to_replace.get_path_name():
if slot_idx < len(current_materials) and current_materials[slot_idx] == new_material.get_path_name():
component_changed_here = True
break
if component_changed_here:
num_components_affected += 1
affected_component_paths.append(comp.get_path_name())
if num_components_affected > 0:
return json.dumps({
"success": True,
"message": f"Successfully replaced material '{material_to_be_replaced_path}' with '{new_material_path}' on {num_components_affected} mesh component(s) across {len(selected_actors)} selected actor(s).",
"affected_actors_count": len(selected_actors),
"affected_components_count": num_components_affected,
"affected_component_paths": affected_component_paths
})
else:
return json.dumps({
"success": False,
"message": f"Failed to replace material. Target material '{material_to_be_replaced_path}' not found or not replaced on any mesh components of selected actors."
})
except Exception as e:
return json.dumps({"success": False, "message": str(e), "traceback": traceback.format_exc()})
def ue_replace_materials_on_specified_actors_components(actor_paths: List[str], material_to_be_replaced_path: str, new_material_path: str) -> str:
try:
material_to_replace = _load_material_interface(material_to_be_replaced_path)
new_material = _load_material_interface(new_material_path)
actors_to_process = _get_actors_by_paths(actor_paths)
if not actors_to_process:
return json.dumps({"success": False, "message": "No valid actors found from the provided paths."})
all_mesh_components_in_actors = []
for actor in actors_to_process:
components = actor.get_components_by_class(unreal.MeshComponent.static_class())
all_mesh_components_in_actors.extend(c for c in components if c)
if not all_mesh_components_in_actors:
return json.dumps({"success": False, "message": "No mesh components found on the specified actors."})
initial_materials_map = {}
for comp in all_mesh_components_in_actors:
initial_materials_map[comp.get_path_name()] = _get_component_material_paths(comp)
unreal.EditorLevelLibrary.replace_mesh_components_materials_on_actors(
actors_to_process,
material_to_replace,
new_material
)
num_components_affected = 0
affected_component_paths = []
for comp in all_mesh_components_in_actors:
current_materials = _get_component_material_paths(comp)
original_materials = initial_materials_map.get(comp.get_path_name(), [])
component_changed_here = False
for slot_idx, original_mat_path in enumerate(original_materials):
if original_mat_path == material_to_replace.get_path_name():
if slot_idx < len(current_materials) and current_materials[slot_idx] == new_material.get_path_name():
component_changed_here = True
break
if component_changed_here:
num_components_affected += 1
affected_component_paths.append(comp.get_path_name())
if num_components_affected > 0:
return json.dumps({
"success": True,
"message": f"Successfully replaced material '{material_to_be_replaced_path}' with '{new_material_path}' on {num_components_affected} mesh component(s) across {len(actors_to_process)} specified actor(s).",
"affected_actors_count": len(actors_to_process),
"affected_components_count": num_components_affected,
"affected_component_paths": affected_component_paths
})
else:
return json.dumps({
"success": False,
"message": f"Failed to replace material. Target material '{material_to_be_replaced_path}' not found or not replaced on any mesh components of specified actors."
})
except Exception as e:
return json.dumps({"success": False, "message": str(e), "traceback": traceback.format_exc()})
def ue_replace_meshes_on_selected_actors_components(mesh_to_be_replaced_path: str, new_mesh_path: str) -> str:
"""Replaces static meshes on components of selected actors using Unreal's batch API if available."""
try:
# Check if mesh_to_be_replaced_path exists (if specified)
if mesh_to_be_replaced_path and mesh_to_be_replaced_path.lower() not in ["", "none", "any"]:
try:
_ = _load_static_mesh(mesh_to_be_replaced_path)
except FileNotFoundError:
return json.dumps({
"success": False,
"message": f"The mesh_to_be_replaced_path '{mesh_to_be_replaced_path}' does not exist as a StaticMesh asset.",
"error_type": "MeshToReplaceNotFound"
})
selected_actors = unreal.EditorLevelLibrary.get_selected_level_actors()
if not selected_actors:
return json.dumps({"success": True, "message": "No actors selected.", "changed_actors_count": 0, "changed_components_count": 0})
mesh_to_replace = None
if mesh_to_be_replaced_path and mesh_to_be_replaced_path.lower() not in ["", "none", "any"]:
mesh_to_replace = _load_static_mesh(mesh_to_be_replaced_path)
new_mesh = _load_static_mesh(new_mesh_path)
# Gather all static mesh components from selected actors
all_mesh_components = []
for actor in selected_actors:
comps = actor.get_components_by_class(unreal.StaticMeshComponent.static_class())
all_mesh_components.extend(c for c in comps if c)
if not all_mesh_components:
return json.dumps({"success": False, "message": "No static mesh components found on selected actors."})
# Save initial mesh paths for change detection
initial_meshes_map = {comp.get_path_name(): comp.static_mesh.get_path_name() if comp.static_mesh else "" for comp in all_mesh_components}
# Use Unreal's batch API if available
if hasattr(unreal.EditorLevelLibrary, "replace_mesh_components_meshes_on_actors"):
unreal.EditorLevelLibrary.replace_mesh_components_meshes_on_actors(
selected_actors,
mesh_to_replace,
new_mesh
)
else:
# Fallback to manual replacement if batch API is not available
for comp in all_mesh_components:
current_mesh = comp.static_mesh
should_replace = False
if not mesh_to_replace:
if current_mesh != new_mesh:
should_replace = True
elif current_mesh and current_mesh.get_path_name() == mesh_to_replace.get_path_name():
if current_mesh.get_path_name() != new_mesh.get_path_name():
should_replace = True
elif not current_mesh and not mesh_to_replace:
should_replace = True
if should_replace:
comp.set_static_mesh(new_mesh)
# Detect changes
changed_components_count = 0
affected_component_paths = []
for comp in all_mesh_components:
before = initial_meshes_map.get(comp.get_path_name(), "")
after = comp.static_mesh.get_path_name() if comp.static_mesh else ""
if mesh_to_replace:
if before == mesh_to_replace.get_path_name() and after == new_mesh.get_path_name():
changed_components_count += 1
affected_component_paths.append(comp.get_path_name())
else:
if before != after and after == new_mesh.get_path_name():
changed_components_count += 1
affected_component_paths.append(comp.get_path_name())
if changed_components_count > 0:
return json.dumps({
"success": True,
"message": f"Successfully replaced mesh on {changed_components_count} static mesh component(s) across {len(selected_actors)} selected actor(s).",
"affected_actors_count": len(selected_actors),
"affected_components_count": changed_components_count,
"affected_component_paths": affected_component_paths
})
else:
return json.dumps({
"success": False,
"message": f"Failed to replace mesh. Target mesh '{mesh_to_be_replaced_path}' not found or not replaced on any static mesh components of selected actors."
})
except FileNotFoundError as e:
unreal.log_error(f"MCP: Asset loading error in ue_replace_meshes_on_selected_actors_components: {e}")
return json.dumps({"success": False, "message": str(e), "traceback": traceback.format_exc()})
except TypeError as e:
unreal.log_error(f"MCP: Asset type error in ue_replace_meshes_on_selected_actors_components: {e}")
return json.dumps({"success": False, "message": str(e), "traceback": traceback.format_exc()})
except Exception as e:
unreal.log_error(f"MCP: Error in ue_replace_meshes_on_selected_actors_components: {e}\n{traceback.format_exc()}")
return json.dumps({"success": False, "message": str(e), "traceback": traceback.format_exc()})
def ue_replace_meshes_on_specified_actors_components(actor_paths: List[str], mesh_to_be_replaced_path: str, new_mesh_path: str) -> str:
"""Replaces static meshes on components of specified actors using Unreal's batch API if available."""
try:
# Check if mesh_to_be_replaced_path exists (if specified)
if mesh_to_be_replaced_path and mesh_to_be_replaced_path.lower() not in ["", "none", "any"]:
try:
_ = _load_static_mesh(mesh_to_be_replaced_path)
except FileNotFoundError:
return json.dumps({
"success": False,
"message": f"The mesh_to_be_replaced_path '{mesh_to_be_replaced_path}' does not exist as a StaticMesh asset.",
"error_type": "MeshToReplaceNotFound"
})
actors_to_process = _get_actors_by_paths(actor_paths)
if not actors_to_process:
return json.dumps({"success": False, "message": "No valid actors found from the provided paths."})
mesh_to_replace = None
if mesh_to_be_replaced_path and mesh_to_be_replaced_path.lower() not in ["", "none", "any"]:
mesh_to_replace = _load_static_mesh(mesh_to_be_replaced_path)
new_mesh = _load_static_mesh(new_mesh_path)
# Gather all static mesh components from specified actors
all_mesh_components = []
for actor in actors_to_process:
comps = actor.get_components_by_class(unreal.StaticMeshComponent.static_class())
all_mesh_components.extend(c for c in comps if c)
if not all_mesh_components:
# Get the actual actor types and names for better diagnosis
actor_info = [{"name": actor.get_name(), "class": actor.get_class().get_name()} for actor in actors_to_process]
actors_materials_info = _get_materials_map_for_actors(actors_to_process)
actors_meshes_info = _get_meshes_map_for_actors(actors_to_process)
actors_skel_meshes_info = _get_skeletal_meshes_map_for_actors(actors_to_process)
return json.dumps({
"success": False,
"message": "No static mesh components found on specified actors.",
"specified_actors_info": actor_info,
"current_materials": actors_materials_info,
"current_meshes": actors_meshes_info,
"current_skeletal_meshes": actors_skel_meshes_info
})
# Save initial mesh paths for change detection
initial_meshes_map = {comp.get_path_name(): comp.static_mesh.get_path_name() if comp.static_mesh else "" for comp in all_mesh_components}
# Use Unreal's batch API if available
if hasattr(unreal.EditorLevelLibrary, "replace_mesh_components_meshes_on_actors"):
unreal.EditorLevelLibrary.replace_mesh_components_meshes_on_actors(
actors_to_process,
mesh_to_replace,
new_mesh
)
else:
# Fallback to manual replacement if batch API is not available
for comp in all_mesh_components:
current_mesh = comp.static_mesh
should_replace = False
if not mesh_to_replace:
if current_mesh != new_mesh:
should_replace = True
elif current_mesh and current_mesh.get_path_name() == mesh_to_replace.get_path_name():
if current_mesh.get_path_name() != new_mesh.get_path_name():
should_replace = True
elif not current_mesh and not mesh_to_replace:
should_replace = True
if should_replace:
comp.set_static_mesh(new_mesh)
# Detect changes
changed_components_count = 0
affected_component_paths = []
unchanged_components_info = []
for comp in all_mesh_components:
before = initial_meshes_map.get(comp.get_path_name(), "")
after = comp.static_mesh.get_path_name() if comp.static_mesh else ""
owner_actor = comp.get_owner()
owner_name = owner_actor.get_name() if owner_actor else "Unknown"
if mesh_to_replace:
if before == mesh_to_replace.get_path_name() and after == new_mesh.get_path_name():
changed_components_count += 1
affected_component_paths.append(comp.get_path_name())
else:
is_candidate = before == mesh_to_replace.get_path_name()
unchanged_components_info.append({
"component_path": comp.get_path_name(),
"component_name": comp.get_name(),
"actor_name": owner_name,
"current_mesh": before,
"is_candidate": is_candidate,
"reason": (
"Component is a candidate for replacement (matches mesh_to_be_replaced_path) but was not changed"
if is_candidate else
("Current mesh doesn't match the mesh to be replaced" if before != mesh_to_replace.get_path_name() else "Failed to set new mesh")
)
})
else:
if before != after and after == new_mesh.get_path_name():
changed_components_count += 1
affected_component_paths.append(comp.get_path_name())
else:
unchanged_components_info.append({
"component_path": comp.get_path_name(),
"component_name": comp.get_name(),
"actor_name": owner_name,
"current_mesh": before,
"is_candidate": False,
"reason": "Component already has the target mesh" if before == new_mesh.get_path_name() else "Failed to set new mesh"
})
unchanged_components_info = unchanged_components_info if 'unchanged_components_info' in locals() else []
if changed_components_count > 0:
return json.dumps({
"success": True,
"message": f"Successfully replaced mesh on {changed_components_count} static mesh component(s) across {len(actors_to_process)} specified actor(s).",
"affected_actors_count": len(actors_to_process),
"affected_components_count": changed_components_count,
"affected_component_paths": affected_component_paths,
"unchanged_components": unchanged_components_info
})
else:
actors_materials_info = _get_materials_map_for_actors(actors_to_process)
actors_meshes_info = _get_meshes_map_for_actors(actors_to_process)
actors_skel_meshes_info = _get_skeletal_meshes_map_for_actors(actors_to_process)
unchanged_components_info = unchanged_components_info if 'unchanged_components_info' in locals() else []
return json.dumps({
"success": False,
"message": f"Failed to replace mesh. Target mesh '{mesh_to_be_replaced_path}' not found or not replaced on any static mesh components of specified actors.",
"current_materials": actors_materials_info,
"current_meshes": actors_meshes_info,
"current_skeletal_meshes": actors_skel_meshes_info,
"unchanged_components": unchanged_components_info
})
except FileNotFoundError as e:
unreal.log_error(f"MCP: Asset loading error in ue_replace_meshes_on_specified_actors_components: {e}")
return json.dumps({"success": False, "message": str(e), "traceback": traceback.format_exc()})
except TypeError as e:
unreal.log_error(f"MCP: Asset type error in ue_replace_meshes_on_specified_actors_components: {e}")
return json.dumps({"success": False, "message": str(e), "traceback": traceback.format_exc()})
except Exception as e:
unreal.log_error(f"MCP: Error in ue_replace_meshes_on_specified_actors_components: {e}\n{traceback.format_exc()}")
return json.dumps({"success": False, "message": str(e), "traceback": traceback.format_exc()})
def ue_replace_selected_actors_with_blueprint(blueprint_asset_path: str) -> str:
"""Replaces the currently selected actors with new actors spawned from a specified Blueprint asset path using Unreal's official API."""
import unreal
import json
import traceback
try:
selected_actors = unreal.EditorLevelLibrary.get_selected_level_actors()
if not selected_actors:
return json.dumps({"success": False, "message": "No actors selected."})
# Check if the blueprint asset exists
blueprint = unreal.EditorAssetLibrary.load_asset(blueprint_asset_path)
if not blueprint:
return json.dumps({"success": False, "message": f"Blueprint asset not found at path: {blueprint_asset_path}"})
# Use the official API
unreal.EditorLevelLibrary.replace_selected_actors(blueprint_asset_path)
return json.dumps({
"success": True,
"message": f"Replaced {len(selected_actors)} actors with Blueprint '{blueprint_asset_path}' using official API.",
"replaced_actors_count": len(selected_actors)
})
except Exception as e:
return json.dumps({"success": False, "message": str(e), "traceback": traceback.format_exc()})
|
# Nanite On ์ํค๋ ์ฝ๋
import unreal
selected_assets = unreal.EditorUtilityLibrary.get_selected_assets()
# For๋ฌธ ์ฐ๋ ์ด์ : ์์ selected_asset๋ค์ array๋ก ๋ฐํ๋๊ธฐ ๋๋ฌธ์ for๋ฌธ์ ์ฌ์ฉํ์ฌ ๊ฐ๊ฐ์ asset์ list๋ฅผ ๊ฐ์ ธ์์ผ ํ๋ค.
# ๋ฆฌ์คํธ์ ํผ์ฒ๋ฅผ ๊ฐ์ ธ์ค๊ธฐ ์ํด์๋ ํ๋์ฉ ๊ฐ์ ธ์์ผ ํ๋ค. array๋ก ๊ฐ์ ธ์ค๋ฉด ์๋ฌ๊ฐ ๋ฐ์ํ๋ค.
for nanitemesh in selected_assets :
meshNaniteSettings : bool = nanitemesh.get_editor_property('nanite_settings')
meshNaniteSettings.enabled = False
print(meshNaniteSettings.enabled)
|
import unreal
file_a = "/project/.fbx"
file_b = "/project/.fbx"
imported_scenes_path = "/project/"
print 'Preparing import options...'
advanced_mesh_options = unreal.DatasmithStaticMeshImportOptions()
advanced_mesh_options.set_editor_property('max_lightmap_resolution', unreal.DatasmithImportLightmapMax.LIGHTMAP_512)
advanced_mesh_options.set_editor_property('min_lightmap_resolution', unreal.DatasmithImportLightmapMin.LIGHTMAP_64)
advanced_mesh_options.set_editor_property('generate_lightmap_u_vs', True)
advanced_mesh_options.set_editor_property('remove_degenerates', True)
base_options = unreal.DatasmithImportBaseOptions()
base_options.set_editor_property('include_geometry', True)
base_options.set_editor_property('include_material', True)
base_options.set_editor_property('include_light', True)
base_options.set_editor_property('include_camera', True)
base_options.set_editor_property('include_animation', True)
base_options.set_editor_property('static_mesh_options', advanced_mesh_options)
base_options.set_editor_property('scene_handling', unreal.DatasmithImportScene.CURRENT_LEVEL)
base_options.set_editor_property('asset_options', []) # Not used
dg_options = unreal.DatasmithDeltaGenImportOptions()
dg_options.set_editor_property('merge_nodes', False)
dg_options.set_editor_property('optimize_duplicated_nodes', False)
dg_options.set_editor_property('remove_invisible_nodes', False)
dg_options.set_editor_property('simplify_node_hierarchy', False)
dg_options.set_editor_property('import_var', True)
dg_options.set_editor_property('var_path', "")
dg_options.set_editor_property('import_pos', True)
dg_options.set_editor_property('pos_path', "")
dg_options.set_editor_property('import_tml', True)
dg_options.set_editor_property('tml_path', "")
dg_options.set_editor_property('textures_dir', "")
dg_options.set_editor_property('intermediate_serialization', unreal.DatasmithDeltaGenIntermediateSerializationType.DISABLED)
dg_options.set_editor_property('colorize_materials', False)
dg_options.set_editor_property('generate_lightmap_u_vs', False)
dg_options.set_editor_property('import_animations', True)
# Direct import to scene and assets:
print 'Importing directly to scene...'
unreal.DeltaGenLibrary.import_(file_a, imported_scenes_path, base_options, None, False)
#2-stage import step 1:
print 'Parsing to scene object...'
scene = unreal.DatasmithDeltaGenSceneElement.construct_datasmith_scene_from_file(file_b, imported_scenes_path, base_options, dg_options)
print 'Resulting datasmith scene: ' + str(scene)
print '\tProduct name: ' + str(scene.get_product_name())
print '\tMesh actor count: ' + str(len(scene.get_all_mesh_actors()))
print '\tLight actor count: ' + str(len(scene.get_all_light_actors()))
print '\tCamera actor count: ' + str(len(scene.get_all_camera_actors()))
print '\tCustom actor count: ' + str(len(scene.get_all_custom_actors()))
print '\tMaterial count: ' + str(len(scene.get_all_materials()))
print '\tAnimationTimeline count: ' + str(len(scene.get_all_animation_timelines()))
print '\tVariant count: ' + str(len(scene.get_all_variants()))
# Modify one of the Timelines
# Warning: The Animation nested structure is all USTRUCTs, which are value types, and the Array accessor returns
# a copy. Meaning something like timeline[0].name = 'new_name' will set the name on the COPY of anim_nodes[0]
timelines = scene.get_all_animation_timelines()
if len(timelines) > 0:
tim_0 = timelines[0]
old_name = tim_0.name
print 'Timeline old name: ' + old_name
tim_0.name += '_MODIFIED'
modified_name = tim_0.name
print 'Anim node modified name: ' + modified_name
timelines[0] = tim_0
scene.set_all_animation_timelines(timelines)
# Check modification
new_timelines = scene.get_all_animation_timelines()
print 'Anim node retrieved modified name: ' + new_timelines[0].name
assert new_timelines[0].name == modified_name, "Node modification didn't work!"
# Restore to previous state
tim_0 = new_timelines[0]
tim_0.name = old_name
new_timelines[0] = tim_0
scene.set_all_animation_timelines(new_timelines)
# 2-stage import step 2:
print 'Importing assets and actors...'
result = scene.import_scene()
print 'Import results: '
print '\tImported actor count: ' + str(len(result.imported_actors))
print '\tImported mesh count: ' + str(len(result.imported_meshes))
print '\tImported level sequences: ' + str([a.get_name() for a in result.animations])
print '\tImported level variant sets asset: ' + str(result.level_variant_sets.get_name())
if result.import_succeed:
print 'Import succeeded!'
else:
print 'Import failed!'
|
import unreal
import os
def duplicate_assets():
# instances of unreal classes
editor_util = unreal.EditorUtilityLibrary()
editor_asset_lib = unreal.EditorAssetLibrary()
# get the selected assets
selected_assets = editor_util.get_selected_assets()
num_assets = len(selected_assets)
# hard coded value
num_copies = 5
total_num_copies = num_copies * num_copies
progress_text_label = "Duplicating Assets..."
running = True
with unreal.ScopedSlowTask(total_num_copies, progress_text_label) as slow_tasks:
# display dialog
slow_tasks.make_dialog(True)
for asset in selected_assets:
# get the asset name and the path to be duplicated
asset_name = asset.get_fname()
asset_path = editor_asset_lib.get_path_name_for_loaded_asset(asset)
source_path = os.path.dirname(asset_path)
for i in range(num_copies):
# if cancel btn is pressed
if slow_tasks.should_cancel():
running = False
break
new_name = "{}_{}".format(asset_name, i)
dest_path = os.path.join(source_path, new_name)
duplicate = editor_asset_lib.duplicate_asset(asset_path, dest_path)
slow_tasks.enter_progress_frame(1)
if duplicate is None:
unreal.log_warning("Duplicate from {} at {} already exists".format(source_path, dest_path))
if not running:
break
unreal.log("{} assets duplicated".format(num_assets))
|
import pyvfx_boilerplate.boilerplate_ui as bpui
try:
import maya.cmds as cmds
import maya.mel as mel
MAYA = True
except ImportError:
MAYA = False
try:
import nuke
NUKE = True
except ImportError:
NUKE = False
try:
import hou # noqa
HOUDINI = True
except ImportError:
HOUDINI = False
try:
import MaxPlus
THREEDSMAX = True
except ImportError:
THREEDSMAX = False
try:
import bpy
BLENDER = True
except ImportError:
BLENDER = False
try:
import unreal # noqa
UNREAL = True
except ImportError:
UNREAL = False
rootMenuName = "pyvfx"
def activate(dockable=False):
bpr = bpui.BoilerplateRunner(bpui.Boilerplate)
kwargs = {}
kwargs["dockable"] = dockable
bpr.run_main(**kwargs)
mcmd = "import pyvfx_boilerplate.menu\npyvfx_boilerplate.menu.activate({})"
if NUKE:
m = nuke.menu("Nuke")
menuname = "{}/boilerplate UI".format(rootMenuName)
m.addCommand("{}/boilerplate UI".format(rootMenuName), mcmd.format(""))
m.addCommand("{} dockable".format(menuname), mcmd.format("True"))
elif MAYA:
MainMayaWindow = mel.eval("$temp = $gMainWindow")
if not cmds.menu("pyvfxMenuItemRoot", exists=True):
cmds.menu(
"pyvfxMenuItemRoot",
label=rootMenuName,
parent=MainMayaWindow,
tearOff=True,
allowOptionBoxes=True,
)
cmds.menuItem(
label="boilerplate UI",
parent="pyvfxMenuItemRoot",
ec=True,
command=mcmd.format(""),
)
cmds.menuItem(
label="boilerplate UI dockable",
parent="pyvfxMenuItemRoot",
ec=True,
command=mcmd.format("True"),
)
elif HOUDINI:
print("add menu code here for Houdini")
activate()
elif UNREAL:
# http://golaem.com/project/-crowd-documentation/rendering-unreal-engine
# https://github.com/project/
print("add menu code here for Unreal")
activate()
elif THREEDSMAX:
def activate_dockable():
activate(True)
MaxPlus.MenuManager.UnregisterMenu(rootMenuName)
mb = MaxPlus.MenuBuilder(rootMenuName)
menuitem = "boilerplate UI"
menuitemD = "{} dockable".format(menuitem)
menulist = [
(menuitem, menuitem, activate),
(menuitemD, menuitemD, activate_dockable),
]
for item in menulist:
action = MaxPlus.ActionFactory.Create(item[0], item[1], item[2])
mb.AddItem(action)
menu = mb.Create(MaxPlus.MenuManager.GetMainMenu())
elif BLENDER:
# a little of This
# https://blender.stackexchange.com/project/-ht-upper-bar-append-add-menus-in-two-places
# and a little of this
# https://blenderartists.org/project/-a-custom-menu-option/project/
class PyvfxBoilerplateActivateOperator(bpy.types.Operator):
""" start the pyvfx_boilerplate ui"""
bl_idname = "pyvfx_boilerplate_activate"
bl_label = "boilerplate UI"
def execute(self, context):
activate()
return {"FINISHED"}
class TOPBAR_MT_pyvfx_menu(bpy.types.Menu):
""" create the pyvfx top menu and pyvfx menu item"""
bl_label = rootMenuName
def draw(self, context):
""" create the pyvfx menu item"""
layout = self.layout
layout.operator("pyvfx_boilerplate_activate")
def menu_draw(self, context):
""" create the pyvfx top menu"""
self.layout.menu("TOPBAR_MT_pyvfx_menu")
def register():
bpy.utils.register_class(PyvfxBoilerplateActivateOperator)
bpy.utils.register_class(TOPBAR_MT_pyvfx_menu)
bpy.types.TOPBAR_MT_editor_menus.append(TOPBAR_MT_pyvfx_menu.menu_draw)
def unregister():
bpy.utils.unregister_class(PyvfxBoilerplateActivateOperator)
bpy.types.TOPBAR_MT_editor_menus.remove(TOPBAR_MT_pyvfx_menu.menu_draw)
bpy.utils.unregister_class(TOPBAR_MT_pyvfx_menu)
register()
else:
activate()
|
import unreal
from .char_asset_common import *
HEAD_BONE = "Bip001-Head"
ROOT_BONE = "Root"
BONES_TO_CHECK = [HEAD_BONE]
LOOK_AT_AXIS_BS = unreal.Vector(0, -1, 0) # the vector in bone space
ORIENTATION_COS_THRESHOLD = 0.8
skeletal_meshes = []
ref_pose : unreal.AnimPose = None
check_res = True
msg = ""
bone_names : [unreal.Name] = []
# check root bone
def check_root_bone(
asset : unreal.SkeletalMesh,
ref_pose : unreal.AnimPose):
global ROOT_BONE
global check_res, msg, bone_names
if bone_names[0] != ROOT_BONE:
msg += f"[SKM Asset Checker] ้ชจ้ชผ็ฝๆ ผ '{asset.get_name()}' ็ๆ น้ชจ้ชผๅฝๅๅฟ
้กปไธบ '{ROOT_BONE}'\n"
check_res = False
return
# check head bone and root bone
def check_bones_existence(
asset : unreal.SkeletalMesh,
ref_pose : unreal.AnimPose):
global BONES_TO_CHECK
global check_res, msg, bone_names
for bone in BONES_TO_CHECK:
if bone not in bone_names:
msg += f"[SKM Asset Checker] ้ชจ้ชผ '{bone}' ๅจ้ชจ้ชผ็ฝๆ ผ '{asset.get_name()}' ไธญไธๅญๅจใ\n"
check_res = False
return
# Head bone's look at axis need to
# align with the forward vector in object space
def check_head_bone_orientation(
asset : unreal.SkeletalMesh,
ref_pose : unreal.AnimPose):
global HEAD_BONE, LOOK_AT_AXIS_BS
global check_res, msg, bone_names
head_bone_transform : unreal.Transform = ref_pose.get_bone_pose(HEAD_BONE, space=unreal.AnimPoseSpaces.WORLD)
look_at_axis_ws : unreal.Vector = (head_bone_transform.transform_direction(LOOK_AT_AXIS_BS))
look_at_axis_ws.normalize()
fwd_vector_ws : unreal.Vector = unreal.Vector(1, 0, 0)
cos = fwd_vector_ws.dot(look_at_axis_ws)
unreal.log(f'[SKM Asset Checker] look_at_axis_ws: {look_at_axis_ws}')
unreal.log(f'[SKM Asset Checker] dot product: {cos}')
if cos < ORIENTATION_COS_THRESHOLD:
msg += f"[SKM Asset Checker] ้ชจ้ชผ็ฝๆ ผ '{asset.get_name()}' ็้ชจ้ชผ '{HEAD_BONE}' ็ๆณจ่ง่ฝดๅ({LOOK_AT_AXIS_BS.x}, {LOOK_AT_AXIS_BS.y}, {LOOK_AT_AXIS_BS.z}) ไธ่ง่ฒๆจกๅ็ฉบ้ด็ๅๅ้็ธๅทฎ่ฟๅคง๏ผไธๆปก่ถณ่ง่ใ\n"
check_res = False
return
def main(jump_out_pass_window : bool = False) -> bool:
global skeletal_meshes
global msg
global bone_names
### CHECK IF SKELETAL MESH ###
skeletal_meshes = filter_out_skeletal_mesh()
### CHECK SKM ASSET ###
with unreal.ScopedEditorTransaction("SKM Check") as trans:
try:
for asset in skeletal_meshes:
skeleton : unreal.Skeleton = asset.get_editor_property('skeleton')
ref_pose : unreal.AnimPose = skeleton.get_reference_pose()
bone_names = ref_pose.get_bone_names()
check_bones_existence(asset, ref_pose)
check_root_bone(asset, ref_pose)
check_head_bone_orientation(asset, ref_pose)
msg += "\n"
if check_res:
if jump_out_pass_window:
unreal.EditorDialog.show_message(
title="Success",
message=f"[SKM Asset Checker] ้ชจ้ชผ็ฝๆ ผ '{asset.get_name()}' ๆฃๆฅ้่ฟใ",
message_type=unreal.AppMsgType.OK
)
return True
else:
raise Exception(f"้ชจ้ชผๆฃๆฅๅคฑ่ดฅ๏ผ\n{msg}")
trans.cancel()
return False
except Exception as e:
unreal.EditorDialog.show_message(
title="Error",
message=str(e),
message_type=unreal.AppMsgType.OK
)
trans.cancel()
return False
|
# -*- coding: utf-8 -*-
import unreal
def do_some_things(*args, **kwargs):
unreal.log("do_some_things start:")
for arg in args:
unreal.log(arg)
unreal.log("do_some_things end.")
|
# AdvancedSkeleton To ModularRig
# Copyright (C) Animation Studios
# email: [email protected]
# exported using AdvancedSkeleton version:x.xx
import unreal
import os
import re
engineVersion = unreal.SystemLibrary.get_engine_version()
asExportVersion = 'x.xx'
asExportTemplate = '4x'
asVariables = True
print ('AdvancedSkeleton To ModularControlRig (Unreal:'+engineVersion+') (AsExport:'+str(asExportVersion)+') (Template:'+asExportTemplate+')')
utilityBase = unreal.GlobalEditorUtilityBase.get_default_object()
selectedAssets = utilityBase.get_selected_assets()
if len(selectedAssets)<1:
raise Exception('Nothing selected, you must select a ControlRig')
selectedAsset = selectedAssets[0]
if selectedAsset.get_class().get_name() != 'ControlRigBlueprint':
raise Exception('Selected object is not a ControlRigBlueprint, you must select a ControlRigBlueprint')
blueprint = selectedAsset
RigGraphDisplaySettings = blueprint.get_editor_property('rig_graph_display_settings')
RigGraphDisplaySettings.set_editor_property('node_run_limit',256)
library = blueprint.get_local_function_library()
library_controller = blueprint.get_controller(library)
hierarchy = blueprint.hierarchy
hierarchy_controller = hierarchy.get_controller()
ModularRigController = blueprint.get_modular_rig_controller()
PreviousEndPlug = 'RigUnit_BeginExecution.ExecuteContext'
def asObjExists (obj):
RigElementKeys = hierarchy.get_all_keys()
LocObject = None
for key in RigElementKeys:
if key.name == obj:
return True
return False
def asGetKeyFromName (name):
all_keys = hierarchy.get_all_keys(traverse = True)
for key in all_keys:
if key.name == name:
return key
return ''
def asConnect (target_key_name, connector_key_name):
connector_key = asGetKeyFromName (connector_key_name)
target_key = asGetKeyFromName (target_key_name)
ModularRigController.connect_connector_to_element (connector_key, target_key)
def asAddFace ():
global PreviousEndPlug
pathName = selectedAsset.get_path_name()
dirName = os.path.dirname(pathName)
asFace = unreal.ControlRigBlueprintFactory.create_new_control_rig_asset(dirName+'/asFace')
asFace.set_auto_vm_recompile(False)
hierarchy2 = asFace.hierarchy
hierarchy2_controller = hierarchy2.get_controller()
rigVMModel = asFace.get_controller_by_name('RigVMModel')
rigVMModel.add_unit_node_from_struct_path('/project/.RigUnit_BeginExecution', 'Execute', unreal.Vector2D(0, 0), 'RigUnit_BeginExecution')
# Create FacePanel
hierarchy2_controller.add_null('ctrlBoxOffset', '', unreal.Transform(location=[0,0,9],rotation=[0,0,0],scale=[1,1,1]))
control_settings_ctrl_box = unreal.RigControlSettings()
control_settings_ctrl_box.animation_type = unreal.RigControlAnimationType.ANIMATION_CONTROL
control_settings_ctrl_box.control_type = unreal.RigControlType.VECTOR2D
control_settings_ctrl_box.display_name = 'None'
control_settings_ctrl_box.draw_limits = True
control_settings_ctrl_box.shape_color = unreal.LinearColor(1, 1, 0, 1)
control_settings_ctrl_box.shape_name = 'Square_Thick'
control_settings_ctrl_box.shape_visible = True
control_settings_ctrl_box.is_transient_control = False
control_settings_ctrl_box.limit_enabled = [unreal.RigControlLimitEnabled(False, False), unreal.RigControlLimitEnabled(False, False)]
control_settings_ctrl_box.minimum_value = unreal.RigHierarchy.make_control_value_from_vector2d(unreal.Vector2D(0, 0))
control_settings_ctrl_box.maximum_value = unreal.RigHierarchy.make_control_value_from_vector2d(unreal.Vector2D(0, 0))
control_settings_ctrl_box.primary_axis = unreal.RigControlAxis.Y
hierarchy2_controller.add_control('ctrlBox', unreal.RigElementKey(type=unreal.RigElementType.NULL, name='ctrlBoxOffset'), control_settings_ctrl_box, unreal.RigHierarchy.make_control_value_from_vector2d(unreal.Vector2D(0, 0)))
hierarchy2.set_control_shape_transform(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name='ctrlBox'), unreal.Transform(location=[0,0,0],rotation=[0,0,90],scale=[0.6,2,1]), True)
# Place FacePanel
rigVMModel.add_unit_node_from_struct_path('/project/.RigUnit_Item', 'Execute', unreal.Vector2D(-848, 384), 'Item')
rigVMModel.set_pin_default_value('Item.Item', '(Type=Connector,Name="Root")')
rigVMModel.set_pin_expansion('Item.Item', True)
rigVMModel.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(-496, 368), 'GetTransform')
rigVMModel.set_pin_default_value('GetTransform.Item', '(Type=Bone,Name="None")')
rigVMModel.set_pin_expansion('GetTransform.Item', True)
rigVMModel.set_pin_default_value('GetTransform.Space', 'GlobalSpace')
rigVMModel.set_pin_default_value('GetTransform.bInitial', 'False')
rigVMModel.add_template_node('Set Transform::Execute(in Item,in Space,in bInitial,in Value,in Weight,in bPropagateToChildren)', unreal.Vector2D(256, -32), 'Set Transform')
rigVMModel.resolve_wild_card_pin('Set Transform.Value', 'FTransform', '/project/.Transform')
rigVMModel.set_pin_default_value('Set Transform.Item', '(Type=Null,Name="ctrlBoxOffset")')
rigVMModel.set_pin_expansion('Set Transform.Item', True)
rigVMModel.set_pin_default_value('Set Transform.Space', 'GlobalSpace')
rigVMModel.set_pin_default_value('Set Transform.bInitial', 'False')
rigVMModel.set_pin_default_value('Set Transform.Value', '(Rotation=(X=0,Y=0,Z=0,W=1),Translation=(X=0,Y=0,Z=0),Scale3D=(X=1,Y=1,Z=1))')
rigVMModel.set_pin_expansion('Set Transform.Value', True)
rigVMModel.set_pin_expansion('Set Transform.Value.Rotation', False)
rigVMModel.set_pin_expansion('Set Transform.Value.Translation', False)
rigVMModel.set_pin_expansion('Set Transform.Value.Scale3D', False)
rigVMModel.set_pin_default_value('Set Transform.Weight', '1')
rigVMModel.set_pin_default_value('Set Transform.bPropagateToChildren', 'True')
rigVMModel.add_unit_node_from_struct_path('/project/.RigVMFunction_MathTransformMake', 'Execute', unreal.Vector2D(-480, 32), 'RigVMFunction_MathTransformMake')
rigVMModel.set_pin_default_value('RigVMFunction_MathTransformMake.Translation', '(X=0,Y=0,Z=-30)')
rigVMModel.set_pin_expansion('RigVMFunction_MathTransformMake.Translation', True)
rigVMModel.set_pin_default_value('RigVMFunction_MathTransformMake.Rotation', '(X=-0,Y=0.707107,Z=0,W=0.707107)')
rigVMModel.set_pin_expansion('RigVMFunction_MathTransformMake.Rotation', False)
rigVMModel.set_pin_default_value('RigVMFunction_MathTransformMake.Scale', '(X=2.000000,Y=2.000000,Z=2.000000)')
rigVMModel.set_pin_expansion('RigVMFunction_MathTransformMake.Scale', True)
rigVMModel.add_template_node('Multiply::Execute(in A,in B,out Result)', unreal.Vector2D(-176, 128), 'Multiply')
rigVMModel.resolve_wild_card_pin('Multiply.A', 'FTransform', '/project/.Transform')
rigVMModel.set_pin_default_value('Multiply.A', '(Rotation=(X=0,Y=0,Z=0,W=1),Translation=(X=0,Y=0,Z=0),Scale3D=(X=1,Y=1,Z=1))')
rigVMModel.set_pin_expansion('Multiply.A', False)
rigVMModel.set_pin_expansion('Multiply.A.Rotation', False)
rigVMModel.set_pin_expansion('Multiply.A.Translation', False)
rigVMModel.set_pin_expansion('Multiply.A.Scale3D', False)
rigVMModel.set_pin_default_value('Multiply.B', '(Rotation=(X=0,Y=0,Z=0,W=1),Translation=(X=0,Y=0,Z=0),Scale3D=(X=1,Y=1,Z=1))')
rigVMModel.set_pin_expansion('Multiply.B', False)
rigVMModel.set_pin_expansion('Multiply.B.Rotation', False)
rigVMModel.set_pin_expansion('Multiply.B.Translation', False)
rigVMModel.set_pin_expansion('Multiply.B.Scale3D', False)
rigVMModel.add_link('Item.Item', 'GetTransform.Item')
rigVMModel.add_link(PreviousEndPlug, 'Set Transform.ExecuteContext')
PreviousEndPlug='Set Transform.ExecuteContext'
rigVMModel.add_link('RigVMFunction_MathTransformMake.Result', 'Multiply.A')
rigVMModel.add_link('GetTransform.Transform', 'Multiply.B')
rigVMModel.add_link('Multiply.Result', 'Set Transform.Value')
ctrls=["ctrlBrow_R","ctrlBrow_L","ctrlEye_R","ctrlEye_L","ctrlCheek_R","ctrlCheek_L","ctrlNose_R","ctrlNose_L","ctrlLips_M","ctrlMouth_M","ctrlMouthCorner_R","ctrlMouthCorner_L","ctrlPhonemes_M","ctrlEmotions_M"]
ctrlXs=[-1.5,1.5, -1.5,1.5, -1.5,1.5, -1.5,1.5, 0,0, -1.5,1.5, -1.5,1.5, -1.5,1.5]
ctrlYs=[8.0,8.0, 5.5,5.5, 3,3, 1.5,1.5, 0.0, -1.5, -4.0,-4.0, -6.5,-6.5]
bsXps=["brow_innerRaiser_R","brow_innerRaiser_L","eye_left_R","eye_left_L","cheek_out_R","cheek_out_L","nose_wide_R","nose_wide_L","lip_left_M","mouth_wide_M","mouth_wide_R","mouth_wide_L","",""]
bsXns=["brow_innerlower_R","brow_innerlower_L","eye_right_R","eye_right_L","cheek_in_R","cheek_in_L","nose_narrow_R","nose_narrow_L","lip_right_M","mouth_narrow_M","mouth_narrow_R","mouth_narrow_L","",""]
bsYps=["brow_raiser_R","brow_raiser_L","eye_up_R","eye_up_L","cheek_raiser_R","cheek_raiser_L","nose_raiser_R","nose_raiser_L","lip_up_M","mouth_close","mouth_raiser_R","mouth_raiser_L","",""]
bsYns=["brow_lower_R","brow_lower_L","eye_down_R","eye_down_L","","","","","lip_down_M","mouth_open_M","mouth_lower_R","mouth_lower_L","",""]
# bss=["brow_innerRaiser_R","brow_innerlower_R","brow_raiser_R","brow_lower_R","brow_squeeze_R","brow_outerUpDown_R","brow_innerRaiser_L","brow_innerlower_L","brow_raiser_L","brow_lower_L","brow_squeeze_L","brow_outerUpDown_L","eye_left_R","eye_right_R","eye_up_R","eye_down_R","blink_R","squint_R","eye_left_L","eye_right_L","eye_up_L","eye_down_L","blink_L","squint_L","cheek_out_R","cheek_in_R","cheek_raiser_R","cheek_out_L","cheek_in_L","cheek_raiser_L","nose_wide_R","nose_narrow_R","nose_raiser_R","nose_wide_L","nose_narrow_L","nose_raiser_L","lip_left_M","lip_right_M","lip_up_M","lip_down_M","lip_upperPressPos_M","lip_upperPressNeg_M","lip_lowerPressPos_M","lip_lowerPressNeg_M","lip_upperSqueezePos_M","lip_upperSqueezeNeg_M","lip_lowerSqueezePos_M","lip_lowerSqueezeNeg_M","lip_upperRollPos_M","lip_upperRollNeg_M","lip_lowerRollPos_M","lip_lowerRollNeg_M","lip_upperPuckerPos_M","lip_upperPuckerNeg_M","lip_lowerPuckerPos_M","lip_lowerPuckerNeg_M",
#"mouth_wide_M","mouth_narrow_M","mouth_close_M","mouth_open_M","mouth_jawForwardIn_M","mouth_jawForwardOut_M","mouth_jawSideIn_M","mouth_jawSideOut_M","mouth_wide_R","mouth_narrow_R","mouth_raiser_R","mouth_lower_R","mouth_wide_L","mouth_narrow_L","mouth_raiser_L","mouth_lower_L","aaa_M","eh_M","ahh_M","ohh_M","uuu_M","iee_M","rrr_M","www_M","sss_M","fff_M","tth_M","mbp_M","ssh_M","schwa_M","gk_M","lntd_M","happy_M","angry_M","sad_M","surprise_M","fear_M","disgust_M","contempt_M"]
yPos=600
#PreviousEndPlug = 'RigUnit_BeginExecution.ExecuteContext'
for i in range(len(ctrls)):
ctrl = ctrls[i]
maxX = float (1)
minX = float (-1)
maxY = float (1)
minY = float (-1)
limitEnabled = True
if re.search("ctrlCheek_", ctrl) or re.search("ctrlNose_", ctrl):
minY = 0
if ctrl=="ctrlMouth_M":
maxY = 0
if ctrl=="ctrlPhonemes_M" or ctrl=="ctrlEmotions_M":
limitEnabled = False
minX = 0
minY = 0
x = ctrl.split("_")
if len(x)>1:
baseName = x[0]
side = '_'+x[1]
attrExtras=[]
bsExtras=[]
if re.search("ctrlBrow_", ctrl):
attrExtras=["squeeze"+side,"outerUpDown"+side] #Unreal seems to not work well with Left & Righ ctrl using same named ctrl
bsExtras=["brow_squeeze"+side,"brow_outerUpDown"+side]
if re.search("ctrlEye_", ctrl):
attrExtras=["blink"+side,"squint"+side]
bsExtras=["blink"+side,"squint"+side]
if ctrl=="ctrlLips_M":
attrExtras=["upperPress"+side,"lowerPress"+side,"upperSqueeze"+side,"lowerSqueeze"+side,"upperRoll"+side,"lowerRoll"+side,"upperPucker"+side,"lowerPucker"+side]
bsExtras=["lip_upperPressPos_M","lip_lowerPressPos_M","lip_upperSqueezePos_M","lip_lowerSqueezePos_M","lip_upperRollPos_M","lip_lowerRollPos_M","lip_upperPuckerPos_M","lip_lowerPuckerPos_M"]
if ctrl=="ctrlMouth_M":
attrExtras=["jawForward"+side,"jawSide"+side]
bsExtras=["mouth_jawForwardIn_M","mouth_jawSideIn_M"]
if ctrl=="ctrlEmotions_M":
attrExtras=["happy"+side,"angry"+side,"sad"+side,"surprise"+side,"fear"+side,"disgust"+side,"contempt"+side]
bsExtras=["happy_M","angry_M","sad_M","surprise_M","fear_M","disgust_M","contempt_M"]
xForm = unreal.Transform(location=[ctrlXs[i],0,ctrlYs[i]],rotation=[0,0,0],scale=[1,1,1])
settings = unreal.RigControlSettings()
settings.animation_type = unreal.RigControlAnimationType.ANIMATION_CONTROL
settings.control_type = unreal.RigControlType.VECTOR2D
settings.display_name = 'None'
settings.draw_limits = limitEnabled
settings.shape_color = unreal.LinearColor(1, 1, 0, 1)
settings.shape_name = 'Default'
settings.shape_visible = True
settings.is_transient_control = False
settings.limit_enabled = [unreal.RigControlLimitEnabled(limitEnabled, limitEnabled), unreal.RigControlLimitEnabled(limitEnabled, limitEnabled)]
settings.minimum_value = unreal.RigHierarchy.make_control_value_from_vector2d(unreal.Vector2D(minX, minY))
settings.maximum_value = unreal.RigHierarchy.make_control_value_from_vector2d(unreal.Vector2D(maxX, maxY))
settings.primary_axis = unreal.RigControlAxis.Y
hierarchy2_controller.add_control(ctrl, unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name='ctrlBox'), settings, unreal.RigHierarchy.make_control_value_from_vector2d(unreal.Vector2D(0, 0)))
hierarchy2.set_control_shape_transform(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=ctrl), unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[0.050000,0.050000,0.050000]), True)
hierarchy2.set_control_offset_transform(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=ctrl), xForm, True, True)
hierarchy2.set_control_value(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=ctrl), unreal.RigHierarchy.make_control_value_from_vector2d(unreal.Vector2D(0, 0)), unreal.RigControlValueType.CURRENT)
#addAttr
for y in range(len(attrExtras)):
settings = unreal.RigControlSettings()
settings.animation_type = unreal.RigControlAnimationType.ANIMATION_CHANNEL
settings.control_type = unreal.RigControlType.FLOAT
settings.display_name = attrExtras[y]
settings.draw_limits = True
settings.shape_color = unreal.LinearColor(1.000000, 0.000000, 0.000000, 1.000000)
settings.shape_name = 'Default'
settings.shape_visible = True
settings.is_transient_control = False
settings.limit_enabled = [unreal.RigControlLimitEnabled(False, False)]
settings.minimum_value = unreal.RigHierarchy.make_control_value_from_float(0.000000)
settings.maximum_value = unreal.RigHierarchy.make_control_value_from_float(1.000000)
settings.primary_axis = unreal.RigControlAxis.X
hierarchy2_controller.add_control(attrExtras[y], unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=ctrl), settings, unreal.RigHierarchy.make_control_value_from_float(0.000000))
#attr loop
for x in range(4+len(bsExtras)):
if x==0:
bs = bsXps[i]
mult = '1'
axis = 'X'
if x==1:
bs = bsXns[i]
mult = '-1'
axis = 'X'
if x==2:
bs = bsYps[i]
mult = '1'
axis = 'Y'
if x==3:
bs = bsYns[i]
mult = '-1'
axis = 'Y'
if x>3:
bs = bsExtras[x-4]
mult = '1'
axis = attrExtras[x-4]
if bs=='':
continue
hierarchy2_controller.add_curve(bs, 0)
scv = rigVMModel.add_unit_node_from_struct_path('/project/.RigUnit_SetCurveValue', 'Execute', unreal.Vector2D(200, yPos), 'SetCurveValue').get_name()
rigVMModel.set_pin_default_value(scv+'.Curve', bs)
# rigVMModel.add_link(c+'.Result', scv+'.Value')
rigVMModel.add_link(PreviousEndPlug, scv+'.ExecuteContext')
PreviousEndPlug = scv+'.ExecuteContext'
if x>3:
gac = rigVMModel.add_template_node('GetAnimationChannel::Execute(out Value,in Control,in Channel,in bInitial)', unreal.Vector2D(-550, yPos), 'RigUnit_GetFloatAnimationChannel').get_name()
rigVMModel.set_pin_default_value(gac+'.Control', ctrl)
rigVMModel.set_pin_default_value(gac+'.Channel', axis)
rigVMModel.resolve_wild_card_pin(gac+'.Value', 'float', 'None')
rigVMModel.add_link(gac+'.Value', scv+'.Value')
else:
gcv = rigVMModel.add_unit_node_from_struct_path('/project/.RigUnit_GetControlVector2D', 'Execute', unreal.Vector2D(-550, yPos), 'GetControlVector2D').get_name()
rigVMModel.set_pin_default_value(gcv+'.Control', ctrl)
m = rigVMModel.add_template_node('Multiply::Execute(in A,in B,out Result)', unreal.Vector2D(-200, yPos), 'Multiply').get_name()
c = rigVMModel.add_template_node('Clamp::Execute(in Value,in Minimum,in Maximum,out Result)', unreal.Vector2D(0, yPos), 'Clamp').get_name()
rigVMModel.add_link(gcv+'.Vector.'+axis, m+'.A')
rigVMModel.add_link(m+'.Result', c+'.Value')
rigVMModel.set_pin_default_value(c+'.Maximum', '100')
rigVMModel.add_link(c+'.Result', scv+'.Value')
rigVMModel.set_pin_default_value(m+'.B', mult)
#eyeRot
if re.search("ctrlEye_", ctrl) and x==2:
eyeMultX = rigVMModel.add_template_node('Multiply::Execute(in A,in B,out Result)', unreal.Vector2D(512, yPos ), 'MultiplyX').get_name()
eyeMultY = rigVMModel.add_template_node('Multiply::Execute(in A,in B,out Result)', unreal.Vector2D(512, yPos+100), 'MultiplyY').get_name()
rigVMModel.resolve_wild_card_pin(eyeMultX+'.A', 'double', 'None')
rigVMModel.resolve_wild_card_pin(eyeMultY+'.A', 'double', 'None')
rigVMModel.set_pin_default_value(eyeMultX+'.A', '1.000000')
rigVMModel.set_pin_default_value(eyeMultY+'.A', '1.000000')
rigVMModel.set_pin_default_value(eyeMultX+'.B', '30.000000')
rigVMModel.set_pin_default_value(eyeMultY+'.B', '30.000000')
qfu = rigVMModel.add_unit_node_from_struct_path('/project/.RigVMFunction_MathQuaternionFromEuler', 'Execute', unreal.Vector2D(705, yPos), 'RigVMFunction_MathQuaternionFromEuler').get_name()
rigVMModel.set_pin_default_value(qfu+'.Euler', '(X=0.000000,Y=0.000000,Z=0.000000)')
rigVMModel.set_pin_expansion(qfu+'.Euler', True)
rigVMModel.set_pin_default_value(qfu+'.RotationOrder', 'ZYX')
rigVMModel.add_link(gcv+'.Vector.X', eyeMultX+'.A')
rigVMModel.add_link(gcv+'.Vector.Y', eyeMultY+'.A')
rigVMModel.add_link(eyeMultX+'.Result', qfu+'.Euler.Y')
rigVMModel.add_link(eyeMultY+'.Result', qfu+'.Euler.X')
srt = rigVMModel.add_template_node('Set Relative Transform::Execute(in Child,in Parent,in bParentInitial,in Value,in Weight,in bPropagateToChildren)', unreal.Vector2D(1056, yPos), 'RigUnit_SetRelativeTransformForItem').get_name()
rigVMModel.set_pin_default_value(srt+'.Child', '(Type=Bone,Name="unrealEyeJoint'+side+'")')
rigVMModel.set_pin_default_value(srt+'.Parent', '(Type=Bone,Name="unrealEyeJoint'+side+'")')
rigVMModel.resolve_wild_card_pin(srt+'.Value', 'FTransform', '/project/.Transform')
rigVMModel.add_link(qfu+'.Result', srt+'.Value.Rotation')
rigVMModel.add_link(PreviousEndPlug, srt+'.ExecuteContext')
PreviousEndPlug = srt+'.ExecuteContext'
yPos = yPos+200
# asFace.recompile_modular_rig()
all_keys2 = hierarchy2.get_all_keys(traverse = True)
asFace.convert_hierarchy_elements_to_spawner_nodes(hierarchy2,all_keys2)
asFace.turn_into_control_rig_module()
unreal.BlueprintEditorLibrary.compile_blueprint(asFace)
#blueprint.recompile_modular_rig()
unreal.EditorAssetLibrary.save_asset(dirName+'/asFace', only_if_is_dirty=False)
module_class = unreal.load_class(None, (dirName+'/asFace.asFace_C'))
ModularRigController.add_module (module_name='asFace', class_= module_class , parent_module_path='Root:Spine:Neck')
unreal.BlueprintEditorLibrary.compile_blueprint(blueprint)
def main ():
RigElementKeys = hierarchy.get_all_keys()
target_key = asGetKeyFromName ('spine_01_socket')
if not (target_key):
#remove old sockets
for key in RigElementKeys:
x = re.search("_socket", str(key.name))
if x:
hierarchy_controller.remove_element(key)
hierarchy_controller.add_socket('spine_01_socket', unreal.RigElementKey(type=unreal.RigElementType.BONE, name='spine_01'), unreal.Transform(location=[0,0,0],rotation=[-0,0,-0],scale=[1,1,1]), False, unreal.LinearColor(1, 1, 1, 1), '')
hierarchy_controller.add_socket('neck_socket', unreal.RigElementKey(type=unreal.RigElementType.BONE, name='neck'), unreal.Transform(location=[0,0,0],rotation=[-0,0,-0],scale=[1,1,1]), False, unreal.LinearColor(1, 1, 1, 1), '')
for side in ['_r','_l']:
hierarchy_controller.add_socket('shoulder'+side+'_socket', unreal.RigElementKey(type=unreal.RigElementType.BONE, name='upperArm'+side), unreal.Transform(location=[0,0,0],rotation=[-0,0,-0],scale=[1,1,1]), False, unreal.LinearColor(1, 1, 1, 1), '')
hierarchy_controller.add_socket('hand'+side+'_socket', unreal.RigElementKey(type=unreal.RigElementType.BONE, name='hand'+side), unreal.Transform(location=[0,0,0],rotation=[-0,0,-0],scale=[1,1,1]), False, unreal.LinearColor(1, 1, 1, 1), '')
module_class = unreal.load_class(None, '/project/.Spine_C')
ModularRigController.add_module (module_name='Spine', class_= module_class , parent_module_path='Root')
# ModularRigController.set_config_value_in_module('Root','Scale Root Controls Override','2')
# ModularRigController.set_config_value_in_module('Root:Spine','Module Settings','Control Size=3')
#blueprint.add_member_variable('test6','ModuleSettings')
#vars = blueprint.get_member_variables ()
#x = getattr(vars[0], 'default_value')
#ModularRigController.bind_module_variable('Root:Spine','Module Settings','test3')
module_class = unreal.load_class(None, '/project/.Neck_C')
ModularRigController.add_module (module_name='Neck', class_= module_class , parent_module_path='Root:Spine')
for side in ['_r','_l']:
module_class = unreal.load_class(None, '/project/.Shoulder_C')
ModularRigController.add_module (module_name='Shoulder'+side, class_= module_class , parent_module_path='Root:Spine')
module_class = unreal.load_class(None, '/project/.Arm_C')
ModularRigController.add_module (module_name='Arm'+side, class_= module_class , parent_module_path='Root:Spine:Shoulder'+side)
module_class = unreal.load_class(None, '/project/.Leg_C')
ModularRigController.add_module (module_name='Leg'+side, class_= module_class , parent_module_path='Root')
for finger in ['index','middle','ring','pinky','thumb']:
module_class = unreal.load_class(None, '/project/.Finger_C')
ModularRigController.add_module (module_name='Finger'+finger+side, class_= module_class , parent_module_path='Root:Spine:Shoulder'+side+':Arm'+side)
if includeFaceRig:
asAddFace ()
print ('First run Complete, Now open the ControlRig, then run the python-script again.')
return
asConnect ('root' , 'Root:Root')
asConnect ('spine_01_socket' , 'Root:Spine:Spine Primary')
asConnect ('spine_05' , 'Root:Spine:Spine End Bone')
asConnect ('neck_socket' , 'Root:Spine:Neck:Neck Primary')
asConnect ('neck_01' , 'Root:Spine:Neck:Neck Start Bone')
asConnect ('head' , 'Root:Spine:Neck:Head Bone')
for side in ['_r','_l']:
asConnect ('shoulder'+side+'_socket' , 'Root:Spine:Shoulder'+side+':Shoulder Primary')
asConnect ('spine_05' , 'Root:Spine:Shoulder'+side+':Chest Bone')
asConnect ('hand'+side+'_socket' , 'Root:Spine:Shoulder'+side+':Arm'+side+':Arm Primary')
asConnect ('spine_01_socket' , 'Root:Leg'+side+':Leg Primary')
asConnect ('thigh'+side , 'Root:Leg'+side+':Thigh Bone')
asConnect ('foot'+side , 'Root:Leg'+side+':Foot Bone')
for finger in ['index','middle','ring','pinky','thumb']:
asConnect ('hand'+side+'_socket' , 'Root:Spine:Shoulder'+side+':Arm'+side+':Finger'+finger+side+':Finger Primary')
if finger == 'thumb':
asConnect (finger+'_01'+side , 'Root:Spine:Shoulder'+side+':Arm'+side+':Finger'+finger+side+':Start Bone')
else:
asConnect (finger+'_metacarpal'+side , 'Root:Spine:Shoulder'+side+':Arm'+side+':Finger'+finger+side+':Start Bone')
asConnect (finger+'_03'+side , 'Root:Spine:Shoulder'+side+':Arm'+side+':Finger'+finger+side+':End Bone')
if includeFaceRig:
asConnect ('head' , 'Root:Spine:Neck:asFace:Root')
print ('Second run complete.')
if __name__ == "__main__":
main()
|
import unreal
import re
from typing import List, Literal
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) -> object :
#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[object] = 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)
ar_numbers = re.findall("\d+", str_selected_asset)
i_number = ar_numbers[0]
print(ar_numbers)
print(i_number)
num = int(i_number)
BaseBP :str = '/project/'
BaseAnimBP :str = '/project/'
Basepath :str = '/project/' + str(num) + '/'
assetPath :str = Basepath + '/project/'
bsNames :List[str] = ["IdleRun_BS_Peaceful", "IdleRun_BS_Battle", "Down_BS", "Groggy_BS", "LockOn_BS", "Airborne_BS"]
Base1D :str = Basepath + "Base_BS_1D"
Base2D :str = Basepath + "Base_BS_2D"
defaultSamplingVector :object = unreal.Vector(0.0, 0.0, 0.0)
defaultSampler :object = unreal.BlendSample()
defaultSampler.set_editor_property("sample_value",defaultSamplingVector)
for i in bsNames:
bsDir = assetPath + i
#2D BS๋ก ์ ์ํด์ผํ ๊ฒฝ์ฐ / LockOn_BS
if i == "LockOn_BS":
unreal.EditorAssetLibrary.duplicate_asset(Base2D,bsDir)
else:
BSLoaded = unreal.EditorAssetLibrary.duplicate_asset(Base1D,bsDir)
'''BP setting start'''
BPPath = Basepath + '/Blueprints/' + "CH_M_NA_" + str(num) + "_Blueprint"
AnimBPPath = Basepath + '/Blueprints/' + "CH_M_NA_" + str(num) + "_AnimBP"
SkeletonPath = Basepath + "CH_M_NA_" + str(num) + "_Skeleton"
Skeleton = unreal.EditorAssetLibrary.load_asset(SkeletonPath)
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)
|
๏ปฟ"""
Fixes the environment lighting in the scene by spawning and setting up the required light actors.
This script searches for any existing environment light actors in the level and removes them.
It then spawns and configures new light actors such as SkySphere, Directional Light, Post Process Volume,
Skylight, Atmospheric Fog, and Sphere Reflection Capture to set up the environment lighting.
Parameters:
- location: A tuple of three floats representing the initial location for spawning the light actors.
- shift: A tuple of three floats representing the shift to apply to the location for each spawned light actor.
- sun_brightness: The brightness of the sun in the SkySphere.
- sun_height: The height of the sun in the SkySphere.
- cloud_speed: The speed of the clouds in the SkySphere.
- cloud_opacity: The opacity of the clouds in the SkySphere.
- color_saturation: The saturation for PostProcessVolume
- direction_light_intensity: The intensity of the Directional Light.
- direction_light_rotation: A tuple of three floats representing the rotation of the Directional Light.
- direction_light_color: A tuple of four floats representing the color of the Directional Light in RGBA format.
- sky_light_scale: The intensity scale of the Skylight.
- folder: The folder path where the spawned actors will be placed in the editor.
Example:
To fix the environment lighting, call the `fix_environment_light` function without any arguments.
fix_environment_light()
"""
from typing import Tuple
import unreal
from Common import spawn_actor_from_class
def fix_environment_light(
location: Tuple[float, float, float] = (0.0, 0.0, 0.0),
shift: Tuple[float, float, float] = (-200.0, 0.0, 0.0),
sun_brightness: float = 75.0,
sun_height: float = 0.736771,
cloud_speed: float = 2.0,
cloud_opacity: float = 1.0,
color_saturation: float = 1.5,
direction_light_intensity: float = 2.0,
direction_light_rotation: Tuple[float, float, float] = (0, -55.0, -45.0),
direction_light_color: Tuple[float, float, float, float] = (1.0, 1.0, 0.760525, 1.0),
sky_light_scale: float = 3.5,
folder: str = "Lighting"
):
location = unreal.Vector(*location)
shift = unreal.Vector(*shift)
folder = unreal.Name(folder)
direction_light_rotation = unreal.Rotator(*direction_light_rotation)
color_saturation = unreal.Vector4(1.0, 1.0, 1.0, color_saturation)
for actor in unreal.EditorLevelLibrary.get_all_level_actors():
name: str = actor.get_name()
if not name.startswith("light_environment"):
continue
print(f"Setup destroy bad environment light: {actor}")
path = actor.get_path_name()
actor.destroy_actor()
unreal.EditorAssetLibrary.delete_asset(path)
bp_sky_sphere = unreal.EditorAssetLibrary.load_blueprint_class("/project/")
sky_sphere = spawn_actor_from_class(bp_sky_sphere, location)
sky_sphere.set_folder_path(folder)
sky_sphere.set_actor_label("SkySphere")
sky_sphere.set_editor_property("Sun Brightness", sun_brightness)
sky_sphere.set_editor_property("Cloud Speed", cloud_speed)
sky_sphere.set_editor_property("Cloud Opacity", cloud_opacity)
sky_sphere.set_editor_property("Cloud Opacity", cloud_opacity)
sky_sphere.set_editor_property("Sun Height", sun_height)
location += shift
directional_light = spawn_actor_from_class(unreal.DirectionalLight, location)
directional_light.set_folder_path(folder)
directional_light.set_actor_rotation(direction_light_rotation, True)
directional_light.light_component.set_intensity(direction_light_intensity)
directional_light.light_component.set_atmosphere_sun_light(True)
directional_light.light_component.set_light_color(unreal.LinearColor(*direction_light_color))
location += shift
post_process_volume = spawn_actor_from_class(unreal.PostProcessVolume, location)
post_process_volume.set_folder_path(folder)
post_process_volume.unbound = True
settings = post_process_volume.settings
settings.override_auto_exposure_bias = True
settings.override_auto_exposure_min_brightness = True
settings.override_auto_exposure_max_brightness = True
settings.override_color_saturation = True
settings.auto_exposure_bias = 0.0
settings.auto_exposure_min_brightness = 1.0
settings.auto_exposure_max_brightness = 1.0
settings.color_saturation = color_saturation
location += shift
sky_light = spawn_actor_from_class(unreal.SkyLight, location)
sky_light.set_folder_path(folder)
sky_light.light_component.set_intensity(sky_light_scale)
location += shift
atmospheric_fog = spawn_actor_from_class(unreal.AtmosphericFog, location)
atmospheric_fog.set_folder_path(folder)
atmospheric_fog.atmospheric_fog_component.set_precompute_params(
density_height=0.5,
max_scattering_order=4,
inscatter_altitude_sample_num=32)
location += shift
sphere_reflection_capture = spawn_actor_from_class(unreal.SphereReflectionCapture, location)
sphere_reflection_capture.set_folder_path(folder)
location += shift
if __name__ == '__main__':
fix_environment_light()
|
# This scripts describes the process of capturing an managing properties with a little more
# detail than test_variant_manager.py
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()
var_set1 = unreal.VariantSet()
var_set1.set_display_text("My VariantSet")
var1 = unreal.Variant()
var1.set_display_text("Variant 1")
# Adds the objects to the correct parents
lvs.add_variant_set(var_set1)
var_set1.add_variant(var1)
# Spawn a simple cube static mesh actor
cube = unreal.EditorAssetLibrary.load_asset("StaticMesh'/project/.Cube'")
spawned_actor = None
if cube:
location = unreal.Vector()
rotation = unreal.Rotator()
spawned_actor = unreal.EditorLevelLibrary.spawn_actor_from_object(cube, location, rotation)
spawned_actor.set_actor_label("Cube Actor")
else:
print ("Failed to find Cube asset!")
if spawned_actor is None:
print ("Failed to spawn an actor for the Cube asset!")
quit()
# Bind spawned_actor to all our variants
var1.add_actor_binding(spawned_actor)
# See which properties can be captured from any StaticMeshActor
capturable_by_class = unreal.VariantManagerLibrary.get_capturable_properties(unreal.StaticMeshActor.static_class())
# See which properties can be captured from our specific spawned_actor
# This will also return the properties for any custom component structure we might have setup on the actor
capturable_props = unreal.VariantManagerLibrary.get_capturable_properties(spawned_actor)
print ("Capturable properties for actor '" + spawned_actor.get_actor_label() + "':")
for prop in capturable_props:
print ("\t" + prop)
print ("Capturable properties for its class:")
for prop in capturable_by_class:
print ("\t" + prop)
# Returns nullptr for invalid paths. This will also show an error in the Output Log
prop1 = var1.capture_property(spawned_actor, "False property path")
assert prop1 is None
# Comparison is case insensitive: The property is named "Can be Damaged", but this still works
prop2 = var1.capture_property(spawned_actor, "cAn Be DAMAged")
assert prop2 is not None and prop2.get_full_display_string() == "Can be Damaged"
# Attempts to capture the same property more than once are ignored, and None is returned
prop2attempt2 = var1.capture_property(spawned_actor, "Can Be Damaged")
assert prop2attempt2 is None
# Check which properties have been captured for some actor in a variant
print ("Captured properties for '" + spawned_actor.get_actor_label() + "' so far:")
captured_props = var1.get_captured_properties(spawned_actor)
for captured_prop in captured_props:
print ("\t" + captured_prop.get_full_display_string())
# Capture property in a component
prop3 = var1.capture_property(spawned_actor, "Static Mesh Component / Relative Location")
assert prop3 is not None and prop3.get_full_display_string() == "Static Mesh Component / Relative Location"
# Can't capture the component itself. This will also show an error in the Output Log
prop4 = var1.capture_property(spawned_actor, "Static Mesh Component")
assert prop4 is None
# Capture material property
prop5 = var1.capture_property(spawned_actor, "Static Mesh Component / Material[0]")
assert prop5 is not None
# Removing property captures
var1.remove_captured_property(spawned_actor, prop2)
var1.remove_captured_property_by_name(spawned_actor, "Static Mesh Component / Relative Location")
print ("Captured properties for '" + spawned_actor.get_actor_label() + "' at the end:")
captured_props = var1.get_captured_properties(spawned_actor)
for captured_prop in captured_props:
print ("\t" + captured_prop.get_full_display_string())
# Should only have the material property left
assert len(captured_props) == 1 and captured_props[0].get_full_display_string() == "Static Mesh Component / Material[0]"
|
import unreal
mat_mi_clear = "/project/.uasset"
loaded_mat_clear = unreal.load_asset(mat_mi_clear)
loaded_subsystem = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem)
selected_assets: list[unreal.Object] = unreal.EditorUtilityLibrary.get_selected_assets()
selected_sm:unreal.SkeletalMesh = selected_assets[0]
target_diffuse_display_name: str
sm_materials = selected_sm.materials
sm_mats_length = len(selected_sm.materials)
sm_path = selected_sm.get_path_name()
sm_folder = '/'.join(sm_path.split('/')[:-1])
outline_folder_path = sm_folder + '/project/'
duplicate_this_outline = outline_folder_path + '/' + selected_sm.get_name() + '_Outline_Vrm4u'
does_main_outline_exist = loaded_subsystem.does_asset_exist(duplicate_this_outline)
if does_main_outline_exist == False:
print('Character main vrm4u outline does not exist')
exit()
loaded_be_duplicated = unreal.load_asset(duplicate_this_outline)
## duplicate outline materials
outline_materials = []
for sm_material in sm_materials:
sm_material: unreal.SkeletalMaterial
loaded_sm_mat = sm_material.material_interface # .get_path_name().split('/')[0] + '_Outline'
outline_mat_name = loaded_sm_mat.get_name() + '_Outline_Vrm4u'
outline_path_name = outline_folder_path + '/' + outline_mat_name
check = loaded_subsystem.does_asset_exist(outline_path_name)
if check == True:
outline_materials.append(unreal.load_asset(outline_path_name))
else:
outline_materials.append(loaded_mat_clear)
# find data asset
destination_path_array = selected_sm.get_path_name().split('/')
new_da_path = '/'.join(destination_path_array[:-1]) + '/DA_' + selected_sm.get_name()
blueprint_asset = unreal.EditorAssetLibrary.load_asset(new_da_path)
# set outline materials to data asset
property_info = {'Outline_Materials': outline_materials}
blueprint_asset.set_editor_properties(property_info)
loaded_subsystem.save_asset(new_da_path)
|
import unreal
@unreal.uclass()
class PythonBridgeImplementation(unreal.PythonBridge):
@unreal.ufunction(override=True)
def function_implemented_in_python(self):
unreal.log_warning("Wow! This is the BEST")
|
import unreal
unreal.log("123131231232")
# ๅปบ่ฎฎdatasmithๅฏผๅ
ฅ็ดๆฅ็github็repo: https://github.com/arash-sh/project/.py
def import_3dxml(file_path, destination_path="/project/"):
"""
ๅฏผๅ
ฅ 3DXML ๆไปถๅฐ Unreal Engine ไธญใ
ๅๆฐ:
file_path (str): 3DXML ๆไปถ็ๅฎๆด่ทฏๅพใ
destination_path (str): ๅฏผๅ
ฅๅ่ตไบงๅจ Unreal Engine ไธญ็ๅญๅจ่ทฏๅพใ
"""
# ่ทๅ Datasmith ๅฏผๅ
ฅๅจ
datasmith_factory = unreal.DatasmithImportFactory()
# ่ฎพ็ฝฎๅฏผๅ
ฅ้้กน
import_options = unreal.DatasmithImportOptions()
import_options.base_options.import_type = unreal.DatasmithImportType.ASSETS
# import_options.base_options.asset_options =
import_options.base_options.include_animation = False
import_options.base_options.include_camera = False
import_options.base_options.include_geometry = True
import_options.base_options.include_light = False
import_options.base_options.include_material = False
import_options.base_options.scene_handling = unreal.DatasmithImportScene.ASSETS_ONLY
import_options.base_options.static_mesh_options.max_lightmap_resolution = 64
import_options.base_options.static_mesh_options.min_lightmap_resolution = 16
import_options.base_options.static_mesh_options.generate_lightmap_u_vs = False
# import_options.file_path = file_path
# import_options.file_name = file_name
datasmith_factory = unreal.DatasmithImportFactory()
# ๅๅปบๅฏผๅ
ฅไปปๅก
import_task = unreal.AssetImportTask()
import_task.set_editor_property("async_",True) # Perform the import asynchronously for file formats where async import is available
import_task.set_editor_property("automated", True) # avoid dialog box
import_task.set_editor_property("destination_path", destination_path)
import_task.set_editor_property("factory", datasmith_factory)
import_task.set_editor_property("filename", file_name) # Filename to import
import_task.set_editor_property("options", import_options)
import_task.set_editor_property("replace_existing ", True)
import_task.set_editor_property("save",False)
# use GetObject() to get the object that was imported
if (is_async_import_complete(import_task)):
imported_object = import_task.get_editor_property("imported_object")
if imported_object:
unreal.log(f"Successfully imported: {imported_object.get_name()}")
else:
unreal.log_warning("Import failed. Please check the file path or file format.")
# ๆง่กๅฏผๅ
ฅไปปๅก
unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks([import_task])
# ๆๅฐๅฏผๅ
ฅ็ปๆ
if import_task.imported_object_paths:
for imported_object in import_task.imported_object_paths:
unreal.log(f"ๆๅๅฏผๅ
ฅ: {imported_object}")
else:
unreal.log_warning("ๅฏผๅ
ฅๅคฑ่ดฅ๏ผ่ฏทๆฃๆฅๆไปถ่ทฏๅพๆๆไปถๆ ผๅผๆฏๅฆๆญฃ็กฎใ")
# ไฝฟ็จ็คบไพ
# ๆฟๆขไธบไฝ ็ 3DXML ๆไปถ่ทฏๅพ
file_path = r"D:/project/.3dxml"
import_3dxml(file_path)
# TODO:datasmithๅบๆฏ
|
๏ปฟ# coding: utf-8
import unreal
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-vrm")
parser.add_argument("-rig")
parser.add_argument("-debugeachsave")
args = parser.parse_args()
#print(args.vrm)
######
rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints()
print(rigs)
for r in rigs:
s:str = r.get_path_name()
ss:str = args.rig
if (s.find(ss) < 0):
print("no rig")
else:
rig = r
h_mod = rig.get_hierarchy_modifier()
elements = h_mod.get_selection()
print(unreal.SystemLibrary.get_engine_version())
if (unreal.SystemLibrary.get_engine_version()[0] == '5'):
c = rig.get_controller()
else:
c = rig.controller
g = c.get_graph()
n = g.get_nodes()
mesh = rig.get_preview_mesh()
morphList = mesh.get_all_morph_target_names()
morphListWithNo = morphList[:]
morphListRenamed = []
morphListRenamed.clear()
for i in range(len(morphList)):
morphListWithNo[i] = '{}'.format(morphList[i])
print(morphListWithNo)
###### root
key = unreal.RigElementKey(unreal.RigElementType.SPACE, 'MorphControlRoot_s')
space = h_mod.get_space(key)
if (space.get_editor_property('index') < 0):
space = h_mod.add_space('MorphControlRoot_s', space_type=unreal.RigSpaceType.SPACE)
else:
space = key
a:unreal.RigUnit_CollectionItems = unreal.RigUnit_CollectionItems()
print(a)
# ้
ๅใใผใ่ฟฝๅ
values_forCurve:unreal.RigVMStructNode = []
items_forControl:unreal.RigVMStructNode = []
items_forCurve:unreal.RigVMStructNode = []
for node in n:
print(node)
print(node.get_node_title())
# set curve num
if (node.get_node_title() == 'For Loop'):
print(node)
pin = node.find_pin('Count')
print(pin)
c.set_pin_default_value(pin.get_pin_path(), str(len(morphList)))
# curve name array pin
if (node.get_node_title() == 'Select'):
print(node)
pin = node.find_pin('Values')
#print(pin)
#print(pin.get_array_size())
#print(pin.get_default_value())
values_forCurve.append(pin)
# items
if (node.get_node_title() == 'Items'):
if ("Type=Curve," in c.get_pin_default_value(node.find_pin('Items').get_pin_path())):
items_forCurve.append(node.find_pin('Items'))
else:
items_forControl.append(node.find_pin('Items'))
print(values_forCurve)
# reset controller
for e in reversed(h_mod.get_elements()):
if (e.type!= unreal.RigElementType.CONTROL):
continue
tmp = h_mod.get_control(e)
if (tmp.space_name == 'MorphControlRoot_s'):
#if (str(e.name).rstrip('_c') in morphList):
# continue
print('delete')
#print(str(e.name))
h_mod.remove_element(e)
# curve array
for v in values_forCurve:
c.clear_array_pin(v.get_pin_path())
for morph in morphList:
tmp = "{}".format(morph)
c.add_array_pin(v.get_pin_path(), default_value=tmp)
# curve controller
for morph in morphListWithNo:
name_c = "{}_c".format(morph)
key = unreal.RigElementKey(unreal.RigElementType.CONTROL, name_c)
try:
control = h_mod.get_control(key)
if (control.get_editor_property('index') < 0):
k = h_mod.add_control(name_c,
control_type=unreal.RigControlType.FLOAT,
space_name=space.name,
gizmo_color=[1.0, 0.0, 0.0, 1.0],
)
control = h_mod.get_control(k)
except:
k = h_mod.add_control(name_c,
control_type=unreal.RigControlType.FLOAT,
space_name=space.name,
gizmo_color=[1.0, 0.0, 0.0, 1.0],
)
control = h_mod.get_control(k)
control.set_editor_property('gizmo_visible', False)
control.set_editor_property('gizmo_enabled', False)
h_mod.set_control(control)
morphListRenamed.append(control.get_editor_property('name'))
if (args.debugeachsave == '1'):
try:
unreal.EditorAssetLibrary.save_loaded_asset(rig)
except:
print('save error')
#unreal.SystemLibrary.collect_garbage()
# curve Control array
for v in items_forControl:
c.clear_array_pin(v.get_pin_path())
for morph in morphListRenamed:
tmp = '(Type=Control,Name='
tmp += "{}".format(morph)
tmp += ')'
c.add_array_pin(v.get_pin_path(), default_value=tmp)
# curve Float array
for v in items_forCurve:
c.clear_array_pin(v.get_pin_path())
for morph in morphList:
tmp = '(Type=Curve,Name='
tmp += "{}".format(morph)
tmp += ')'
c.add_array_pin(v.get_pin_path(), default_value=tmp)
|
import unreal
import argparse
import DTUControlRigHelpers
import importlib
importlib.reload(DTUControlRigHelpers)
# Info about Python with IKRigs here:
# https://docs.unrealengine.com/5.2/en-US/using-python-to-create-and-edit-ik-rigs-in-unreal-engine/
# https://docs.unrealengine.com/5.2/en-US/using-python-to-create-and-edit-ik-retargeter-assets-in-unreal-engine/
# Figure out the forward axis for a child bone
def get_bone_forward_axis(child_bone_relative_pos):
forward = "X+"
if abs(child_bone_relative_pos.x) > max(abs(child_bone_relative_pos.y), abs(child_bone_relative_pos.z)): forward = 'X' + forward[1]
if abs(child_bone_relative_pos.y) > max(abs(child_bone_relative_pos.x), abs(child_bone_relative_pos.z)): forward = 'Y' + forward[1]
if abs(child_bone_relative_pos.z) > max(abs(child_bone_relative_pos.x), abs(child_bone_relative_pos.y)): forward = 'Z' + forward[1]
if forward[0] == 'X' and child_bone_relative_pos.x > 0: forward = forward[0] + '+'
if forward[0] == 'X' and child_bone_relative_pos.x < 0: forward = forward[0] + '-'
if forward[0] == 'Y' and child_bone_relative_pos.y > 0: forward = forward[0] + '+'
if forward[0] == 'Y' and child_bone_relative_pos.y < 0: forward = forward[0] + '-'
if forward[0] == 'Z' and child_bone_relative_pos.z > 0: forward = forward[0] + '+'
if forward[0] == 'Z' and child_bone_relative_pos.z < 0: forward = forward[0] + '-'
return forward
parser = argparse.ArgumentParser(description = 'Creates an IKRetargetter between two control rigs')
parser.add_argument('--sourceIKRig', help='Source IKRig to Use')
parser.add_argument('--targetIKRig', help='Target IKRig to Use')
args = parser.parse_args()
# Retageter name is Source_to_Target
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
source_rig_name = args.sourceIKRig.split('.')[-1]
target_rig_name = args.targetIKRig.split('.')[-1]
# Check if it exists
package_path = args.targetIKRig.rsplit('/', 1)[0] + '/'
asset_name = source_rig_name.replace('_IKRig', '') + '_to_' + target_rig_name.replace('_IKRig', '') + '_IKRetargeter'
rtg = skel_mesh = unreal.load_asset(name = package_path + asset_name )
# If not, create a new one
if not rtg:
rtg = asset_tools.create_asset( asset_name=asset_name,
package_path=package_path,
asset_class=unreal.IKRetargeter,
factory=unreal.IKRetargetFactory())
# Get the IK Retargeter controller
rtg_controller = unreal.IKRetargeterController.get_controller(rtg)
# Load the Source and Target IK Rigs
source_ik_rig = unreal.load_asset(name = args.sourceIKRig)
target_ik_rig = unreal.load_asset(name = args.targetIKRig)
source_ikr_controller = unreal.IKRigController.get_controller(source_ik_rig)
target_ikr_controller = unreal.IKRigController.get_controller(target_ik_rig)
# Load the Source and Target Skeletal Meshes
source_ik_mesh = unreal.IKRigController.get_controller(source_ik_rig).get_skeletal_mesh()
target_ik_mesh = unreal.IKRigController.get_controller(target_ik_rig).get_skeletal_mesh()
# Assign the Source and Target IK Rigs
rtg_controller.set_ik_rig(unreal.RetargetSourceOrTarget.SOURCE, source_ik_rig)
rtg_controller.set_ik_rig(unreal.RetargetSourceOrTarget.TARGET, target_ik_rig)
rtg_controller.auto_map_chains(unreal.AutoMapChainType.EXACT, True)
# Get the root rotation
source_asset_import_data = source_ik_mesh.get_editor_property('asset_import_data')
target_asset_import_data = target_ik_mesh.get_editor_property('asset_import_data')
source_force_front_x = source_asset_import_data.get_editor_property('force_front_x_axis')
target_force_front_x = target_asset_import_data.get_editor_property('force_front_x_axis')
# Rotate the root if needed so the character faces forward
if source_force_front_x == False and target_force_front_x == True:
rotation_offset = unreal.Rotator()
rotation_offset.yaw = 90
rtg_controller.set_rotation_offset_for_retarget_pose_bone("root", rotation_offset.quaternion(), unreal.RetargetSourceOrTarget.TARGET)
# Setup the root translation
root_chain_settings = rtg_controller.get_retarget_chain_settings('Root')
root_chain_fk_settings = root_chain_settings.get_editor_property('fk')
root_chain_fk_settings.set_editor_property('translation_mode', unreal.RetargetTranslationMode.ABSOLUTE)
rtg_controller.set_retarget_chain_settings('Root', root_chain_settings)
# Set the root Settings (not the root chain settings)
root_settings = rtg_controller.get_root_settings()
root_settings.blend_to_source = 1.0 # Fixes a hitch in the MM_Run_Fwd conversion
rtg_controller.set_root_settings(root_settings)
# Get the bone limit data
bone_limits = DTUControlRigHelpers.get_bone_limits_from_skeletalmesh(target_ik_mesh)
# Align chains
source_skeleton = source_ik_mesh.get_editor_property('skeleton')
target_skeleton = target_ik_mesh.get_editor_property('skeleton')
source_reference_pose = source_skeleton.get_reference_pose()
target_reference_pose = target_skeleton.get_reference_pose()
def single_axis_bend(target_bone, source_bone):
axis_x, axis_y, axis_z = bone_limits[str(target_bone)].get_preferred_angle()
source_bone_transform = source_reference_pose.get_ref_bone_pose(source_bone, space=unreal.AnimPoseSpaces.LOCAL)
source_bone_rotation = source_bone_transform.get_editor_property('rotation').rotator()
source_angle = abs(max(source_bone_rotation.get_editor_property("pitch"), source_bone_rotation.get_editor_property("yaw"), source_bone_rotation.get_editor_property("roll"), key=lambda x: abs(x)))
new_rot = unreal.Rotator()
if axis_x > 0.01: new_rot.set_editor_property('roll', source_angle) #X
if axis_x < -0.01: new_rot.set_editor_property('roll', source_angle * -1.0) #X
if axis_y > 0.01: new_rot.set_editor_property('pitch', source_angle) #Y
if axis_y < -0.01: new_rot.set_editor_property('pitch', source_angle * -1.0) #Y
if axis_z > 0.01: new_rot.set_editor_property('yaw', source_angle) #Z
if axis_z < -0.01: new_rot.set_editor_property('yaw', source_angle * -1.0) #Z
rtg_controller.set_rotation_offset_for_retarget_pose_bone(target_bone, new_rot.quaternion(), unreal.RetargetSourceOrTarget.TARGET)
def dual_axis_target_bend(target_bone, source_bone, target_end_bone, source_end_bone):
source_bone_transform = source_reference_pose.get_ref_bone_pose(source_bone, space=unreal.AnimPoseSpaces.WORLD)
source_end_bone_transform = source_reference_pose.get_ref_bone_pose(source_end_bone, space=unreal.AnimPoseSpaces.WORLD)
source_relative_position = source_end_bone_transform.get_editor_property('translation') - source_bone_transform.get_editor_property('translation')
# Fix the axis if the target character is facing right
if source_force_front_x == False and target_force_front_x == True:
new_relative_position = unreal.Vector()
new_relative_position.x = source_relative_position.y * -1.0
new_relative_position.y = source_relative_position.x * -1.0
new_relative_position.z = source_relative_position.z
source_relative_position = new_relative_position
target_bone_transform_world = target_reference_pose.get_ref_bone_pose(target_bone, space=unreal.AnimPoseSpaces.WORLD)
target_end_bone_transform_world = target_reference_pose.get_ref_bone_pose(target_end_bone, space=unreal.AnimPoseSpaces.WORLD)
target_relative_position = target_end_bone_transform_world.get_editor_property('translation') - target_bone_transform_world.get_editor_property('translation')
target_position = target_bone_transform_world.get_editor_property('translation') + source_relative_position #- (target_relative_position - source_relative_position)
new_pos = target_bone_transform_world.inverse_transform_location(target_position)
target_child_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(target_skeleton, target_bone, target_end_bone)
target_child_bone_transform_local = target_reference_pose.get_ref_bone_pose(target_child_bone, space=unreal.AnimPoseSpaces.LOCAL)
forward_direction = get_bone_forward_axis(target_child_bone_transform_local.get_editor_property('translation'))
# Make a rotator to point the joints at the new
new_rot = unreal.Rotator()
if forward_direction[0] == 'X':
y_rot = unreal.MathLibrary.deg_atan(new_pos.z / new_pos.x) * -1.0
z_rot = unreal.MathLibrary.deg_atan(new_pos.y / new_pos.x)
new_rot.set_editor_property('pitch', y_rot) #Y
new_rot.set_editor_property('yaw', z_rot) #Z
if forward_direction == 'Y+':
x_rot = unreal.MathLibrary.deg_atan(new_pos.z / new_pos.y) #* -1.0
z_rot = unreal.MathLibrary.deg_atan(new_pos.x / new_pos.y) * -1.0
new_rot.set_editor_property('yaw', z_rot) #Z
new_rot.set_editor_property('roll', x_rot) #X
if forward_direction == 'Y-':
x_rot = unreal.MathLibrary.deg_atan(new_pos.z / new_pos.y) * -1.0
z_rot = unreal.MathLibrary.deg_atan(new_pos.x / new_pos.y) * -1.0
new_rot.set_editor_property('yaw', z_rot) #Z
new_rot.set_editor_property('roll', x_rot) #X
if forward_direction[0] == 'Z':
x_rot = unreal.MathLibrary.deg_atan(new_pos.y / new_pos.z)
y_rot = unreal.MathLibrary.deg_atan(new_pos.x / new_pos.z) * -1.0
new_rot.set_editor_property('roll', x_rot) #X
new_rot.set_editor_property('pitch', y_rot) #Y
# Set the new rotation on the joint
rtg_controller.set_rotation_offset_for_retarget_pose_bone(target_bone, new_rot.quaternion(), unreal.RetargetSourceOrTarget.TARGET)
# Single Axis Bends (Elbow, Knee, etc)
for chain in ['LeftArm', 'RightArm', 'LeftLeg', 'RightLeg']:
source_start_bone = source_ikr_controller.get_retarget_chain_start_bone(chain)
source_end_bone = source_ikr_controller.get_retarget_chain_end_bone(chain)
target_start_bone = target_ikr_controller.get_retarget_chain_start_bone(chain)
target_end_bone = target_ikr_controller.get_retarget_chain_end_bone(chain)
target_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(target_skeleton, target_start_bone, target_end_bone)
source_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(source_skeleton, source_start_bone, source_end_bone)
single_axis_bend(target_bone, source_bone)
# Dual Axis Bends (Elbow, Knee, etc)
for chain in ['LeftArm', 'RightArm', 'LeftLeg', 'RightLeg']:
source_start_bone = source_ikr_controller.get_retarget_chain_start_bone(chain)
source_end_bone = source_ikr_controller.get_retarget_chain_end_bone(chain)
target_start_bone = target_ikr_controller.get_retarget_chain_start_bone(chain)
target_end_bone = target_ikr_controller.get_retarget_chain_end_bone(chain)
# Get the joint (elbow, knee)
target_joint_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(target_skeleton, target_start_bone, target_end_bone)
source_joint_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(source_skeleton, source_start_bone, source_end_bone)
# Got one deeper (hand, foot)
target_end_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(target_skeleton, target_joint_bone, target_end_bone)
source_end_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(source_skeleton, source_joint_bone, source_end_bone)
dual_axis_target_bend(target_start_bone, source_start_bone, target_end_bone, source_end_bone)
# Single Axis Chains (fingers)
for chain in ['RightThumb', 'RightIndex', 'RightMiddle', 'RightRing', 'RightPinky', 'LeftThumb', 'LeftIndex', 'LeftMiddle', 'LeftRing', 'LeftPinky']:
source_start_bone = source_ikr_controller.get_retarget_chain_start_bone(chain)
source_end_bone = source_ikr_controller.get_retarget_chain_end_bone(chain)
target_start_bone = target_ikr_controller.get_retarget_chain_start_bone(chain)
target_end_bone = target_ikr_controller.get_retarget_chain_end_bone(chain)
while target_start_bone and source_start_bone and target_start_bone != target_end_bone and source_start_bone != source_end_bone:
target_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(target_skeleton, target_start_bone, target_end_bone)
source_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(source_skeleton, source_start_bone, source_end_bone)
single_axis_bend(target_bone, source_bone)
target_start_bone = target_bone
source_start_bone = source_bone
|
# Copyright (C) 2024 Louis Vottero [email protected] All rights reserved.
from . import graph as unreal_graph
from .. import util
if util.in_unreal:
import unreal
def get_bones(control_rig=None, return_names=False):
rig = None
if control_rig:
rig = control_rig
else:
rig = unreal_graph.get_current_control_rig()
if not rig:
util.warning('No control rig found')
return
elements = rig.hierarchy.get_all_keys()
found = []
for element in elements:
if element.type == unreal.RigElementType.BONE:
if return_names:
element = str(element.name)
found.append(element)
else:
found.append(element)
return found
|
import unreal
lst_actors = unreal.EditorLevelLibrary.get_all_level_actors()
for act in lst_actors:
act_label = act.get_actor_label()
print(act_label)
|
import unreal
from PIL import Image
import os
def process_images(input_files, output_file):
img1 = Image.open(input_files[0])
img2 = Image.open(input_files[1])
img3 = Image.open(input_files[2])
width1, height1 = img1.size
width2, height2 = img2.size
width3, height3 = img3.size
gap_width = 12
result_img = Image.new('RGB', (width1 + width2 + width3 + 2 * gap_width, max(height1, height2, height3)), color='#aeaeae')
result_img.paste(img1, (0, 0))
result_img.paste(img2, (width1 + gap_width, 0))
result_img.paste(img3, (width1 + width2 + 2 * gap_width, 0))
result_img.save(output_file)
# Remove input images
for file in input_files:
os.remove(file)
saveDataDir = unreal.Paths.project_saved_dir()
screenshotsDir = saveDataDir + "/project/"
input_directory = screenshotsDir + "/Process/"
output_directory = screenshotsDir
# Create the input and output directories if they do not exist
os.makedirs(input_directory, exist_ok=True)
os.makedirs(output_directory, exist_ok=True)
png_files = sorted([f for f in os.listdir(input_directory) if f.endswith('.png')])
for i in range(0, len(png_files), 3):
input_files = [os.path.join(input_directory, png_files[i+j]) for j in range(3)]
output_file_name = f'{os.path.splitext(png_files[i])[0].replace("_1", "")}_All.png'
output_file = os.path.join(output_directory, output_file_name)
print(f'Processing {output_file_name}')
process_images(input_files, output_file)
|
import unreal
actors = unreal.GameplayStatics.get_all_actors_with_tag(unreal.EditorLevelLibrary.get_editor_world(),
unreal.Name('roadsys_decal'))
count = 0
for actor in actors:
comp = actor.get_component_by_class(unreal.HierarchicalInstancedStaticMeshComponent)
level = actor.get_outer()
unreal.EditorLevelLibrary.set_current_level_by_name(level.get_path_name().split('.')[-1].split(':')[0])
levelStreaming = unreal.GameplayStatics.get_streaming_level(unreal.EditorLevelLibrary.get_editor_world(),
level.get_full_name().split(":")[0])
unreal.log(level.get_full_name())
unreal.log(levelStreaming)
static_mesh = comp.static_mesh
instance_num = comp.get_instance_count()
create_list = []
for i in range(instance_num):
trans = comp.get_instance_transform(i, True)
new_actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.StaticMeshActor, trans.translation)
new_actor.set_actor_label('xPCG_Roadsys_decals_{}'.format(count))
new_actor.static_mesh_component.set_static_mesh(static_mesh)
new_actor.set_actor_transform(trans, False, False)
new_actor.tags = ['roadsys', 'roadsys_decal', static_mesh.get_name()]
create_list.append(new_actor)
count += 1
# delete bp
unreal.EditorLevelLibrary.destroy_actor(actor)
|
# Copyright (c) <2021> Side Effects Software Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. The name of Side Effects Software may not be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
""" An example script that uses the API and
HoudiniEngineV2.asyncprocessor.ProcessHDA. ProcessHDA is configured with the
asset to instantiate, as well as 2 inputs: a geometry input (a cube) and a
curve input (a helix).
ProcessHDA is then activiated upon which the asset will be instantiated,
inputs set, and cooked. The ProcessHDA class's on_post_processing() function is
overridden to fetch the input structure and logged. The other state/phase
functions (on_pre_instantiate(), on_post_instantiate() etc) are overridden to
simply log the function name, in order to observe progress in the log.
"""
import math
import unreal
from HoudiniEngineV2.asyncprocessor import ProcessHDA
_g_processor = None
class ProcessHDAExample(ProcessHDA):
@staticmethod
def _print_api_input(in_input):
print('\t\tInput type: {0}'.format(in_input.__class__))
print('\t\tbKeepWorldTransform: {0}'.format(in_input.keep_world_transform))
print('\t\tbImportAsReference: {0}'.format(in_input.import_as_reference))
if isinstance(in_input, unreal.HoudiniPublicAPIGeoInput):
print('\t\tbPackBeforeMerge: {0}'.format(in_input.pack_before_merge))
print('\t\tbExportLODs: {0}'.format(in_input.export_lo_ds))
print('\t\tbExportSockets: {0}'.format(in_input.export_sockets))
print('\t\tbExportColliders: {0}'.format(in_input.export_colliders))
elif isinstance(in_input, unreal.HoudiniPublicAPICurveInput):
print('\t\tbCookOnCurveChanged: {0}'.format(in_input.cook_on_curve_changed))
print('\t\tbAddRotAndScaleAttributesOnCurves: {0}'.format(in_input.add_rot_and_scale_attributes_on_curves))
input_objects = in_input.get_input_objects()
if not input_objects:
print('\t\tEmpty input!')
else:
print('\t\tNumber of objects in input: {0}'.format(len(input_objects)))
for idx, input_object in enumerate(input_objects):
print('\t\t\tInput object #{0}: {1}'.format(idx, input_object))
if hasattr(in_input, 'supports_transform_offset') and in_input.supports_transform_offset():
print('\t\t\tObject Transform Offset: {0}'.format(in_input.get_input_object_transform_offset(idx)))
if isinstance(input_object, unreal.HoudiniPublicAPICurveInputObject):
print('\t\t\tbClosed: {0}'.format(input_object.is_closed()))
print('\t\t\tCurveMethod: {0}'.format(input_object.get_curve_method()))
print('\t\t\tCurveType: {0}'.format(input_object.get_curve_type()))
print('\t\t\tReversed: {0}'.format(input_object.is_reversed()))
print('\t\t\tCurvePoints: {0}'.format(input_object.get_curve_points()))
def on_failure(self):
print('on_failure')
global _g_processor
_g_processor = None
def on_complete(self):
print('on_complete')
global _g_processor
_g_processor = None
def on_pre_instantiation(self):
print('on_pre_instantiation')
def on_post_instantiation(self):
print('on_post_instantiation')
def on_post_auto_cook(self, cook_success):
print('on_post_auto_cook, success = {0}'.format(cook_success))
def on_pre_process(self):
print('on_pre_process')
def on_post_processing(self):
print('on_post_processing')
# Fetch inputs, iterate over it and log
node_inputs = self.asset_wrapper.get_inputs_at_indices()
parm_inputs = self.asset_wrapper.get_input_parameters()
if not node_inputs:
print('No node inputs found!')
else:
print('Number of node inputs: {0}'.format(len(node_inputs)))
for input_index, input_wrapper in node_inputs.items():
print('\tInput index: {0}'.format(input_index))
self._print_api_input(input_wrapper)
if not parm_inputs:
print('No parameter inputs found!')
else:
print('Number of parameter inputs: {0}'.format(len(parm_inputs)))
for parm_name, input_wrapper in parm_inputs.items():
print('\tInput parameter name: {0}'.format(parm_name))
self._print_api_input(input_wrapper)
def on_post_auto_bake(self, bake_success):
print('on_post_auto_bake, succes = {0}'.format(bake_success))
def get_test_hda_path():
return '/project/.copy_to_curve_1_0'
def get_test_hda():
return unreal.load_object(None, get_test_hda_path())
def get_geo_asset_path():
return '/project/.Cube'
def get_geo_asset():
return unreal.load_object(None, get_geo_asset_path())
def build_inputs():
print('configure_inputs')
# get the API singleton
houdini_api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
node_inputs = {}
# Create a geo input
geo_input = houdini_api.create_empty_input(unreal.HoudiniPublicAPIGeoInput)
# Set the input objects/assets for this input
geo_object = get_geo_asset()
geo_input.set_input_objects((geo_object, ))
# store the input data to the HDA as node input 0
node_inputs[0] = geo_input
# Create a curve input
curve_input = houdini_api.create_empty_input(unreal.HoudiniPublicAPICurveInput)
# Create a curve wrapper/helper
curve_object = unreal.HoudiniPublicAPICurveInputObject(curve_input)
# Make it a Nurbs curve
curve_object.set_curve_type(unreal.HoudiniPublicAPICurveType.NURBS)
# Set the points of the curve, for this example we create a helix
# consisting of 100 points
curve_points = []
for i in range(100):
t = i / 20.0 * math.pi * 2.0
x = 100.0 * math.cos(t)
y = 100.0 * math.sin(t)
z = i
curve_points.append(unreal.Transform([x, y, z], [0, 0, 0], [1, 1, 1]))
curve_object.set_curve_points(curve_points)
# Set the curve wrapper as an input object
curve_input.set_input_objects((curve_object, ))
# Store the input data to the HDA as node input 1
node_inputs[1] = curve_input
return node_inputs
def run():
# Create the processor with preconfigured inputs
global _g_processor
_g_processor = ProcessHDAExample(
get_test_hda(), node_inputs=build_inputs())
# Activate the processor, this will starts instantiation, and then cook
if not _g_processor.activate():
unreal.log_warning('Activation failed.')
else:
unreal.log('Activated!')
if __name__ == '__main__':
run()
|
import unreal
from ueGear.controlrig.paths import CONTROL_RIG_FUNCTION_PATH
import ueGear.controlrig.manager as ueMan
from ueGear.controlrig.components import base_component, EPIC_control_01
from ueGear.controlrig.helpers import controls
# TODO:
# [ ] Multiple joints can be generated by the component
# [ ] The start of each bone should have its own fk control.
# [ ] The end joint should be driven the "head" fk control
class Component(base_component.UEComponent):
name = "neck"
mgear_component = "EPIC_neck_01"
def __init__(self):
super().__init__()
self.functions = {'construction_functions': ['construct_neck'],
'forward_functions': ['forward_neck'],
'backwards_functions': ['backwards_neck'],
}
self.cr_variables = {}
# Control Rig Inputs
self.cr_inputs = {'construction_functions': ['parent'],
'forward_functions': [],
'backwards_functions': [],
}
# Control Rig Outputs
self.cr_output = {'construction_functions': ['root'],
'forward_functions': [],
'backwards_functions': [],
}
# mGear
self.inputs = []
self.outputs = []
def create_functions(self, controller: unreal.RigVMController = None):
if controller is None:
return
# calls the super method
super().create_functions(controller)
# Generate Function Nodes
for evaluation_path in self.functions.keys():
# Skip the forward function creation if no joints are needed to be driven
if evaluation_path == 'forward_functions' and self.metadata.joints is None:
continue
# Skip the backwards function creation if no joints are needed to be driven
if evaluation_path == 'backwards_functions' and self.metadata.joints is None:
continue
for cr_func in self.functions[evaluation_path]:
new_node_name = f"{self.name}_{cr_func}"
ue_cr_node = controller.get_graph().find_node_by_name(new_node_name)
# Create Component if doesn't exist
if ue_cr_node is None:
ue_cr_ref_node = controller.add_external_function_reference_node(CONTROL_RIG_FUNCTION_PATH,
cr_func,
unreal.Vector2D(0.0, 0.0),
node_name=new_node_name)
# In Unreal, Ref Node inherits from Node
ue_cr_node = ue_cr_ref_node
else:
# if exists, add it to the nodes
self.nodes[evaluation_path].append(ue_cr_node)
unreal.log_error(f" Cannot create function {new_node_name}, it already exists")
continue
self.nodes[evaluation_path].append(ue_cr_node)
# Gets the Construction Function Node and sets the control name
func_name = self.functions['construction_functions'][0]
construct_func = base_component.get_construction_node(self, f"{self.name}_{func_name}")
if construct_func is None:
unreal.log_error(" Create Functions Error - Cannot find construct singleton node")
def populate_bones(self, bones: list[unreal.RigBoneElement] = None, controller: unreal.RigVMController = None):
"""
populates the bone shoulder joint node
"""
if bones is None or len(bones) < 3:
unreal.log_error(f"[Bone Populate] Failed no Bones found: Found {len(bones)} bones")
return
if controller is None:
unreal.log_error("[Bone Populate] Failed no Controller found")
return
for bone in bones:
bone_name = bone.key.name
# Unique name for this skeleton node array
array_node_name = f"{self.metadata.fullname}_RigUnit_ItemArray"
# node doesn't exists, create the joint node
if not controller.get_graph().find_node_by_name(array_node_name):
self._init_master_joint_node(controller, array_node_name, bones)
node = controller.get_graph().find_node_by_name(array_node_name)
self.add_misc_function(node)
def init_input_data(self, controller: unreal.RigVMController):
self._connect_bones(controller)
def _connect_bones(self, controller: unreal.RigVMController):
"""Connects the bone array list to the construction node"""
bone_node_name = f"{self.metadata.fullname}_RigUnit_ItemArray"
construction_node_name = self.nodes["construction_functions"][0].get_name()
forward_node_name = self.nodes["forward_functions"][0].get_name()
backwards_node_name = self.nodes["backwards_functions"][0].get_name()
controller.add_link(f'{bone_node_name}.Items',
f'{construction_node_name}.fk_joints')
controller.add_link(f'{bone_node_name}.Items',
f'{forward_node_name}.Array')
controller.add_link(f'{bone_node_name}.Items',
f'{backwards_node_name}.fk_joints')
def populate_control_scale(self, controller: unreal.RigVMController):
"""
Generates a scale value per a control
"""
import ueGear.controlrig.manager as ueMan
# Generates the array node
array_name = ueMan.create_array_node(f"{self.metadata.fullname}_control_scales", controller)
array_node = controller.get_graph().find_node_by_name(array_name)
self.add_misc_function(array_node)
# connects the node of scales to the construction node
construction_func_name = self.nodes["construction_functions"][0].get_name()
controller.add_link(f'{array_name}.Array',
f'{construction_func_name}.control_sizes')
pins_exist = ueMan.array_node_has_pins(array_name, controller)
reduce_ratio = 4.0
"""Magic number to try and get the maya control scale to be similar to that of unreal.
As the mGear uses a square and ueGear uses a cirlce.
"""
pin_index = 0
# Calculates the unreal scale for the control and populates it into the array node.
for control_name in self.metadata.controls:
aabb = self.metadata.controls_aabb[control_name]
unreal_size = [round(element / reduce_ratio, 4) for element in aabb[1]]
# todo: this is a test implementation for the spine, for a more robust validation, each axis should be checked.
# rudementary way to check if the bounding box might be flat, if it is then
# the first value if applied onto the axis
if unreal_size[0] == unreal_size[1] and unreal_size[2] < 1.0:
unreal_size[2] = unreal_size[0]
if not pins_exist:
existing_pin_count = len(array_node.get_pins()[0].get_sub_pins())
if existing_pin_count < len(self.metadata.controls_aabb):
controller.insert_array_pin(f'{array_name}.Values',
-1,
'')
controller.set_pin_default_value(f'{array_name}.Values.{pin_index}',
f'(X={unreal_size[0]},Y={unreal_size[1]},Z={unreal_size[2]})',
False)
pin_index += 1
def populate_control_names(self, controller: unreal.RigVMController):
import ueGear.controlrig.manager as ueMan
names_node = ueMan.create_array_node(f"{self.metadata.fullname}_control_names", controller)
node_names = controller.get_graph().find_node_by_name(names_node)
self.add_misc_function(node_names)
# Connecting nodes needs to occur first, else the array node does not know the type and will not accept default
# values
construction_func_name = self.nodes["construction_functions"][0].get_name()
controller.add_link(f'{names_node}.Array',
f'{construction_func_name}.fk_names')
# Checks the pins
name_pins_exist = ueMan.array_node_has_pins(names_node, controller)
pin_index = 0
for control_name in self.metadata.controls:
if not name_pins_exist:
found_node = controller.get_graph().find_node_by_name(names_node)
existing_pin_count = len(found_node.get_pins()[0].get_sub_pins())
if existing_pin_count < len(self.metadata.controls):
controller.insert_array_pin(f'{names_node}.Values',
-1,
'')
controller.set_pin_default_value(f'{names_node}.Values.{pin_index}',
control_name,
False)
pin_index += 1
def populate_control_transforms(self, controller: unreal.RigVMController = None):
"""Updates the transform data for the controls generated, with the data from the mgear json
file.
"""
import ueGear.controlrig.manager as ueMan
trans_node = ueMan.create_array_node(f"{self.metadata.fullname}_control_transforms", controller)
node_trans = controller.get_graph().find_node_by_name(trans_node)
self.add_misc_function(node_trans)
# Connecting nodes needs to occur first, else the array node does not know the type and will not accept default
# values
construction_func_name = self.nodes["construction_functions"][0].get_name()
controller.add_link(f'{trans_node}.Array',
f'{construction_func_name}.control_transforms')
# Checks the pins
trans_pins_exist = ueMan.array_node_has_pins(trans_node, controller)
pin_index = 0
for control_name in self.metadata.controls:
control_transform = self.metadata.control_transforms[control_name]
if not trans_pins_exist:
found_node = controller.get_graph().find_node_by_name(trans_node)
existing_pin_count = len(found_node.get_pins()[0].get_sub_pins())
if existing_pin_count < len(self.metadata.controls):
controller.insert_array_pin(f'{trans_node}.Values',
-1,
'')
quat = control_transform.rotation
pos = control_transform.translation
controller.set_pin_default_value(f"{trans_node}.Values.{pin_index}",
f"(Rotation=(X={quat.x},Y={quat.y},Z={quat.z},W={quat.w}), "
f"Translation=(X={pos.x},Y={pos.y},Z={pos.z}),"
f"Scale3D=(X=1.000000,Y=1.000000,Z=1.000000))",
True)
pin_index += 1
# TODO: setup an init_controls method and move this method and the populate controls method into it
self.populate_control_names(controller)
self.populate_control_scale(controller)
self.populate_control_shape_offset(controller)
self.populate_control_colour(controller)
def populate_control_colour(self, controller):
cr_func = self.functions["construction_functions"][0]
construction_node = f"{self.name}_{cr_func}"
for i, control_name in enumerate(self.metadata.controls):
colour = self.metadata.controls_colour[control_name]
controller.insert_array_pin(f'{construction_node}.control_colours', -1, '')
controller.set_pin_default_value(f'{construction_node}.control_colours.{i}.R', f"{colour[0]}", False)
controller.set_pin_default_value(f'{construction_node}.control_colours.{i}.G', f"{colour[1]}", False)
controller.set_pin_default_value(f'{construction_node}.control_colours.{i}.B', f"{colour[2]}", False)
controller.set_pin_default_value(f'{construction_node}.control_colours.{i}.A', "1", False)
def populate_control_shape_offset(self, controller: unreal.RigVMController):
"""
As some controls have there pivot at the same position as the transform, but the control is actually moved
away from that pivot point. We use the bounding box position as an offset for the control shape.
"""
import ueGear.controlrig.manager as ueMan
# Generates the array node
array_name = ueMan.create_array_node(f"{self.metadata.fullname}_control_offset", controller)
array_node = controller.get_graph().find_node_by_name(array_name)
self.add_misc_function(array_node)
# connects the node of scales to the construction node
construction_func_name = self.nodes["construction_functions"][0].get_name()
controller.add_link(f'{array_name}.Array',
f'{construction_func_name}.control_offsets')
pins_exist = ueMan.array_node_has_pins(array_name, controller)
pin_index = 0
for control_name in self.metadata.controls:
aabb = self.metadata.controls_aabb[control_name]
bb_center = aabb[0]
if not pins_exist:
existing_pin_count = len(array_node.get_pins()[0].get_sub_pins())
if existing_pin_count < len(self.metadata.controls_aabb):
controller.insert_array_pin(f'{array_name}.Values',
-1,
'')
controller.set_pin_default_value(f'{array_name}.Values.{pin_index}',
f'(X={bb_center[0]},Y={bb_center[1]},Z={bb_center[2]})',
False)
pin_index += 1
class ManualComponent(Component):
name = "EPIC_neck_01"
def __init__(self):
super().__init__()
self.functions = {'construction_functions': ['manual_construct_neck'],
'forward_functions': ['forward_neck'],
'backwards_functions': ['backwards_neck'],
}
self.is_manual = True
# These are the roles that will be parented directly under the parent component.
self.root_control_children = ["ik", "fk0"]
self.hierarchy_schematic_roles = {}
# Default to fall back onto
self.default_shape = "Box_Thick"
self.control_shape = {
"ik": "Box_Thick",
"head": "Box_Thick"
}
# ignores building the controls with the specific role
self.skip_roles = ["ik"]
def create_functions(self, controller: unreal.RigVMController):
EPIC_control_01.ManualComponent.create_functions(self, controller)
self.setup_dynamic_hierarchy_roles(self.metadata.settings['division'], end_control_role="head")
def setup_dynamic_hierarchy_roles(self, fk_count, end_control_role=None):
"""Manual controls have some dynamic control creation. This function sets up the
control relationship for the dynamic control hierarchy."""
# Calculate the amount of fk's based on the division amount
for i in range(fk_count):
parent_role = f"fk{i}"
child_index = i+1
child_role = f"fk{child_index}"
# end of the fk chain, parent the end control if one specified
if child_index >= fk_count:
if end_control_role:
self.hierarchy_schematic_roles[parent_role] = [end_control_role]
continue
self.hierarchy_schematic_roles[parent_role] = [child_role]
def initialize_hierarchy(self, hierarchy_controller: unreal.RigHierarchyController):
"""Performs the hierarchical restructuring of the internal components controls"""
# Parent control hierarchy using roles
for parent_role in self.hierarchy_schematic_roles.keys():
child_roles = self.hierarchy_schematic_roles[parent_role]
parent_ctrl = self.control_by_role[parent_role]
for child_role in child_roles:
child_ctrl = self.control_by_role[child_role]
hierarchy_controller.set_parent(child_ctrl.rig_key, parent_ctrl.rig_key)
def generate_manual_controls(self, hierarchy_controller: unreal.RigHierarchyController):
"""Creates all the manual controls for the Spine"""
# Stores the controls by Name
control_table = dict()
for control_name in self.metadata.controls:
new_control = controls.CR_Control(name=control_name)
role = self.metadata.controls_role[control_name]
# Skip a control that contains a role that has any of the keywords to skip
if any([skip in role for skip in self.skip_roles]):
continue
# stored metadata values
control_transform = self.metadata.control_transforms[control_name]
control_colour = self.metadata.controls_colour[control_name]
control_aabb = self.metadata.controls_aabb[control_name]
control_offset = control_aabb[0]
control_scale = [control_aabb[1][0] / 4.0,
control_aabb[1][1] / 4.0,
control_aabb[1][2] / 4.0]
# Set the colour, required before build
new_control.colour = control_colour
if role not in self.control_shape.keys():
new_control.shape_name = self.default_shape
else:
new_control.shape_name = self.control_shape[role]
# Generate the Control
new_control.build(hierarchy_controller)
# Sets the controls position, and offset translation and scale of the shape
new_control.set_transform(quat_transform=control_transform)
new_control.shape_transform_global(pos=control_offset, scale=control_scale, rotation=[90,0,0])
control_table[control_name] = new_control
# Stores the control by role, for loopup purposes later
self.control_by_role[role] = new_control
self.initialize_hierarchy(hierarchy_controller)
def populate_control_transforms(self, controller: unreal.RigVMController = None):
construction_func_name = self.nodes["construction_functions"][0].get_name()
fk_controls = []
ik_controls = []
for role_key in self.control_by_role.keys():
# Generates the list of fk controls
if 'fk' in role_key or "head" in role_key:
control = self.control_by_role[role_key]
fk_controls.append(control)
else:
control = self.control_by_role[role_key]
ik_controls.append(control)
def update_input_plug(plug_name, control_list):
"""
Simple helper function making the plug population reusable for ik and fk
"""
control_metadata = []
for entry in control_list:
if entry.rig_key.type == unreal.RigElementType.CONTROL:
t = "Control"
if entry.rig_key.type == unreal.RigElementType.NULL:
t = "Null"
n = entry.rig_key.name
entry = f'(Type={t}, Name="{n}")'
control_metadata.append(entry)
concatinated_controls = ",".join(control_metadata)
controller.set_pin_default_value(
f'{construction_func_name}.{plug_name}',
f"({concatinated_controls})",
True,
setup_undo_redo=True,
merge_undo_action=True)
update_input_plug("ik_controls", ik_controls)
update_input_plug("fk_controls", fk_controls)
|
๏ปฟ# coding: utf-8
from asyncio.windows_events import NULL
from platform import java_ver
import unreal
import argparse
print("VRM4U python begin")
print (__file__)
parser = argparse.ArgumentParser()
parser.add_argument("-vrm")
parser.add_argument("-rig")
parser.add_argument("-meta")
args = parser.parse_args()
print(args.vrm)
reg = unreal.AssetRegistryHelpers.get_asset_registry();
##
rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints()
print(rigs)
for r in rigs:
s:str = r.get_path_name()
ss:str = args.rig
if (s.find(ss) < 0):
print("no rig")
else:
rig = r
#rig = rigs[10]
hierarchy = unreal.ControlRigBlueprintLibrary.get_hierarchy(rig)
h_con = hierarchy.get_controller()
r_con = rig.get_controller()
graph = r_con.get_graph()
node = graph.get_nodes()
def checkAndSwapPinBoneToContorl(pin):
subpins = pin.get_sub_pins()
#print(subpins)
if (len(subpins) != 2):
return;
typePin = pin.find_sub_pin('Type')
namePin = pin.find_sub_pin('Name')
#if (typePin==None or namePin==None):
if (typePin==None):
return;
#if (typePin.get_default_value() == '' or namePin.get_default_value() == ''):
if (typePin.get_default_value() == ''):
return;
if (typePin.get_default_value() != 'Bone'):
return;
print(typePin.get_default_value() + ' : ' + namePin.get_default_value())
r_con.set_pin_default_value(typePin.get_pin_path(), 'Control', True, False)
print('swap end')
#end check pin
bonePin = None
controlPin = None
while(len(hierarchy.get_bones()) > 0):
e = hierarchy.get_bones()[-1]
h_con.remove_all_parents(e)
h_con.remove_element(e)
h_con.import_bones(unreal.ControlRigBlueprintLibrary.get_preview_mesh(rig).skeleton)
##
for n in node:
pins = n.get_pins()
for pin in pins:
if (pin.is_array()):
if (pin.get_array_size() > 40):
# long bone list
typePin = pin.get_sub_pins()[0].find_sub_pin('Type')
if (typePin != None):
if (typePin.get_default_value() == 'Bone'):
bonePin = pin
continue
if (typePin.get_default_value() == 'Control'):
if ('Name="pelvis"' in r_con.get_pin_default_value(n.find_pin('Items').get_pin_path())):
controlPin = pin
continue
for item in pin.get_sub_pins():
checkAndSwapPinBoneToContorl(item)
else:
checkAndSwapPinBoneToContorl(pin)
for e in hierarchy.get_controls():
tmp = "{}".format(e.name)
if (tmp.endswith('_ctrl') == False):
continue
if (tmp.startswith('thumb_0') or tmp.startswith('index_0') or tmp.startswith('middle_0') or tmp.startswith('ring_0') or tmp.startswith('pinky_0')):
print('')
else:
continue
c = hierarchy.find_control(e)
print(e.name)
#ttt = unreal.RigComputedTransform(transform=[[0.0, 0.0, 2.0], [90.0, 0.0, 0.0], [0.03, 0.03, 0.25]])
#ttt = unreal.RigComputedTransform(transform=[[0.0, 0.0, 2.0], [90.0, 0.0, 0.0], [0.03, 0.03, 0.25]])
ttt = unreal.Transform(location=[0.0, 0.0, 2.0], rotation=[0.0, 0.0, 90.0], scale=[0.03, 0.03, 0.25])
hierarchy.set_control_shape_transform(e, ttt, True)
'''
shape = c.get_editor_property('shape')
init = shape.get_editor_property('initial')
#init = shape.get_editor_property('current')
local = init.get_editor_property('local')
local = ttt
init.set_editor_property('local', local)
gl = init.get_editor_property('global_')
gl = ttt
init.set_editor_property('global_', gl)
shape.set_editor_property('initial', init)
shape.set_editor_property('current', init)
c.set_editor_property('shape', shape)
'''
###
swapBoneTable = [
["Root",""],
["Pelvis","hips"],
["spine_01","spine"],
["spine_02","chest"],
["spine_03","upperChest"],
["clavicle_l","leftShoulder"],
["UpperArm_L","leftUpperArm"],
["lowerarm_l","leftLowerArm"],
["Hand_L","leftHand"],
["index_01_l","leftIndexProximal"],
["index_02_l","leftIndexIntermediate"],
["index_03_l","leftIndexDistal"],
["middle_01_l","leftMiddleProximal"],
["middle_02_l","leftMiddleIntermediate"],
["middle_03_l","leftMiddleDistal"],
["pinky_01_l","leftLittleProximal"],
["pinky_02_l","leftLittleIntermediate"],
["pinky_03_l","leftLittleDistal"],
["ring_01_l","leftRingProximal"],
["ring_02_l","leftRingIntermediate"],
["ring_03_l","leftRingDistal"],
["thumb_01_l","leftThumbProximal"],
["thumb_02_l","leftThumbIntermediate"],
["thumb_03_l","leftThumbDistal"],
["lowerarm_twist_01_l",""],
["upperarm_twist_01_l",""],
["clavicle_r","rightShoulder"],
["UpperArm_R","rightUpperArm"],
["lowerarm_r","rightLowerArm"],
["Hand_R","rightHand"],
["index_01_r","rightIndexProximal"],
["index_02_r","rightIndexIntermediate"],
["index_03_r","rightIndexDistal"],
["middle_01_r","rightMiddleProximal"],
["middle_02_r","rightMiddleIntermediate"],
["middle_03_r","rightMiddleDistal"],
["pinky_01_r","rightLittleProximal"],
["pinky_02_r","rightLittleIntermediate"],
["pinky_03_r","rightLittleDistal"],
["ring_01_r","rightRingProximal"],
["ring_02_r","rightRingIntermediate"],
["ring_03_r","rightRingDistal"],
["thumb_01_r","rightThumbProximal"],
["thumb_02_r","rightThumbIntermediate"],
["thumb_03_r","rightThumbDistal"],
["lowerarm_twist_01_r",""],
["upperarm_twist_01_r",""],
["neck_01","neck"],
["head","head"],
["Thigh_L","leftUpperLeg"],
["calf_l","leftLowerLeg"],
["calf_twist_01_l",""],
["Foot_L","leftFoot"],
["ball_l","leftToes"],
["thigh_twist_01_l",""],
["Thigh_R","rightUpperLeg"],
["calf_r","rightLowerLeg"],
["calf_twist_01_r",""],
["Foot_R","rightFoot"],
["ball_r","rightToes"],
["thigh_twist_01_r",""],
["index_metacarpal_l",""],
["index_metacarpal_r",""],
["middle_metacarpal_l",""],
["middle_metacarpal_r",""],
["ring_metacarpal_l",""],
["ring_metacarpal_r",""],
["pinky_metacarpal_l",""],
["pinky_metacarpal_r",""],
#custom
["eye_l", "leftEye"],
["eye_r", "rightEye"],
]
humanoidBoneList = [
"hips",
"leftUpperLeg",
"rightUpperLeg",
"leftLowerLeg",
"rightLowerLeg",
"leftFoot",
"rightFoot",
"spine",
"chest",
"upperChest", # 9 optional
"neck",
"head",
"leftShoulder",
"rightShoulder",
"leftUpperArm",
"rightUpperArm",
"leftLowerArm",
"rightLowerArm",
"leftHand",
"rightHand",
"leftToes",
"rightToes",
"leftEye",
"rightEye",
"jaw",
"leftThumbProximal", # 24
"leftThumbIntermediate",
"leftThumbDistal",
"leftIndexProximal",
"leftIndexIntermediate",
"leftIndexDistal",
"leftMiddleProximal",
"leftMiddleIntermediate",
"leftMiddleDistal",
"leftRingProximal",
"leftRingIntermediate",
"leftRingDistal",
"leftLittleProximal",
"leftLittleIntermediate",
"leftLittleDistal",
"rightThumbProximal",
"rightThumbIntermediate",
"rightThumbDistal",
"rightIndexProximal",
"rightIndexIntermediate",
"rightIndexDistal",
"rightMiddleProximal",
"rightMiddleIntermediate",
"rightMiddleDistal",
"rightRingProximal",
"rightRingIntermediate",
"rightRingDistal",
"rightLittleProximal",
"rightLittleIntermediate",
"rightLittleDistal", #54
]
for i in range(len(humanoidBoneList)):
humanoidBoneList[i] = humanoidBoneList[i].lower()
for i in range(len(swapBoneTable)):
swapBoneTable[i][0] = swapBoneTable[i][0].lower()
swapBoneTable[i][1] = swapBoneTable[i][1].lower()
### ๅ
จใฆใฎ้ชจ
modelBoneElementList = []
modelBoneNameList = []
for e in hierarchy.get_bones():
if (e.type == unreal.RigElementType.BONE):
modelBoneElementList.append(e)
modelBoneNameList.append("{}".format(e.name))
## meta ๅๅพ
reg = unreal.AssetRegistryHelpers.get_asset_registry();
a = reg.get_all_assets();
if (args.meta):
for aa in a:
print(aa.get_editor_property("package_name"))
print(aa.get_editor_property("asset_name"))
if ((unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("package_name"))+"."+unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("asset_name"))) == unreal.StringLibrary.conv_name_to_string(args.meta)):
#if (aa.get_editor_property("object_path") == args.meta):
v:unreal.VrmMetaObject = aa
vv = aa.get_asset()
break
if (vv == None):
for aa in a:
if ((unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("package_name"))+"."+unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("asset_name"))) == unreal.StringLibrary.conv_name_to_string(args.meta)):
#if (aa.get_editor_property("object_path") == args.vrm):
v:unreal.VrmAssetListObject = aa
vv = v.get_asset().vrm_meta_object
break
meta = vv
# Backwards Bone Names
allBackwardsNode = []
def r_nodes(node):
b = False
try:
allBackwardsNode.index(node)
except:
b = True
if (b == True):
allBackwardsNode.append(node)
linknode = node.get_linked_source_nodes()
for n in linknode:
r_nodes(n)
linknode = node.get_linked_target_nodes()
for n in linknode:
r_nodes(n)
for n in node:
if (n.get_node_title() == 'Backwards Solve'):
r_nodes(n)
print(len(allBackwardsNode))
print(len(node))
def boneOverride(pin):
subpins = pin.get_sub_pins()
if (len(subpins) != 2):
return
typePin = pin.find_sub_pin('Type')
namePin = pin.find_sub_pin('Name')
if (typePin==None):
return
if (namePin==None):
return
controlName = namePin.get_default_value()
if (controlName==''):
return
if (controlName.endswith('_ctrl')):
return
if (controlName.endswith('_space')):
return
r_con.set_pin_default_value(typePin.get_pin_path(), 'Bone', True, False)
table = [i for i in swapBoneTable if i[0]==controlName]
if (len(table) == 0):
# use node or no control
return
if (table[0][0] == 'root'):
metaTable = "{}".format(hierarchy.get_bones()[0].name)
else:
metaTable = meta.humanoid_bone_table.get(table[0][1])
if (metaTable == None):
metaTable = 'None'
#print(table[0][1])
#print('<<')
#print(controlName)
#print('<<<')
#print(metaTable)
r_con.set_pin_default_value(namePin.get_pin_path(), metaTable, True, False)
#for e in meta.humanoid_bone_table:
for n in allBackwardsNode:
pins = n.get_pins()
for pin in pins:
if (pin.is_array()):
# finger ็กๅคๆใใงใใฏ
linknode = n.get_linked_target_nodes()
if (len(linknode) == 1):
if (linknode[0].get_node_title()=='At'):
continue
for p in pin.get_sub_pins():
boneOverride(p)
else:
boneOverride(pin)
#sfsdjfkasjk
### ้ชจๅๅฏพๅฟ่กจใHumanoidๅ -> Modelๅ
humanoidBoneToModel = {"" : ""}
humanoidBoneToModel.clear()
humanoidBoneToMannequin = {"" : ""}
humanoidBoneToMannequin.clear()
# humanoidBone -> modelBone ใฎใใผใใซไฝใ
for searchHumanoidBone in humanoidBoneList:
bone_h = None
for e in meta.humanoid_bone_table:
if ("{}".format(e).lower() == searchHumanoidBone):
bone_h = e;
break;
if (bone_h==None):
# not found
continue
bone_m = meta.humanoid_bone_table[bone_h]
try:
i = modelBoneNameList.index(bone_m)
except:
i = -1
if (i < 0):
# no bone
continue
humanoidBoneToModel["{}".format(bone_h).lower()] = "{}".format(bone_m)
#humanoidBoneToMannequin["{}".format(bone_h).lower()] = "{}".format(bone_m).lower(bone_h)
#print(humanoidBoneToModel)
#print(bonePin)
#print(controlPin)
if (bonePin != None and controlPin !=None):
r_con.clear_array_pin(bonePin.get_pin_path())
r_con.clear_array_pin(controlPin.get_pin_path())
#c.clear_array_pin(v.get_pin_path())
#tmp = '(Type=Control,Name='
#tmp += "{}".format('aaaaa')
#tmp += ')'
#r_con.add_array_pin(bonePin.get_pin_path(), default_value=tmp)
for e in swapBoneTable:
try:
i = 0
humanoidBoneToModel[e[1]]
except:
i = -1
if (i < 0):
# no bone
continue
#e[0] -> grayman
#e[1] -> humanoid
#humanoidBoneToModel[e[1]] -> modelBone
bone = unreal.RigElementKey(unreal.RigElementType.BONE, humanoidBoneToModel[e[1]])
space = unreal.RigElementKey(unreal.RigElementType.NULL, "{}_s".format(e[0]))
#print('aaa')
#print(bone)
#print(space)
#p = hierarchy.get_first_parent(humanoidBoneToModel[result[0][1]])
t = hierarchy.get_global_transform(bone)
#print(t)
hierarchy.set_global_transform(space, t, True)
if (bonePin != None and controlPin !=None):
tmp = '(Type=Control,Name='
tmp += "{}".format(e[0])
tmp += ')'
r_con.add_array_pin(controlPin.get_pin_path(), default_value=tmp, setup_undo_redo=False)
tmp = '(Type=Bone,Name='
tmp += "\"{}\"".format(humanoidBoneToModel[e[1]])
tmp += ')'
r_con.add_array_pin(bonePin.get_pin_path(), default_value=tmp, setup_undo_redo=False)
# for bone name space
namePin = bonePin.get_sub_pins()[-1].find_sub_pin('Name')
r_con.set_pin_default_value(namePin.get_pin_path(), "{}".format(humanoidBoneToModel[e[1]]), True, False)
# skip invalid bone, controller
# disable node
def disableNode(toNoneNode):
print(toNoneNode)
print("gfgf")
pins = toNoneNode.get_pins()
for pin in pins:
typePin = pin.find_sub_pin('Type')
namePin = pin.find_sub_pin('Name')
if (typePin==None or namePin==None):
continue
print(f'DisablePin {typePin.get_default_value()} : {namePin.get_default_value()}')
# control
key = unreal.RigElementKey(unreal.RigElementType.CONTROL, "{}".format(namePin.get_default_value()))
# disable node
r_con.set_pin_default_value(namePin.get_pin_path(), 'None', True, False)
if (typePin.get_default_value() == 'Control'):
#disable control
if (hierarchy.contains(key) == True):
settings = h_con.get_control_settings(key)
if ("5.1." in unreal.SystemLibrary.get_engine_version()):
settings.set_editor_property('shape_visible', False)
else:
settings.set_editor_property('shape_enabled', False)
ttt = hierarchy.get_global_control_shape_transform(key, True)
ttt.scale3d.set(0.001, 0.001, 0.001)
hierarchy.set_control_shape_transform(key, ttt, True)
h_con.set_control_settings(key, settings)
for n in node:
pins = n.get_pins()
for pin in pins:
if (pin.is_array()):
continue
else:
typePin = pin.find_sub_pin('Type')
namePin = pin.find_sub_pin('Name')
if (typePin==None or namePin==None):
continue
if (typePin.get_default_value() != 'Bone'):
continue
if (namePin.is_u_object() == True):
continue
if (len(n.get_linked_source_nodes()) > 0):
continue
key = unreal.RigElementKey(unreal.RigElementType.BONE, namePin.get_default_value())
if (hierarchy.contains(key) == True):
continue
print(f'disable linked node from {typePin.get_default_value()} : {namePin.get_default_value()}')
for toNoneNode in n.get_linked_target_nodes():
disableNode(toNoneNode)
## morph
# -vrm vrm -rig rig -debugeachsave 0
#args.vrm
#args.rig
command = 'VRM4U_CreateMorphTargetControllerUE5.py ' + '-vrm ' + args.vrm + ' -rig ' + args.rig + ' -debugeachsave 0'
print(command)
unreal.PythonScriptLibrary.execute_python_command(command)
unreal.ControlRigBlueprintLibrary.recompile_vm(rig)
|
# Copyright (c) <2021> Side Effects Software Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. The name of Side Effects Software may not be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
""" An example script that uses the API and
HoudiniEngineV2.asyncprocessor.ProcessHDA. ProcessHDA is configured with the
asset to instantiate, as well as 2 inputs: a geometry input (a cube) and a
curve input (a helix).
ProcessHDA is then activiated upon which the asset will be instantiated,
inputs set, and cooked. The ProcessHDA class's on_post_processing() function is
overridden to fetch the input structure and logged. The other state/phase
functions (on_pre_instantiate(), on_post_instantiate() etc) are overridden to
simply log the function name, in order to observe progress in the log.
"""
import math
import unreal
from HoudiniEngineV2.asyncprocessor import ProcessHDA
_g_processor = None
class ProcessHDAExample(ProcessHDA):
@staticmethod
def _print_api_input(in_input):
print('\t\tInput type: {0}'.format(in_input.__class__))
print('\t\tbKeepWorldTransform: {0}'.format(in_input.keep_world_transform))
print('\t\tbImportAsReference: {0}'.format(in_input.import_as_reference))
if isinstance(in_input, unreal.HoudiniPublicAPIGeoInput):
print('\t\tbPackBeforeMerge: {0}'.format(in_input.pack_before_merge))
print('\t\tbExportLODs: {0}'.format(in_input.export_lo_ds))
print('\t\tbExportSockets: {0}'.format(in_input.export_sockets))
print('\t\tbExportColliders: {0}'.format(in_input.export_colliders))
elif isinstance(in_input, unreal.HoudiniPublicAPICurveInput):
print('\t\tbCookOnCurveChanged: {0}'.format(in_input.cook_on_curve_changed))
print('\t\tbAddRotAndScaleAttributesOnCurves: {0}'.format(in_input.add_rot_and_scale_attributes_on_curves))
input_objects = in_input.get_input_objects()
if not input_objects:
print('\t\tEmpty input!')
else:
print('\t\tNumber of objects in input: {0}'.format(len(input_objects)))
for idx, input_object in enumerate(input_objects):
print('\t\t\tInput object #{0}: {1}'.format(idx, input_object))
if hasattr(in_input, 'supports_transform_offset') and in_input.supports_transform_offset():
print('\t\t\tObject Transform Offset: {0}'.format(in_input.get_input_object_transform_offset(idx)))
if isinstance(input_object, unreal.HoudiniPublicAPICurveInputObject):
print('\t\t\tbClosed: {0}'.format(input_object.is_closed()))
print('\t\t\tCurveMethod: {0}'.format(input_object.get_curve_method()))
print('\t\t\tCurveType: {0}'.format(input_object.get_curve_type()))
print('\t\t\tReversed: {0}'.format(input_object.is_reversed()))
print('\t\t\tCurvePoints: {0}'.format(input_object.get_curve_points()))
def on_failure(self):
print('on_failure')
global _g_processor
_g_processor = None
def on_complete(self):
print('on_complete')
global _g_processor
_g_processor = None
def on_pre_instantiation(self):
print('on_pre_instantiation')
def on_post_instantiation(self):
print('on_post_instantiation')
def on_post_auto_cook(self, cook_success):
print('on_post_auto_cook, success = {0}'.format(cook_success))
def on_pre_process(self):
print('on_pre_process')
def on_post_processing(self):
print('on_post_processing')
# Fetch inputs, iterate over it and log
node_inputs = self.asset_wrapper.get_inputs_at_indices()
parm_inputs = self.asset_wrapper.get_input_parameters()
if not node_inputs:
print('No node inputs found!')
else:
print('Number of node inputs: {0}'.format(len(node_inputs)))
for input_index, input_wrapper in node_inputs.items():
print('\tInput index: {0}'.format(input_index))
self._print_api_input(input_wrapper)
if not parm_inputs:
print('No parameter inputs found!')
else:
print('Number of parameter inputs: {0}'.format(len(parm_inputs)))
for parm_name, input_wrapper in parm_inputs.items():
print('\tInput parameter name: {0}'.format(parm_name))
self._print_api_input(input_wrapper)
def on_post_auto_bake(self, bake_success):
print('on_post_auto_bake, succes = {0}'.format(bake_success))
def get_test_hda_path():
return '/project/.copy_to_curve_1_0'
def get_test_hda():
return unreal.load_object(None, get_test_hda_path())
def get_geo_asset_path():
return '/project/.Cube'
def get_geo_asset():
return unreal.load_object(None, get_geo_asset_path())
def build_inputs():
print('configure_inputs')
# get the API singleton
houdini_api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
node_inputs = {}
# Create a geo input
geo_input = houdini_api.create_empty_input(unreal.HoudiniPublicAPIGeoInput)
# Set the input objects/assets for this input
geo_object = get_geo_asset()
geo_input.set_input_objects((geo_object, ))
# store the input data to the HDA as node input 0
node_inputs[0] = geo_input
# Create a curve input
curve_input = houdini_api.create_empty_input(unreal.HoudiniPublicAPICurveInput)
# Create a curve wrapper/helper
curve_object = unreal.HoudiniPublicAPICurveInputObject(curve_input)
# Make it a Nurbs curve
curve_object.set_curve_type(unreal.HoudiniPublicAPICurveType.NURBS)
# Set the points of the curve, for this example we create a helix
# consisting of 100 points
curve_points = []
for i in range(100):
t = i / 20.0 * math.pi * 2.0
x = 100.0 * math.cos(t)
y = 100.0 * math.sin(t)
z = i
curve_points.append(unreal.Transform([x, y, z], [0, 0, 0], [1, 1, 1]))
curve_object.set_curve_points(curve_points)
# Set the curve wrapper as an input object
curve_input.set_input_objects((curve_object, ))
# Store the input data to the HDA as node input 1
node_inputs[1] = curve_input
return node_inputs
def run():
# Create the processor with preconfigured inputs
global _g_processor
_g_processor = ProcessHDAExample(
get_test_hda(), node_inputs=build_inputs())
# Activate the processor, this will starts instantiation, and then cook
if not _g_processor.activate():
unreal.log_warning('Activation failed.')
else:
unreal.log('Activated!')
if __name__ == '__main__':
run()
|
import unreal
ground_truth_input = "ASplineCar1:car,SM_Ramp2:ramp,SM_Cube4:cube"
args = unreal.SystemLibrary.get_command_line()
tokens, switches, params = unreal.SystemLibrary.parse_command_line(args);
if "ground_truth" in params:
ground_truth_input = str(params["ground_truth"])
#separate ground_truth_input by coma
gt_requests = ground_truth_input.split(',')
actor_names = []
for gt in gt_requests:
actor_names.append(gt.split(':')[0])
# Get the editor actor subsystem
actor_subsys = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
lst_actors = unreal.EditorLevelLibrary.get_all_level_actors()
non_gt_index = len(actor_names)
for act in lst_actors:
if act.root_component == None:
continue
actor_in_ground_truth = False
act_label = act.get_actor_label()
ground_truth_index = non_gt_index
for target_actor in actor_names:
if target_actor == act_label:
#find the index of the ground truth actor in actor_names
ground_truth_index = actor_names.index(target_actor)
print("Ground truth actor found: " + act_label)
print("With Ground Truth Index: " + str(ground_truth_index))
print(actor_names)
break
children = act.get_components_by_class(unreal.PrimitiveComponent)
#find all PrimitiveComponents
for child in children:
child.set_render_custom_depth(True)
child.set_custom_depth_stencil_value(ground_truth_index)
|
# Copyright Epic Games, Inc. All Rights Reserved.
import os
import re
import unreal
import tempfile
import flow.cmd
import unrealcmd
import prettyprinter
#-------------------------------------------------------------------------------
def _fuzzy_find_code(prompt):
import fzf
import subprocess as sp
rg_args = (
"rg",
"--files",
"--path-separator=/",
"--no-ignore",
"-g*.cpp", "-g*.Build.cs",
"--ignore-file=" + os.path.abspath(__file__ + "/../../dirs.rgignore"),
)
rg = sp.Popen(rg_args, stdout=sp.PIPE, stderr=sp.DEVNULL, stdin=sp.DEVNULL)
ret = None
for reply in fzf.run(None, prompt=prompt, ext_stdin=rg.stdout):
ret = reply
break
rg.stdout.close()
rg.terminate()
return ret
#-------------------------------------------------------------------------------
class _Builder(object):
def __init__(self, ue_context):
self._args = []
self._ue_context = ue_context
self._targets = ()
self._projected = False
self.set_platform(unreal.Platform.get_host())
self.set_variant("development")
def set_targets(self, *targets): self._targets = targets
def set_platform(self, platform): self._platform = platform
def set_variant(self, variant): self._variant = variant
def set_projected(self, value=True):self._projected = value
def add_args(self, *args):
self._args += list(args)
def read_actions(self):
platform = self._platform
variant = self._variant
targets = (x.get_name() for x in self._targets)
args = self._args
projected = any(x.is_project_target() for x in self._targets)
if self._projected or projected:
if project := self._ue_context.get_project():
args = ("-Project=" + str(project.get_path()), *args)
ubt = self._ue_context.get_engine().get_ubt()
yield from ubt.read_actions(*targets, platform, variant, *args)
#-------------------------------------------------------------------------------
class _PrettyPrinter(prettyprinter.Printer):
def __init__(self, logger):
self._source_re = re.compile(r"^(\s+\[[0-9/]+\]\s+|)([^ ]+\.[a-z]+)")
self._error_re = re.compile("([Ee]rror:|ERROR|Exception: |error LNK|error C)")
self._warning_re = re.compile("(warning C|[Ww]arning: |note:)")
self._progress_re = re.compile(r"^\s*@progress\s+('([^']+)'|\w+)(\s+(\d+))?")
self._for_target_re = re.compile(r"^\*\* For ([^\s]+) \*\*")
self._percent = 0
self._for_target = ""
self._section = None
self._logger = logger
self._error_file = tempfile.TemporaryFile(mode="w+t")
def print_error_summary(self):
import textwrap
import shutil
msg_width = shutil.get_terminal_size(fallback=(9999,0))[0]
error_file = self._error_file
error_file.seek(0);
files = {}
for line in error_file:
m = re.search(r"\s*(.+\.[a-z]+)[(:](\d+)[,:)0-9]+\s*(.+)$", line[1:])
if not m:
continue
line_no = int(m.group(2), 0)
lines = files.setdefault(m.group(1), {})
msgs = lines.setdefault(line_no, set())
msgs.add((line[0] != "W", m.group(3)))
if not files:
return
print()
print(flow.cmd.text.light_yellow("Errors and warnings:"))
print()
msg_width -= 6
for file_path, lines in files.items():
print(flow.cmd.text.white(file_path))
for line in sorted(lines.keys()):
msgs = lines[line]
print(
" Line",
flow.cmd.text.white(line),
flow.cmd.text.grey("/ " + os.path.basename(file_path))
)
for is_error, msg in msgs:
decorator = flow.cmd.text.light_red if is_error else flow.cmd.text.light_yellow
with decorator:
for msg_line in textwrap.wrap(msg, width=msg_width):
print(" ", msg_line)
def _print(self, line):
if " Creating library " in line:
return
progress = self._progress_re.search(line)
if progress:
next_section = progress.group(2)
if next_section:
self._percent = min(int(progress.group(3)), 100)
if next_section != self._section:
self._section = next_section
self._logger.print_info(self._section)
return
if self._error_re.search(line):
line = line.lstrip()
print("E", line, sep="", file=self._error_file)
print(flow.cmd.text.light_red(line))
return
if self._warning_re.search(line):
line = line.lstrip()
if "note:" not in line:
print("W", line, sep="", file=self._error_file)
print(flow.cmd.text.light_yellow(line))
return
for_target = self._for_target_re.search(line)
if for_target:
for_target = for_target.group(1)
self._for_target = for_target[:5]
return
out = ""
if self._section != None:
out = flow.cmd.text.grey("%3d%%" % self._percent) + " "
source = self._source_re.search(line)
if source:
spos, epos = source.span(2)
if self._for_target:
out += flow.cmd.text.grey(self._for_target)
out += " "
out += line[:spos]
out += flow.cmd.text.white(line[spos:epos])
out += line[epos:]
else:
out += line
print(out)
#-------------------------------------------------------------------------------
class _BuildCmd(unrealcmd.Cmd):
""" The 'fileormod' argument allows the build to be constrained to a specific
module or source file to. It accepts one of the following forms as input;
CoreTest - builds the target's "CoreTest" module
CoreTest/SourceFile.cpp - compiles CoreTest/Private/**/SourceFile.cpp
path/project/.cpp - absolute or relative single file to compile
- - fuzzy find the file/modules to build (single dash)
"""
_variant = unrealcmd.Arg("development", "The build variant to have the build build")
fileormod = unrealcmd.Arg("", "Constrain build to a single file or module")
ubtargs = unrealcmd.Arg([str], "Arguments to pass to UnrealBuildTool")
clean = unrealcmd.Opt(False, "Cleans the current build")
nouht = unrealcmd.Opt(False, "Skips building UnrealHeaderTool")
noxge = unrealcmd.Opt(False, "Disables IncrediBuild")
analyze = unrealcmd.Opt(("", "visualcpp"), "Run static analysis (add =pvsstudio for PVS)")
projected = unrealcmd.Opt(False, "Add the -Project= argument when running UnrealBuildTool")
complete_analyze = ("visualcpp", "pvsstudio")
#complete_ubtargs = ...see end of file
def complete_fileormod(self, prefix):
search_roots = (
"Source/Runtime/*",
"Source/Developer/*",
"Source/Editor/*",
)
ue_context = self.get_unreal_context()
if prefix:
from pathlib import Path
for root in search_roots:
for suffix in ("./Private/", "./Internal/"):
haystack = root[:-1] + prefix + suffix
yield from (x.name for x in ue_context.glob(haystack + "**/*.cpp"))
else:
seen = set()
for root in search_roots:
for item in (x for x in ue_context.glob(root) if x.is_dir()):
if item.name not in seen:
seen.add(item.name)
yield item.name
yield item.name + "/"
def _add_file_or_module(self, builder):
file_or_module = self.args.fileormod
self._constrained_build = bool(file_or_module)
if not file_or_module:
return
if file_or_module == "-":
print("Select .cpp/.Build.cs...", end="")
file_or_module = _fuzzy_find_code(".build [...] ")
if not file_or_module:
raise SystemExit
if file_or_module.endswith(".Build.cs"):
file_or_module = os.path.basename(file_or_module)[:-9]
ue_context = self.get_unreal_context()
all_modules = True
if project := ue_context.get_project():
project_path_str = str(project.get_dir())
all_modules = any(x in project_path_str for x in ("EngineTest", "Samples"))
if all_modules:
builder.add_args("-AllModules")
# If there's no ./\ in the argument then it is deemed to be a module
if not any((x in ".\\/") for x in file_or_module):
builder.add_args("-Module=" + file_or_module)
return
# We're expecting a file
if os.path.isfile(file_or_module):
file_or_module = os.path.abspath(file_or_module)
# (...N.B. an elif follows)
# Perhaps this is in module/file shorthand?
elif shorthand := file_or_module.split("/"):
rglob_pattern = "/".join(shorthand[1:])
search_roots = (
"Source/Runtime/",
"Source/Developer/",
"Source/Editor/",
)
for root in search_roots:
for item in ue_context.glob(root + shorthand[0]):
if file := next(item.rglob(rglob_pattern), None):
file_or_module = str(file.resolve())
break
builder.add_args("-SingleFile=" + file_or_module)
def is_constrained_build(self):
return getattr(self, "_constrained_build", False)
def get_builder(self):
ue_context = self.get_unreal_context()
builder = _Builder(ue_context)
if self.args.clean: builder.add_args("-Clean")
if self.args.nouht: builder.add_args("-NoBuildUHT")
if self.args.noxge: builder.add_args("-NoXGE")
if self.args.analyze: builder.add_args("-StaticAnalyzer=" + self.args.analyze)
if self.args.ubtargs: builder.add_args(*self.args.ubtargs)
if self.args.projected: builder.set_projected() # forces -Project=
builder.add_args("-Progress")
# Handle shortcut to compile a specific module or individual file.
self._add_file_or_module(builder)
return builder
def run_build(self, builder):
try: exec_context = self._exec_context
except AttributeError: self._exec_context = self.get_exec_context()
exec_context = self._exec_context
# Inform the user of the current build configuration
self.print_info("Build configuration")
ue_context = self.get_unreal_context()
ubt = ue_context.get_engine().get_ubt()
for config in (x for x in ubt.read_configurations() if x.exists()):
level = config.get_level()
try:
for category, name, value in config.read_values():
name = flow.cmd.text.white(name)
print(category, ".", name, " = ", value, " (", level.name.title(), ")", sep="")
except IOError as e:
self.print_warning(f"Failed loading '{config.get_path()}'")
self.print_warning(str(e))
continue
self.print_info("Running UnrealBuildTool")
printer = _PrettyPrinter(self)
try:
for cmd, args in builder.read_actions():
cmd = exec_context.create_runnable(cmd, *args)
printer.run(cmd)
if ret := cmd.get_return_code():
break
else:
return
except KeyboardInterrupt:
raise KeyboardInterrupt("Waiting for UBT...")
finally:
printer.print_error_summary()
return ret
#-------------------------------------------------------------------------------
class Build(_BuildCmd, unrealcmd.MultiPlatformCmd):
""" Direct access to running UBT """
target = unrealcmd.Arg(str, "Name of the target to build")
platform = unrealcmd.Arg("", "Platform to build (default = host)")
variant = _BuildCmd._variant
def complete_target(self, prefix):
ue_context = self.get_unreal_context()
yield from (x.name[:-10] for x in ue_context.glob("Source/*.Target.cs"))
yield from (x.name[:-10] for x in ue_context.glob("Source/Programs/**/*.Target.cs"))
@unrealcmd.Cmd.summarise
def main(self):
self.use_all_platforms()
ue_context = self.get_unreal_context()
targets = self.args.target.split()
targets = map(ue_context.get_target_by_name, targets)
builder = self.get_builder()
builder.set_targets(*targets)
builder.set_variant(self.args.variant)
if self.args.platform:
try: platform = self.get_platform(self.args.platform).get_name()
except ValueError: platform = self.args.platform
builder.set_platform(platform)
return self.run_build(builder)
#-------------------------------------------------------------------------------
class Editor(_BuildCmd, unrealcmd.MultiPlatformCmd):
""" Builds the editor. By default the current host platform is targeted. This
can be overridden using the '--platform' option to cross-compile the editor."""
variant = _BuildCmd._variant
noscw = unrealcmd.Opt(False, "Skip building ShaderCompileWorker")
nopak = unrealcmd.Opt(False, "Do not build UnrealPak")
nointworker = unrealcmd.Opt(False, "Exclude the implicit InterchangeWorker dependency")
platform = unrealcmd.Opt("", "Platform to build the editor for")
@unrealcmd.Cmd.summarise
def main(self):
self.use_all_platforms()
builder = self.get_builder()
builder.set_variant(self.args.variant)
if self.args.platform:
platform = self.get_platform(self.args.platform).get_name()
builder.set_platform(platform)
ue_context = self.get_unreal_context()
editor_target = ue_context.get_target_by_type(unreal.TargetType.EDITOR)
targets = (editor_target,)
editor_only = self.is_constrained_build() # i.e. single file or module
editor_only |= bool(self.args.analyze)
editor_only |= self.args.variant != "development"
if not editor_only:
if not self.args.noscw:
targets = (*targets, ue_context.get_target_by_name("ShaderCompileWorker"))
if not self.args.nopak:
targets = (*targets, ue_context.get_target_by_name("UnrealPak"))
if not self.args.nointworker:
prog_target = ue_context.get_target_by_name("InterchangeWorker")
if prog_target.get_type() == unreal.TargetType.PROGRAM:
targets = (*targets, prog_target)
builder.set_targets(*targets)
return self.run_build(builder)
#-------------------------------------------------------------------------------
class Program(_BuildCmd, unrealcmd.MultiPlatformCmd):
""" Builds a program for the current host platform (unless the --platform
argument is provided) """
program = unrealcmd.Arg(str, "Target name of the program to build")
variant = _BuildCmd._variant
platform = unrealcmd.Opt("", "Platform to build the program for")
def complete_program(self, prefix):
ue_context = self.get_unreal_context()
for depth in ("*", "*/*"):
for target_cs in ue_context.glob(f"Source/Programs/{depth}/*.Target.cs"):
yield target_cs.name[:-10]
@unrealcmd.Cmd.summarise
def main(self):
ue_context = self.get_unreal_context()
target = ue_context.get_target_by_name(self.args.program)
builder = self.get_builder()
builder.set_targets(target)
builder.set_variant(self.args.variant)
self.use_all_platforms()
if self.args.platform:
platform = self.get_platform(self.args.platform).get_name()
builder.set_platform(platform)
return self.run_build(builder)
#-------------------------------------------------------------------------------
class Server(_BuildCmd, unrealcmd.MultiPlatformCmd):
""" Builds the server target for the host platform """
platform = unrealcmd.Arg("", "Platform to build the server for")
variant = _BuildCmd._variant
complete_platform = ("win64", "linux")
@unrealcmd.Cmd.summarise
def main(self):
# Set up the platform, defaulting to the host if none was given.
platform = self.args.platform
if not platform:
platform = unreal.Platform.get_host()
self.use_platform(self.args.platform)
ue_context = self.get_unreal_context()
target = ue_context.get_target_by_type(unreal.TargetType.SERVER)
builder = self.get_builder()
builder.set_targets(target)
builder.set_variant(self.args.variant)
if self.args.platform:
platform = self.get_platform(self.args.platform).get_name()
builder.set_platform(platform)
return self.run_build(builder)
#-------------------------------------------------------------------------------
class _Runtime(_BuildCmd, unrealcmd.MultiPlatformCmd):
platform = unrealcmd.Arg("", "Build the runtime for this platform")
variant = _BuildCmd._variant
@unrealcmd.Cmd.summarise
def _main_impl(self, target):
platform = self.args.platform
if not platform:
platform = unreal.Platform.get_host().lower()
self.use_platform(platform)
platform = self.get_platform(platform).get_name()
builder = self.get_builder()
builder.set_platform(platform)
builder.set_targets(target)
builder.set_variant(self.args.variant)
return self.run_build(builder)
#-------------------------------------------------------------------------------
class Client(_Runtime):
""" Builds the client runtime """
def main(self):
ue_context = self.get_unreal_context()
target = ue_context.get_target_by_type(unreal.TargetType.CLIENT)
return super()._main_impl(target)
#-------------------------------------------------------------------------------
class Game(_Runtime):
""" Builds the game runtime target binary executable """
def main(self):
ue_context = self.get_unreal_context()
target = ue_context.get_target_by_type(unreal.TargetType.GAME)
return super()._main_impl(target)
#-------------------------------------------------------------------------------
class _CleanImpl(object):
def main(self):
self.args.clean = True
return super().main()
def _make_clean_command(base):
return type("CleanImpl", (_CleanImpl, base), {})
CleanEditor = _make_clean_command(Editor)
CleanProgram = _make_clean_command(Program)
CleanServer = _make_clean_command(Server)
CleanClient = _make_clean_command(Client)
CleanGame = _make_clean_command(Game)
#-------------------------------------------------------------------------------
_BuildCmd.complete_ubtargs = (
"-2015", "-2017", "-2019", "-AllModules", "-alwaysgeneratedsym",
"-Architectures", "-build-as-framework", "-BuildPlugin", "-BuildVersion",
"-BundleVersion", "-Clean", "-CLion", "-CMakefile", "-CodeliteFiles",
"-CompileAsDll", "-CompileChaos", "-CompilerArguments", "-CompilerVersion",
"-CppStd", "-CreateStub", "-Define:", "-DependencyList", "-Deploy",
"-DisableAdaptiveUnity", "-DisablePlugin", "-DisableUnity", "-distribution",
"-dSYM", "-EdditProjectFiles", "-EnableASan", "-EnableMSan",
"-EnablePlugin", "-EnableTSan", "-EnableUBSan",
"-FailIfGeneratedCodeChanges", "-FastMonoCalls", "-FastPDB", "-FlushMac",
"-ForceDebugInfo", "-ForceHeaderGeneration", "-ForceHotReload",
"-ForceUnity", "-Formal", "-FromMsBuild", "-generatedsymbundle",
"-generatedsymfile", "-GPUArchitectures", "-IgnoreJunk",
"-ImportCertificate", "-ImportCertificatePassword", "-ImportProvision",
"-IncrementalLinking", "-Input", "-IWYU", "-KDevelopfile",
"-LinkerArguments", "-LiveCoding", "-LiveCodingLimit",
"-LiveCodingManifest", "-LiveCodingModules", "-Log", "-LTCG", "-Makefile",
"-Manifest", "-MapFile", "-MaxParallelActions", "-Modular", "-Module",
"-Monolithic", "-NoBuildUHT", "-NoCompileChaos", "-NoDebugInfo", "-NoDSYM",
"-NoEngineChanges", "-NoFASTBuild", "-NoFastMonoCalls", "-NoHotReload",
"-NoHotReloadFromIDE", "-NoIncrementalLinking", "-NoLink",
"-NoManifestChanges", "-NoMutex", "-NoPCH", "-NoPDB", "-NoSharedPCH",
"-NoUBTMakefiles", "-NoUseChaos", "-NoXGE", "-ObjSrcMap", "-Output",
"-OverrideBuildEnvironment", "-PGOOptimize", "-PGOProfile", "-Plugin",
"-Precompile", "-Preprocess", "-PrintDebugInfo", "-Progress",
"-ProjectDefine:", "-ProjectFileFormat", "-ProjectFiles",
"-PublicSymbolsByDefault", "-QMakefile", "-Quiet", "-RemoteIni", "-Rider",
"-rtti", "-ShadowVariableErrors", "-SharedBuildEnvironment",
"-ShowIncludes", "-SingleFile", "-SkipBuild", "-skipcrashlytics",
"-SkipDeploy", "-SkipPreBuildTargets", "-SkipRulesCompile",
"-StaticAnalyzer", "-StressTestUnity", "-Strict", "-stripsymbols",
"-ThinLTO", "-Timestamps", "-Timing", "-ToolChain", "-Tracing",
"-UniqueBuildEnvironment", "-UseChaos", "-UsePrecompiled", "-Verbose",
"-VeryVerbose", "-VSCode", "-VSMac", "-WaitMutex", "-WarningsAsErrors",
"-WriteOutdatedActions", "-XCodeProjectFiles", "-XGEExport",
)
|
# Copyright Epic Games, Inc. All Rights Reserved
# Third-party
import unreal
@unreal.uclass()
class BaseActionMenuEntry(unreal.ToolMenuEntryScript):
"""
This is a custom Unreal Class that adds executable python menus to the
Editor
"""
def __init__(self, callable_method, parent=None):
"""
Constructor
:param callable_method: Callable method to execute
"""
super(BaseActionMenuEntry, self).__init__()
self._callable = callable_method
self.parent = parent
@unreal.ufunction(override=True)
def execute(self, context):
"""
Executes the callable method
:param context:
:return:
"""
self._callable()
@unreal.ufunction(override=True)
def can_execute(self, context):
"""
Determines if a menu can be executed
:param context:
:return:
"""
return True
@unreal.ufunction(override=True)
def get_tool_tip(self, context):
"""
Returns the tool tip for the menu
:param context:
:return:
"""
return self.data.tool_tip
@unreal.ufunction(override=True)
def get_label(self, context):
"""
Returns the label of the menu
:param context:
:return:
"""
return self.data.name
|
import unreal
selected_asset = unreal.EditorUtilityLibrary.get_selected_assets()[0]
print(selected_asset)
new_length = unreal.FrameNumber(50)
new_t0 = unreal.FrameNumber(0)
new_t1 = unreal.FrameNumber(50)
controller = unreal.AnimSequencerController(selected_asset)
|
# Copyright (C) 2024 Louis Vottero [email protected] All rights reserved.
import sys
import unreal
from .. import qt
from ..process_manager import ui_process_manager
app = None
if not qt.QApplication.instance():
app = qt.QApplication(sys.argv)
def process_manager():
window = ui_process_manager.ProcessManagerWindow()
window.show()
unreal.parent_external_window_to_slate(window.winId(), unreal.SlateParentWindowSearchMethod.MAIN_WINDOW)
|
import unreal
# from .SceneCapture2DActor import SceneCapture2DActor
import random
import time
import numpy as np
class TaskScene:
def __init__(self,original_objects_label=None):
if original_objects_label:
self.original_objects_label = original_objects_label
else:
self.original_objects_label = ['Floor',
'ExponentialHeightFog',
'StarSkySphere',
'SunSky',
'GeoReferencingSystem',
'GlobalPostProcessVolume']
def initialize(self):
unreal.EditorLevelLibrary.load_level('/project/.SimBlank')
actors=unreal.EditorLevelLibrary.get_all_level_actors()
for actor in actors:
if actor.get_actor_label() not in self.original_objects_label:
print(f"destroyed {actor.get_actor_label()}")
actor.destroy_actor()
def add_object(self,asset_path, label, translation, rotation, scale=None):
'''
translation: (x,y,z) tuple
rotation: (pitch,yaw,roll) tuple
'''
# Load the asset into memory
asset = unreal.EditorAssetLibrary.load_asset(asset_path)
# Check if the asset is valid
if asset:
# Specify the location and rotation where you want to spawn the asset
spawn_location = unreal.Vector(*translation) # X, Y, Z coordinates
spawn_rotation = unreal.Rotator(*rotation) # Pitch, Yaw, Roll rotation
# Spawn the asset at the specified location and rotation
spawned_actor = unreal.EditorLevelLibrary.spawn_actor_from_object(asset, spawn_location, spawn_rotation)
spawned_actor.set_actor_label(label)
if scale:
spawned_actor.set_actor_scale3d(unreal.Vector(scale, scale, scale))
if spawned_actor:
print(f"Successfully spawned asset at {spawn_location}.")
else:
print("Failed to spawn asset.")
else:
print(f"Failed to load asset from path: {asset_path}.")
pass
def template_scene(self):
'''
1. load and clean the scene
2. add objects
'''
#
wood_table = "/project/.table_wood"
coffee_mug = "/project/.coffee_mug"
wine = "/project/.3d_wine_bottle_model"
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[i:i + block_size, j:j + block_size]
if sub_map.all():
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):
i, j = block_position
assert bool_map[i:i + block_size, j:j + block_size].all()
bool_map[i:i + block_size, j:j + block_size] = False
return bool_map
self.initialize()
num_coffee_mug = random.choice(range(1, 3))
num_wine = random.choice(range(1, 3))
limits = [[-90, 90], [-40, 40]]
height = 77
bool_map = np.bool_(np.ones((180, 80)))
num_coffee_mug = 3
num_wine = 3
block_size = 30
self.add_object(wood_table, "table_wood", (0, 0, 0), (0, 0, 0))
time.sleep(3)
for i in range(num_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]
self.add_object(coffee_mug, f"coffee_mug_{i}", (x, y, height), (0, 0, 0))
time.sleep(0.2)
else:
print("No empty space found for coffee mug.")
break
for i in range(num_wine):
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]
self.add_object(wine, f"wine_{i}", (x, y, height), (0, 0, 0), scale=0.1)
time.sleep(0.2)
else:
print("No empty space found for wine.")
break
test=TaskScene()
test.template_scene()
|
# Should be used with internal UE API in later versions of UE
"""
Automatically create material instances based on mesh names
(as they are similar to material names and texture names)
"""
import unreal
import os
OVERWRITE_EXISTING = False
def set_material_instance_texture(material_instance_asset, material_parameter, texture_path):
if not unreal.editor_asset_library.does_asset_exist(texture_path):
unreal.log_warning("Can't find texture: " + texture_path)
return False
tex_asset = unreal.editor_asset_library.find_asset_data(texture_path).get_asset()
return unreal.material_editing_library.set_material_instance_texture_parameter_value(material_instance_asset,
material_parameter, tex_asset)
base_material = unreal.editor_asset_library.find_asset_data("/project/")
AssetTools = unreal.AssetToolsHelpers.get_asset_tools()
MaterialEditingLibrary = unreal.material_editing_library
EditorAssetLibrary = unreal.editor_asset_library
# noinspection DuplicatedCode
def create_material_instance(material_instance_folder, mesh_name):
material_instance_name = "MI_" + mesh_name.replace("RT", "").replace("LT", "")
material_instance_path = os.path.join(material_instance_folder, material_instance_name)
if EditorAssetLibrary.does_asset_exist(material_instance_path):
# material_instance_asset = EditorAssetLibrary.find_asset_data(material_instance_path).get_asset()
unreal.log("Asset already exists")
if OVERWRITE_EXISTING:
EditorAssetLibrary.delete_asset(material_instance_path)
else:
return
material_instance_asset = AssetTools.create_asset(material_instance_name, material_instance_folder,
unreal.MaterialInstanceConstant,
unreal.MaterialInstanceConstantFactoryNew())
# Set parent material
MaterialEditingLibrary.set_material_instance_parent(material_instance_asset, base_material.get_asset())
base_color_texture = os.path.join(material_instance_folder,
"T_" + mesh_name.replace("RT", "").replace("LT", "") + "_BC")
if EditorAssetLibrary.does_asset_exist(base_color_texture):
set_material_instance_texture(material_instance_asset, "Base Color", base_color_texture)
mask_texture = os.path.join(material_instance_folder, "T_" + mesh_name.replace("RT", "").replace("LT", "") + "_Mk")
if EditorAssetLibrary.does_asset_exist(mask_texture):
set_material_instance_texture(material_instance_asset, "Mask", mask_texture)
normal_texture = os.path.join(material_instance_folder, "T_" + mesh_name.replace("RT", "").replace("LT", "") + "_N")
if EditorAssetLibrary.does_asset_exist(normal_texture):
set_material_instance_texture(material_instance_asset, "Normal", normal_texture)
roughness_texture = os.path.join(material_instance_folder,
"T_" + mesh_name.replace("RT", "").replace("LT", "") + "_R")
if EditorAssetLibrary.does_asset_exist(roughness_texture):
set_material_instance_texture(material_instance_asset, "Roughness", roughness_texture)
metal_texture = os.path.join(material_instance_folder, "T_" + mesh_name.replace("RT", "").replace("LT", "") + "_M")
if EditorAssetLibrary.does_asset_exist(metal_texture):
set_material_instance_texture(material_instance_asset, "Metal", metal_texture)
EditorAssetLibrary.save_asset(material_instance_path)
asset_reg = unreal.AssetRegistryHelpers.get_asset_registry()
asset_root_dir = '/project/'
assets = asset_reg.get_assets_by_path(asset_root_dir, recursive=True)
for asset in assets:
if asset.asset_class == "SkeletalMesh":
create_material_instance(str(asset.package_path), str(asset.asset_name))
|
๏ปฟ# 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
|
import unreal
asset_path:str
key:str
value:str
loaded_asset = unreal.EditorAssetLibrary.load_asset(asset_path)
unreal.EditorAssetLibrary.set_metadata_tag(loaded_asset, key, value)
|
# -*- coding: utf-8 -*-
import os
import re
import json
import clique
import copy
import logging
from typing import List, Any
from contextlib import contextmanager
import time
import semver
import pyblish.api
import ayon_api
from ayon_core.pipeline import (
register_loader_plugin_path,
register_creator_plugin_path,
register_inventory_action_path,
deregister_loader_plugin_path,
deregister_creator_plugin_path,
deregister_inventory_action_path,
AYON_CONTAINER_ID,
get_current_project_name,
)
from ayon_core.lib import StringTemplate
from ayon_core.pipeline.context_tools import (
get_current_folder_entity
)
from ayon_core.tools.utils import host_tools
from ayon_core.host import HostBase, ILoadHost, IPublishHost
from ayon_unreal import UNREAL_ADDON_ROOT
import unreal # noqa
# Rename to Ayon once parent module renames
logger = logging.getLogger("ayon_core.hosts.unreal")
AYON_CONTAINERS = "AyonContainers"
AYON_ROOT_DIR = "/project/"
AYON_ASSET_DIR = "/project/"
CONTEXT_CONTAINER = "Ayon/context.json"
UNREAL_VERSION = semver.VersionInfo(
*os.getenv("AYON_UNREAL_VERSION").split(".")
)
PLUGINS_DIR = os.path.join(UNREAL_ADDON_ROOT, "plugins")
PUBLISH_PATH = os.path.join(PLUGINS_DIR, "publish")
LOAD_PATH = os.path.join(PLUGINS_DIR, "load")
CREATE_PATH = os.path.join(PLUGINS_DIR, "create")
INVENTORY_PATH = os.path.join(PLUGINS_DIR, "inventory")
class UnrealHost(HostBase, ILoadHost, IPublishHost):
"""Unreal host implementation.
For some time this class will re-use functions from module based
implementation for backwards compatibility of older unreal projects.
"""
name = "unreal"
def install(self):
install()
def get_containers(self):
return ls()
@staticmethod
def show_tools_popup():
"""Show tools popup with actions leading to show other tools."""
show_tools_popup()
@staticmethod
def show_tools_dialog():
"""Show tools dialog with actions leading to show other tools."""
show_tools_dialog()
def update_context_data(self, data, changes):
content_path = unreal.Paths.project_content_dir()
op_ctx = content_path + CONTEXT_CONTAINER
attempts = 3
for i in range(attempts):
try:
with open(op_ctx, "w+") as f:
json.dump(data, f)
break
except IOError as e:
if i == attempts - 1:
raise Exception(
"Failed to write context data. Aborting.") from e
unreal.log_warning("Failed to write context data. Retrying...")
i += 1
time.sleep(3)
continue
def get_context_data(self):
content_path = unreal.Paths.project_content_dir()
op_ctx = content_path + CONTEXT_CONTAINER
if not os.path.isfile(op_ctx):
return {}
with open(op_ctx, "r") as fp:
data = json.load(fp)
return data
def install():
"""Install Unreal configuration for AYON."""
print("-=" * 40)
logo = '''.
.
ยท
โ
ยทโ/
ยท-โโขโ-ยท
/ \\ /โยท / \\
โ \\ โ / โ
\\ \\ ยท / /
\\\\ โ โ //
\\\\/ \\//
___
โ โ
โ โ
โ โ
โ___โ
-ยท
ยท-โโโ-โ A Y O N โ-โโโ-ยท
by YNPUT
.
'''
print(logo)
print("installing Ayon for Unreal ...")
print("-=" * 40)
logger.info("installing Ayon for Unreal")
pyblish.api.register_host("unreal")
pyblish.api.register_plugin_path(str(PUBLISH_PATH))
register_loader_plugin_path(str(LOAD_PATH))
register_creator_plugin_path(str(CREATE_PATH))
register_inventory_action_path(str(INVENTORY_PATH))
_register_callbacks()
_register_events()
def uninstall():
"""Uninstall Unreal configuration for Ayon."""
pyblish.api.deregister_plugin_path(str(PUBLISH_PATH))
deregister_loader_plugin_path(str(LOAD_PATH))
deregister_creator_plugin_path(str(CREATE_PATH))
deregister_inventory_action_path(str(INVENTORY_PATH))
def _register_callbacks():
"""
TODO: Implement callbacks if supported by UE
"""
pass
def _register_events():
"""
TODO: Implement callbacks if supported by UE
"""
pass
def ls():
"""List all containers.
List all found in *Content Manager* of Unreal and return
metadata from them. Adding `objectName` to set.
"""
ar = unreal.AssetRegistryHelpers.get_asset_registry()
# UE 5.1 changed how class name is specified
class_name = ["/project/", "AyonAssetContainer"] if UNREAL_VERSION.major == 5 and UNREAL_VERSION.minor > 0 else "AyonAssetContainer" # noqa
ayon_containers = ar.get_assets_by_class(class_name, True)
# get_asset_by_class returns AssetData. To get all metadata we need to
# load asset. get_tag_values() work only on metadata registered in
# Asset Registry Project settings (and there is no way to set it with
# python short of editing ini configuration file).
for asset_data in ayon_containers:
asset = asset_data.get_asset()
data = unreal.EditorAssetLibrary.get_metadata_tag_values(asset)
data["objectName"] = asset_data.asset_name
yield cast_map_to_str_dict(data)
def ls_inst():
ar = unreal.AssetRegistryHelpers.get_asset_registry()
# UE 5.1 changed how class name is specified
class_name = [
"/project/",
"AyonPublishInstance"
] if (
UNREAL_VERSION.major == 5
and UNREAL_VERSION.minor > 0
) else "AyonPublishInstance" # noqa
instances = ar.get_assets_by_class(class_name, True)
# get_asset_by_class returns AssetData. To get all metadata we need to
# load asset. get_tag_values() work only on metadata registered in
# Asset Registry Project settings (and there is no way to set it with
# python short of editing ini configuration file).
for asset_data in instances:
asset = asset_data.get_asset()
data = unreal.EditorAssetLibrary.get_metadata_tag_values(asset)
data["objectName"] = asset_data.asset_name
yield cast_map_to_str_dict(data)
def parse_container(container):
"""To get data from container, AyonAssetContainer must be loaded.
Args:
container(str): path to container
Returns:
dict: metadata stored on container
"""
asset = unreal.EditorAssetLibrary.load_asset(container)
data = unreal.EditorAssetLibrary.get_metadata_tag_values(asset)
data["objectName"] = asset.get_name()
data = cast_map_to_str_dict(data)
return data
def publish():
"""Shorthand to publish from within host."""
import pyblish.util
return pyblish.util.publish()
def containerise(name, namespace, nodes, context, loader=None, suffix="_CON"):
"""Bundles *nodes* (assets) into a *container* and add metadata to it.
Unreal doesn't support *groups* of assets that you can add metadata to.
But it does support folders that helps to organize asset. Unfortunately
those folders are just that - you cannot add any additional information
to them. Ayon Integration Plugin is providing way out - Implementing
`AssetContainer` Blueprint class. This class when added to folder can
handle metadata on it using standard
:func:`unreal.EditorAssetLibrary.set_metadata_tag()` and
:func:`unreal.EditorAssetLibrary.get_metadata_tag_values()`. It also
stores and monitor all changes in assets in path where it resides. List of
those assets is available as `assets` property.
This is list of strings starting with asset type and ending with its path:
`Material /project/.TestMaterial`
"""
# 1 - create directory for container
root = "/Game"
container_name = f"{name}{suffix}"
new_name = move_assets_to_path(root, container_name, nodes)
# 2 - create Asset Container there
path = f"{root}/{new_name}"
create_container(container=container_name, path=path)
namespace = path
data = {
"schema": "ayon:container-2.0",
"id": AYON_CONTAINER_ID,
"name": new_name,
"namespace": namespace,
"loader": str(loader),
"representation": context["representation"]["id"],
}
# 3 - imprint data
imprint(f"{path}/{container_name}", data)
return path
def instantiate(root, name, data, assets=None, suffix="_INS"):
"""Bundles *nodes* into *container*.
Marking it with metadata as publishable instance. If assets are provided,
they are moved to new path where `AyonPublishInstance` class asset is
created and imprinted with metadata.
This can then be collected for publishing by Pyblish for example.
Args:
root (str): root path where to create instance container
name (str): name of the container
data (dict): data to imprint on container
assets (list of str): list of asset paths to include in publish
instance
suffix (str): suffix string to append to instance name
"""
container_name = f"{name}{suffix}"
# if we specify assets, create new folder and move them there. If not,
# just create empty folder
if assets:
new_name = move_assets_to_path(root, container_name, assets)
else:
new_name = create_folder(root, name)
path = f"{root}/{new_name}"
create_publish_instance(instance=container_name, path=path)
imprint(f"{path}/{container_name}", data)
def imprint(node, data):
loaded_asset = unreal.EditorAssetLibrary.load_asset(node)
for key, value in data.items():
# Support values evaluated at imprint
if callable(value):
value = value()
# Unreal doesn't support NoneType in metadata values
if value is None:
value = ""
unreal.EditorAssetLibrary.set_metadata_tag(
loaded_asset, key, str(value)
)
with unreal.ScopedEditorTransaction("Ayon containerising"):
unreal.EditorAssetLibrary.save_asset(node)
def show_tools_popup():
"""Show popup with tools.
Popup will disappear on click or losing focus.
"""
from ayon_unreal.api import tools_ui
tools_ui.show_tools_popup()
def show_tools_dialog():
"""Show dialog with tools.
Dialog will stay visible.
"""
from ayon_unreal.api import tools_ui
tools_ui.show_tools_dialog()
def show_creator():
host_tools.show_creator()
def show_loader():
host_tools.show_loader(use_context=True)
def show_publisher():
host_tools.show_publish()
def show_manager():
host_tools.show_scene_inventory()
def show_experimental_tools():
host_tools.show_experimental_tools_dialog()
def create_folder(root: str, name: str) -> str:
"""Create new folder.
If folder exists, append number at the end and try again, incrementing
if needed.
Args:
root (str): path root
name (str): folder name
Returns:
str: folder name
Example:
>>> create_folder("/project/")
/project/
>>> create_folder("/project/")
/project/
"""
eal = unreal.EditorAssetLibrary
index = 1
while True:
if eal.does_directory_exist(f"{root}/{name}"):
name = f"{name}{index}"
index += 1
else:
eal.make_directory(f"{root}/{name}")
break
return name
def move_assets_to_path(root: str, name: str, assets: List[str]) -> str:
"""Moving (renaming) list of asset paths to new destination.
Args:
root (str): root of the path (eg. `/Game`)
name (str): name of destination directory (eg. `Foo` )
assets (list of str): list of asset paths
Returns:
str: folder name
Example:
This will get paths of all assets under `/project/` and move them
to `/project/`. If `/project/` already exists, then resulting
path will be `/project/`
>>> assets = unreal.EditorAssetLibrary.list_assets("/project/")
>>> move_assets_to_path("/Game", "NewTest", assets)
NewTest
"""
eal = unreal.EditorAssetLibrary
name = create_folder(root, name)
unreal.log(assets)
for asset in assets:
loaded = eal.load_asset(asset)
eal.rename_asset(asset, f"{root}/{name}/{loaded.get_name()}")
return name
def create_container(container: str, path: str) -> unreal.Object:
"""Helper function to create Asset Container class on given path.
This Asset Class helps to mark given path as Container
and enable asset version control on it.
Args:
container (str): Asset Container name
path (str): Path where to create Asset Container. This path should
point into container folder
Returns:
:class:`unreal.Object`: instance of created asset
Example:
create_container(
"/project/",
"modelingFooCharacter_CON"
)
"""
factory = unreal.AyonAssetContainerFactory()
tools = unreal.AssetToolsHelpers().get_asset_tools()
return tools.create_asset(container, path, None, factory)
def create_publish_instance(instance: str, path: str) -> unreal.Object:
"""Helper function to create Ayon Publish Instance on given path.
This behaves similarly as :func:`create_ayon_container`.
Args:
path (str): Path where to create Publish Instance.
This path should point into container folder
instance (str): Publish Instance name
Returns:
:class:`unreal.Object`: instance of created asset
Example:
create_publish_instance(
"/project/",
"modelingFooCharacter_INST"
)
"""
factory = unreal.AyonPublishInstanceFactory()
tools = unreal.AssetToolsHelpers().get_asset_tools()
return tools.create_asset(instance, path, None, factory)
def cast_map_to_str_dict(umap) -> dict:
"""Cast Unreal Map to dict.
Helper function to cast Unreal Map object to plain old python
dict. This will also cast values and keys to str. Useful for
metadata dicts.
Args:
umap: Unreal Map object
Returns:
dict
"""
return {str(key): str(value) for (key, value) in umap.items()}
def get_subsequences(sequence: unreal.LevelSequence):
"""Get list of subsequences from sequence.
Args:
sequence (unreal.LevelSequence): Sequence
Returns:
list(unreal.LevelSequence): List of subsequences
"""
tracks = get_tracks(sequence)
subscene_track = next(
(
t
for t in tracks
if t.get_class() == unreal.MovieSceneSubTrack.static_class()
),
None,
)
if subscene_track is not None and subscene_track.get_sections():
return subscene_track.get_sections()
return []
def set_sequence_hierarchy(
seq_i, seq_j, max_frame_i, min_frame_j, max_frame_j, map_paths
):
# Get existing sequencer tracks or create them if they don't exist
tracks = get_tracks(seq_i)
subscene_track = None
visibility_track = None
for t in tracks:
if t.get_class() == unreal.MovieSceneSubTrack.static_class():
subscene_track = t
if (t.get_class() ==
unreal.MovieSceneLevelVisibilityTrack.static_class()):
visibility_track = t
if not subscene_track:
subscene_track = add_track(seq_i, unreal.MovieSceneSubTrack)
if not visibility_track:
visibility_track = add_track(
seq_i, unreal.MovieSceneLevelVisibilityTrack)
# Create the sub-scene section
subscenes = subscene_track.get_sections()
subscene = None
for s in subscenes:
if s.get_editor_property('sub_sequence') == seq_j:
subscene = s
break
if not subscene:
subscene = subscene_track.add_section()
subscene.set_row_index(len(subscene_track.get_sections()))
subscene.set_editor_property('sub_sequence', seq_j)
subscene.set_range(
min_frame_j,
max_frame_j + 1)
# Create the visibility section
ar = unreal.AssetRegistryHelpers.get_asset_registry()
maps = []
for m in map_paths:
# Unreal requires to load the level to get the map name
unreal.EditorLevelLibrary.save_all_dirty_levels()
unreal.EditorLevelLibrary.load_level(m)
maps.append(str(ar.get_asset_by_object_path(m).asset_name))
vis_section = visibility_track.add_section()
index = len(visibility_track.get_sections())
vis_section.set_range(
min_frame_j,
max_frame_j + 1)
vis_section.set_visibility(unreal.LevelVisibility.VISIBLE)
vis_section.set_row_index(index)
vis_section.set_level_names(maps)
if min_frame_j > 1:
hid_section = visibility_track.add_section()
hid_section.set_range(
1,
min_frame_j)
hid_section.set_visibility(unreal.LevelVisibility.HIDDEN)
hid_section.set_row_index(index)
hid_section.set_level_names(maps)
if max_frame_j < max_frame_i:
hid_section = visibility_track.add_section()
hid_section.set_range(
max_frame_j + 1,
max_frame_i + 1)
hid_section.set_visibility(unreal.LevelVisibility.HIDDEN)
hid_section.set_row_index(index)
hid_section.set_level_names(maps)
def generate_sequence(h, h_dir):
tools = unreal.AssetToolsHelpers().get_asset_tools()
sequence = tools.create_asset(
asset_name=h,
package_path=h_dir,
asset_class=unreal.LevelSequence,
factory=unreal.LevelSequenceFactoryNew()
)
project_name = get_current_project_name()
filtered_dir = "/project/"
folder_path = h_dir.replace(filtered_dir, "")
folder_entity = ayon_api.get_folder_by_path(
project_name,
folder_path,
fields={
"id",
"attrib.fps",
"attrib.clipIn",
"attrib.clipOut"
}
)
# unreal default frame range value
fps = 60.0
min_frame = sequence.get_playback_start()
max_frame = sequence.get_playback_end()
if folder_entity:
min_frame = folder_entity["attrib"]["clipIn"]
max_frame = folder_entity["attrib"]["clipOut"]
fps = folder_entity["attrib"]["fps"]
else:
unreal.log_warning(
"Folder Entity not found. Using default Unreal frame range value."
)
sequence.set_display_rate(
unreal.FrameRate(fps, 1.0))
sequence.set_playback_start(min_frame)
sequence.set_playback_end(max_frame)
sequence.set_work_range_start(min_frame / fps)
sequence.set_work_range_end(max_frame / fps)
sequence.set_view_range_start(min_frame / fps)
sequence.set_view_range_end(max_frame / fps)
tracks = get_tracks(sequence)
track = None
for t in tracks:
if (t.get_class() ==
unreal.MovieSceneCameraCutTrack.static_class()):
track = t
break
if not track:
track = add_track(sequence, unreal.MovieSceneCameraCutTrack)
return sequence, (min_frame, max_frame)
def find_common_name(asset_name):
# Find the common prefix
prefix_match = re.match(r"(.*?)([_]{1,2}v\d+)(.*?)$", asset_name)
if not prefix_match:
return
name, _, ext = prefix_match.groups()
return f"{name}_{ext}"
def _get_comps_and_assets(
component_class, asset_class, old_assets, new_assets, selected
):
eas = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
components = []
if selected:
sel_actors = eas.get_selected_level_actors()
for actor in sel_actors:
comps = actor.get_components_by_class(component_class)
components.extend(comps)
else:
comps = eas.get_all_level_actors_components()
components = [
c for c in comps if isinstance(c, component_class)
]
# Get all the static meshes among the old assets in a dictionary with
# the name as key
selected_old_assets = {}
for a in old_assets:
asset = unreal.EditorAssetLibrary.load_asset(a)
if isinstance(asset, asset_class):
asset_name = find_common_name(asset.get_name())
selected_old_assets[asset_name] = asset
# Get all the static meshes among the new assets in a dictionary with
# the name as key
selected_new_assets = {}
for a in new_assets:
asset = unreal.EditorAssetLibrary.load_asset(a)
if isinstance(asset, asset_class):
asset_name = find_common_name(asset.get_name())
selected_new_assets[asset_name] = asset
return components, selected_old_assets, selected_new_assets
def replace_static_mesh_actors(old_assets, new_assets, selected):
smes = unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem)
static_mesh_comps, old_meshes, new_meshes = _get_comps_and_assets(
unreal.StaticMeshComponent,
unreal.StaticMesh,
old_assets,
new_assets,
selected
)
for old_name, old_mesh in old_meshes.items():
new_mesh = new_meshes.get(old_name)
if not new_mesh:
continue
smes.replace_mesh_components_meshes(
static_mesh_comps, old_mesh, new_mesh)
def replace_skeletal_mesh_actors(old_assets, new_assets, selected):
skeletal_mesh_comps, old_meshes, new_meshes = _get_comps_and_assets(
unreal.SkeletalMeshComponent,
unreal.SkeletalMesh,
old_assets,
new_assets,
selected
)
for old_name, old_mesh in old_meshes.items():
new_mesh = new_meshes.get(old_name)
if not new_mesh:
continue
for comp in skeletal_mesh_comps:
if comp.get_skeletal_mesh_asset() == old_mesh:
comp.set_skeletal_mesh_asset(new_mesh)
comp.set_animation_mode(unreal.AnimationMode.ANIMATION_SINGLE_NODE)
animation_sequence = get_animation_sequence(new_mesh)
print(
"Discovering target animation sequence for "
f"replacing: {animation_sequence}"
)
if animation_sequence:
comp.override_animation_data(
animation_sequence,
is_looping=True,
is_playing=True,
position=0.000000,
play_rate=1.000000
)
def replace_fbx_skeletal_mesh_actors(old_assets, new_assets, selected):
skeletal_mesh_comps, old_meshes, new_meshes = _get_comps_and_assets(
unreal.SkeletalMeshComponent,
unreal.AnimSequence,
old_assets,
new_assets,
selected
)
for old_name, old_mesh in old_meshes.items():
new_mesh = new_meshes.get(old_name)
if not new_mesh:
continue
for comp in skeletal_mesh_comps:
if comp.animation_data.anim_to_play == old_mesh:
print(
"Discovering target animation sequence for "
f"replacing: {new_mesh}"
)
comp.override_animation_data(
new_mesh,
is_looping=True,
is_playing=True,
position=0.000000,
play_rate=1.000000
)
def get_animation_sequence(new_mesh):
"""Get the animation sequence associated with a new skeletal mesh.
Args:
new_mesh (unreal.SkeletalMesh): The new skeletal mesh.
Returns:
unreal.AnimSequence: The animation sequence associated with the new
mesh, or None if not found.
"""
mesh_path = new_mesh.get_path_name()
directory = unreal.Paths.split(mesh_path)[0]
asset_content = unreal.EditorAssetLibrary.list_assets(
directory, recursive=False, include_folder=True)
for asset in asset_content:
anim_asset_obj = unreal.EditorAssetLibrary.load_asset(asset)
if anim_asset_obj.get_class().get_name() == "AnimSequence":
return anim_asset_obj
return None
def replace_geometry_cache_actors(old_assets, new_assets, selected):
geometry_cache_comps, old_caches, new_caches = _get_comps_and_assets(
unreal.GeometryCacheComponent,
unreal.GeometryCache,
old_assets,
new_assets,
selected
)
for old_name, old_mesh in old_caches.items():
new_mesh = new_caches.get(old_name)
print(f"Discovering target geometry cache for replacing : {new_mesh}")
if not new_mesh:
continue
for comp in geometry_cache_comps:
if comp.geometry_cache == old_mesh:
comp.set_geometry_cache(new_mesh)
def delete_asset_if_unused(container, asset_content):
ar = unreal.AssetRegistryHelpers.get_asset_registry()
references = set()
for asset_path in asset_content:
asset = ar.get_asset_by_object_path(asset_path)
refs = ar.get_referencers(
asset.package_name,
unreal.AssetRegistryDependencyOptions(
include_soft_package_references=False,
include_hard_package_references=True,
include_searchable_names=False,
include_soft_management_references=False,
include_hard_management_references=False
))
if not refs:
continue
references = references.union(set(refs))
# Filter out references that are in the Temp folder
cleaned_references = {
ref for ref in references if not str(ref).startswith("/Temp/")}
# Check which of the references are Levels
for ref in cleaned_references:
loaded_asset = unreal.EditorAssetLibrary.load_asset(ref)
if isinstance(loaded_asset, unreal.World):
# If there is at least a level, we can stop, we don't want to
# delete the container
return
unreal.log("Previous version unused, deleting...")
# No levels, delete the asset
unreal.EditorAssetLibrary.delete_directory(container["namespace"])
@contextmanager
def maintained_selection():
"""Stub to be either implemented or replaced.
This is needed for old publisher implementation, but
it is not supported (yet) in UE.
"""
try:
yield
finally:
pass
@contextmanager
def select_camera(sequence):
"""Select camera during context
Args:
sequence (Objects): Level Sequence Object
"""
camera_actors = find_camera_actors_in_camera_tracks(sequence)
actor_subsys = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
selected_actors = actor_subsys.get_selected_level_actors()
actor_subsys.select_nothing()
for actor in camera_actors:
actor_subsys.set_actor_selection_state(actor, True)
try:
yield
finally:
for actor in camera_actors:
if actor in selected_actors:
actor_subsys.set_actor_selection_state(actor, True)
else:
actor_subsys.set_actor_selection_state(actor, False)
def format_asset_directory(context, directory_template, asset_name_template):
"""Setting up the asset directory path and name.
Args:
context (dict): context
directory_template (str): directory template path
asset_name_template (str): asset name template
Returns:
tuple[str, str]: asset directory, asset name
"""
data = copy.deepcopy(context)
if "{product[type]}" in directory_template:
unreal.warning(
"Deprecated settings: AYON is using settings "
"that won't work in future releases. "
"Details: {product[type]} in the template should "
"be replaced with {product[productType]}."
)
directory_template = directory_template.replace(
"{product[type]}", "{product[productType]}")
if "{folder[type]}" in directory_template:
unreal.warning(
"Deprecated settings: AYON is using settings "
"that won't work in future releases. "
"Details: {folder[type]} in the template should "
"be replaced with {folder[folderType]}."
)
directory_template = directory_template.replace(
"{folder[type]}", "{folder[folderType]}")
version = data["version"]["version"]
# if user set {version[version]},
# the copied data from data["version"]["version"] convert
# to set the version of the exclusive version folder
if version < 0:
data["version"]["version"] = "hero"
else:
data["version"]["version"] = f"v{version:03d}"
asset_name_with_version = StringTemplate(asset_name_template).format_strict(data)
asset_dir = StringTemplate(directory_template).format_strict(data)
return f"{AYON_ROOT_DIR}/{asset_dir}", asset_name_with_version
def show_audit_dialog(missing_asset):
"""
Show a dialog to inform the user about missing assets.
"""
message = "The following asset was missing in the content plugi/project/"
message += f"{missing_asset}.\n"
message += "Loading the asset into Game Content instead."
unreal.EditorDialog.show_message(
"Missing Assets", message, unreal.AppMsgType.OK
)
def get_sequence(files):
"""Get sequence from filename.
This will only return files if they exist on disk as it tries
to collect the sequence using the filename pattern and searching
for them on disk.
Supports negative frame ranges like -001, 0000, 0001 and -0001,
0000, 0001.
Arguments:
files (str): List of files
Returns:
Optional[list[str]]: file sequence.
"""
collections, _remainder = clique.assemble(
files,
patterns=[clique.PATTERNS["frames"]],
minimum_items=1)
if len(collections) > 1:
raise ValueError(
f"Multiple collections found for {collections}. "
"This is a bug.")
return [os.path.basename(filename) for filename in collections[0]]
def find_camera_actors_in_camera_tracks(sequence) -> list[Any]:
"""Find the camera actors in the tracks from the Level Sequence
Args:
tracks (Object): Level Seqence Asset
Returns:
Object: Camera Actor
"""
camera_tracks = []
camera_objects = []
camera_tracks = get_camera_tracks(sequence)
if camera_tracks:
for camera_track in camera_tracks:
sections = camera_track.get_sections()
for section in sections:
binding_id = section.get_camera_binding_id()
bound_objects = unreal.LevelSequenceEditorBlueprintLibrary.get_bound_objects(
binding_id)
for camera_object in bound_objects:
camera_objects.append(camera_object.get_path_name())
world = unreal.EditorLevelLibrary.get_editor_world()
sel_actors = unreal.GameplayStatics().get_all_actors_of_class(
world, unreal.CameraActor)
actors = [a for a in sel_actors if a.get_path_name() in camera_objects]
return actors
def get_frame_range(sequence):
"""Get the Clip in/out value from the camera tracks located inside
the level sequence
Args:
sequence (Object): Level Sequence
Returns:
int32, int32 : Start Frame, End Frame
"""
camera_tracks = get_camera_tracks(sequence)
if not camera_tracks:
return sequence.get_playback_start(), sequence.get_playback_end()
for camera_track in camera_tracks:
sections = camera_track.get_sections()
for section in sections:
return section.get_start_frame(), section.get_end_frame()
def get_camera_tracks(sequence):
"""Get the list of movie scene camera cut tracks in the level sequence
Args:
sequence (Object): Level Sequence
Returns:
list: list of movie scene camera cut tracks
"""
camera_tracks = []
tracks = get_tracks(sequence)
for track in tracks:
if str(track).count("MovieSceneCameraCutTrack"):
camera_tracks.append(track)
return camera_tracks
def get_frame_range_from_folder_attributes(folder_entity=None):
"""Get the current clip In/Out value
Args:
folder_entity (dict): folder Entity.
Returns:
int, int: clipIn, clipOut.
"""
if folder_entity is None:
folder_entity = get_current_folder_entity(fields={"attrib"})
folder_attributes = folder_entity["attrib"]
frame_start = (
int(folder_attributes.get("frameStart"))
if folder_attributes.get("frameStart") else 1
)
frame_end = (
int(folder_attributes.get("frameEnd"))
if folder_attributes.get("frameEnd") else 1
)
return frame_start, frame_end
def get_dir_from_existing_asset(asset_dir, asset_name):
"""Get asset dir if the asset already existed
Args:
asset_dir (str): asset dir
Returns:
str: asset dir
"""
if unreal.EditorAssetLibrary.does_asset_exist(
f"{asset_dir}/{asset_name}"
):
return asset_dir
asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
asset_template = asset_dir.replace("/Game", "")
for package in asset_registry.get_all_assets():
package_dir = str(package.package_path)
if asset_template in package_dir and \
unreal.EditorAssetLibrary.does_asset_exist(
f"{package_dir}/{asset_name}"
):
return package_dir
return None
def get_top_hierarchy_folder(path):
"""Get top hierarchy of the path
Args:
path (str): path
Returns:
str: top hierarchy directory
"""
# Split the path by the directory separator '/'
path = path.replace(f"{AYON_ROOT_DIR}/", "")
# Return the first part
parts = [part for part in path.split('/') if part]
return parts[0]
def generate_hierarchy_path(name, folder_name, asset_root, master_dir_name, suffix=""):
asset_name = f"{folder_name}_{name}" if folder_name else name
hierarchy_dir = f"{AYON_ROOT_DIR}/{master_dir_name}"
tools = unreal.AssetToolsHelpers().get_asset_tools()
asset_dir, container_name = tools.create_unique_asset_name(asset_root, suffix=suffix)
suffix = "_CON"
container_name += suffix
if not unreal.EditorAssetLibrary.does_directory_exist(asset_dir):
unreal.EditorAssetLibrary.make_directory(asset_dir)
return asset_dir, hierarchy_dir, container_name, asset_name
def remove_map_and_sequence(container):
asset_dir = container.get('namespace')
# Create a temporary level to delete the layout level.
unreal.EditorLevelLibrary.save_all_dirty_levels()
unreal.EditorAssetLibrary.make_directory(f"{AYON_ROOT_DIR}/tmp")
tmp_level = f"{AYON_ROOT_DIR}/project/"
if not unreal.EditorAssetLibrary.does_asset_exist(f"{tmp_level}.temp_map"):
unreal.EditorLevelLibrary.new_level(tmp_level)
else:
unreal.EditorLevelLibrary.load_level(tmp_level)
unreal.EditorLevelLibrary.save_all_dirty_levels()
# Delete the camera directory.
if unreal.EditorAssetLibrary.does_directory_exist(asset_dir):
unreal.EditorAssetLibrary.delete_directory(asset_dir)
# Load the default level
default_level_path = "/project/"
unreal.EditorLevelLibrary.load_level(default_level_path)
unreal.EditorAssetLibrary.delete_directory(f"{AYON_ROOT_DIR}/tmp")
def update_container(container, project_name, repre_entity, loaded_assets=None):
asset_dir = container.get('namespace')
data = {
"representation": repre_entity["id"],
"parent": repre_entity["versionId"],
"project_name": project_name
}
if loaded_assets is not None:
data["loaded_assets"] = loaded_assets
imprint(
"{}/{}".format(
asset_dir,
container.get('container_name')),
data
)
def generate_master_level_sequence(tools, asset_dir, asset_name,
hierarchy_dir, master_dir_name,
suffix=""):
# Create map for the shot, and create hierarchy of map. If the maps
# already exist, we will use them.
master_level = f"{hierarchy_dir}/{master_dir_name}_map.{master_dir_name}_map"
if not unreal.EditorAssetLibrary.does_asset_exist(master_level):
unreal.EditorLevelLibrary.new_level(f"{hierarchy_dir}/{master_dir_name}_map")
asset_level = f"{asset_dir}/{asset_name}_map.{asset_name}_map"
if suffix:
asset_level = (
f"{asset_dir}/{asset_name}_map_{suffix}.{asset_name}_map_{suffix}"
)
if not unreal.EditorAssetLibrary.does_asset_exist(asset_level):
unreal.EditorLevelLibrary.new_level(asset_level)
unreal.EditorLevelLibrary.load_level(master_level)
unreal.EditorLevelUtils.add_level_to_world(
unreal.EditorLevelLibrary.get_editor_world(),
asset_level,
unreal.LevelStreamingDynamic
)
sequences = []
frame_ranges = []
root_content = unreal.EditorAssetLibrary.list_assets(
hierarchy_dir, recursive=False, include_folder=False)
existing_sequences = [
unreal.EditorAssetLibrary.find_asset_data(asset)
for asset in root_content
if unreal.EditorAssetLibrary.find_asset_data(
asset).get_class().get_name() == 'LevelSequence'
]
if not existing_sequences:
sequence, frame_range = generate_sequence(master_dir_name, hierarchy_dir)
sequences.append(sequence)
frame_ranges.append(frame_range)
else:
for e in existing_sequences:
sequences.append(e.get_asset())
frame_ranges.append((
e.get_asset().get_playback_start(),
e.get_asset().get_playback_end()))
shot_name = f"{asset_dir}/{asset_name}.{asset_name}"
if suffix:
shot_name = (
f"{asset_dir}/{asset_name}_{suffix}.{asset_name}_{suffix}"
)
shot = None
if not unreal.EditorAssetLibrary.does_asset_exist(shot_name):
shot = tools.create_asset(
asset_name=asset_name if not suffix else f"{asset_name}_{suffix}",
package_path=asset_dir,
asset_class=unreal.LevelSequence,
factory=unreal.LevelSequenceFactoryNew()
)
else:
shot = unreal.load_asset(shot_name)
# sequences and frame_ranges have the same length
for i in range(0, len(sequences) - 1):
set_sequence_hierarchy(
sequences[i], sequences[i + 1],
frame_ranges[i][1],
frame_ranges[i + 1][0], frame_ranges[i + 1][1],
[asset_level])
return shot, master_level, asset_level, sequences, frame_ranges
def get_tracks(sequence):
"""Backward compatibility for deprecated function of get_master_tracks() in UE 5.5
Args:
sequence (unreal.LevelSequence): Level Sequence
Returns:
Array(MovieSceneTracks): Movie scene tracks
"""
if (
UNREAL_VERSION.major == 5
and UNREAL_VERSION.minor > 4
):
return sequence.get_tracks()
else:
return sequence.get_master_tracks()
def add_track(sequence, track):
"""Backward compatibility for deprecated function of add_master_track() in UE 5.5
Args:
sequence (unreal.LevelSequence): Level Sequence
Returns:
MovieSceneTrack: Any tracks inherited from unreal.MovieSceneTrack
"""
if (
UNREAL_VERSION.major == 5
and UNREAL_VERSION.minor > 4
):
return sequence.add_track(track)
else:
return sequence.add_master_track(track)
|
import unreal
def log():
print('Hello World')
unreal.log("Logging Info")
unreal.log_warning("Logging Warning")
unreal.log_error("Logging Error")
def error():
print('Exception:')
Test = 1/0
def non_ascii():
print('ไฝ ๅฅฝไธ็')
def large_output():
engine_content = unreal.EditorAssetLibrary.list_assets('/Engine')
for item in engine_content[:1000]:
print(item)
print('Done.')
def message_box():
result = unreal.EditorDialog().show_message("Title", "Hello World", unreal.AppMsgType.YES_NO_CANCEL, unreal.AppReturnType.YES)
print(f"{result = }")
def workspace_import():
import other_module
other_module.hello_world()
log()
|
# Copyright Epic Games, Inc. All Rights Reserved.
import os
import re
import shutil
import unreal
#-------------------------------------------------------------------------------
class Platform(unreal.Platform):
name = "Android"
def _read_env(self):
version = self.get_version()
prefix = f"Android/{version}/"
env_vars = {}
# sdk
env_vars["ANDROID_HOME"] = "android-sdk-windows/" if version == "-22" else ""
# jdk
if version <= "-22":
env_vars["JAVA_HOME"] = "jdk1.8.0_77/"
elif version <= "-25":
env_vars["JAVA_HOME"] = "jre/"
else:
env_vars["JAVA_HOME"] = "jbr/"
# ndk
if version <= "-22":
env_vars["NDKROOT"] = "android-ndk-r14b/"
else:
if sdks_root := os.getenv("UE_SDKS_ROOT"):
from pathlib import Path
ndk_dir = Path(sdks_root)
ndk_dir /= "Host" + unreal.Platform.get_host()
ndk_dir /= prefix
ndk_dir /= "ndk"
if ndk_dir.is_dir():
ndk_ver = max(x.name for x in ndk_dir.glob("*") if x.is_dir())
env_vars["NDKROOT"] = "ndk/" + ndk_ver
env_vars.setdefault("NDKROOT", "ndk/")
# dispatch
for env_var, template in env_vars.items():
value = os.getenv(env_var)
if not value:
value = prefix + template
yield env_var, value
def _get_version_ue4(self):
dot_cs = self.get_unreal_context().get_engine().get_dir()
dot_cs /= "Source/project/.cs"
try:
import re
with open(dot_cs, "rt") as cs_in:
cs_in.read(8192)
lines = iter(cs_in)
next(x for x in lines if "override string GetRequiredSDKString()" in x)
next(lines) # {
for i in range(5):
line = next(lines)
if m := re.search(r'return "(-\d+)"', line):
return m.group(1)
except (StopIteration, FileNotFoundError):
pass
def _get_version_ue5(self):
func = "GetAutoSDKDirectoryForMainVersion"
dot_cs = "Source/project/"
version = self._get_version_helper_ue5(dot_cs + ".Versions.cs", func)
return version or self._get_version_helper_ue5(dot_cs + ".cs", func)
def _get_android_home(self):
out = next((v for k,v in self._read_env() if k == "ANDROID_HOME"), None)
if not out:
return
for prefix in ("", unreal.Platform.get_sdks_dir()):
if os.path.isdir(prefix + out):
return prefix + out
def _get_adb(self):
home_dir = self._get_android_home()
return home_dir + "/platform-tools/adb" if home_dir else "adb"
def _get_aapt(self):
home_dir = self._get_android_home()
if not home_dir:
return "aapt"
try:
build_tools_dir = home_dir + "/build-tools/"
latest = ""
for item in os.scandir(build_tools_dir):
latest = max(latest, item.name)
if latest and os.path.isdir(build_tools_dir):
return build_tools_dir + latest + "/aapt"
except FileNotFoundError:
return
def _get_cook_form(self, target):
if target == "game": return "Android_ASTC"
if target == "client": return "Android_ASTCClient"
|
# -*- coding: utf-8 -*-
import unreal
def do_some_things(*args, **kwargs):
unreal.log("do_some_things start:")
for arg in args:
unreal.log(arg)
unreal.log("do_some_things end.")
|
import unreal
from pathlib import Path
from meta_human_dna_utilities.material import update_material_instance_params
from meta_human_dna_utilities.content_browser import copy_asset_to_folder
from meta_human_dna_utilities.blueprint import create_child_anim_blueprint
from meta_human_dna_utilities.constants import (
RecomputeTangentsVertexMaskChannel,
SKELETAL_MESH_LOD_INFO_PROPERTIES
)
def get_skeletal_mesh_materials(skeletal_mesh: unreal.SkeletalMesh) -> dict:
materials = {}
for index, material in enumerate(skeletal_mesh.materials):
materials[str(material.get_editor_property('imported_material_slot_name'))] = index
return materials
def set_material_slots(skeletal_mesh: unreal.SkeletalMesh, material_instances: dict):
new_materials = unreal.Array(unreal.SkeletalMaterial)
for material in skeletal_mesh.materials:
slot_name = material.get_editor_property('imported_material_slot_name')
material_instance = material_instances.get(str(slot_name))
if material_instance:
new_materials.append(unreal.SkeletalMaterial(
material_interface=material_instance,
material_slot_name=slot_name,
))
else:
new_materials.append(material)
skeletal_mesh.set_editor_property('materials', new_materials)
def set_head_mesh_settings(
skeletal_mesh: unreal.SkeletalMesh,
head_material_name: str,
face_control_rig_asset: unreal.ControlRig,
face_anim_bp_asset: unreal.Blueprint,
material_instances: dict,
texture_disk_folder: Path,
texture_content_folder: str
) -> unreal.SkeletalMesh:
skeletal_mesh_subsystem = unreal.get_editor_subsystem(
unreal.SkeletalMeshEditorSubsystem
)
if head_material_name:
section_index = get_skeletal_mesh_materials(skeletal_mesh).get(head_material_name)
if section_index is None:
raise ValueError(
f"Head material {head_material_name} was not found in {skeletal_mesh.get_path_name()}"
)
# first turn on recompute tangents for the section
skeletal_mesh_subsystem.set_section_recompute_tangent( # type: ignore
skeletal_mesh=skeletal_mesh,
lod_index=0,
section_index=section_index,
recompute_tangent=True
)
# then set the recompute tangents vertex mask channel to green
skeletal_mesh_subsystem.set_section_recompute_tangents_vertex_mask_channel( # type: ignore
skeletal_mesh=skeletal_mesh,
lod_index=0,
section_index=section_index,
recompute_tangents_vertex_mask_channel=RecomputeTangentsVertexMaskChannel.GREEN
)
# set the skin cache usage to enabled
lods_info = skeletal_mesh.get_editor_property('lod_info').copy() # type: ignore
lod0_info = unreal.SkeletalMeshLODInfo()
# transfer the values from the original lod0_info to the new lod0_info
if len(lods_info) >= 1:
for property_name in SKELETAL_MESH_LOD_INFO_PROPERTIES:
lod0_info.set_editor_property(
property_name,
lods_info[0].get_editor_property(property_name)
)
# make sure to set the skin cache usage to enabled
lod0_info.set_editor_property('skin_cache_usage', unreal.SkinCacheUsage.ENABLED)
lod_info_array = unreal.Array(unreal.SkeletalMeshLODInfo)
lod_info_array.append(lod0_info)
# transfer the values from the original lod_info array to the new lod_info array
# if there are more than one lod_info elements
if len(lods_info) > 1:
for i in range(1, len(lods_info)):
lod_info_array.append(lods_info[i])
# re-assign the lod_info array to the skeletal mesh
skeletal_mesh.set_editor_property('lod_info', lod_info_array)
# set the control rig
skeletal_mesh.set_editor_property('default_animating_rig', face_control_rig_asset)
# set the post process anim blueprint
animation_blueprint = unreal.EditorAssetLibrary.load_blueprint_class(face_anim_bp_asset.get_path_name())
skeletal_mesh.set_editor_property(
'post_process_anim_blueprint',
animation_blueprint
)
# set the user asset data
asset_user_data = unreal.Array(unreal.AssetUserData)
asset_user_data.append(unreal.DNAAsset()) # type: ignore
asset_user_data.append(unreal.AssetGuideline())
skeletal_mesh.set_editor_property('asset_user_data', asset_user_data)
# set the material slots on the skeletal mesh
set_material_slots(skeletal_mesh, material_instances)
# set the material instance params
for material_instance in material_instances.values():
update_material_instance_params(
material_instance=material_instance,
maps_folder=texture_disk_folder,
content_folder=texture_content_folder
)
return skeletal_mesh
def get_head_mesh_assets(
content_folder: str,
skeletal_mesh: unreal.SkeletalMesh,
face_control_rig_asset_path: str,
face_anim_bp_asset_path: str,
material_slot_to_instance_mapping: dict,
copy_assets: bool = False,
post_fix: str = ''
) -> tuple[unreal.ControlRig, unreal.Blueprint, dict]:
# copy the needed assets to the content folder if copy_assets is True
if copy_assets:
face_control_rig_asset = copy_asset_to_folder(
asset_path=face_control_rig_asset_path,
content_folder=content_folder,
overwrite=False,
post_fix=post_fix
)
# Todo: https://dev.epicgames.com/project/-us/unreal-engine/python-api/project/?application_version=5.4#unreal.ControlRigBlueprint.set_preview_mesh
face_anim_bp_asset = copy_asset_to_folder(
asset_path=face_anim_bp_asset_path,
content_folder=content_folder,
overwrite=False,
post_fix=post_fix
)
# face_anim_bp_asset = create_child_anim_blueprint(
# parent_anim_blueprint=unreal.load_asset(face_anim_bp_asset_path),
# target_skeleton=skeletal_mesh.skeleton,
# asset_path=f"{content_folder}/ABP_{skeletal_mesh.get_name()}_FaceMesh_PostProcess"
# )
material_instances = {}
for material_slot, material_asset_path in material_slot_to_instance_mapping.items():
if material_asset_path:
material_instances[material_slot] = copy_asset_to_folder(
asset_path=material_asset_path,
content_folder=content_folder + '/Materials',
overwrite=False,
post_fix=post_fix
)
else:
face_control_rig_asset = unreal.load_asset(face_control_rig_asset_path)
face_anim_bp_asset = unreal.load_asset(face_anim_bp_asset_path)
material_instances = {}
for material_slot, material_asset_path in material_slot_to_instance_mapping.items():
if material_asset_path:
material_instances[material_slot] = unreal.load_asset(material_asset_path)
hierarchy_controller = face_control_rig_asset.get_hierarchy_controller() # type: ignore
# remove all the bones from the hierarchy controller
for key in face_control_rig_asset.hierarchy.get_all_keys(): # type: ignore
if key.type == unreal.RigElementType.BONE:
hierarchy_controller.remove_element(key)
# then import the bones from the skeletal mesh
hierarchy_controller.import_bones(
skeletal_mesh.skeleton,
replace_existing_bones=True
) # type: ignore
# set the target skeleton for the face anim blueprint
face_anim_bp_asset.set_editor_property('target_skeleton', skeletal_mesh.skeleton) # type: ignore
return face_control_rig_asset, face_anim_bp_asset, material_instances # type: ignore
|
import unreal
import sys
sys.path.append('C:/project/-packages')
from PySide import QtGui
# This function will receive the tick from Unreal
def __QtAppTick__(delta_seconds):
for window in opened_windows:
window.eventTick(delta_seconds)
# This function will be called when the application is closing.
def __QtAppQuit__():
unreal.unregister_slate_post_tick_callback(tick_handle)
# This function is called by the windows when they are closing. (Only if the connection is properly made.)
def __QtWindowClosed__(window=None):
if window in opened_windows:
opened_windows.remove(window)
# This part is for the initial setup. Need to run once to spawn the application.
unreal_app = QtGui.QApplication.instance()
if not unreal_app:
unreal_app = QtGui.QApplication(sys.argv)
tick_handle = unreal.register_slate_post_tick_callback(__QtAppTick__)
unreal_app.aboutToQuit.connect(__QtAppQuit__)
existing_windows = {}
opened_windows = []
# desired_window_class: class QtGui.QWidget : The window class you want to spawn
# return: The new or existing window
def spawnQtWindow(desired_window_class=None):
window = existing_windows.get(desired_window_class, None)
if not window:
window = desired_window_class()
existing_windows[desired_window_class] = window
window.aboutToClose = __QtWindowClosed__
if window not in opened_windows:
opened_windows.append(window)
window.show()
window.activateWindow()
return window
|
๏ปฟ# 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)
humanoidBoneList = [
"hips",
"leftUpperLeg",
"rightUpperLeg",
"leftLowerLeg",
"rightLowerLeg",
"leftFoot",
"rightFoot",
"spine",
"chest",
"upperChest",
"neck",
"head",
"leftShoulder",
"rightShoulder",
"leftUpperArm",
"rightUpperArm",
"leftLowerArm",
"rightLowerArm",
"leftHand",
"rightHand",
"leftToes",
"rightToes",
"leftEye",
"rightEye",
"jaw",
"leftThumbProximal",
"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",
]
for i in range(len(humanoidBoneList)):
humanoidBoneList[i] = humanoidBoneList[i].lower()
######
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
print(unreal.SystemLibrary.get_engine_version())
if (unreal.SystemLibrary.get_engine_version()[0] == '5'):
c = rig.get_controller()#rig.controller
else:
c = rig.controller
g = c.get_graph()
n = g.get_nodes()
print(n)
#c.add_branch_node()
#c.add_array_pin()
a:unreal.RigUnit_CollectionItems = unreal.RigUnit_CollectionItems()
# print(a)
# ้
ๅใใผใ่ฟฝๅ
collectionItem_forControl:unreal.RigVMStructNode = None
collectionItem_forBone:unreal.RigVMStructNode = None
for node in n:
if (node.get_node_title() == 'Items' or node.get_node_title() == 'Collection from Items'):
#print(node.get_node_title())
#node = unreal.RigUnit_CollectionItems.cast(node)
pin = node.find_pin('Items')
print(pin.get_array_size())
print(pin.get_default_value())
if (pin.get_array_size() < 40):
continue
if 'Type=Bone' in pin.get_default_value():
collectionItem_forBone= node
if 'Type=Control' in pin.get_default_value():
collectionItem_forControl = node
#nn = unreal.EditorFilterLibrary.by_class(n,unreal.RigUnit_CollectionItems.static_class())
## 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
# controller array
if (collectionItem_forControl == None):
collectionItem_forControl = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute')
items_forControl = collectionItem_forControl.find_pin('Items')
c.clear_array_pin(items_forControl.get_pin_path())
# bone array
if (collectionItem_forBone == None):
collectionItem_forBone = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute')
items_forBone = collectionItem_forBone.find_pin('Items')
c.clear_array_pin(items_forBone.get_pin_path())
## h_mod
rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints()
rig = rigs[0]
print(items_forControl)
print(items_forBone)
humanoidBoneTable = {"dummy" : "dummy"}
humanoidBoneTable.clear()
for h in meta.humanoid_bone_table:
bone_h = "{}".format(h).lower()
bone_m = "{}".format(meta.humanoid_bone_table[h]).lower()
try:
i = list(humanoidBoneTable.values()).index(bone_m)
except:
i = -1
if (bone_h!="" and bone_m!="" and i==-1):
humanoidBoneTable[bone_h] = bone_m
for bone_h in humanoidBoneList:
bone_m = humanoidBoneTable.get(bone_h, None)
if bone_m == None:
continue
#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):
if (True):
tmp = '(Type=Bone,Name='
#tmp += "{}".format(bone_m).lower()
tmp += bone_m
tmp += ')'
c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp)
#print(bone_m)
tmp = '(Type=Control,Name='
#tmp += "{}".format(bone_h).lower() + '_c'
tmp += bone_h + '_c'
tmp += ')'
#print(c)
c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp)
#print(bone_h)
#for e in h_mod.get_elements():
# if (e.type == unreal.RigElementType.CONTROL):
# tmp = '(Type=Control,Name='
# tmp += "{}".format(e.name)
# tmp += ')'
# c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp)
# print(e.name)
# if (e.type == unreal.RigElementType.BONE):
# tmp = '(Type=Bone,Name='
# tmp += "{}".format(e.name)
# tmp += ')'
# c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp)
# print(e.name)
#print(i.get_all_pins_recursively())
#ii:unreal.RigUnit_CollectionItems = n[1]
#pp = ii.get_editor_property('Items')
#print(pp)
#print(collectionItem.get_all_pins_recursively()[0])
#i.get_editor_property("Items")
#c.add_array_pin("Execute")
# arrayใไผธใฐใ
#i.get_all_pins_recursively()[0].get_pin_path()
#c.add_array_pin(i.get_all_pins_recursively()[0].get_pin_path(), default_value='(Type=Bone,Name=Global)')
#rig = rigs[10]
|
import unreal
import pyblish.api
class CollectInstanceMembers(pyblish.api.InstancePlugin):
"""
Collect members of instance.
This collector will collect the assets for the families that support to
have them included as External Data, and will add them to the instance
as members.
"""
order = pyblish.api.CollectorOrder + 0.1
hosts = ["unreal"]
families = ["camera", "look", "unrealStaticMesh", "uasset"]
label = "Collect Instance Members"
def process(self, instance):
"""Collect members of instance."""
self.log.info("Collecting instance members")
ar = unreal.AssetRegistryHelpers.get_asset_registry()
inst_path = instance.data.get('instance_path')
inst_name = inst_path.split('/')[-1]
pub_instance = ar.get_asset_by_object_path(
f"{inst_path}.{inst_name}").get_asset()
if not pub_instance:
self.log.error(f"{inst_path}.{inst_name}")
raise RuntimeError(f"Instance {instance} not found.")
if not pub_instance.get_editor_property("add_external_assets"):
# No external assets in the instance
return
assets = pub_instance.get_editor_property('asset_data_external')
members = [asset.get_path_name() for asset in assets]
self.log.debug(f"Members: {members}")
instance.data["members"] = members
|
import unreal
# --- ์ธ๋ถ ์ฃผ์
๋ณ์ ์๋ด ---
# ๋ธ๋ฃจํ๋ฆฐํธ ๋๋ ๋ค๋ฅธ ์คํฌ๋ฆฝํธ์์ ์ด ์คํฌ๋ฆฝํธ๋ฅผ ์คํํ๊ธฐ ์ ์ ์๋ ๋ณ์๋ค์ ๋ฐ๋์ ์ ์ํด์ผ ํฉ๋๋ค.
# ์์ (๋ธ๋ฃจํ๋ฆฐํธ์ Execute Python Script ๋
ธ๋์ 'Python Script' ํ์ ์
๋ ฅ):
#
# output_path = "/project/"
# master_path = "/project/"
# source_parent_prefix = "Basic_Master_Mat"
# suffix = "_CN"
# parameters_str = "emissive_color_mult:0.1; Tint:1,0,0,1"
# do_reparent = True
# do_parameter_edit = True
# do_apply_to_actor = True
# do_process_static_meshes = True # ์คํํฑ ๋ฉ์ ์ปดํฌ๋ํธ๋ ์ฒ๋ฆฌํ ์ง ์ฌ๋ถ
# do_check_source_prefix = True # ๋ถ๋ชจ ๋จธํฐ๋ฆฌ์ผ์ ์ด๋ฆ ์ ๋์ฌ๋ฅผ ๊ฒ์ฌํ ์ง ์ฌ๋ถ
# do_overwrite_existing = False # ์ด๋ฏธ ์กด์ฌํ๋ ์์
์ ๊ฐ์ ๋ก ๋ฎ์ด์ธ์ง ์ฌ๋ถ
def parse_parameters_string(params_string):
"""
์ธ๋ฏธ์ฝ๋ก (;)์ผ๋ก ๊ตฌ๋ถ๋ ํ๋ผ๋ฏธํฐ ๋ฌธ์์ด์ ํ์ฑํฉ๋๋ค.
- ์ค์นผ๋ผ: param_name:0.5
- ๋ฒกํฐ: param_name:1,0,0,1 (R,G,B) ๋๋ (R,G,B,A)
- ํ
์ค์ฒ: param_name:/project/.MyTexture
์์: "scalar_param:0.5; vector_param:1,0,0,1; texture_param:/project/"
"""
unreal.log("ํ๋ผ๋ฏธํฐ ๋ฌธ์์ด ํ์ฑ ์์...")
parsed_params = []
if not params_string or not isinstance(params_string, str):
return parsed_params
asset_lib = unreal.EditorAssetLibrary
# ํ๋ผ๋ฏธํฐ ์์ ์ธ๋ฏธ์ฝ๋ก ์ผ๋ก ๋ถ๋ฆฌํฉ๋๋ค.
pairs = [pair.strip() for pair in params_string.split(';') if pair.strip()]
for pair in pairs:
if ':' not in pair:
unreal.log_warning(f" - ํ๋ผ๋ฏธํฐ ํ์ฑ ๊ฒฝ๊ณ : ์๋ชป๋ ํ์์ ์์ ๊ฑด๋๋๋๋ค -> '{pair}'")
continue
key, value_str = pair.split(':', 1)
key = key.strip()
value_str = value_str.strip()
if not key or not value_str:
unreal.log_warning(f" - ํ๋ผ๋ฏธํฐ ํ์ฑ ๊ฒฝ๊ณ : ๋น์ด์๋ ํค ๋๋ ๊ฐ์ ๊ฑด๋๋๋๋ค -> '{pair}'")
continue
# ๊ฐ์ ์ ํ์ ํ๋ณํฉ๋๋ค.
# 1. ํ
์ค์ฒ ํ๋ผ๋ฏธํฐ (์ฝํ
์ธ ๋ธ๋ผ์ฐ์ ๊ฒฝ๋ก)
if value_str.startswith('/Game/') or value_str.startswith('/Engine/'):
texture_asset = asset_lib.load_asset(value_str)
if isinstance(texture_asset, unreal.Texture):
parsed_params.append({'name': key, 'type': 'texture', 'value': texture_asset})
unreal.log(f" - ํ
์ค์ฒ ํ๋ผ๋ฏธํฐ ๋ฐ๊ฒฌ: '{key}' -> '{value_str}'")
else:
unreal.log_warning(f" - ํ๋ผ๋ฏธํฐ ํ์ฑ ๊ฒฝ๊ณ : ํ
์ค์ฒ๋ฅผ ์ฐพ์ ์ ์๊ฑฐ๋ ์ ํจํ์ง ์์ต๋๋ค -> '{value_str}'")
# 2. ๋ฒกํฐ ํ๋ผ๋ฏธํฐ (r,g,b,a)
elif ',' in value_str:
try:
color_parts = [float(c.strip()) for c in value_str.split(',')]
if len(color_parts) == 3:
color = unreal.LinearColor(color_parts[0], color_parts[1], color_parts[2], 1.0)
parsed_params.append({'name': key, 'type': 'vector', 'value': color})
unreal.log(f" - ๋ฒกํฐ ํ๋ผ๋ฏธํฐ ๋ฐ๊ฒฌ: '{key}' -> {color}")
elif len(color_parts) == 4:
color = unreal.LinearColor(color_parts[0], color_parts[1], color_parts[2], color_parts[3])
parsed_params.append({'name': key, 'type': 'vector', 'value': color})
unreal.log(f" - ๋ฒกํฐ ํ๋ผ๋ฏธํฐ ๋ฐ๊ฒฌ: '{key}' -> {color}")
else:
unreal.log_warning(f" - ํ๋ผ๋ฏธํฐ ํ์ฑ ๊ฒฝ๊ณ : ๋ฒกํฐ ๊ฐ์ 3๊ฐ ๋๋ 4๊ฐ์ ์ซ์์ฌ์ผ ํฉ๋๋ค -> '{value_str}'")
except ValueError:
unreal.log_warning(f" - ํ๋ผ๋ฏธํฐ ํ์ฑ ๊ฒฝ๊ณ : ๋ฒกํฐ์ ์ผ๋ถ๋ฅผ ์ซ์๋ก ๋ณํํ ์ ์์ต๋๋ค -> '{value_str}'")
# 3. ์ค์นผ๋ผ ํ๋ผ๋ฏธํฐ
else:
try:
scalar_value = float(value_str)
parsed_params.append({'name': key, 'type': 'scalar', 'value': scalar_value})
unreal.log(f" - ์ค์นผ๋ผ ํ๋ผ๋ฏธํฐ ๋ฐ๊ฒฌ: '{key}' -> {scalar_value}")
except ValueError:
unreal.log_warning(f" - ํ๋ผ๋ฏธํฐ ํ์ฑ ๊ฒฝ๊ณ : ์ค์นผ๋ผ ๊ฐ์ ์ซ์๋ก ๋ณํํ ์ ์์ต๋๋ค -> '{value_str}'")
return parsed_params
def run_actor_material_conditional_reparent_logic():
unreal.log("์กฐ๊ฑด๋ถ ๋จธํฐ๋ฆฌ์ผ ๋ณต์ฌ ๋ฐ ๋ถ๋ชจ ๊ต์ฒด ๋ก์ง์ ์์ํฉ๋๋ค.")
# --- ๋ด๋ถ ๋ณ์ ์ฌ์ง์ (๊ฐ๋
์ฑ์ ์ํด ์ธ๋ถ ๋ณ์๋ฅผ ๋ด๋ถ ๋ณ์๋ก ํ ๋น) ---
DESTINATION_FOLDER = output_path
NEW_PARENT_MATERIAL_PATH = master_path
SOURCE_PARENT_MATERIAL_PREFIX = source_parent_prefix
SUFFIX = suffix
PARAMETERS_TO_SET = parse_parameters_string(parameters_str)
DO_REPARENT = do_reparent
DO_PARAMETER_EDIT = do_parameter_edit
DO_APPLY_TO_ACTOR = do_apply_to_actor
DO_PROCESS_STATIC_MESHES = do_process_static_meshes
DO_CHECK_SOURCE_PREFIX = do_check_source_prefix
DO_OVERWRITE_EXISTING = do_overwrite_existing
unreal.log(f"ํ์ฑ๋ ํ๋ผ๋ฏธํฐ: {PARAMETERS_TO_SET}")
asset_lib = unreal.EditorAssetLibrary
editor_actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
# ๊ต์ฒดํ ๋ถ๋ชจ ๋จธํฐ๋ฆฌ์ผ ์์
๋ก๋
new_parent_material = asset_lib.load_asset(NEW_PARENT_MATERIAL_PATH)
if DO_REPARENT and (not new_parent_material or not isinstance(new_parent_material, unreal.Material)):
unreal.log_error(f"์ค๋ฅ: ์ ๋ง์คํฐ ๋จธํฐ๋ฆฌ์ผ์ ์ฐพ์ ์ ์๊ฑฐ๋ ์ ํจํ์ง ์์ต๋๋ค: {NEW_PARENT_MATERIAL_PATH}")
return
# ์ ํ๋ ์กํฐ ๊ฐ์ ธ์ค๊ธฐ
selected_actors = editor_actor_subsystem.get_selected_level_actors()
if not selected_actors:
unreal.log_warning("์ค๋ฅ: ๋ ๋ฒจ ๋ทฐํฌํธ์์ ์กํฐ๋ฅผ ๋จผ์ ์ ํํด์ฃผ์ธ์.")
return
unreal.log(f"์ด {len(selected_actors)}๊ฐ์ ์ ํ๋ ์กํฐ์ ๋ํ ์์
์ ์์ํฉ๋๋ค.")
total_materials_processed_across_actors = 0
with unreal.ScopedEditorTransaction("Configurable Multi-Actor Material Processor") as transaction:
for selected_actor in selected_actors:
unreal.log(f"========== ์กํฐ ์ฒ๋ฆฌ ์์: '{selected_actor.get_actor_label()}' ==========")
selected_actor.modify()
# ์ฒ๋ฆฌํ ์ปดํฌ๋ํธ ๋ชฉ๋ก์ ์ค๋นํฉ๋๋ค.
components_to_process = []
# ์ค์ผ๋ ํ ๋ฉ์ ์ปดํฌ๋ํธ๋ฅผ ๋ชฉ๋ก์ ์ถ๊ฐํฉ๋๋ค.
skeletal_mesh_components = selected_actor.get_components_by_class(unreal.SkeletalMeshComponent)
components_to_process.extend(skeletal_mesh_components)
# ์คํํฑ ๋ฉ์ ์ปดํฌ๋ํธ๋ ์ฒ๋ฆฌํ๋๋ก ์ค์ ๋ ๊ฒฝ์ฐ, ๋ชฉ๋ก์ ์ถ๊ฐํฉ๋๋ค.
if DO_PROCESS_STATIC_MESHES:
static_mesh_components = selected_actor.get_components_by_class(unreal.StaticMeshComponent)
components_to_process.extend(static_mesh_components)
if not components_to_process:
unreal.log_warning(f" - ๊ฒฝ๊ณ : ์ฒ๋ฆฌํ ์ค์ผ๋ ํ ๋๋ ์คํํฑ ๋ฉ์ ์ปดํฌ๋ํธ๊ฐ ์์ด ๊ฑด๋๋๋๋ค.")
continue
# --- ํด๋ ์ด๋ฆ ๊ฒฐ์ ์ ์ํ ๊ธฐ์ค ์์
์ด๋ฆ ์ฐพ๊ธฐ ---
base_name_for_folder = ""
# 1. ์ค์ผ๋ ํ ๋ฉ์์์ ๊ธฐ์ค ์ด๋ฆ ์ฐพ๊ธฐ
for comp in skeletal_mesh_components:
if comp.skeletal_mesh:
base_name_for_folder = comp.skeletal_mesh.get_name()
unreal.log(f" - ํด๋ ๊ธฐ์ค ์์
: ์ค์ผ๋ ํ ๋ฉ์ '{base_name_for_folder}'")
break
# 2. ์คํํฑ ๋ฉ์์์ ๊ธฐ์ค ์ด๋ฆ ์ฐพ๊ธฐ (์์์ ๋ชป ์ฐพ์์ ๊ฒฝ์ฐ)
if not base_name_for_folder and DO_PROCESS_STATIC_MESHES:
if "static_mesh_components" in locals() and static_mesh_components:
for comp in static_mesh_components:
if comp.static_mesh:
base_name_for_folder = comp.static_mesh.get_name()
unreal.log(f" - ํด๋ ๊ธฐ์ค ์์
: ์คํํฑ ๋ฉ์ '{base_name_for_folder}'")
break
# 3. ํด๋ฐฑ: ์กํฐ ์ด๋ฆ ์ฌ์ฉ
if not base_name_for_folder:
base_name_for_folder = selected_actor.get_actor_label()
unreal.log(f" - ๊ฒฝ๊ณ : ๊ธฐ์ค ๋ฉ์ ์์
์ ์ฐพ์ง ๋ชปํด ์กํฐ ์ด๋ฆ '{base_name_for_folder}'์(๋ฅผ) ์ฌ์ฉํฉ๋๋ค.")
# ๊ธฐ์ค ์ด๋ฆ์ ๊ธฐ๋ฐ์ผ๋ก ๋์ ํด๋ ๊ฒฝ๋ก ์์ฑ
clean_base_name = base_name_for_folder.replace(' ', '_')
actor_destination_folder = f"{DESTINATION_FOLDER.rstrip('/')}/{clean_base_name}"
# ๊ฒฝ๋ก ์์ฑ
if not asset_lib.does_directory_exist(actor_destination_folder):
asset_lib.make_directory(actor_destination_folder)
unreal.log(f" - ๋ฐ๊ฒฌ๋ ์ด ์ปดํฌ๋ํธ ์: {len(components_to_process)}๊ฐ. ๋์ ํด๋: '{actor_destination_folder}'")
materials_processed_on_actor = 0
for mesh_comp in components_to_process:
component_name = mesh_comp.get_name()
num_materials = mesh_comp.get_num_materials()
unreal.log(f"--- ์ปดํฌ๋ํธ ์ฒ๋ฆฌ ์์: '{component_name}' (๋จธํฐ๋ฆฌ์ผ ์ฌ๋กฏ: {num_materials}๊ฐ) ---")
if num_materials == 0:
continue
mesh_comp.modify()
materials_to_apply_on_comp = {}
for index in range(num_materials):
material_instance = mesh_comp.get_material(index)
if not isinstance(material_instance, unreal.MaterialInstanceConstant):
continue
material_to_process = None
is_newly_created = False
if material_instance.get_name().endswith(SUFFIX):
unreal.log(f" [{index}๋ฒ ์ฌ๋กฏ] ์ด๋ฏธ {SUFFIX} ๋จธํฐ๋ฆฌ์ผ์ด ์ ์ฉ๋์ด ์์ต๋๋ค. ์ฌ์ฒ๋ฆฌํฉ๋๋ค: {material_instance.get_name()}")
material_to_process = material_instance
else:
parent_material = material_instance.get_editor_property('parent')
if not parent_material:
unreal.log(f" [{index}๋ฒ ์ฌ๋กฏ] ๊ฑด๋๋๋๋ค. ์ด์ : ๋ถ๋ชจ ๋จธํฐ๋ฆฌ์ผ์ด ์์ต๋๋ค.")
continue
if DO_REPARENT and parent_material == new_parent_material:
unreal.log(f" [{index}๋ฒ ์ฌ๋กฏ] ๊ฑด๋๋๋๋ค. ์ด์ : ๋ถ๋ชจ๊ฐ ์ด๋ฏธ ๋ชฉํ ๋จธํฐ๋ฆฌ์ผ์
๋๋ค.")
continue
if DO_CHECK_SOURCE_PREFIX and not parent_material.get_name().startswith(SOURCE_PARENT_MATERIAL_PREFIX):
unreal.log(f" [{index}๋ฒ ์ฌ๋กฏ] ๊ฑด๋๋๋๋ค. ์ด์ : ๋ถ๋ชจ ์ด๋ฆ์ด '{SOURCE_PARENT_MATERIAL_PREFIX}'(์ผ)๋ก ์์ํ์ง ์์ต๋๋ค: {parent_material.get_name()}")
continue
unreal.log(f" [{index}๋ฒ ์ฌ๋กฏ] ์กฐ๊ฑด ์ผ์น. ์ฒ๋ฆฌ๋ฅผ ์์ํฉ๋๋ค: {material_instance.get_name()}")
original_path = material_instance.get_path_name()
original_name = material_instance.get_name()
new_name = f"{original_name}{SUFFIX}"
new_path = f"{actor_destination_folder.rstrip('/')}/{new_name}"
if DO_OVERWRITE_EXISTING:
unreal.log(f" ๋ฎ์ด์ฐ๊ธฐ ์ต์
ํ์ฑํ. '{new_name}'์(๋ฅผ) ๊ฐ์ ๋ก ๋ณต์ ํฉ๋๋ค.")
material_to_process = asset_lib.duplicate_asset(original_path, new_path)
else:
if asset_lib.does_asset_exist(new_path):
unreal.log(f" ์์
์ด ์ด๋ฏธ ์กด์ฌํ์ฌ ๋ก๋ํฉ๋๋ค: {new_path}")
material_to_process = asset_lib.load_asset(new_path)
else:
material_to_process = asset_lib.duplicate_asset(original_path, new_path)
is_newly_created = True
if not material_to_process:
if is_newly_created:
unreal.log_error(f" ์คํจ: {SUFFIX} ์์
์ ์์ฑํ๊ฑฐ๋ ๋ก๋ํ ์ ์์ด ๊ฑด๋๋๋๋ค.")
continue
material_to_process.modify()
if DO_REPARENT:
current_parent = material_to_process.get_editor_property('parent')
if current_parent != new_parent_material:
unreal.log(f" > ๋ถ๋ชจ ๋ณ๊ฒฝ ์๋: '{material_to_process.get_name()}'")
unreal.MaterialEditingLibrary.set_material_instance_parent(material_to_process, new_parent_material)
parent_after_change = material_to_process.get_editor_property('parent')
if parent_after_change == new_parent_material:
unreal.log(" + ํ์ธ: ๋ถ๋ชจ ๋ณ๊ฒฝ์ด ์์
์ ์ฑ๊ณต์ ์ผ๋ก ์ ์ฉ๋์์ต๋๋ค.")
else:
unreal.log_warning(f" ์คํจ ํ์ธ: ๋ถ๋ชจ ๋ณ๊ฒฝ์ด ์ค์ ๋ก ์ ์ฉ๋์ง ์์์ต๋๋ค. ์ด ๋จธํฐ๋ฆฌ์ผ์ ๋๋จธ์ง ์ฒ๋ฆฌ๋ฅผ ๊ฑด๋๋๋๋ค.")
continue
else:
unreal.log(f" > ๋ถ๋ชจ๊ฐ ์ด๋ฏธ ๋ชฉํ ๋จธํฐ๋ฆฌ์ผ์ด๋ฏ๋ก ๋ณ๊ฒฝ์ ๊ฑด๋๋๋๋ค.")
if DO_PARAMETER_EDIT and PARAMETERS_TO_SET:
unreal.log(f" - '{material_to_process.get_name()}'์ ํ๋ผ๋ฏธํฐ ๊ฐ์ ์์ ํฉ๋๋ค.")
for param_info in PARAMETERS_TO_SET:
param_name = param_info['name']
param_type = param_info['type']
param_value = param_info['value']
success = False
if param_type == 'scalar':
success = unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(material_to_process, param_name, param_value)
elif param_type == 'vector':
success = unreal.MaterialEditingLibrary.set_material_instance_vector_parameter_value(material_to_process, param_name, param_value)
elif param_type == 'texture':
if param_value:
success = unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value(material_to_process, param_name, param_value)
if success:
unreal.log(f" - '{param_type}' ํ๋ผ๋ฏธํฐ '{param_name}' ๊ฐ์ ์ฑ๊ณต์ ์ผ๋ก ์ค์ ํ์ต๋๋ค.")
else:
unreal.log(f" - ์ ๋ณด: '{param_name}' ํ๋ผ๋ฏธํฐ๊ฐ ์๊ฑฐ๋ ํ์
์ด ์ผ์นํ์ง ์์ ๊ฑด๋๋๋๋ค.")
asset_lib.save_loaded_asset(material_to_process)
if is_newly_created:
materials_to_apply_on_comp[index] = material_to_process
if materials_to_apply_on_comp:
materials_processed_on_actor += len(materials_to_apply_on_comp)
if DO_APPLY_TO_ACTOR:
if not materials_to_apply_on_comp:
unreal.log(f" '{component_name}' ์ปดํฌ๋ํธ์ ์๋ก ์ ์ฉํ ๋จธํฐ๋ฆฌ์ผ์ด ์์ด ์ ์ฉ ๋จ๊ณ๋ฅผ ๊ฑด๋๋๋๋ค.")
else:
unreal.log(f" -> '{component_name}' ์ปดํฌ๋ํธ์ {len(materials_to_apply_on_comp)}๊ฐ์ ์ ๋จธํฐ๋ฆฌ์ผ์ ์ ์ฉํฉ๋๋ค.")
for index, new_mat in materials_to_apply_on_comp.items():
mesh_comp.set_material(index, new_mat)
material_after_set = mesh_comp.get_material(index)
if material_after_set != new_mat:
current_mat_path = material_after_set.get_path_name() if material_after_set else "None"
unreal.log_error(f" - ์ ์ฉ ์คํจ ํ์ธ! ์ฌ๋กฏ์ ๋จธํฐ๋ฆฌ์ผ์ด ๋ณ๊ฒฝ๋์ง ์์์ต๋๋ค.")
unreal.log_error(f" (ํ์ฌ ์ฌ๋กฏ์ ๋จธํฐ๋ฆฌ์ผ: {current_mat_path})")
unreal.log_error(f" - ์์ธ ์ถ์ : Sequencer์ Material Track์ด ์ด ์ฌ๋กฏ์ ์ ์ดํ๊ณ ์์ ์ ์์ต๋๋ค.")
else:
if materials_to_apply_on_comp:
unreal.log(f" - ์กํฐ์ ๋จธํฐ๋ฆฌ์ผ ์ ์ฉ ๋จ๊ณ(do_apply_to_actor=False)๋ ๊ฑด๋๋๋๋ค.")
total_materials_processed_across_actors += materials_processed_on_actor
if total_materials_processed_across_actors == 0:
unreal.log_warning("์ฒ๋ฆฌ๋ ๋จธํฐ๋ฆฌ์ผ์ด ์์ด ์ ์ฒด ์์
์ ์ทจ์ํฉ๋๋ค.")
transaction.cancel()
return
unreal.log(f"๋ชจ๋ ์กํฐ์ ๋จธํฐ๋ฆฌ์ผ ์ฒ๋ฆฌ๊ฐ ์๋ฃ๋์์ต๋๋ค. (์ด {total_materials_processed_across_actors}๊ฐ ์ฒ๋ฆฌ)")
# ์คํฌ๋ฆฝํธ ์คํ
run_actor_material_conditional_reparent_logic()
|
# /project/
# @CBgameDev Optimisation Script - Log Blueprints With Tick Enabled
# /project/
import unreal
import os
EditAssetLib = unreal.EditorAssetLibrary()
# SkeletalMeshLib = unreal.BlueprintFunctionLibrary() #dont think need
TickFunctionality = unreal.TickFunction()
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 == "Blueprint":
_BlueprintAsset = unreal.Blueprint.cast(_assetData.get_asset())
unreal.TickFunction.
unreal.log(_assetData.get_asset().get_editor_property("allow_tick_before_begin_play"))
# _assetData.get_editor_property("allow_tick_before_begin_play")
# unreal.Actor.cast(_BlueprintAsset.get_default_object())
# unreal.log(_assetData.get_asset().get_default_object())
# unreal.log(unreal.Actor.cast(_assetData.get_asset()))
# EditAssetLib.load_blueprint_class(_BlueprintAsset)
# _BlueprintAsset.TickFunctionality.get_editor_property("start_with_tick_enabled")
# .get_editor_property("allow_tick_before_begin_play ")
# _BlueprintAsset.get_default_object(_assetData.get_asset()).TickFunctionality
unreal.log("is a blueprint")
LogStringsArray.append(" %s ------------> At Path: %s \n" % (_assetName, _assetPathName))
# unreal.log("Asset Name: %s Path: %s \n" % (_assetName, _assetPathName))
numOfOptimisations += 1
# new way
asset_obj = EditAssetLib.load_asset(asset)
# isTickOn = asset_obj.get_editor_property(unreal.TickFunction.get_editor_property)
# important documentation: https://docs.unrealengine.com/4.26/en-US/project/.html
if ST.should_cancel():
break
ST.enter_progress_frame(1, asset)
# Write results into a log file
# /project/
TitleOfOptimisation = "Log Blueprints With Tick Enabled"
DescOfOptimisation = "Searches the entire project for blueprints which have tick enabled and that we could consider turning off"
SummaryMessageIntro = "-- Assets With 0 References That We Could Consider Deleting --"
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
import sys
sys.path.append("/project/-packages")
from PySide import QtCore, QtGui, QtUiTools
def rename_assets(search_pattern, replace_pattern, use_case):
# instances of unreal classes
system_lib = unreal.SystemLibrary()
editor_util = unreal.EditorUtilityLibrary()
string_lib = unreal.StringLibrary()
# get the selected assets
selected_assets = editor_util.get_selected_assets()
num_assets = len(selected_assets)
replaced = 0
unreal.log("Selected {} assets".format(num_assets))
# loop over each asset and rename
for asset in selected_assets:
asset_name = system_lib.get_object_name(asset)
unreal.log(asset_name)
# check if the asset name contains the to be replaced text
if string_lib.contains(asset_name, search_pattern, use_case = use_case):
search_case = unreal.SearchCase.CASE_SENSITIVE if use_case else unreal.SearchCase.IGNORE_CASE
replaced_name = string_lib.replace(asset_name, search_pattern, replace_pattern, search_case = search_case)
editor_util.rename_asset(asset, replaced_name)
replaced += 1
unreal.log("Replaced {} with {}".format(asset_name, replaced_name))
else:
unreal.log("{} did not match the search pattern, was skipped".format(asset_name))
unreal.log("Replaced {} of {} assets".format(replaced, num_assets))
class RenameGUI(QtGui.QWidget):
def __init__(self, parent=None):
super(RenameGUI, self).__init__(parent)
# load the created GUI
self.widget = QtUiTools.QUiLoader().load("/project/.ui")
self.widget.setParent(self)
# set the size of widget
self.widget.setGeometry(0, 0, self.widget.width(), self.widget.height())
# find the interaction elements
self.search = self.widget.findChild(QtGui.QLineEdit, "searchPattern")
self.replace = self.widget.findChild(QtGui.QLineEdit, "replacePattern")
self.use_case = self.widget.findChild(QtGui.QCheckBox, "checkBox")
# find and assign trigger to pushButton
self.rename_button = self.widget.findChild(QtGui.QPushButton, "pushButton")
self.rename_button.clicked.connect(self.rename_handler)
def rename_handler(self):
search_pattern = self.search.text()
replace_pattern = self.replace.text()
use_case = self.use_case.isChecked()
rename_assets(search_pattern, replace_pattern, use_case)
# only create an instance when it is not already running
app = None
if not QtGui.QApplication.instance():
app = QtGui.QApplication(sys.argv)
# start the GUI
window = RenameGUI()
window.show()
|
# Copyright Epic Games, Inc. All Rights Reserved
"""
Deadline Job object used to submit jobs to the render farm
"""
# Built-In
import logging
# Third-party
import unreal
# Internal
from deadline_utils import merge_dictionaries, get_deadline_info_from_preset
from deadline_enums import DeadlineJobStatus
logger = logging.getLogger("DeadlineJob")
class DeadlineJob:
""" Unreal Deadline Job object """
# ------------------------------------------------------------------------------------------------------------------
# Magic Methods
def __init__(self, job_info=None, plugin_info=None, job_preset: unreal.DeadlineJobPreset=None):
""" Constructor """
self._job_id = None
self._job_info = {}
self._plugin_info = {}
self._aux_files = []
self._job_status: DeadlineJobStatus = DeadlineJobStatus.UNKNOWN
self._job_progress = 0.0
# Jobs details updated by server after submission
self._job_details = None
# Update the job, plugin and aux file info from the data asset
if job_info and plugin_info:
self.job_info = job_info
self.plugin_info = plugin_info
if job_preset:
self.job_info, self.plugin_info = get_deadline_info_from_preset(job_preset=job_preset)
def __repr__(self):
return f"{self.__class__.__name__}({self.job_name}, {self.job_id})"
# ------------------------------------------------------------------------------------------------------------------
# Public Properties
@property
def job_info(self):
"""
Returns the Deadline job info
:return: Deadline job Info as a dictionary
:rtype: dict
"""
return self._job_info
@job_info.setter
def job_info(self, value: dict):
"""
Sets the Deadline Job Info
:param value: Value to set on the job info.
"""
if not isinstance(value, dict):
raise TypeError(f"Expected `dict` found {type(value)}")
self._job_info = merge_dictionaries(self.job_info, value)
if "AuxFiles" in self._job_info:
# Set the auxiliary files for this instance
self._aux_files = self._job_info.get("AuxFiles", [])
# Remove the aux files array from the dictionary, doesn't belong there
self._job_info.pop("AuxFiles")
@property
def plugin_info(self):
"""
Returns the Deadline plugin info
:return: Deadline plugin Info as a dictionary
:rtype: dict
"""
return self._plugin_info
@plugin_info.setter
def plugin_info(self, value: dict):
"""
Sets the Deadline Plugin Info
:param value: Value to set on plugin info.
"""
if not isinstance(value, dict):
raise TypeError(f"Expected `dict` found {type(value)}")
self._plugin_info = merge_dictionaries(self.plugin_info, value)
@property
def job_id(self):
"""
Return the deadline job ID. This is the ID returned by the service after the job has been submitted
"""
return self._job_id
@property
def job_name(self):
"""
Return the deadline job name.
"""
return self.job_info.get("Name", "Unnamed Job")
@job_name.setter
def job_name(self, value):
"""
Updates the job name on the instance. This also updates the job name in the job info dictionary
:param str value: job name
"""
self.job_info.update({"Name": value})
@property
def aux_files(self):
"""
Returns the Auxiliary files for this job
:return: List of Auxiliary files
"""
return self._aux_files
@property
def job_status(self):
"""
Return the current job status
:return: Deadline status
"""
if not self.job_details:
return DeadlineJobStatus.UNKNOWN
if "Job" not in self.job_details and "Status" not in self.job_details["Job"]:
return DeadlineJobStatus.UNKNOWN
# Some Job statuses are represented as "Rendering (1)" to indicate the
# current status of the job and the number of tasks performing the
# current status. We only care about the job status so strip out the
# extra information. Task details are returned to the job details
# object which can be queried in a different implementation
return self.get_job_status_enum(self.job_details["Job"]["Status"].split()[0])
@job_status.setter
def job_status(self, value):
"""
Return the current job status
:param DeadlineJobStatus value: Job status to set on the object.
:return: Deadline status
"""
# Statuses are expected to live in the job details object. Usually this
# property is only explicitly set if the status of a job is unknown.
# for example if the service detects a queried job is non-existent on
# the farm
# NOTE: If the structure of how job status are represented in the job
# details changes, this implementation will need to be updated.
# Currently job statuses are represented in the jobs details as
# {"Job": {"Status": "Unknown"}}
# "value" is expected to be an Enum so get the name of the Enum and set
# it on the job details. When the status property is called,
# this will be re-translated back into an enum. The reason for this is,
# the native job details object returned from the service has no
# concept of the job status enum. This is an internal
# representation which allows for more robust comparison operator logic
if self.job_details and isinstance(self.job_details, dict):
self.job_details.update({"Job": {"Status": value.name}})
@property
def job_progress(self):
"""
Returns the current job progress
:return: Deadline job progress as a float value
"""
if not self.job_details:
return 0.0
if "Job" in self.job_details and "Progress" in self.job_details["Job"]:
progress_str = self._job_details["Job"]["Progress"]
progress_str = progress_str.split()[0]
return float(progress_str) / 100 # 0-1 progress
@property
def job_details(self):
"""
Returns the job details from the deadline service.
:return: Deadline Job details
"""
return self._job_details
@job_details.setter
def job_details(self, value):
"""
Sets the job details from the deadline service. This is typically set
by the service, but can be used as a general container for job
information.
"""
self._job_details = value
# ------------------------------------------------------------------------------------------------------------------
# Public Methods
def get_submission_data(self):
"""
Returns the submission data used by the Deadline service to submit a job
:return: Dictionary with job, plugin, auxiliary info
:rtype: dict
"""
return {
"JobInfo": self.job_info,
"PluginInfo": self.plugin_info,
"AuxFiles": self.aux_files
}
# ------------------------------------------------------------------------------------------------------------------
# Protected Methods
@staticmethod
def get_job_status_enum(job_status):
"""
This method returns an enum representing the job status from the server
:param job_status: Deadline job status
:return: Returns the job_status as an enum
:rtype DeadlineJobStatus
"""
# Convert this job status returned by the server into the job status
# enum representation
# Check if the job status name has an enum representation, if not check
# the value of the job_status.
# Reference: https://docs.thinkboxsoftware.com/project/.1/1_User%20Manual/project/-jobs.html#job-property-values
try:
status = DeadlineJobStatus(job_status)
except ValueError:
try:
status = getattr(DeadlineJobStatus, job_status)
except Exception as exp:
raise RuntimeError(f"An error occurred getting the Enum status type of {job_status}. Error: \n\t{exp}")
return status
|
"""
# Unreal Editor Pipeline Plugin Manager
* Description:
Autoloads pipeline friendly plugins.
"""
import json
from pathlib import Path
from lucid.unreal import editor
import lucid.unreal.paths
import unreal
PLUGIN_NAME_K = 'plugin_name'
PLUGIN_CMD_K = 'startup_cmd'
SHELF_ICON = unreal.Name('EditorViewport.ShaderComplexityMode')
BUTTON_ICON = unreal.Name('WidgetDesigner.LayoutTransform')
def load_toolbar_plugins() -> None:
menu = editor.create_toolbar_submenu(section_name='Lucid',
dropdown_name='Plugins',
section_label='plugins',
small_style_name=SHELF_ICON)
for p in lucid.unreal.paths.PLUGINS_DIR.glob('*'):
ctx_file = Path(p, 'context.json')
if not ctx_file.exists():
continue # Not a pipeline friendly plugin
with open(ctx_file) as file:
ctx_data = json.load(file)
label = ctx_data[PLUGIN_NAME_K]
command = ctx_data[PLUGIN_CMD_K]
editor.add_dropdown_button(
menu_id=menu,
label=label,
command=command,
section_label='plugins',
small_style_name=BUTTON_ICON
)
|
# 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 using the API to instantiate an HDA and set a landscape
input.
"""
import unreal
_g_wrapper = None
def get_test_hda_path():
return '/project/.hilly_landscape_erode_1_0'
def get_test_hda():
return unreal.load_object(None, get_test_hda_path())
def load_map():
return unreal.EditorLoadingAndSavingUtils.load_map('/project/.LandscapeInputExample')
def get_landscape():
return unreal.EditorLevelLibrary.get_actor_reference('PersistentLevel.Landscape_0')
def configure_inputs(in_wrapper):
print('configure_inputs')
# Unbind from the delegate
in_wrapper.on_post_instantiation_delegate.remove_callable(configure_inputs)
# Create a landscape input
landscape_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPILandscapeInput)
# Send landscapes as heightfields
landscape_input.landscape_export_type = unreal.HoudiniLandscapeExportType.HEIGHTFIELD
# Keep world transform
landscape_input.keep_world_transform = True
# Set the input objects/assets for this input
landscape_object = get_landscape()
landscape_input.set_input_objects((landscape_object, ))
# copy the input data to the HDA as node input 0
in_wrapper.set_input_at_index(0, landscape_input)
# We can now discard the API input object
landscape_input = None
def print_api_input(in_input):
print('\t\tInput type: {0}'.format(in_input.__class__))
print('\t\tbKeepWorldTransform: {0}'.format(in_input.keep_world_transform))
if isinstance(in_input, unreal.HoudiniPublicAPILandscapeInput):
print('\t\tbLandscapeAutoSelectComponent: {0}'.format(in_input.landscape_auto_select_component))
print('\t\tbLandscapeExportLighting: {0}'.format(in_input.landscape_export_lighting))
print('\t\tbLandscapeExportMaterials: {0}'.format(in_input.landscape_export_materials))
print('\t\tbLandscapeExportNormalizedUVs: {0}'.format(in_input.landscape_export_normalized_u_vs))
print('\t\tbLandscapeExportSelectionOnly: {0}'.format(in_input.landscape_export_selection_only))
print('\t\tbLandscapeExportTileUVs: {0}'.format(in_input.landscape_export_tile_u_vs))
print('\t\tbLandscapeExportType: {0}'.format(in_input.landscape_export_type))
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))
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():
# Load the example map
load_map()
# get the API singleton
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
global _g_wrapper
# instantiate an asset with auto-cook enabled
_g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform())
# Configure inputs on_post_instantiation, after instantiation, but before first cook
_g_wrapper.on_post_instantiation_delegate.add_callable(configure_inputs)
# Print the input state after the cook and output creation.
_g_wrapper.on_post_processing_delegate.add_callable(print_inputs)
if __name__ == '__main__':
run()
|
# -*- coding: utf-8 -*-
import unreal
import Utilities.Utils
def print_refs(packagePath):
print("-" * 70)
results, parentsIndex = unreal.PythonBPLib.get_all_refs(packagePath, True)
print ("resultsCount: {}".format(len(results)))
assert len(results) == len(parentsIndex), "results count not equal parentIndex count"
print("{} Referencers Count: {}".format(packagePath, len(results)))
def _print_self_and_children(results, parentsIndex, index, gen):
if parentsIndex[index] < -1:
return
print ("{}{}".format("\t" * (gen +1), results[index]))
parentsIndex[index] = -2
for j in range(index + 1, len(parentsIndex), 1):
if parentsIndex[j] == index:
_print_self_and_children(results, parentsIndex, j, gen + 1)
for i in range(len(results)):
if parentsIndex[i] >= -1:
_print_self_and_children(results, parentsIndex, i, 0)
def print_deps(packagePath):
print("-" * 70)
results, parentsIndex = unreal.PythonBPLib.get_all_deps(packagePath, True)
print ("resultsCount: {}".format(len(results)))
assert len(results) == len(parentsIndex), "results count not equal parentIndex count"
print("{} Dependencies Count: {}".format(packagePath, len(results)))
def _print_self_and_children(results, parentsIndex, index, gen):
if parentsIndex[index] < -1:
return
print ("{}{}".format("\t" * (gen +1), results[index]))
parentsIndex[index] = -2
for j in range(index + 1, len(parentsIndex), 1):
if parentsIndex[j] == index:
_print_self_and_children(results, parentsIndex, j, gen + 1)
for i in range(len(results)):
if parentsIndex[i] >= -1:
_print_self_and_children(results, parentsIndex, i, 0)
def print_related(packagePath):
print_deps(packagePath)
print_refs(packagePath)
def print_selected_assets_refs():
assets = Utilities.Utils.get_selected_assets()
for asset in assets:
print_refs(asset.get_outermost().get_path_name())
def print_selected_assets_deps():
assets = Utilities.Utils.get_selected_assets()
for asset in assets:
print_deps(asset.get_outermost().get_path_name())
def print_selected_assets_related():
assets = Utilities.Utils.get_selected_assets()
for asset in assets:
print_related(asset.get_outermost().get_path_name())
def print_who_used_custom_depth():
world = unreal.EditorLevelLibrary.get_editor_world()
allActors = unreal.GameplayStatics.get_all_actors_of_class(world, unreal.Actor)
print(len(allActors))
errorCount = 0
for actor in allActors:
comps = actor.get_components_by_class(unreal.PrimitiveComponent)
for comp in comps:
if comp.render_custom_depth:
errorCount += 1
# v = comp.get_editor_property("custom_depth_stencil_value")
# m = comp.get_editor_property("custom_depth_stencil_write_mask")
print("actor: {} comp: {} enabled Custom depth ".format(actor.get_name(), comp.get_name()))
# errorCount += 1
print("Custom Depth comps: {}".format(errorCount))
|
# -*- coding utf-8 -*-
import unreal
"""
using
import TPS_Modules.generate_skeletalmesh_lod as generate_skeletalmesh_lod
import importlib
importlib.reload(generate_skeletalmesh_lod)
generate_skeletalmesh_lod.generate_skeletalmesh_lod()
"""
def generate_skeletalmesh_lod():
# ้ธๆใใฆใใใขใปใใใๅๅพ
util = unreal.EditorUtilityLibrary.get_default_object()
asset_list = util.get_selected_asset_data()
unreal.log("Start generate_skeletalmesh_lod")
for asset in asset_list:
skeletal_mesh = asset.get_asset()
# LOD้
ๅ
lod_info = []
# BaseใฎใขใใซใฏๅคๆดใใใใชใใใBaseใฎLODใๅๅพใใ่จญๅฎ
base_lod_info = skeletal_mesh.get_editor_property("lod_info")
lod_info.append(base_lod_info[0])
unreal.log(len(base_lod_info))
# ScreenSizeใฎ่จญๅฎ
screen_size_array = [0.8, 0.6, 0.4, 0.3]
# BaseLODใใใฎ้ ็นใฎๅฒๅใ่จญๅฎ
vert_parcentage_array = [0.06, 0.03, 0.02, 0.01]
# ใชใใฏใทใงใณใฎๆนๆณใ่จญๅฎ
termination_array = [1, 1, 1, 1]
# Fixed ScreenSize
for screen_size in screen_size_array:
per_platform_float = unreal.PerPlatformFloat()
per_platform_float.set_editor_property("default", screen_size)
info = unreal.SkeletalMeshLODInfo()
info.set_editor_property("screen_size", per_platform_float)
lod_info.append(info)
# BaseLodใฎๆฌกใใ้ๅงใใใใใซcountๅคๆฐใ1ใซ่จญๅฎ
count = 1
for i in range(len(screen_size_array)):
optimization_setting = unreal.SkeletalMeshOptimizationSettings()
optimization_setting.set_editor_property("num_of_vert_percentage", vert_parcentage_array[i])
# ้ ็นใฎ%็ใงๅๆธ็ใๆฑบๅฎ
optimization_setting.set_editor_property("termination_criterion", unreal.SkeletalMeshTerminationCriterion.cast(termination_array[i]))
lod_info[count].set_editor_property("reduction_settings", optimization_setting)
count += 1
# LODInfoใ่จญๅฎ
skeletal_mesh.set_editor_property("lod_info", lod_info)
# LODใๅ็ๆ
skeletal_mesh.regenerate_lod(len(lod_info), True)
# MinLodใฎ่จญๅฎ
min_lod = [1]
for setting_val in min_lod:
per_platform_int = unreal.PerPlatformInt()
per_platform_int.set_editor_property("default", setting_val)
skeletal_mesh.set_editor_property("min_lod", per_platform_int)
# Save SkeletalMesh LOD
unreal.EditorAssetLibrary.save_asset(asset.get_full_name(), only_if_is_dirty=False)
unreal.log("End generate_skeletalmesh_lod")
|
import os
import time
import unreal
if __name__ == "__main__":
case_dir = "/project/"
cnt = 0
pose_file = os.path.join(case_dir, f"rd_placement{cnt}.txt")
while os.path.exists(pose_file):
case_type = f"Rd{cnt}Marker"
prefix = f"tag{case_type}"
holder_prefix = f"holder{case_type}"
print(f"Marker prefix: {prefix}")
# marker poses from IMP
f_stream = open(pose_file, "r")
imp_data = f_stream.readlines()
tag_num = len(imp_data) - 1
print(f"Marker number {tag_num}")
height = 175
decal_scale = [.01, 0.13208, 0.102]
cube_scale = [.01, .67, .52]
player_x, player_y = -272.0, 64.999985
cube_mesh = unreal.EditorAssetLibrary.find_asset_data('/project/').get_asset()
for i in range(tag_num):
line = imp_data[i+1].strip()
print(line)
line = line.split()
# scale 100 converting meters to centimeters
x, y, theta = float(line[1]) * 100 + player_x, -float(line[2]) * 100 + player_y, -float(line[3]) * 180 / 3.14
# get texture file
if i<9:
tex_path = f"/project/-00{i+1}_mat"
else:
tex_path = f"/project/-0{i+1}_mat"
if unreal.EditorAssetLibrary.does_asset_exist(tex_path):
my_tex = unreal.EditorAssetLibrary.find_asset_data(tex_path).get_asset()
my_decal = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.DecalActor,[0,0,0])
my_decal.set_actor_label(f"xxx{prefix}{i}")
my_decal.set_decal_material(my_tex)
my_decal.set_actor_location_and_rotation([x, y, height], unreal.Rotator(-90, 180, theta), False, True)
my_decal.set_actor_scale3d(decal_scale)
my_decal.set_folder_path(f"/{case_type}")
time.sleep(.1)
my_decal.set_actor_label(f"{prefix}{i}")
my_cube = unreal.EditorLevelLibrary.spawn_actor_from_object(cube_mesh, [0, 0, 0])
my_cube.set_actor_label(f"xxx{holder_prefix}{i}")
my_cube.set_actor_location_and_rotation([x, y, height], unreal.Rotator(-90, 180, theta), False, True)
my_cube.set_actor_scale3d(cube_scale)
my_cube.set_folder_path(f"/{case_type}")
my_cube.set_mobility(unreal.ComponentMobility.MOVABLE)
time.sleep(.1)
my_cube.set_actor_label(f"{holder_prefix}{i}")
else:
print(f"cannot find tex {tex_path}")
f_stream.close()
cnt += 1
pose_file = os.path.join(case_dir, f"rd_placement{cnt}.txt")
|
# -*- coding: utf-8 -*-
"""
"""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
__author__ = 'timmyliang'
__email__ = '[email protected]'
__date__ = '2021-08-18 19:44:01'
import re
import unreal
import inspect
import builtins
bp, = unreal.EditorUtilityLibrary.get_selected_assets()
bp_path = bp.get_path_name()
gc = unreal.load_object(None, "%s_C" % bp_path)
cdo = unreal.get_default_object(gc)
# cdo.call_method("TestCall",args=(unreal.World(),))
@unreal.uclass()
class TempObj(unreal.Object):
pass
map = {
"IntProperty":int,
"StrProperty":str,
"ArrayProperty":list,
"Object":TempObj
}
def guess_call(obj, name, num=999):
# obj.call_method(name, (unreal.World(),''))
# return
regx = r"takes at most (\d+) argument"
try:
obj.call_method(name, tuple([i for i in range(num)]))
except Exception as e:
error = str(e)
print(error)
match = re.search(regx, error)
assert match,u"ๆพไธๅฐๅฝๆฐ"
count = int(match.group(1))
print("count",count)
regx = re.compile(r"allowed Class type: '(\D+?)'")
regx2 = re.compile(r"NativizeProperty: Cannot nativize '(\D+)' as '(\D+)' \((\D+)\)")
args = tuple()
for i in reversed(range(count)):
try:
print(args)
obj.call_method(name, args + tuple([None for j in range(i + 1)]))
args += (1,)
except Exception as e:
error = str(e)
# print(error)
match = regx.search(error)
typ_string = match.group(1) if match else regx2.search(error).group(3)
typ = getattr(unreal,typ_string,None)
# print(typ_string)
# print(map.get(typ_string))
typ = map.get(typ_string,getattr(builtins,typ_string,getattr(unreal,typ_string,lambda:[])))
args += (typ(),)
print('call',args)
obj.call_method(name, args=tuple(reversed(args)))
guess_call(cdo, "MyCall")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.