text
stringlengths 15
267k
|
|---|
import unreal
import sys
sys.path.append('Z:/project/')
import lib_narrs
|
#Thanks to Mystfit https://github.com/project/-StableDiffusionTools/project/
import os, sys, subprocess
import urllib.request
from urllib.parse import urlparse
from subprocess import CalledProcessError
import unreal
dependencies = {
"omegaconf": {},
"einops": {},
"clip": {},
"kornia": {},
"gitpython": {"module": "git"},
"pytorch_lightning": {},
"torch": {"args": "--extra-index-url https://download.pytorch.org/project/"},
"torchvision": {"args": "--extra-index-url https://download.pytorch.org/project/"},
"torchaudio": {"args": "--extra-index-url https://download.pytorch.org/project/"},
"diffusers": {"url": "https://github.com/project/.git"},
"transformers": {},
"scipy":{},
"ftfy": {},
"realesrgan": {},
"accelerate": {},
"xformers": {"url": "https://github.com/project/.0.14/xformers-0.0.14.dev0-cp39-cp39-win_amd64.whl", "upgrade": True},
"taming-transformers-rom1504": {}
}
# TODO: There's an unreal function to return this path
pythonpath = os.path.abspath(unreal.Paths().make_standard_filename(os.path.join("..", "ThirdParty", "Python3", "Win64", "python.exe")))
pythonheaders = os.path.abspath(unreal.Paths().make_standard_filename(os.path.join(unreal.Paths().engine_source_dir(), "ThirdParty", "Python3", "Win64", "include")))
pythonlibs = os.path.abspath(unreal.Paths().make_standard_filename(os.path.join(unreal.Paths().engine_source_dir(), "ThirdParty", "Python3", "Win64", "libs")))
def install_dependencies(pip_dependencies):
deps_installed = True
with unreal.ScopedSlowTask(len(pip_dependencies), "Installing dependencies") as slow_task:
slow_task.make_dialog(True)
for dep_name, dep_options in pip_dependencies.items():
print(dep_options)
dep_path = dep_options["url"] if "url" in dep_options.keys() else ""
dep_force_upgrade = dep_options["upgrade"] if "upgrade" in dep_options.keys() else True
extra_flags = dep_options["args"].split(' ') if "args" in dep_options.keys() else []
print("Installing dependency " + dep_name)
if slow_task.should_cancel(): # True if the user has pressed Cancel in the UI
break
slow_task.enter_progress_frame(1.0, f"Installing dependency {dep_name}")
if dep_path:
if dep_path.endswith(".whl"):
print("Dowloading wheel")
wheel_path = download_wheel(dep_name, dep_path)
dep_name = [f"{wheel_path}"]
elif dep_path.endswith(".git"):
print("Downloading git repository")
#path = clone_dependency(dep_name, dep_path)
dep_name = [f"git+{dep_path}#egg={dep_name}"]
#extra_flags += ["--global-option=build_ext", f"--global-option=-I'{pythonheaders}'", f"--global-option=-L'{pythonlibs}'"]
else:
dep_name = dep_name.split(' ')
if dep_force_upgrade:
extra_flags.append("--upgrade")
try:
print(subprocess.check_output([f"{pythonpath}", '-m', 'pip', 'install'] + extra_flags + dep_name), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except CalledProcessError as e:
print("Return code for dependency {0} was non-zero. Returned {1} instead".format(dep_name, str(e.returncode)))
print("Command:")
print(" ".join([f"{pythonpath}", '-m', 'pip', 'install'] + extra_flags + dep_name))
print("Output:")
print(e.output)
deps_installed = False
return deps_installed
def clone_dependency(repo_name, repo_url):
from git import Repo, exc
import git
print("Cloning dependency " + repo_name)
repo_path = os.path.join(unreal.Paths().engine_saved_dir(), "pythonrepos", repo_name)
repo = None
try:
repo = Repo.clone_from(repo_url, repo_path)
except git.exc.GitCommandError as e:
repo = Repo(repo_path)
if repo:
# Handle long path lengths for windows
# Make sure long paths are enabled at the system level
# https://learn.microsoft.com/en-us/project/-paths-not-working-in-windows-2019.html
repo.config_writer().set_value("core", "longpaths", True).release()
# Make sure the repo has all submodules available
output = repo.git.submodule('update', '--init', '--recursive')
requirements_file = os.path.normpath(os.path.join(repo_path, "requirements.txt"))
# Update repo dependencies
if os.path.exists(requirements_file):
try:
subprocess.check_call([pythonpath, '-m', 'pip', 'install', '-r', requirements_file])
except CalledProcessError as e:
print("Failed to install repo requirements.txt")
command = " ".join([pythonpath, '-m', 'pip', 'install', '-r', requirements_file])
print(f"Command: {command}")
return os.path.normpath(repo_path)
def download_wheel(wheel_name, wheel_url):
wheel_folder = os.path.normpath(os.path.join(unreal.Paths().engine_saved_dir(), "pythonwheels"))
if not os.path.exists(wheel_folder):
os.makedirs(wheel_folder)
wheel_file = urlparse(wheel_url)
wheel_path = os.path.normpath(os.path.join(wheel_folder, f"{os.path.basename(wheel_file.path)}"))
if not os.path.exists(wheel_path):
urllib.request.urlretrieve(wheel_url, wheel_path)
return os.path.normpath(wheel_path)
if __name__ == "__main__":
global SD_dependencies_installed
SD_dependencies_installed = install_dependencies(dependencies)
|
# coding: utf-8
import unreal
import argparse
print("VRM4U python begin")
print (__file__)
parser = argparse.ArgumentParser()
parser.add_argument("-rigSrc")
parser.add_argument("-rigDst")
args = parser.parse_args()
#print(args.vrm)
######
## rig 取得
reg = unreal.AssetRegistryHelpers.get_asset_registry();
a = reg.get_all_assets();
for aa in a:
if (aa.get_editor_property("object_path") == args.rigSrc):
rigSrc = aa.get_asset()
if (aa.get_editor_property("object_path") == args.rigDst):
rigDst = aa.get_asset()
print(rigSrc)
print(rigDst)
modSrc = rigSrc.get_hierarchy_modifier()
modDst = rigDst.get_hierarchy_modifier()
conSrc = rigSrc.controller
conDst = rigDst.controller
graSrc = conSrc.get_graph()
graDst = conDst.get_graph()
modDst.initialize()
print(rig[3])
meta = vv
rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints()
rig = rigs[0]
h_mod = rig.get_hierarchy_modifier()
elements = h_mod.get_selection()
c = rig.controller
g = c.get_graph()
n = g.get_nodes()
print(n)
#c.add_branch_node()
#c.add_array_pin()
a:unreal.RigUnit_CollectionItems = unreal.RigUnit_CollectionItems()
print(a)
# 配列ノード追加
collectionItem_forControl:unreal.RigVMStructNode = None
collectionItem_forBone:unreal.RigVMStructNode = None
for node in n:
if (node.get_node_title() == 'Items'):
#print(node.get_node_title())
#node = unreal.RigUnit_CollectionItems.cast(node)
pin = node.find_pin('Items')
print(pin.get_array_size())
print(pin.get_default_value())
if (pin.get_array_size() < 40):
continue
if 'Type=Bone' in pin.get_default_value():
collectionItem_forBone= node
if 'Type=Control' in pin.get_default_value():
collectionItem_forControl = node
#nn = unreal.EditorFilterLibrary.by_class(n,unreal.RigUnit_CollectionItems.static_class())
# controller array
if (collectionItem_forControl == None):
collectionItem_forControl = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute')
items_forControl = collectionItem_forControl.find_pin('Items')
c.clear_array_pin(items_forControl.get_pin_path())
# bone array
if (collectionItem_forBone == None):
collectionItem_forBone = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute')
items_forBone = collectionItem_forBone.find_pin('Items')
c.clear_array_pin(items_forBone.get_pin_path())
## h_mod
rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints()
rig = rigs[0]
h_mod = rig.get_hierarchy_modifier()
## meta 取得
reg = unreal.AssetRegistryHelpers.get_asset_registry();
a = reg.get_all_assets();
for aa in a:
if (aa.get_editor_property("object_path") == args.vrm):
v:unreal.VrmAssetListObject = aa
vv = v.get_asset().vrm_meta_object
print(vv)
meta = vv
for bone_h in meta.humanoid_bone_table:
bone_m = meta.humanoid_bone_table[bone_h]
try:
i = humanoidBoneList.index(bone_h.lower())
except:
i = -1
if (i >= 0):
tmp = '(Type=Bone,Name='
tmp += "{}".format(bone_m).lower()
tmp += ')'
c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp)
#print(bone_m)
tmp = '(Type=Control,Name='
tmp += "{}".format(bone_h).lower() + '_c'
tmp += ')'
c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp)
#print(bone_h)
#for e in h_mod.get_elements():
# if (e.type == unreal.RigElementType.CONTROL):
# tmp = '(Type=Control,Name='
# tmp += "{}".format(e.name)
# tmp += ')'
# c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp)
# print(e.name)
# if (e.type == unreal.RigElementType.BONE):
# tmp = '(Type=Bone,Name='
# tmp += "{}".format(e.name)
# tmp += ')'
# c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp)
# print(e.name)
#print(i.get_all_pins_recursively())
#ii:unreal.RigUnit_CollectionItems = n[1]
#pp = ii.get_editor_property('Items')
#print(pp)
#print(collectionItem.get_all_pins_recursively()[0])
#i.get_editor_property("Items")
#c.add_array_pin("Execute")
# arrayを伸ばす
#i.get_all_pins_recursively()[0].get_pin_path()
#c.add_array_pin(i.get_all_pins_recursively()[0].get_pin_path(), default_value='(Type=Bone,Name=Global)')
#rig = rigs[10]
|
"""
Configuration for the auto-report system.
Controls whether auto-reporting is enabled and configures the Cloudflare Worker endpoint.
"""
import os
import json
from typing import Optional
try:
import unreal
UE_AVAILABLE = True
except ImportError:
UE_AVAILABLE = False
class AutoReportConfig:
"""Configuration manager for the auto-report system."""
def __init__(self, config_dir: str = None):
"""
Initialize the configuration manager.
Args:
config_dir: Directory to store configuration files. If None, will use UE Saved directory.
"""
self.config_dir = config_dir or self._get_default_config_dir()
self.config_file = os.path.join(self.config_dir, 'auto_report_config.json')
self._load_config()
def _get_default_config_dir(self) -> str:
"""Get the default configuration directory."""
try:
if UE_AVAILABLE and hasattr(unreal, 'Paths'):
saved_dir = unreal.Paths.project_saved_dir()
if saved_dir:
return os.path.join(saved_dir, 'MagicOptimizer', 'Config')
except Exception:
pass
# Fallback to current directory
return os.path.join(os.getcwd(), 'Saved', 'MagicOptimizer', 'Config')
def _load_config(self):
"""Load configuration from file or create default."""
try:
# First try to get settings from UE
ue_settings = self._get_ue_settings()
if ue_settings:
# Use UE settings as base, merge with defaults
self.config = self._get_default_config()
self.config.update(ue_settings)
return
# Fallback to file-based config
os.makedirs(self.config_dir, exist_ok=True)
if os.path.exists(self.config_file):
with open(self.config_file, 'r', encoding='utf-8') as f:
self.config = json.load(f)
else:
# Create default configuration
self.config = self._get_default_config()
self._save_config()
except Exception:
# Fallback to default config
self.config = self._get_default_config()
def _get_default_config(self) -> dict:
"""Get the default configuration."""
return {
'enabled': True,
'worker_url': os.environ.get('MAGICOPTIMIZER_WORKER_URL', ''),
'include_logs': True,
'include_knowledge': True,
'max_log_lines': 1000,
'report_errors': True,
'report_optimizations': True,
'report_sessions': False,
'anonymize_data': True,
'rate_limit': {
'max_reports_per_hour': 10,
'max_reports_per_day': 50
}
}
def _get_ue_settings(self) -> dict:
"""Get settings from Unreal Engine if available."""
try:
# Try to import and use the UE settings module
from . import ue_settings
return {
'enabled': ue_settings.is_auto_reporting_enabled() and ue_settings.has_user_consent(),
'worker_url': ue_settings.get_worker_url(),
'include_logs': ue_settings.should_include_logs(),
'include_knowledge': ue_settings.should_include_knowledge(),
'max_log_lines': ue_settings.get_max_log_lines(),
'report_errors': ue_settings.should_report_errors(),
'report_optimizations': ue_settings.should_report_optimizations(),
'report_sessions': ue_settings.should_report_sessions(),
'anonymize_data': ue_settings.should_anonymize_data()
}
except Exception:
pass
return {}
def _save_config(self):
"""Save configuration to file."""
try:
with open(self.config_file, 'w', encoding='utf-8') as f:
json.dump(self.config, f, indent=2, ensure_ascii=False)
except Exception:
pass # Don't break functionality if config save fails
def is_enabled(self) -> bool:
"""Check if auto-reporting is enabled."""
return self.config.get('enabled', True)
def get_worker_url(self) -> str:
"""Get the Cloudflare Worker URL."""
return self.config.get('worker_url', '')
def set_worker_url(self, url: str):
"""Set the Cloudflare Worker URL."""
self.config['worker_url'] = url
self._save_config()
def should_include_logs(self) -> bool:
"""Check if logs should be included in reports."""
return self.config.get('include_logs', True)
def should_include_knowledge(self) -> bool:
"""Check if knowledge data should be included in reports."""
return self.config.get('include_knowledge', True)
def get_max_log_lines(self) -> int:
"""Get the maximum number of log lines to include."""
return self.config.get('max_log_lines', 1000)
def should_report_errors(self) -> bool:
"""Check if errors should be reported."""
return self.config.get('report_errors', True)
def should_report_optimizations(self) -> bool:
"""Check if optimizations should be reported."""
return self.config.get('report_optimizations', True)
def should_report_sessions(self) -> bool:
"""Check if session reports should be sent."""
return self.config.get('report_sessions', False)
def should_anonymize_data(self) -> bool:
"""Check if data should be anonymized."""
return self.config.get('anonymize_data', True)
def get_rate_limit(self) -> dict:
"""Get rate limiting configuration."""
return self.config.get('rate_limit', {})
def set_enabled(self, enabled: bool):
"""Enable or disable auto-reporting."""
self.config['enabled'] = enabled
self._save_config()
def set_include_logs(self, include: bool):
"""Set whether logs should be included."""
self.config['include_logs'] = include
self._save_config()
def set_include_knowledge(self, include: bool):
"""Set whether knowledge data should be included."""
self.config['include_knowledge'] = include
self._save_config()
def set_max_log_lines(self, max_lines: int):
"""Set the maximum number of log lines to include."""
self.config['max_log_lines'] = max_lines
self._save_config()
def set_report_errors(self, report: bool):
"""Set whether errors should be reported."""
self.config['report_errors'] = report
self._save_config()
def set_report_optimizations(self, report: bool):
"""Set whether optimizations should be reported."""
self.config['report_optimizations'] = report
self._save_config()
def set_report_sessions(self, report: bool):
"""Set whether session reports should be sent."""
self.config['report_sessions'] = report
self._save_config()
def set_anonymize_data(self, anonymize: bool):
"""Set whether data should be anonymized."""
self.config['anonymize_data'] = anonymize
self._save_config()
def get_config_summary(self) -> dict:
"""Get a summary of the current configuration."""
return {
'enabled': self.is_enabled(),
'worker_url_configured': bool(self.get_worker_url()),
'include_logs': self.should_include_logs(),
'include_knowledge': self.should_include_knowledge(),
'max_log_lines': self.get_max_log_lines(),
'report_errors': self.should_report_errors(),
'report_optimizations': self.should_report_optimizations(),
'report_sessions': self.should_report_sessions(),
'anonymize_data': self.should_anonymize_data()
}
def reset_to_defaults(self):
"""Reset configuration to defaults."""
self.config = self._get_default_config()
self._save_config()
# Global configuration instance
_config = None
def get_config() -> AutoReportConfig:
"""Get the global configuration instance."""
global _config
if _config is None:
_config = AutoReportConfig()
return _config
def is_auto_reporting_enabled() -> bool:
"""Check if auto-reporting is enabled."""
config = get_config()
return config.is_enabled()
def get_worker_url() -> str:
"""Get the configured worker URL."""
config = get_config()
return config.get_worker_url()
def should_include_logs() -> bool:
"""Check if logs should be included."""
config = get_config()
return config.should_include_logs()
def should_include_knowledge() -> bool:
"""Check if knowledge data should be included."""
config = get_config()
return config.should_include_knowledge()
def get_max_log_lines() -> int:
"""Get the maximum number of log lines to include."""
config = get_config()
return config.get_max_log_lines()
def should_report_errors() -> bool:
"""Check if errors should be reported."""
config = get_config()
return config.should_report_errors()
def should_report_optimizations() -> bool:
"""Check if optimizations should be reported."""
config = get_config()
return config.should_report_optimizations()
def should_report_sessions() -> bool:
"""Check if session reports should be sent."""
config = get_config()
return config.should_report_sessions()
def should_anonymize_data() -> bool:
"""Check if data should be anonymized."""
config = get_config()
return config.should_anonymize_data()
|
import unreal
def get_time_of_day(actor: unreal.Actor):
return actor.get_editor_property("Time of Day")
def set_time_of_day(actor: unreal.Actor, time_of_day: float):
actor.set_editor_property("Time of Day", time_of_day)
level_editor_subsystem = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem)
actors = unreal.EditorLevelLibrary.get_all_level_actors()
for actor in actors:
if actor.get_name() == "Ultra_Dynamic_Sky_C_0":
tod = actor.get_editor_property("Time of Day")
print(tod)
break
if actor.get_name() == "Ultra_Dynamic_Sky_C_0":
set_time_of_day(actor, 1000)
print(get_time_of_day(actor))
|
# filename:list_plugins.py
# #Generated for: Mr. Gary
# By: Juniper (ChatGPT) April 8, 2025 v4
# run in UE python (REPL) bash: exec(open("E:/UNREAL ENGINE/TEMPLATE PROJECTS/project/.py").read())
import unreal
registry = unreal.AssetRegistryHelpers.get_asset_registry()
plugin_assets = registry.get_assets_by_path('/project/', recursive=True)
plugin_names = set()
for asset in plugin_assets:
plugin_name = asset.package_name.split('/')[2]
plugin_names.add(plugin_name)
for name in sorted(plugin_names):
print(f"{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.
""" 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()
|
# This file is based on templates provided and copyrighted by Autodesk, Inc.
# This file has been modified by Epic Games, Inc. and is subject to the license
# file included in this repository.
from collections import namedtuple, defaultdict
import copy
import os
import unreal
import sgtk
# A named tuple to store LevelSequence edits: the sequence/project/
# the edit is in.
SequenceEdit = namedtuple("SequenceEdit", ["sequence", "track", "section"])
HookBaseClass = sgtk.get_hook_baseclass()
class UnrealSessionCollector(HookBaseClass):
"""
Collector that operates on the Unreal session. Should inherit from the basic
collector hook.
You can read more about collectors here:
http://developer.shotgunsoftware.com/tk-multi-publish2/collector.html
Here's Maya's implementation for reference:
https://github.com/project/-maya/project/-multi-publish2/project/.py
"""
@property
def settings(self):
"""
Dictionary defining the settings that this collector expects to receive
through the settings parameter in the process_current_session and
process_file methods.
A dictionary on the following form::
{
"Settings Name": {
"type": "settings_type",
"default": "default_value",
"description": "One line description of the setting"
}
The type string should be one of the data types that toolkit accepts as
part of its environment configuration.
"""
# grab any base class settings
collector_settings = super(UnrealSessionCollector, self).settings or {}
# Add setting specific to this collector.
work_template_setting = {
"Work Template": {
"type": "template",
"default": None,
"description": "Template path for artist work files. Should "
"correspond to a template defined in "
"templates.yml. If configured, is made available"
"to publish plugins via the collected item's "
"properties. ",
},
}
collector_settings.update(work_template_setting)
return collector_settings
def process_current_session(self, settings, parent_item):
"""
Analyzes the current session in Unreal and parents a subtree of
items under the parent_item passed in.
:param dict settings: Configured settings for this collector
:param parent_item: Root item instance
"""
# Create an item representing the current Unreal session
parent_item = self.collect_current_session(settings, parent_item)
# Collect assets selected in Unreal
self.collect_selected_assets(parent_item)
def collect_current_session(self, settings, parent_item):
"""
Creates an item that represents the current Unreal session.
:param dict settings: Configured settings for this collector
:param parent_item: Parent Item instance
:returns: Item of type unreal.session
"""
# Create the session item for the publish hierarchy
# In Unreal, the current session can be defined as the current level/map (.umap)
# Don't create a session item for now since the .umap does not need to be published
session_item = parent_item
# Get the icon path to display for this item
icon_path = os.path.join(
self.disk_location,
os.pardir,
"icons",
"unreal.png"
)
# Set the icon for the session item
# Will also be used for the children items parented to the session item
session_item.set_icon_from_path(icon_path)
# Set the project root
unreal_sg = sgtk.platform.current_engine().unreal_sg_engine
project_root = unreal_sg.get_shotgun_work_dir()
# Important to convert "/" in path returned by Unreal to "\" for templates to work
project_root = project_root.replace("/", "\\")
session_item.properties["project_root"] = project_root
self.logger.info("Current Unreal project folder is: %s." % (project_root))
# If a work template is defined, add it to the item properties so
# that it can be used by publish plugins
work_template_setting = settings.get("Work Template")
if work_template_setting:
publisher = self.parent
work_template = publisher.get_template_by_name(work_template_setting.value)
if work_template:
# Override the work template to use the project root from Unreal and not the default root for templates
work_template = sgtk.TemplatePath(work_template.definition, work_template.keys, project_root)
session_item.properties["work_template"] = work_template
self.logger.debug("Work template defined for Unreal collection.")
self.logger.info("Collected current Unreal session")
return session_item
def create_asset_item(self, parent_item, asset_path, asset_type, asset_name, display_name=None):
"""
Create an unreal item under the given parent item.
:param asset_path: The unreal asset path, as a string.
:param asset_type: The unreal asset type, as a string.
:param asset_name: The unreal asset name, as a string.
:param display_name: Optional display name for the item.
:returns: The created item.
"""
item_type = "unreal.asset.%s" % asset_type
asset_item = parent_item.create_item(
item_type, # Include the asset type for the publish plugin to use
asset_type, # Display type
display_name or asset_name, # Display name of item instance
)
# Set asset properties which can be used by publish plugins
asset_item.properties["asset_path"] = asset_path
asset_item.properties["asset_name"] = asset_name
asset_item.properties["asset_type"] = asset_type
return asset_item
def collect_selected_assets(self, parent_item):
"""
Creates items for assets selected in Unreal.
:param parent_item: Parent Item instance
"""
unreal_sg = sgtk.platform.current_engine().unreal_sg_engine
sequence_edits = None
# Iterate through the selected assets and get their info and add them as items to be published
for asset in unreal_sg.selected_assets:
if asset.asset_class_path.asset_name == "LevelSequence":
if sequence_edits is None:
sequence_edits = self.retrieve_sequence_edits()
self.collect_level_sequence(parent_item, asset, sequence_edits)
else:
self.create_asset_item(
parent_item,
# :class:`Name` instances, we cast them to strings otherwise
# string operations fail down the line..
"%s" % unreal_sg.object_path(asset),
"%s" % asset.asset_class_path.asset_name,
"%s" % asset.asset_name,
)
def get_all_paths_from_sequence(self, level_sequence, sequence_edits, visited=None):
"""
Retrieve all edit paths from the given Level Sequence to top Level Sequences.
Recursively explore the sequence edits, stop the recursion when a Level
Sequence which is not a sub-sequence of another is reached.
Lists of Level Sequences are returned, where each list contains all the
the Level Sequences to traverse to reach the top Level Sequence from the
starting Level Sequence.
For example if a master Level Sequence contains some `Seq_<seq number>`
sequences and each of them contains shots like `Shot_<seq number>_<shot number>`,
a path for Shot_001_010 would be `[Shot_001_010, Seq_001, Master sequence]`.
If an alternate Cut is maintained with another master level Sequence, both
paths would be detected and returned by this method, e.g.
`[[Shot_001_010, Seq_001, Master sequence], [Shot_001_010, Seq_001, Master sequence 2]]`
Maintain a list of visited Level Sequences to detect cycles.
:param level_sequence: A :class:`unreal.LevelSequence` instance.
:param sequence_edits: A dictionary with :class:`unreal.LevelSequence as keys and
lists of :class:`SequenceEdit` as values.
:param visited: A list of :class:`unreal.LevelSequence` instances, populated
as nodes are visited.
:returns: A list of lists of Level Sequences.
"""
if not visited:
visited = []
visited.append(level_sequence)
self.logger.info("Treating %s" % level_sequence.get_name())
if not sequence_edits[level_sequence]:
# No parent, return a list with a single entry with the current
# sequence
return [[level_sequence]]
all_paths = []
# Loop over parents get all paths starting from them
for edit in sequence_edits[level_sequence]:
if edit.sequence in visited:
self.logger.warning(
"Detected a cycle in edits path %s to %s" % (
"->".join(visited), edit.sequence
)
)
else:
# Get paths from the parent and prepend the current sequence
# to them.
for edit_path in self.get_all_paths_from_sequence(
edit.sequence,
sequence_edits,
copy.copy(visited), # Each visit needs its own stack
):
self.logger.info("Got %s from %s" % (edit_path, edit.sequence.get_name()))
all_paths.append([level_sequence] + edit_path)
return all_paths
def collect_level_sequence(self, parent_item, asset, sequence_edits):
"""
Collect the items for the given Level Sequence asset.
Multiple items can be collected for a given Level Sequence if it appears
in multiple edits.
:param parent_item: Parent Item instance.
:param asset: An Unreal LevelSequence asset.
:param sequence_edits: A dictionary with :class:`unreal.LevelSequence as keys and
lists of :class:`SequenceEdit` as values.
"""
unreal_sg = sgtk.platform.current_engine().unreal_sg_engine
level_sequence = unreal.load_asset(unreal_sg.object_path(asset))
for edits_path in self.get_all_paths_from_sequence(level_sequence, sequence_edits):
# Reverse the path to have it from top master sequence to the shot.
edits_path.reverse()
self.logger.info("Collected %s" % [x.get_name() for x in edits_path])
if len(edits_path) > 1:
display_name = "%s (%s)" % (edits_path[0].get_name(), edits_path[-1].get_name())
else:
display_name = edits_path[0].get_name()
item = self.create_asset_item(
parent_item,
edits_path[0].get_path_name(),
"LevelSequence",
edits_path[0].get_name(),
display_name,
)
# Store the edits on the item so we can leverage them later when
# publishing.
item.properties["edits_path"] = edits_path
def retrieve_sequence_edits(self):
"""
Build a dictionary for all Level Sequences where keys are Level Sequences
and values the list of edits they are in.
:returns: A dictionary of :class:`unreal.LevelSequence` where values are
lists of :class:`SequenceEdit`.
"""
sequence_edits = defaultdict(list)
unreal_sg = sgtk.platform.current_engine().unreal_sg_engine
level_sequence_class = unreal.TopLevelAssetPath("/project/", "LevelSequence")
asset_helper = unreal.AssetRegistryHelpers.get_asset_registry()
# Retrieve all Level Sequence assets
all_level_sequences = asset_helper.get_assets_by_class(level_sequence_class)
for lvseq_asset in all_level_sequences:
lvseq = unreal.load_asset(unreal_sg.object_path(lvseq_asset), unreal.LevelSequence)
# Check shots
for track in lvseq.find_master_tracks_by_type(unreal.MovieSceneCinematicShotTrack):
for section in track.get_sections():
# Not sure if you can have anything else than a MovieSceneSubSection
# in a MovieSceneCinematicShotTrack, but let's be cautious here.
try:
# Get the Sequence attached to the section and check if
# it is the one we're looking for.
section_seq = section.get_sequence()
sequence_edits[section_seq].append(
SequenceEdit(lvseq, track, section)
)
except AttributeError:
pass
return sequence_edits
|
# simulations/project/.py
import unreal
import logging
from typing import Dict, Any
import numpy as np
from .vr_environment import VREnvironment
class PavilionVREnvironment(VREnvironment):
"""Pavilion-based VR environment for emotional reinforcement learning"""
def __init__(self, config: Dict, emotion_network):
super().__init__()
self.config = config
self.emotion_network = emotion_network
self.face_recognition = None # Will be initialized with Pavilion's face recognition
def initialize_environment(self, map_name: str) -> bool:
"""Initialize Pavilion environment and load map"""
try:
# Initialize base VR environment
success = super().initialize_environment(map_name)
if not success:
return False
# Initialize Pavilion-specific components
self._setup_pavilion_components()
logging.info(f"Pavilion VR environment initialized with map: {map_name}")
return True
except Exception as e:
logging.error(f"Error initializing Pavilion environment: {e}")
return False
def _setup_pavilion_components(self):
"""Setup Pavilion-specific components like face recognition"""
# Initialize face recognition
self.face_recognition = self._initialize_face_recognition()
# Setup emotional response tracking
self._setup_emotional_tracking()
def step(self, action: Dict) -> tuple:
"""Take step in environment with emotional feedback"""
# Execute action in base environment
next_state, reward, done, info = super().step(action)
# Get emotional feedback from face recognition
if self.face_recognition:
facial_emotion = self.face_recognition.detect_emotion()
info['facial_emotion'] = facial_emotion
# Update emotional context
emotional_context = self.emotion_network.update_context(
state=next_state,
facial_emotion=info.get('facial_emotion'),
action=action
)
info['emotional_context'] = emotional_context
return next_state, reward, done, info
# simulations/project/.py
from .vr_environment import VREnvironment
import logging
from typing import Dict, Any
import numpy as np
class InteractiveVREnvironment(VREnvironment):
"""Generic VR environment for emotional reinforcement learning"""
def __init__(self, config: Dict, emotion_network):
super().__init__()
self.config = config
self.emotion_network = emotion_network
self.face_recognition = None
self._setup_vr_components()
def initialize_environment(self, map_name: str) -> bool:
"""Initialize VR environment and load map"""
try:
success = super().initialize_environment(map_name)
if not success:
return False
self._setup_interaction_components()
logging.info(f"Interactive VR environment initialized with map: {map_name}")
return True
except Exception as e:
logging.error(f"Error initializing environment: {e}")
return False
def step(self, action: Dict) -> tuple:
# Execute action in base environment
next_state, reward, done, info = super().step(action)
# Get emotional feedback (e.g., via face recognition plugin)
if self.face_recognition:
facial_emotion = self.face_recognition.detect_emotion()
info['facial_emotion'] = facial_emotion
# Update emotional context for the agent
emotional_context = self.emotion_network.update_context(
state=next_state,
facial_emotion=info.get('facial_emotion'),
action=action
)
info['emotional_context'] = emotional_context
return next_state, reward, done, info
def _initialize_face_recognition(self):
# Placeholder: initialize biometric recognition system for VR.
pass
def _setup_emotional_tracking(self):
# Placeholder: setup emotional tracking system.
pass
def _setup_vr_components(self):
"""
Setup VR-specific components such as biometric recognition and
emotional tracking, without any Pavilion-specific dependencies.
"""
self.face_recognition = self._initialize_face_recognition()
self._setup_emotional_tracking()
|
import json
import os.path
import re
import unreal
"""Creates Actor blueprint with static mesh components from json. WARNING: Works only in UE 5.1 internal API
"""
# Change me!
DO_DELETE_IF_EXISTS = False
ASSET_DIR = "/project/"
# ASSET_DIR = "/project/"
# ASSET_DIR = "/project/"
JSON_FILEPATH = "C:/project/ Projects/project/" \
"MapData/project/.json"
ASSET_NAME_OVERRIDE = ""
if ASSET_NAME_OVERRIDE:
ASSET_NAME = ASSET_NAME_OVERRIDE
else:
ASSET_NAME = os.path.basename(JSON_FILEPATH).replace(".json", "")
BFL = unreal.SubobjectDataBlueprintFunctionLibrary
SDS = unreal.get_engine_subsystem(unreal.SubobjectDataSubsystem)
ASSET_PATH = os.path.join(ASSET_DIR, ASSET_NAME)
def get_sub_handle_object(sub_handle):
obj = BFL.get_object(BFL.get_data(sub_handle))
return obj
def add_component(root_data_handle, subsystem, blueprint, new_class, name):
sub_handle, fail_reason = subsystem.add_new_subobject(
params=unreal.AddNewSubobjectParams(
parent_handle=root_data_handle,
new_class=new_class,
blueprint_context=blueprint
)
)
if not fail_reason.is_empty():
raise Exception(f"ERROR from sub_object_subsystem.add_new_subobject: {fail_reason}")
subsystem.rename_subobject(handle=sub_handle, new_name=unreal.Text(name))
subsystem.attach_subobject(owner_handle=root_data_handle, child_to_add_handle=sub_handle)
obj = BFL.get_object(BFL.get_data(sub_handle))
return sub_handle, obj
def create_actor_blueprint(asset_name, asset_dir):
factory = unreal.BlueprintFactory()
factory.set_editor_property("parent_class", unreal.Actor)
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
blueprint = asset_tools.create_asset(asset_name, asset_dir, None, factory)
return blueprint
def add_components_to_blueprint(blueprint):
root_data_handle = SDS.k2_gather_subobject_data_for_blueprint(blueprint)[0]
scene_handle, scene = add_component(root_data_handle, SDS, blueprint, unreal.SceneComponent, name="Scene")
with open(JSON_FILEPATH, "rb") as f:
data = json.load(f)
for i, element in enumerate(data):
path, transform, want_child_actor = element["path"], element["transform"], element.get("want_child_actor", False)
t = re.search(r"\w+\s(?P<path>[\/\w]+).\w+", path)
path = t.group("path") if t else path
if path.startswith("/") and unreal.EditorAssetLibrary.does_asset_exist(path):
my_class = unreal.StaticMeshComponent if not want_child_actor else unreal.ChildActorComponent
sub_handle, building_component = add_component(
scene_handle,
subsystem=SDS,
blueprint=blueprint,
new_class=my_class,
name=f"StaticMesh{i + 1}" if not want_child_actor else f"ChildActor{i + 1}")
if want_child_actor:
assert isinstance(building_component, unreal.ChildActorComponent)
bp_class = unreal.EditorAssetLibrary.load_blueprint_class(path)
building_component.set_child_actor_class(bp_class)
else:
assert isinstance(building_component, unreal.StaticMeshComponent)
mesh = unreal.EditorAssetLibrary.find_asset_data(path).get_asset()
building_component.set_static_mesh(mesh)
building_component.set_editor_property(
name="relative_location",
value=unreal.Vector(transform["loc"][0],
transform["loc"][1],
transform["loc"][2])
)
building_component.set_editor_property(
name="relative_rotation",
value=unreal.Rotator(pitch=transform["rot"][0],
roll=transform["rot"][1],
yaw=transform["rot"][2])
)
building_component.set_editor_property(
name="relative_scale3d",
value=unreal.Vector(transform["scale"][0],
transform["scale"][1],
transform["scale"][2])
)
else:
print(f"Error: Asset {path} doesn't exist")
unreal.EditorAssetLibrary.save_loaded_asset(blueprint)
if unreal.EditorAssetLibrary.does_asset_exist(ASSET_PATH):
if DO_DELETE_IF_EXISTS:
unreal.EditorAssetLibrary.delete_asset(ASSET_PATH)
else:
raise FileExistsError(f"This file {ASSET_PATH} already exists")
blueprint = create_actor_blueprint(ASSET_NAME, ASSET_DIR)
add_components_to_blueprint(blueprint)
|
import os
import shutil
import subprocess
import ce_path_utils
# import dds2png
def copy_dds_files_with_structure(source_dir, target_dir):
for root, _, files in os.walk(source_dir):
# Filter for .dds and its variants
dds_files = [f for f in files if f.endswith('.dds') or '.dds.' in f]
for dds_file in dds_files:
base_name = dds_file.split('.dds')[0] # Extract base name
base_path = os.path.join(root, base_name + '.dds')
# Determine relative path for subfolder structure
relative_path = os.path.relpath(root, source_dir)
target_subfolder = os.path.join(target_dir, relative_path)
os.makedirs(target_subfolder, exist_ok=True)
# Copy all files with the same base name
for variant in files:
if variant.startswith(base_name + '.dds'):
source_file = os.path.join(root, variant)
target_file = os.path.join(target_subfolder, variant)
# Rename base .dds to .dds.0 in the target folder
if variant == base_name + '.dds':
target_file = os.path.join(target_subfolder, base_name + '.dds.0')
shutil.copy2(source_file, target_file)
print(f"Copied: {source_file} -> {target_file}")
def process_dds_files(target_dir, tool_path):
for root, _, files in os.walk(target_dir):
for file in files:
if file.endswith('.dds'):
dds_file_path = os.path.join(root, file)
base_name = file[:-4] # Remove '.dds.0' to get the base name
# Construct the command
command = [tool_path, dds_file_path, '-s']
# command = [tool_path, dds_file_path]
try:
# Execute the command
subprocess.run(command, check=True)
print(f"Processed: {dds_file_path}")
combined_file_path = os.path.join(root, base_name + '.combined.dds')
print(combined_file_path)
# Delete all .dds.x files for this base name
# for variant in files:
# if variant.startswith(base_name + '.dds'):
# variant_path = os.path.join(root, variant)
# os.remove(variant_path)
# print(f"Deleted: {variant_path}")
# filename = dds_file_path.replace(".dds.0", ".dds")
# (base_filename, filename_ext) = os.path.splitext(filename)
# output_filename = base_filename + '.png'
# # Load DDS file using imageio
# dds_image = imageio.imread(filename)
# # Convert numpy array to PIL image
# image = Image.fromarray(dds_image)
# # Save as TGA
# image.save(output_filename)
except subprocess.CalledProcessError as e:
print(f"Error processing {dds_file_path}: {e}")
command = [nvtt_export_path, combined_file_path, '-o', combined_file_path.replace('.dds', '.tga')]
try:
# Execute the command
subprocess.run(command, check=True)
print(f"Processed: {combined_file_path}")
except subprocess.CalledProcessError as e:
print(f"Error processing {combined_file_path}: {e}")
print(file)
break
def import_dds_to_unreal(target_dir):
import unreal
import asset_import_utils
tasks = []
should_break = False
for root, _, files in os.walk(target_dir):
for file in files:
file = file.lower()
if file.endswith('.tga'):
dds_file_path = os.path.join(root, file)
package_name = dds_file_path.replace(target_dir, "/project/").replace("\\", "/")
package_name = package_name.replace('.tga', '')
package_path = package_name[:package_name.rfind("/")]
name = package_name.split("/")[-1]
if unreal.EditorAssetLibrary.does_asset_exist(package_name):
# print(f"Asset already exists: {package_name}")
continue
task = asset_import_utils.build_input_task_simple(dds_file_path, package_path, name)
tasks.append(task)
# should_break = True
# break
# if should_break:
# break
asset_import_utils.execute_import_tasks(tasks)
# Define source and target directories
source_directory = r"/project/"
target_directory = r"/project/-release\KCD1Re\ArtRaw"
tool_path = r"/project/-release\KCD1Re\Tools\AssetConverter\DDS-Unsplitter.exe"
nvtt_export_path = r"/project/ Files\NVIDIA Corporation\NVIDIA Texture Tools\nvtt_export.exe"
# Execute the function
# copy_dds_files_with_structure(ce_path_utils.CRY_ENGINE_OUTPUT_FOLDER_ROOT, target_directory)
# script_dir = os.path.dirname(os.path.abspath(__file__))
# converter_exe = os.path.join(script_dir, "../DDS-Unsplitter.exe")
# process_dds_files(ce_path_utils.CRY_ENGINE_OUTPUT_FOLDER_ROOT, tool_path)
import_dds_to_unreal(target_directory)
|
# Copyright (c) <2021> Side Effects Software Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. The name of Side Effects Software may not be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unreal
""" Example for getting the API instance and starting/creating the Houdini
Engine Session.
"""
def run():
# Get the API singleton
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
# Check if there is an existing valid session
if not api.is_session_valid():
# Create a new session
api.create_session()
if __name__ == '__main__':
run()
|
# -*- coding: utf-8 -*-
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))
|
# Copyright 2020 Tomoaki Yoshida<[email protected]>
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/project/.0/.
#
#
#
# You need following modules to run this script
# + pillow
# + numpy
# + gdal
#
# You can install these modules by running following commands on a posh prompt
# PS> cd /project/ Files\Epic Games\UE_4.25\Engine\Binaries\ThirdParty\Python\Win64
# PS> ./python.exe -m pip install pillow numpy
# GDAL cannot install by this simple method. You need to download whl file from
# https://www.lfd.uci.edu/~gohlke/pythonlibs/#gdal
# and then, install it by the similar command
# PS> ./python.exe -m pip install /project/-2.2.4-cp27-cp27m-win_amd64.whl
#
# You may want to add
# --target="/project/ Files\Epic Games\UE_4.25\Engine\Source\ThirdParty\Python\Win64\Lib\site-packages"
# to each pip install command. Without this --target option, modules will be installed in this folder.
# /project/ Files\Epic Games\UE_4.25\Engine\Binaries\ThirdParty\Python\Win64\Lib\site-packages
import unreal
import gdal
import osr
import os
from PIL import Image, ImageTransform, ImageMath
import numpy as np
al=unreal.EditorAssetLibrary
el=unreal.EditorLevelLibrary
sdir=os.path.dirname(os.path.abspath(__file__))
projdir=os.path.join(sdir,"..")
# Parameters
stepSize=10 # [cm] # landscale cell size
zScale=10 # 100: +/-256 [m], 10: +/-25.6 [m] 1: 256 [cm] # landscape z scale value
zEnhance=1 # optional z scaling factor
zClipping=19.0 # Clip lowest height [m] (None for no clipping)
inputGeotiff=os.path.join(projdir,"Assets","TC-DEM-geo.tif")
outputHeightmap=os.path.join(projdir,"Assets","heightmap.png")
toUEScale=100.*128./zScale # [m]->[cm]->[heightmap unit]
# Utilities
class GeoTIFF:
def __init__(self, file):
self.gt = gdal.Open(file, gdal.GA_ReadOnly)
#self.rast = np.array([self.gt.GetRasterBand(1).ReadAsArray()])
self.image = Image.fromarray(self.gt.GetRasterBand(1).ReadAsArray())
self.src_cs = osr.SpatialReference()
self.dst_cs = osr.SpatialReference()
self.dst_cs.ImportFromWkt(self.gt.GetProjectionRef())
self.setSrcEPSG(6668) # default to JGD2011
# inverse transform from GeoTIFF(UV) to GeoTIFF(Logical)
self.mat = self.gt.GetGeoTransform()
d = 1./(self.mat[5]*self.mat[1]-self.mat[4]*self.mat[2])
self.iaf = np.array([[self.mat[5], -self.mat[2]],
[-self.mat[4], self.mat[1]]])*d
self.offset = np.array([[self.mat[0]], [self.mat[3]]])
def setSrcEPSG(self, epsg):
self.src_cs = osr.SpatialReference()
self.src_cs.ImportFromEPSG(epsg)
self.transform = osr.CoordinateTransformation(self.src_cs, self.dst_cs)
def getUV(self, srcBL):
gtBL = self.transform.TransformPoint(srcBL[1], srcBL[0])
bl=np.array([[gtBL[0]],[gtBL[1]]])
uv = np.dot(self.iaf, bl-self.offset)
return (uv[0][0], uv[1][0])
def getLandscapeBBox():
# search for landscape proxy actors
w=el.get_all_level_actors()
theFirst=True
for a in w:
if(a.get_class().get_name().startswith("Landscape") and not a.get_class().get_name().startswith("LandscapeGizmo")):
#print("Landscape Found : "+ a.get_name())
o,box=a.get_actor_bounds(True)
h=o+box
l=o-box
if(theFirst):
lx=l.x
ly=l.y
hx=h.x
hy=h.y
theFirst=False
else:
if(lx>l.x):
lx=l.x
if(ly>l.y):
ly=l.y
if(hx<h.x):
hx=h.x
if(hy<h.y):
hy=h.y
print("Landscape bounding box: ({0}, {1} - {2}, {3})".format(lx,ly,hx,hy))
print("Landscape size: {0} x {1}".format(hx-lx,hy-ly))
size=(int((hx-lx)/stepSize+1),int((hy-ly)/stepSize+1))
print("Landscape grid size: {0}".format(size))
return (lx,ly,hx,hy,size)
def getGeoReference():
w=el.get_all_level_actors()
theFirst=True
for a in w:
if(a.get_class().get_name().startswith("GeoReferenceBP")):
print("GeoReference Found")
ref=a
return ref
# ----------------------------------------------------------------------------------------
lx,ly,hx,hy,size=getLandscapeBBox()
ref=getGeoReference()
text_label="Projecting coordinates"
nFrames=5
with unreal.ScopedSlowTask(nFrames, text_label) as slow_task:
slow_task.make_dialog(True)
tl=ref.get_bl(lx,ly)
bl=ref.get_bl(lx,hy)
br=ref.get_bl(hx,hy)
tr=ref.get_bl(hx,ly)
zo=ref.get_actor_location()
zobl=ref.get_bl(zo.x,zo.y)
#print("Reference Quad=tl:{0} bl:{1} br:{2} tr:{3}".format(tl, bl, br, tr))
#print("GeoReference in UE {0}".format(zo))
#print("GeoReference in BL {0}".format(zobl))
gt=GeoTIFF(inputGeotiff)
tluv=gt.getUV(tl)
bluv=gt.getUV(bl)
bruv=gt.getUV(br)
truv=gt.getUV(tr)
zouv=gt.getUV(zobl)
#print("Reference Quad on GeoTIFF image =tl:{0} bl:{1} br:{2} tr:{3}".format(tluv, bluv, bruv, truv, zouv))
slow_task.enter_progress_frame(1,"Clipping z range")
print(gt.image.mode)
print(gt.image)
if zClipping is not None:
imageref=Image.new(gt.image.mode,gt.image.size,zClipping)
clippedimg=ImageMath.eval("max(a,b)",a=gt.image,b=imageref)
clippedimg.save(os.path.join(projdir,"Assets","clipped.tif"))
else:
clippedimg=gt.image
slow_task.enter_progress_frame(1,"Transforming image region")
uvf=tluv+bluv+bruv+truv
img=clippedimg.transform(size,Image.QUAD,data=uvf,resample=Image.BICUBIC)
slow_task.enter_progress_frame(1,"Transforming height values")
# scale to match landscape scaling, and offset to align to GeoReference actor
zov=gt.image.getpixel(zouv)
zos=32768-(zov*zEnhance-zo.z/100.)*toUEScale # 32768: mid point (height=0)
iarrf=np.array(img.getdata()).clip(zcmin,zcmax)*toUEScale*zEnhance + zos
slow_task.enter_progress_frame(1,"Converting to 16bit grayscale")
# convert to uint16 using numpy
# PIL cannot handle this operation because of CLIP16() which limits each pixel value in -32768 to 32767.
# This clipping must be avoided because destination dtype is uint16.
iarrs=np.array(iarrf,dtype="uint16")
slow_task.enter_progress_frame(1,"Saving as {0}".format(os.path.basename(outputHeightmap)))
imgS=Image.frombuffer("I;16",img.size,iarrs.data, "raw", "I;16", 0, 1)
imgS.save(outputHeightmap)
print("Heightmap saved as {0}".format(outputHeightmap))
|
import importlib
import unreal
import unlock_all_actors_command
importlib.reload(unlock_all_actors_command)
from unlock_all_actors_command import UnlockAllActorsCommand
if __name__ == '__main__':
command = UnlockAllActorsCommand()
command.add_object_to_root()
command.execute()
|
import unreal
def get_da_list(da:unreal.PrimaryDataAsset, property_name:str) -> list[unreal.Object]:
return unreal.PrimaryDataAsset.get_editor_property(da, property_name)
def get_da_item(da:unreal.PrimaryDataAsset, property_name:str) -> unreal.SkeletalMesh:
return unreal.PrimaryDataAsset.get_editor_property(da, property_name)
def set_da_list(blueprint_asset, property_name:str ,sm_materials):
key_name = property_name
property_info = {key_name: sm_materials}
blueprint_asset.set_editor_properties(property_info)
return blueprint_asset.set_editor_properties(property_info)
def get_sm_materials(selected_sm:unreal.SkeletalMesh) -> list[unreal.MaterialInstanceConstant]:
sm_materials = []
for material in selected_sm.materials:
mic:unreal.MaterialInstanceConstant = material.material_interface
sm_materials.append(mic)
return sm_materials
selected_data_asset: list[unreal.Object] = unreal.EditorUtilityLibrary.get_selected_assets()[0]
loaded_subsystem = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem)
if selected_data_asset.__class__ != unreal.PrimaryDataAsset:
print('Please select a data asset')
exit()
#set variables
da_path = selected_data_asset.get_path_name()
da_materials = get_da_list(selected_data_asset, "Materials")
da_outlines = get_da_list(selected_data_asset, "OutlineMaterials")
da_sm = get_da_item(selected_data_asset, "SkeletalMesh")
da_base_outline = get_da_item(selected_data_asset, "BasicOutlineMaterial")
da_clear = get_da_item(selected_data_asset, "ClearMaterial")
da_cha_name = str(get_da_item(selected_data_asset, "CharacterName"))
da_ca = get_da_item(selected_data_asset, "ChaosCloth")
#####################
#####################
ca_mats = da_ca.get_editor_property('Materials')
new_materials = []
for mi in ca_mats:
mic = mi.material_interface
print(mic)
new_materials.append(mic)
set_da_list(selected_data_asset, "ChaosMaterials", new_materials)
loaded_subsystem.save_asset(da_path)
|
# -*- coding: utf-8 -*-
"""Load Skeletal Mesh alembics."""
from ayon_core.pipeline import AYON_CONTAINER_ID
from ayon_core.lib import EnumDef
from ayon_unreal.api import plugin
from ayon_unreal.api.pipeline import (
create_container,
imprint,
format_asset_directory,
UNREAL_VERSION,
get_dir_from_existing_asset
)
from ayon_core.settings import get_current_project_settings
import unreal # noqa
class SkeletalMeshAlembicLoader(plugin.Loader):
"""Load Unreal SkeletalMesh from Alembic"""
product_types = {"pointcache", "skeletalMesh"}
label = "Import Alembic Skeletal Mesh"
representations = {"abc"}
icon = "cube"
color = "orange"
abc_conversion_preset = "maya"
loaded_asset_dir = "{folder[path]}/{product[name]}_{version[version]}"
loaded_asset_name = "{folder[name]}_{product[name]}_{version[version]}_{representation[name]}" # noqa
show_dialog = False
@classmethod
def apply_settings(cls, project_settings):
super(SkeletalMeshAlembicLoader, cls).apply_settings(project_settings)
# Apply import settings
unreal_settings = project_settings["unreal"]["import_settings"]
cls.abc_conversion_preset = unreal_settings["abc_conversion_preset"]
cls.loaded_asset_dir = unreal_settings["loaded_asset_dir"]
cls.loaded_asset_name = unreal_settings["loaded_asset_name"]
cls.show_dialog = unreal_settings["show_dialog"]
@classmethod
def get_options(cls, contexts):
return [
EnumDef(
"abc_conversion_preset",
label="Alembic Conversion Preset",
items={
"3dsmax": "3dsmax",
"maya": "maya",
"custom": "custom"
},
default=cls.abc_conversion_preset
),
EnumDef(
"abc_material_settings",
label="Alembic Material Settings",
items={
"no_material": "Do not apply materials",
"create_materials": "Create matarials by face sets",
"find_materials": "Search matching materials by face sets",
},
default="Do not apply materials"
)
]
@staticmethod
def get_task(filename, asset_dir, asset_name, replace, loaded_options):
task = unreal.AssetImportTask()
options = unreal.AbcImportSettings()
mat_settings = unreal.AbcMaterialSettings()
conversion_settings = unreal.AbcConversionSettings()
task.set_editor_property('filename', filename)
task.set_editor_property('destination_path', asset_dir)
task.set_editor_property('destination_name', asset_name)
task.set_editor_property('replace_existing', replace)
task.set_editor_property(
'automated', not loaded_options.get("show_dialog"))
task.set_editor_property('save', True)
options.set_editor_property(
'import_type', unreal.AlembicImportType.SKELETAL)
options.sampling_settings.frame_start = loaded_options.get("frameStart")
options.sampling_settings.frame_end = loaded_options.get("frameEnd")
if loaded_options.get("abc_material_settings") == "create_materials":
mat_settings.set_editor_property("create_materials", True)
mat_settings.set_editor_property("find_materials", False)
elif loaded_options.get("abc_material_settings") == "find_materials":
mat_settings.set_editor_property("create_materials", False)
mat_settings.set_editor_property("find_materials", True)
else:
mat_settings.set_editor_property("create_materials", False)
mat_settings.set_editor_property("find_materials", False)
if not loaded_options.get("default_conversion"):
conversion_settings = None
abc_conversion_preset = loaded_options.get("abc_conversion_preset")
if abc_conversion_preset == "maya":
if UNREAL_VERSION.major >= 5 and UNREAL_VERSION.minor >= 4:
conversion_settings = unreal.AbcConversionSettings(
preset=unreal.AbcConversionPreset.MAYA)
else:
conversion_settings = unreal.AbcConversionSettings(
preset=unreal.AbcConversionPreset.CUSTOM,
flip_u=False, flip_v=True,
rotation=[90.0, 0.0, 0.0],
scale=[1.0, -1.0, 1.0])
elif abc_conversion_preset == "3dsmax":
if UNREAL_VERSION.major >= 5:
conversion_settings = unreal.AbcConversionSettings(
preset=unreal.AbcConversionPreset.MAX)
else:
conversion_settings = unreal.AbcConversionSettings(
preset=unreal.AbcConversionPreset.CUSTOM,
flip_u=False, flip_v=True,
rotation=[0.0, 0.0, 0.0],
scale=[1.0, -1.0, 1.0])
else:
data = get_current_project_settings()
preset = (
data["unreal"]["import_settings"]["custom"]
)
conversion_settings = unreal.AbcConversionSettings(
preset=unreal.AbcConversionPreset.CUSTOM,
flip_u=preset["flip_u"],
flip_v=preset["flip_v"],
rotation=[
preset["rot_x"],
preset["rot_y"],
preset["rot_z"]
],
scale=[
preset["scl_x"],
preset["scl_y"],
preset["scl_z"]
]
)
options.conversion_settings = conversion_settings
options.material_settings = mat_settings
task.options = options
return task
def import_and_containerize(
self, filepath, asset_dir, asset_name,
container_name, loaded_options
):
task = None
if not unreal.EditorAssetLibrary.does_asset_exist(
f"{asset_dir}/{asset_name}"):
task = self.get_task(
filepath, asset_dir, asset_name, False, loaded_options)
unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks([task])
if not unreal.EditorAssetLibrary.does_asset_exist(
f"{asset_dir}/{container_name}"):
# Create Asset Container
create_container(container=container_name, path=asset_dir)
return asset_dir
def imprint(
self,
folder_path,
asset_dir,
container_name,
asset_name,
representation,
product_type,
frameStart,
frameEnd,
project_name,
layout
):
data = {
"schema": "ayon:container-2.0",
"id": AYON_CONTAINER_ID,
"folder_path": folder_path,
"namespace": asset_dir,
"container_name": container_name,
"asset_name": asset_name,
"loader": str(self.__class__.__name__),
"representation": representation["id"],
"parent": representation["versionId"],
"product_type": product_type,
"frameStart":frameStart,
"frameEnd": frameEnd,
# TODO these should be probably removed
"asset": folder_path,
"family": product_type,
"project_name": project_name,
"layout": layout
}
imprint(f"{asset_dir}/{container_name}", data)
def load(self, context, name, namespace, options):
"""Load and containerise representation into Content Browser.
Args:
context (dict): application context
name (str): Product name
namespace (str): in Unreal this is basically path to container.
This is not passed here, so namespace is set
by `containerise()` because only then we know
real path.
data (dict): Those would be data to be imprinted.
Returns:
list(str): list of container content
"""
# Create directory for asset and ayon container
folder_entity = context["folder"]
folder_path = folder_entity["path"]
suffix = "_CON"
path = self.filepath_from_context(context)
asset_root, asset_name = format_asset_directory(
context, self.loaded_asset_dir, self.loaded_asset_name
)
tools = unreal.AssetToolsHelpers().get_asset_tools()
asset_dir, container_name = tools.create_unique_asset_name(
asset_root, suffix="")
container_name += suffix
should_use_layout = options.get("layout", False)
# Get existing asset dir if possible, otherwise import & containerize
if should_use_layout and (
existing_asset_dir := get_dir_from_existing_asset(
asset_dir, asset_name)
):
asset_dir = existing_asset_dir
else:
loaded_options = {
"default_conversion": options.get("default_conversion", False),
"abc_conversion_preset": options.get(
"abc_conversion_preset", self.abc_conversion_preset),
"abc_material_settings": options.get("abc_material_settings", "no_material"),
"frameStart": folder_entity["attrib"]["frameStart"],
"frameEnd": folder_entity["attrib"]["frameEnd"]
}
asset_dir = self.import_and_containerize(
path, asset_dir, asset_name,
container_name, loaded_options
)
self.imprint(
folder_path,
asset_dir,
container_name,
asset_name,
context["representation"],
context["product"]["productType"],
folder_entity["attrib"]["frameStart"],
folder_entity["attrib"]["frameEnd"],
context["project"]["name"],
should_use_layout
)
asset_content = unreal.EditorAssetLibrary.list_assets(
asset_dir, recursive=True, include_folder=True
)
for a in asset_content:
unreal.EditorAssetLibrary.save_asset(a)
return asset_content
def update(self, container, context):
folder_path = context["folder"]["path"]
product_type = context["product"]["productType"]
repre_entity = context["representation"]
# Create directory for folder and Ayon container
suffix = "_CON"
path = self.filepath_from_context(context)
asset_root, asset_name = format_asset_directory(
context, self.loaded_asset_dir, self.loaded_asset_name
)
tools = unreal.AssetToolsHelpers().get_asset_tools()
asset_dir, container_name = tools.create_unique_asset_name(
asset_root, suffix="")
container_name += suffix
should_use_layout = container.get("layout", False)
# Get existing asset dir if possible, otherwise import & containerize
if should_use_layout and (
existing_asset_dir := get_dir_from_existing_asset(
asset_dir, asset_name)
):
asset_dir = existing_asset_dir
else:
loaded_options = {
"default_conversion": False,
"abc_conversion_preset": self.abc_conversion_preset,
"frameStart": container.get("frameStart", 1),
"frameEnd": container.get("frameEnd", 1)
}
asset_dir = self.import_and_containerize(
path, asset_dir, asset_name,
container_name, loaded_options
)
self.imprint(
folder_path,
asset_dir,
container_name,
asset_name,
repre_entity,
product_type,
container.get("frameStart", 1),
container.get("frameEnd", 1),
context["project"]["name"],
should_use_layout
)
asset_content = unreal.EditorAssetLibrary.list_assets(
asset_dir, recursive=True, include_folder=False
)
for a in asset_content:
unreal.EditorAssetLibrary.save_asset(a)
def remove(self, container):
path = container["namespace"]
if unreal.EditorAssetLibrary.does_directory_exist(path):
unreal.EditorAssetLibrary.delete_directory(path)
|
# -*- 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 16:46:57'
import unreal
from Qt import QtCore
mesh= unreal.load_asset('/project/.aaa_magellan002_body_d1')
m = unreal.load_asset('/project/.M_UVCapture_Inst')
override_materials = [m]
for actor in unreal.EditorLevelLibrary.get_selected_level_actors():
comp = actor.get_editor_property("static")
# materials = comp.get_editor_property("override_materials")
comp.set_editor_property("static_mesh",mesh)
comp = actor.get_editor_property("static")
comp.set_editor_property("override_materials",override_materials)
|
from typing import Optional, Union
import unreal
@unreal.uclass()
class UnlockAllActorsCommand(unreal.ActorLockerPythonCommand):
current_map = unreal.uproperty(unreal.AssetData)
current_id = unreal.uproperty(int)
maps = unreal.uproperty(unreal.Array(unreal.AssetData))
def load_map(self, map_asset: unreal.AssetData):
print("Open map {0}".format(map_asset.package_name))
subsystem = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem)
return subsystem.load_level(str(map_asset.package_name))
def request_unlock_actors(self):
print("Waiting map {0} to be loaded...".format(self.current_map.package_name))
self.set_editor_timer(self, "on_timer_finished", 1, False, -1)
def execute(self):
asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
all_assets = asset_registry.get_all_assets()
self.maps = [asset for asset in all_assets if asset.asset_class_path.asset_name == "World" and str(asset.package_name).startswith("/Game")]
self.current_id = 0
self.process_next_map()
@unreal.ufunction()
def process_next_map(self):
self.current_map = self.maps[self.current_id]
if self.load_map(self.current_map):
self.request_unlock_actors()
@unreal.ufunction()
def on_timer_finished(self):
print("Map {0} is loaded. Unlocking actors...".format(self.current_map.package_name))
unreal.ActorLockerCommandManager.unlock_all_objects()
asset_subsystem = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem)
asset_subsystem.save_asset(str(self.current_map.package_name))
self.current_id += 1
if self.current_id < len(self.maps):
print("Finished unlocking actors on map {0}.".format(self.current_map.package_name))
self.process_next_map()
else:
print("Finished unlocking actors on all maps.")
unreal.EditorDialog.show_message(unreal.Text("Actor Locker"), unreal.Text("Finished unlocking actors on all maps."), unreal.AppMsgType.OK)
self.remove_object_from_root()
|
# -*- coding utf-8 -*-
import unreal
import os.path
# configure the factory
import_settings = unreal.FbxImportUI()
# import_settings.create_physics_asset = True
import_settings.import_materials = True
# import_settings.import_textures = True
# import_settings.import_animations = True
# メッシュを1つにまとめる
import_settings.static_mesh_import_data.combine_meshes = True
# register tasks
task = unreal.AssetImportTask()
task.automated = True
# UE4上のアセット名
task.destination_name = "SM_Kaiju"
# アセットを保存するフォルダ
task.destination_path = "Game/Kaiju"
# 読み込みたいFBXファイル名を指定する
task.filename = "D:/test.fbx"
task.options = import_settings
tasks = [task]
# タスクを実行
# FBXとマテリアルがインポートされる
asset_tool = unreal.AssetToolsHelpers.get_asset_tools()
asset_tool.import_asset_tasks(tasks)
# インポートされたマテリアルを削除して、同名のマテリアルインスタンスを作成
# このインスタンスをインポートしたメッシュに割り当てる
mesh_data = unreal.EditorAssetLibrary.find_asset_data(task.destination_path + task.destination_name)
master_mat = unreal.EditorAssetLibrary.find_asset_data('/project/')
mesh = mesh_data.get_asset()
|
# -*- coding: UTF-8 -*-
import unreal
# 请替换材质路径
material_path = '/project/'
def set_cliff_mat(static_mesh, LODs, screen_size_array):
# set lod section material
if static_mesh is not None:
if 'cliffSys' in static_mesh.get_name() and isinstance(static_mesh, unreal.StaticMesh):
# static_mesh.set_editor_property("bAutoComputeLODScreenSize", 0)
# default to use the second material slot
# asset_path = static_mesh.get_path_name()
for level in LODs:
unreal.EditorStaticMeshLibrary.set_lod_material_slot(static_mesh, 1, level, 0)
# set lod screen size
# unreal.log(static_mesh)
# static_mesh = unreal.load_asset(asset_path)
# unreal.log(static_mesh)
unreal.EditorStaticMeshLibrary.set_lod_screen_sizes(static_mesh, screen_size_array)
def add_cliff_mat(static_mesh, LODs, mat, screen_size_array):
# get materials
if not mat:
unreal.log_error("material is invalid!")
return
if not static_mesh:
unreal.log_error("static mesh is invalid!")
return
# set lod section material
if static_mesh is not None and mat is not None:
if 'cliffSys' in static_mesh.get_name() and isinstance(static_mesh, unreal.StaticMesh):
# static_mesh.set_editor_property("bAutoComputeLODScreenSize", 0)
new_material = static_mesh.add_material(mat)
slot_num = static_mesh.get_material_index(new_material)
for level in LODs:
unreal.EditorStaticMeshLibrary.set_lod_material_slot(static_mesh, slot_num, level, 0)
# set lod screen size
unreal.EditorStaticMeshLibrary.set_lod_screen_sizes(static_mesh, screen_size_array)
def get_static_mesh_filter_by_name(actors, name):
if len(actors) == 0:
return None
static_mesh_array = []
for actor in actors:
if isinstance(actor, unreal.StaticMeshActor) and actor is not None and name in actor.get_actor_label():
actor.tags = [unreal.Name('cliffsys')]
comp = actor.get_component_by_class(unreal.StaticMeshComponent)
static_mesh = comp.static_mesh
if static_mesh is not None:
asset_path = static_mesh.get_path_name()
static_mesh_asset = unreal.load_asset(asset_path)
static_mesh_array.append(static_mesh_asset)
return static_mesh_array
def run(LODs, add, mat, screen_sizes):
# actors = unreal.GameplayStatics.get_all_actors_of_class(unreal.EditorLevelLibrary.get_editor_world(),
# unreal.StaticMeshActor)
# static_mesh_array = get_static_mesh_filter_by_name(actors, 'xPCG_Cliffsys')
# actors = unreal.GameplayStatics.get_all_actors_of_class(unreal.EditorLevelLibrary.get_editor_world(),
# unreal.StaticMeshActor)
# static_mesh_array = get_static_mesh_filter_by_name(actors, 'xPCG_Cliffsys')
# unreal.EditorAssetLibrary.
static_mesh_array = unreal.EditorUtilityLibrary.get_selected_assets()
# unreal.log("start")
# unreal.log(len(static_mesh_array_A))
# for A in static_mesh_array_A:
# for s in static_mesh_array:
# if s == A:
# unreal.log(s)
# unreal.log(static_mesh_array[0])
if add is False:
for static_mesh in static_mesh_array:
# unreal.log(static_mesh)
set_cliff_mat(static_mesh, LODs, screen_sizes)
else:
for static_mesh in static_mesh_array:
add_cliff_mat(static_mesh, LODs, mat, screen_sizes)
# unreal.log(" finished! ")
# assets = unreal.EditorAssetLibrary.save_loaded_assets(static_mesh_array, True)
# LOD = cliff_lod
# import sys
# sys.path.append("/project/")
# import setCliffLOD2Material as ct
# reload(ct)
run(cliff_lod, add, material, screen_sizes)
# run(cliff_lod, add, material)
# select_assets = unreal.EditorUtilityLibrary.get_selected_assets()
#
# select_assets[0].set_editor_property("bAutoComputeLODScreenSize", 0)
|
import unreal
import pandas as pd
import re
def camel_to_snake(name):
"""Converte CamelCase in snake_case (es. 'HealthPoints' -> 'health_points')."""
name = re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower()
return name
def create_data_assets_from_csv(csv_file, asset_class, package_path):
"""
Crea più Data Asset in Unreal Engine, uno per ogni riga valida del CSV.
:param csv_file: Percorso del file CSV.
:param asset_class: Classe del Data Asset (es. unreal.MyDataAsset).
:param package_path: Percorso della cartella degli asset (es. "/project/").
"""
df = pd.read_csv(csv_file)
for _, row in df.iterrows():
asset_name = str(row.iloc[0]).strip() # Primo valore della riga = nome del Data Asset
asset_full_path = f"{package_path}/{asset_name}"
if unreal.EditorAssetLibrary.does_asset_exist(asset_full_path):
asset = unreal.EditorAssetLibrary.load_asset(asset_full_path)
else:
# Crea il Data Asset
factory = unreal.DataAssetFactory()
asset = unreal.AssetToolsHelpers.get_asset_tools().create_asset(
asset_name,
package_path,
asset_class,
factory
)
if not asset:
print(f"Errore nella creazione del Data Asset: {asset_name}")
continue
# Inserisce i dati nei campi del Data Asset
for col_name, value in row.items():
if col_name == df.columns[0]: # Ignora la colonna del nome
continue
property_name = camel_to_snake(col_name.strip()) # Normalizza il nome
try:
asset.set_editor_property(property_name, value)
except Exception as e:
print(f"Errore nell'impostare {property_name} per {asset_name}: {e}")
# Salva l'asset
unreal.EditorAssetLibrary.save_asset(asset_full_path)
print(f"✅ Data Asset creato: {asset_full_path}")
# Esempio di utilizzo
if __name__ == "__main__":
asset_class = unreal.MyDataAsset # Sostituisci con la tua classe C++
package_path = "/project/"
asset_name = "MyDataAssetInstance"
properties = {
"Value": 42,
"Name": "My Example Data"
}
#create_data_asset(asset_class, package_path, asset_name, properties)
|
# unreal._ObjectBase
# https://api.unrealengine.com/project/.html
import unreal
# object_to_cast: obj unreal.Object : The object you want to cast
# object_class: obj unreal.Class : The class you want to cast the object into
def cast(object_to_cast=None, object_class=None):
try:
return object_class.cast(object_to_cast)
except:
return None
# Cpp ########################################################################################################################################################################################
# Note: Also work using the command : help(unreal.StaticMesh)
# unreal_class: obj : The class you want to know the properties
# return: str List : The available properties (formatted the way you can directly use them to get their values)
def getAllProperties(unreal_class=None):
return unreal.CppLib.get_all_properties(unreal_class)
|
# 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",
)
|
#Glory. To mankind.
import unreal
import os
import enum
import json
from math import *
from typing import Tuple
import re
import time
#Modify this section according to your desires
UnrealNierBaseMaterialDirectory = '/project/' #your game folder
UnrealMaterialsDirectory = '/project/'
UnrealTexturesDirectory = '/project/'
NierTextureDirectoryJpg = "/project/" #dds import not supported by unreal, only jpg or png
NierTextureDirectoryPng = "/project/" #dds import not supported by unreal, only jpg or png
MaterialsJsonPaths = ["/project/.json",
"/project/-014\\materials.json",
"/project/-004\\materials.json"]
#MaterialsJsonPaths = ["/project/.json"]
#Nier material names. Better not to change
NierBaseSimpleMaterialName = "MAT_NierBaseSimple"
NierBaseComplexMaterialName = "MAT_NierBaseComplex"
NierBaseAlbedoOnlyMaterialName = "MAT_NierBaseAlbedoOnly"
#Base Materials
NierBaseSimpleMaterialAsset = unreal.EditorAssetLibrary.find_asset_data(unreal.Paths.combine([UnrealNierBaseMaterialDirectory, NierBaseSimpleMaterialName]))
NierBaseComplexMaterialAsset = unreal.EditorAssetLibrary.find_asset_data(unreal.Paths.combine([UnrealNierBaseMaterialDirectory, NierBaseComplexMaterialName]))
NierBaseAlbedoOnlyMaterialAsset = unreal.EditorAssetLibrary.find_asset_data(unreal.Paths.combine([UnrealNierBaseMaterialDirectory, NierBaseAlbedoOnlyMaterialName]))
#Unreal's libraries
AssetTools = unreal.AssetToolsHelpers.get_asset_tools()
MaterialEditingLibrary = unreal.MaterialEditingLibrary
EditorAssetLibrary = unreal.EditorAssetLibrary
class NierMaterialType(enum.Enum):
simple = 1
complex = 2
albedoOnly = 3
def setMaterialInstanceTextureParameter(materialInstanceAsset, parameterName, texturePath):
if not unreal.EditorAssetLibrary.does_asset_exist(texturePath):
unreal.log_warning("Can't find texture: " + texturePath)
return False
textureAsset = unreal.EditorAssetLibrary.find_asset_data( texturePath ).get_asset()
return unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value(materialInstanceAsset, parameterName, textureAsset)
#importing textures into UE into output path. NierMaterialType and isDecal variables are for defining if given material needs transparent textures. It was made to save disk space.
def importTextures(fileNames: list[str], outputDirectory: str, materialType: NierMaterialType, isDecal: bool, pngOnly: bool) -> None:
texturePaths = []
if pngOnly:
for fileName in fileNames:
texturePaths.append(os.path.join(NierTextureDirectoryPng, fileName + ".png" ))
elif materialType is NierMaterialType.albedoOnly:
texturePaths.append(os.path.join(NierTextureDirectoryPng, fileNames[0] + ".jpg" ))
elif materialType is NierMaterialType.complex:
for i in range(0, 3):
texturePaths.append(os.path.join(NierTextureDirectoryPng, fileNames[i] + ".png" ))
for i in range(3, len(fileNames)):
texturePaths.append(os.path.join(NierTextureDirectoryJpg, fileNames[i] + ".jpg" ))
elif materialType is NierMaterialType.simple and isDecal is False:
for fileName in fileNames:
texturePaths.append(os.path.join(NierTextureDirectoryJpg, fileName + ".jpg" ))
elif materialType is NierMaterialType.simple and isDecal is True:
texturePaths.append(os.path.join(NierTextureDirectoryPng, fileNames[0] + ".png" ))
for i in range(1, len(fileNames)):
texturePaths.append(os.path.join(NierTextureDirectoryJpg, fileNames[i] + ".jpg" ))
assetImportData = unreal.AutomatedAssetImportData()
# set assetImportData attributes
assetImportData.destination_path = outputDirectory
assetImportData.filenames = texturePaths
assetImportData.replace_existing = False
AssetTools.import_assets_automated(assetImportData)
def getMaterialSlotNames(staticMesh) -> list[str]:
staticMeshComponent = unreal.StaticMeshComponent()
staticMeshComponent.set_static_mesh(staticMesh)
return unreal.StaticMeshComponent.get_material_slot_names(staticMeshComponent)
def getNierMaterialType(material: dict[str]) -> NierMaterialType:
if material.get("g_AlbedoMap") is not None and material.get("g_MaskMap") is None and material.get("g_NormalMap") is None:
return NierMaterialType.albedoOnly
if material.get("g_AlbedoMap") is not None and material.get("g_MaskMap") is not None and material.get("g_NormalMap") is not None:
return NierMaterialType.simple
if material.get("g_AlbedoMap1") is not None and material.get("g_AlbedoMap2") is not None and material.get("g_AlbedoMap1"):
return NierMaterialType.complex
def swapToOriginalMaterials() -> None:
selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets()
for selectedAsset in selectedAssets:
for matIndex in range(0, selectedAsset.get_num_sections(0)):
if selectedAsset.get_class().get_name() != "StaticMesh":
continue
selectedAssetMaterialName = str(selectedAsset.get_material(matIndex).get_name())
assetFolder = unreal.Paths.get_path(selectedAsset.get_path_name())
originalMaterial = EditorAssetLibrary.find_asset_data(unreal.Paths.combine([assetFolder, selectedAssetMaterialName[:-5]])).get_asset()
selectedAsset.set_material(matIndex, originalMaterial)
def getNierMaterialDict(materialName: str) -> dict:
for MaterialsJsonPath in MaterialsJsonPaths:
with open(MaterialsJsonPath, 'r') as file:
materialsDict = json.load(file)
if materialsDict.get(materialName) is not None:
return materialsDict[materialName]
for dict in materialsDict:
strDict = str(dict)
if strDict.find(':') != -1:
if strDict[strDict.find(':') + 1:] == materialName:
return dict
return None
def getUniqueMats():
mats = []
selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets()
for selectedAsset in selectedAssets:
for matIndex in range(0, selectedAsset.get_num_sections(0)):
if selectedAsset.get_material(matIndex).get_name() not in mats:
mats.append(selectedAsset.get_material(matIndex).get_name())
print(len(mats))
print(mats)
def syncNierMaterials(pngOnly: bool) -> None:
selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets()
postfix = "_Inst"
#with open(MaterialsJsonPaths, 'r') as file:
# materialsDict = json.load(file)
materialsFolder = UnrealMaterialsDirectory
texturesFolder = UnrealTexturesDirectory
if not unreal.EditorAssetLibrary.does_directory_exist(materialsFolder):
unreal.EditorAssetLibrary.make_directory(materialsFolder)
if not unreal.EditorAssetLibrary.does_directory_exist(texturesFolder):
unreal.EditorAssetLibrary.make_directory(texturesFolder)
for selectedAsset in selectedAssets:
if selectedAsset.get_class().get_name() != "StaticMesh":
continue
if selectedAsset.get_material(0) is None:
continue
for matIndex in range(0, selectedAsset.get_num_sections(0)):
selectedAssetMaterialName = str(selectedAsset.get_material(matIndex).get_name())
if "_ncl" in selectedAssetMaterialName:
selectedAssetMaterialName = selectedAssetMaterialName[0 : selectedAssetMaterialName.find("_ncl")]
if postfix in selectedAssetMaterialName:
print("Nier material is already assigned, skipping Material in " + selectedAsset.get_name())
continue
else:
if unreal.EditorAssetLibrary.does_asset_exist(unreal.Paths.combine([materialsFolder, selectedAssetMaterialName + postfix])): #check, if Nier _Inst asset exist
if EditorAssetLibrary.find_asset_data(unreal.Paths.combine([materialsFolder, selectedAssetMaterialName + postfix])).get_class().get_name() == "ObjectRedirector":
print("Redirector asset found instead of material, skipping " + selectedAsset.get_name())
continue
print("Existing Nier material Inst found, assigning " + selectedAssetMaterialName + postfix + " to " + selectedAsset.get_name())
newMaterial = EditorAssetLibrary.find_asset_data(unreal.Paths.combine([materialsFolder, selectedAssetMaterialName + postfix])).get_asset()
selectedAsset.set_material(matIndex, newMaterial)
else: #if Nier material doesn't exist, create it and import textures, then assign
if getNierMaterialDict(selectedAssetMaterialName) is None:
unreal.log_warning(selectedAssetMaterialName +" not found in materials.json, skipping asset")
continue
material = getNierMaterialDict(selectedAssetMaterialName)
textures = material['Textures']
newMaterial = AssetTools.create_asset(selectedAssetMaterialName + postfix, materialsFolder, unreal.MaterialInstanceConstant, unreal.MaterialInstanceConstantFactoryNew())
if getNierMaterialType(textures) == NierMaterialType.simple:
variables = material['Variables']
isDecal = bool(variables['g_Decal']) or "decal" in selectedAssetMaterialName
importTextures( [ textures["g_AlbedoMap"], textures["g_MaskMap"], textures["g_NormalMap"], textures["g_DetailNormalMap"] ], texturesFolder, NierMaterialType.simple, isDecal, pngOnly)
MaterialEditingLibrary.set_material_instance_parent( newMaterial, NierBaseSimpleMaterialAsset.get_asset() ) # set parent material
setMaterialInstanceTextureParameter(newMaterial, "g_AlbedoMap", unreal.Paths.combine( [ texturesFolder, textures["g_AlbedoMap"] ] ) )
setMaterialInstanceTextureParameter(newMaterial, "g_MaskMap", unreal.Paths.combine( [ texturesFolder, textures["g_MaskMap"]] ) )
setMaterialInstanceTextureParameter(newMaterial, "g_NormalMap", unreal.Paths.combine( [ texturesFolder, textures["g_NormalMap"] ] ) )
if (EditorAssetLibrary.does_asset_exist(unreal.Paths.combine( [ texturesFolder, textures["g_DetailNormalMap"] ] ) )):
MaterialEditingLibrary.set_material_instance_scalar_parameter_value( newMaterial, "bUseDetailMap", 1)
setMaterialInstanceTextureParameter(newMaterial, "g_DetailNormalMap", unreal.Paths.combine( [ texturesFolder, textures["g_DetailNormalMap"] ] ) )
elif getNierMaterialType(textures) == NierMaterialType.complex:
if "testsea" in selectedAssetMaterialName:
continue
importTextures( [ textures["g_AlbedoMap1"], textures["g_AlbedoMap2"], textures["g_AlbedoMap3"], textures["g_MaskMap"], textures["g_NormalMap1"], textures["g_NormalMap2"], textures["g_NormalMap3"] ], texturesFolder, NierMaterialType.complex, False, pngOnly)
MaterialEditingLibrary.set_material_instance_parent( newMaterial, NierBaseComplexMaterialAsset.get_asset() ) # set parent material
setMaterialInstanceTextureParameter(newMaterial, "g_AlbedoMap1", unreal.Paths.combine( [ texturesFolder, textures["g_AlbedoMap1"] ] ) )
setMaterialInstanceTextureParameter(newMaterial, "g_AlbedoMap2", unreal.Paths.combine( [ texturesFolder, textures["g_AlbedoMap2"] ] ) )
setMaterialInstanceTextureParameter(newMaterial, "g_AlbedoMap3", unreal.Paths.combine( [ texturesFolder, textures["g_AlbedoMap3"] ] ) )
setMaterialInstanceTextureParameter(newMaterial, "g_MaskMap", unreal.Paths.combine( [ texturesFolder, textures["g_MaskMap"] ] ) )
setMaterialInstanceTextureParameter(newMaterial, "g_NormalMap1", unreal.Paths.combine( [ texturesFolder, textures["g_NormalMap1"] ] ) )
setMaterialInstanceTextureParameter(newMaterial, "g_NormalMap2", unreal.Paths.combine( [ texturesFolder, textures["g_NormalMap2"] ] ) )
setMaterialInstanceTextureParameter(newMaterial, "g_NormalMap3", unreal.Paths.combine( [ texturesFolder, textures["g_NormalMap3"] ] ) )
elif getNierMaterialType(textures) == NierMaterialType.albedoOnly:
importTextures( [ textures["g_AlbedoMap"] ], texturesFolder, NierMaterialType.albedoOnly, False, pngOnly)
MaterialEditingLibrary.set_material_instance_parent( newMaterial, NierBaseAlbedoOnlyMaterialAsset.get_asset() ) # set parent material
if EditorAssetLibrary.does_asset_exist(unreal.Paths.combine( [ texturesFolder, textures["g_AlbedoMap"] ] ) ):
setMaterialInstanceTextureParameter(newMaterial, "g_AlbedoMap", unreal.Paths.combine( [ texturesFolder, textures["g_AlbedoMap"] ] ) )
else:
print("No textures found for " + newMaterial.get_name())
continue
selectedAsset.set_material(matIndex, newMaterial)
print("Nier Materials syncing end")
def setMobilityForSelectedActors(mobilityType: unreal.ComponentMobility):
actors = unreal.EditorLevelLibrary.get_selected_level_actors()
for actor in actors:
if (actor.get_class().get_name() == "StaticMeshActor"):
actor.set_mobility(mobilityType)
def test():
selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets()
for asset in selectedAssets:
if asset.get_class().get_name() == "Material" and "_Inst" not in asset.get_name():
asset.rename(asset.get_name()+"_Inst")
def test2():
selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets()
for selectedAsset in selectedAssets:
if selectedAsset.get_class().get_name() != "StaticMesh":
continue
for matIndex in range(0, selectedAsset.get_num_sections(0)):
selectedAssetMaterialName = str(selectedAsset.get_material(matIndex).get_name())
assetFolder = unreal.Paths.get_path(selectedAsset.get_path_name())
originalMaterial = EditorAssetLibrary.find_asset_data(unreal.Paths.combine([assetFolder, selectedAssetMaterialName[:-5]])).get_asset()
currentMaterial = selectedAsset.get_material(matIndex)
if currentMaterial.get_class().get_name() == "MaterialInstanceConstant":
if currentMaterial.parent is None:
selectedAsset.set_material(matIndex, originalMaterial)
# asset.rename(asset.get_name()+"_Inst")
#Original Blender script by RaiderB
def fixNierMapPosition():
centerX = 11
centerY = 10
hexRadius = 100
hexCenterToEdge = 50 * sqrt(3)
def getCoords(x, y) -> Tuple[float, float]:
x -= 1
y -= 1
yOff = floor((23 - x) / 2)
x -= centerX
y -= centerY + yOff
return x * hexRadius*1.5, (-y + x%2/2) * hexCenterToEdge * 2
def getCoordsFromName(name: str) -> Tuple[int, int]:
x = int(name[2:4])
y = int(name[4:6])
return x, y
def fixObjPos(obj):
if obj.get_name()[:2] == "g5":
obj.set_actor_transform(new_transform=unreal.Transform(location=[0, 0, 0], rotation=[0, 0, 0], scale=[1, 1, 1]), sweep = False, teleport = False)
return
nX, nY = getCoordsFromName(obj.get_name())
oX, oY = getCoords(nX, nY)
obj.set_actor_transform(new_transform=unreal.Transform(location=[oX*100, -(oY*100), 0], rotation=[0, 0, 0], scale=[1, 1, 1]), sweep = False, teleport = False )
print(oX*100, oY*100)
selectedAssets = unreal.EditorLevelLibrary.get_selected_level_actors()
for obj in selectedAssets:
if not re.match(r"^g\d{5}", obj.get_name()):
continue
fixObjPos(obj)
print("Fixing Nier map position end")
def generateSimpleCollision():
selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets()
step = 100
for i in range(0, len(selectedAssets), step):
print(i)
time.sleep(3)
unreal.EditorStaticMeshLibrary.bulk_set_convex_decomposition_collisions(selectedAssets[i:i + step], 20, 20, 400000)
unreal.EditorAssetLibrary.save_loaded_assets(selectedAssets[i:i + step], False)
def fixBadConvexCollisionForNierStaticMeshes(pathToLogFile: str, searchMask: str):
pathList = []
with open(pathToLogFile, "r") as log_file:
err_gen = (st for st in log_file if searchMask in st)
for item in err_gen:
index = item.find(searchMask)
indexEnd = item.find(".", index)
path = item[index:indexEnd]
if path not in pathList:
print(path)
pathList.append(path)
assets = []
for path in pathList:
asset = unreal.EditorAssetLibrary.find_asset_data(path).get_asset()
assets.append(asset)
unreal.EditorStaticMeshLibrary.remove_collisions(asset)
body_setup = asset.get_editor_property('body_setup')
collision_trace_flag = unreal.CollisionTraceFlag.CTF_USE_COMPLEX_AS_SIMPLE
body_setup.set_editor_property('collision_trace_flag', collision_trace_flag)
asset.set_editor_property('body_setup', body_setup)
print("Fixed Collisions for " + len(pathList) + " objects")
def test3():
selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets()
for asset in selectedAssets:
unreal.EditorStaticMeshLibrary.remove_collisions(asset)
def multipleAttenuationRadiusForSelectedLights():
actors = unreal.EditorLevelLibrary.get_selected_level_actors()
for actor in actors:
print(actor.get_class().get_name())
if actor.get_class().get_name() == "PointLight":
actor.point_light_component.attenuation_radius = 1
def removeLods() -> None:
selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets()
for asset in selectedAssets:
if asset.get_class().get_name() == "StaticMesh":
unreal.EditorStaticMeshLibrary.remove_lods(asset)
class NierLight:
m_flag = 0
m_pos = [0, 0, 0, 0]
m_color = [1, 1, 1, 1]
m_DirAng = [0, 0, 0]
#blender X Y Z = Nier X -Z Y
nierLights = []
lightTypes = ['POINT', 'SPOT']
def isUniqueSpot(targetNierLight: NierLight):
for nierLight in nierLights:
if nierLight.m_pos == targetNierLight.m_pos:
return False
return True
def createLights(gadFilesDirectory: str, bImportPointLights: bool, bImportSpotLights: bool, bSkipDuplicatedLights: bool) -> None:
def spawnLight(nierLight: NierLight) -> None:
if nierLight.m_flag > 2:
print("Unknown light type found, ID = " + str(nierLight.m_flag))
nierLight.m_flag = 0
if nierLight.m_flag == 0:
nierLightLocation = unreal.Vector( nierLight.m_pos[0] * 100, nierLight.m_pos[2] * 100, nierLight.m_pos[1] * 100 )
nierLightRotation = [ 0, 0, 0 ]
lightObj = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.PointLight, nierLightLocation, nierLightRotation)
lightObj.set_actor_label("NierLight")
lightObj.point_light_component.set_light_color(unreal.LinearColor(r=nierLight.m_color[0], g=nierLight.m_color[1], b=nierLight.m_color[2], a=0.0))
lightObj.point_light_component.set_intensity(nierLight.m_color[3] * 10)
lightObj.point_light_component.set_cast_shadows(False)
elif nierLight.m_flag == 1:
nierLightLocation = unreal.Vector( nierLight.m_pos[0] * 100, nierLight.m_pos[2] * 100, nierLight.m_pos[1] * 100 )
#nierLightRotation = [ nierLight.m_DirAng[0], nierLight.m_DirAng[2], nierLight.m_DirAng[1] ]
nierLightRotation = [ 0, 0, 0 ]
lightObj = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.SpotLight, nierLightLocation, nierLightRotation)
lightObj.set_actor_label("NierLight")
lightObj.spot_light_component.set_light_color(unreal.LinearColor(r=nierLight.m_color[0], g=nierLight.m_color[1], b=nierLight.m_color[2], a=0.0))
lightObj.spot_light_component.set_intensity(nierLight.m_color[3] * 10)
lightObj.spot_light_component.set_cast_shadows(False)
#lightObj.add_actor_world_rotation(delta_rotation=[-90, 0, 0], sweep=False, teleport=True)
import xml.etree.ElementTree as ET
print("begin")
files = os.listdir(gadFilesDirectory)
for file in files:
if file.endswith(".gad.xml"):
tree = ET.parse(os.path.join(gadFilesDirectory, file))
work = tree.find("Work")
light = work.find("light")
props = light.findall("prop")
for prop in props:
if prop.attrib["name"] == "m_RoomLightWork":
values = prop.findall("value")
for value in values:
lightProps = value.findall("prop")
nierLight = NierLight()
for lightProp in lightProps:
if lightProp.attrib["name"] == "m_flag":
nierLight.m_flag = int(lightProp.text)
elif lightProp.attrib["name"] == "m_pos":
nierLight.m_pos = [float(num) for num in lightProp.text.split(' ')]
elif lightProp.attrib["name"] == "m_color":
nierLight.m_color = [float(num) for num in lightProp.text.split(' ')]
elif lightProp.attrib["name"] == "m_DirAng":
nierLight.m_DirAng = [float(num) for num in lightProp.text.split(' ')]
if nierLight.m_pos != [0, 0, 0, 1]: #default light position (?) skip
if not isUniqueSpot(nierLight) and bSkipDuplicatedLights:
continue
if nierLight.m_flag == 0 and bImportPointLights:
spawnLight(nierLight)
if nierLight.m_flag == 1 and bImportSpotLights:
spawnLight(nierLight)
if bSkipDuplicatedLights:
nierLights.append(nierLight)
def cosolidate():
print("1")
assetsDirForReplace = "/project/"
assetsDirOriginal = "/project/"
folders = ["g11517_MainArea", "g11617_MainCorridor", "g11716_Theatre", "g11717_TankArea", "g31418_CityRuins1"]
asset_reg = unreal.AssetRegistryHelpers.get_asset_registry()
for folder in folders:
assetsForReplace = asset_reg.get_assets_by_path(unreal.Paths.combine([assetsDirForReplace, folder]))
for asset in assetsForReplace:
assetToReplace = asset.get_asset()
assetOriginal = EditorAssetLibrary.find_asset_data(unreal.Paths.combine([assetsDirOriginal, folder, assetToReplace.get_name()])).get_asset()
#print(unreal.Paths.combine([assetsDirForReplace,folder, assetToReplace.get_name()]))
#print(unreal.Paths.combine([assetsDirForReplace,folder, assetToReplace.get_name()]))
#print(unreal.Paths.combine([assetsDirOriginal, folder, assetToReplace.get_name()]))
print(assetOriginal.get_name())
EditorAssetLibrary.consolidate_assets(assetToReplace, [assetOriginal])
def removeSimpleCollision():
selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets()
for asset in selectedAssets:
unreal.EditorStaticMeshLibrary.remove_collisions(asset)
#cosolidate()
#dirPath = "/project/.cpk_unpacked\\st1\\nier2blender_extracted\\r130.dat"
#createLights(dirPath, True, True, True)
#createLights("/project/.cpk_unpacked\\st1\\nier2blender_extracted\\r130.dat")
#removeLods()
#multipleAttenuationRadiusForSelectedLights()
#swapToOriginalMaterials()
#setMobilityForSelectedActors(unreal.ComponentMobility.MOVABLE)
#swapToOriginalMaterials()
#generateSimpleCollision()
#syncNierMaterials(pngOnly=False)
#getUniqueMats()
#test3()
#removeSimpleCollision()
#fixNierMapPosition()
syncNierMaterials(pngOnly=False)
|
# Copyright (c) <2021> Side Effects Software Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. The name of Side Effects Software may not be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
""" Example script that uses unreal.ActorIterator to iterate over all
HoudiniAssetActors in the editor world, creates API wrappers for them, and
logs all of their parameter tuples.
"""
import unreal
def run():
# Get the API instance
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
# Get the editor world
editor_subsystem = None
world = None
try:
# In UE5 unreal.EditorLevelLibrary.get_editor_world is deprecated and
# unreal.UnrealEditorSubsystem.get_editor_world is the replacement,
# but unreal.UnrealEditorSubsystem does not exist in UE4
editor_subsystem = unreal.UnrealEditorSubsystem()
except AttributeError:
world = unreal.EditorLevelLibrary.get_editor_world()
else:
world = editor_subsystem.get_editor_world()
# Iterate over all Houdini Asset Actors in the editor world
for houdini_actor in unreal.ActorIterator(world, unreal.HoudiniAssetActor):
if not houdini_actor:
continue
# Print the name and label of the actor
actor_name = houdini_actor.get_name()
actor_label = houdini_actor.get_actor_label()
print(f'HDA Actor (Name, Label): {actor_name}, {actor_label}')
# Wrap the Houdini asset actor with the API
wrapper = unreal.HoudiniPublicAPIAssetWrapper.create_wrapper(world, houdini_actor)
if not wrapper:
continue
# Get all parameter tuples of the HDA
parameter_tuples = wrapper.get_parameter_tuples()
if parameter_tuples is None:
# The operation failed, log the error message
error_message = wrapper.get_last_error_message()
if error_message is not None:
print(error_message)
continue
print(f'# Parameter Tuples: {len(parameter_tuples)}')
for name, data in parameter_tuples.items():
print(f'\tParameter Tuple Name: {name}')
type_name = None
values = None
if data.bool_values:
type_name = 'Bool'
values = '; '.join(('1' if v else '0' for v in data.bool_values))
elif data.float_values:
type_name = 'Float'
values = '; '.join((f'{v:.4f}' for v in data.float_values))
elif data.int32_values:
type_name = 'Int32'
values = '; '.join((f'{v:d}' for v in data.int32_values))
elif data.string_values:
type_name = 'String'
values = '; '.join(data.string_values)
if not type_name:
print('\t\tEmpty')
else:
print(f'\t\t{type_name} Values: {values}')
if __name__ == '__main__':
run()
|
# 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()
|
from typing import Dict, List, Any, Optional
import unreal
import json
def search_assets(
search_term: str, asset_class: Optional[str] = None
) -> Dict[str, Any]:
asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
all_assets = asset_registry.get_all_assets()
matching_assets = []
search_term_lower = search_term.lower()
for asset in all_assets:
asset_name = str(asset.asset_name).lower()
package_path = str(asset.package_path).lower()
asset_class_name = str(asset.asset_class_path.asset_name).lower()
name_match = search_term_lower in asset_name
path_match = search_term_lower in package_path
class_match = True
if asset_class:
class_match = asset_class.lower() in asset_class_name
if (name_match or path_match) and class_match:
matching_assets.append(
{
"name": str(asset.asset_name),
"path": str(asset.package_path),
"class": str(asset.asset_class_path.asset_name),
"package_name": str(asset.package_name),
}
)
def relevance_score(asset):
name_exact = search_term_lower == asset["name"].lower()
name_starts = asset["name"].lower().startswith(search_term_lower)
return (name_exact * 3) + (name_starts * 2) + 1
matching_assets.sort(key=relevance_score, reverse=True)
return {
"search_term": search_term,
"asset_class_filter": asset_class,
"total_matches": len(matching_assets),
"assets": matching_assets[:50], # Limit to 50 results
}
def main():
result = search_assets("${search_term}", "${asset_class}")
print(json.dumps(result, indent=2))
if __name__ == "__main__":
main()
|
import unreal
from pathlib import Path
import sys
# sys.path.append(str(Path(__file__).parent.parent.parent.parent.parent.resolve()))
# from importlib import *
# reloads = []
# for k, v in sys.modules.items():
# if k.startswith("pamux_unreal_tools"):
# reloads.append(v)
# for module in reloads:
# reload(module)
from pamux_unreal_tools.builders.material_function_builder import MaterialFunctionBuilder
from pamux_unreal_tools.base.material_expression.material_expression_container_builder_base import MaterialExpressionContainerBuilderBase
from pamux_unreal_tools.generated.material_expression_wrappers import *
from pamux_unreal_tools.base.material_function.material_function_dependencies_base import MaterialFunctionDependenciesBase
from pamux_unreal_tools.base.material_function.material_function_outputs_base import MaterialFunctionOutputs
from pamux_unreal_tools.examples.M_Landscape_Master.interfaces.IFoliageMask import IFoliageMask
from pamux_unreal_tools.factories.material_function_factory import MaterialFunctionFactory
class MF_FoliageMask:
@staticmethod
def load_MF(builder):
return builder.load_MF("/project/",
["LayerSample", "FoliageMask", "Threshold", "Enabled"],
["Result"])
class Inputs:
def __init__(self, builder: MaterialExpressionContainerBuilderBase):
# No Preview
self.layerSample = builder.build_FunctionInput("LayerSample", 0, 0.0, False, False)
self.foliageMask = builder.build_FunctionInput("FoliageMask", 1, 0.0, False, False)
self.threshold = builder.build_FunctionInput("Threshold", 2, 0.0, False, False)
self.enabled = builder.build_FunctionInput("Enabled", 3, True, True, True)
class Builder(MaterialFunctionBuilder):
def __init__(self):
super().__init__(
"/project/",
MaterialFunctionDependenciesBase,
MF_FoliageMask.Inputs,
MaterialFunctionOutputs.Result)
def build(self):
divide = Divide(self.inputs.layerSample.rt, self.inputs.threshold.rt)
floor = Floor(divide.output)
lerp = LinearInterpolate(0.0, self.inputs.layerSample.rt, floor)
subtract = Subtract(lerp.output, self.inputs.foliageMask.rt)
saturate = Saturate(subtract.output)
switch = StaticSwitch(saturate, Constant(0.0), self.inputs.enabled.rt)
switch.output.connectTo(self.outputs.result)
# MF_FoliageMask.Builder().get()
|
import unreal
import json
def move_viewport_camera(location, rotation):
try:
location_vector = unreal.Vector(
location["x"], location["y"], location["z"]
)
rotation_rotator = unreal.Rotator(
rotation["roll"], rotation["pitch"], rotation["yaw"]
)
unreal.EditorLevelLibrary.set_level_viewport_camera_info(
location_vector, rotation_rotator
)
return {
"success": True,
"location": {
"x": location["x"],
"y": location["y"],
"z": location["z"],
},
"rotation": {
"pitch": rotation["pitch"],
"yaw": rotation["yaw"],
"roll": rotation["roll"],
},
}
except Exception as e:
return {"success": False, "error": str(e)}
location_data = ${location}
rotation_data = ${rotation}
if location_data and rotation_data:
result = move_viewport_camera(location_data, rotation_data)
print(json.dumps(result))
else:
print(
json.dumps(
{"success": False, "error": "Location and rotation parameters are required"}
)
)
|
import os
import json
import unreal
from Utilities.Utils import Singleton
class Shelf(metaclass=Singleton):
'''
This is a demo tool for showing how to create Chamelon Tools in Python
'''
MAXIMUM_ICON_COUNT = 12
Visible = "Visible"
Collapsed = "Collapsed"
def __init__(self, jsonPath:str):
self.jsonPath = jsonPath
self.data = unreal.PythonBPLib.get_chameleon_data(self.jsonPath)
self.shelf_data = self.load_data()
self.is_text_readonly = True
self.ui_drop_at_last_aka = "DropAtLast"
self.ui_drop_is_full_aka = "DropIsFull"
self.update_ui(bForce=True)
def update_ui(self, bForce=False):
visibles = [False] * Shelf.MAXIMUM_ICON_COUNT
for i, shortcut in enumerate(self.shelf_data.shortcuts):
if i >= Shelf.MAXIMUM_ICON_COUNT:
continue
self.data.set_visibility(self.get_ui_button_group_name(i), Shelf.Visible)
self.data.set_tool_tip_text(self.get_ui_button_group_name(i), self.shelf_data.shortcuts[i].get_tool_tips())
self.data.set_text(self.get_ui_text_name(i), self.shelf_data.shortcuts[i].text)
# ITEM_TYPE_PY_CMD = 1 ITEM_TYPE_CHAMELEON = 2 ITEM_TYPE_ACTOR = 3 ITEM_TYPE_ASSETS = 4 ITEM_TYPE_ASSETS_FOLDER = 5
icon_name = ["PythonTextGreyIcon_40x.png", "PythonChameleonGreyIcon_40x.png", "LitSphere_40x.png", "Primitive_40x.png", "folderIcon.png"][shortcut.drop_type-1]
if os.path.exists(os.path.join(os.path.dirname(__file__), f"Images/{icon_name}")):
self.data.set_image_from(self.get_ui_img_name(i), f"Images/{icon_name}")
else:
unreal.log_warning("file: {} not exists in this tool's folder: {}".format(f"Images/{icon_name}", os.path.join(os.path.dirname(__file__))))
visibles[i] = True
for i, v in enumerate(visibles):
if not v:
self.data.set_visibility(self.get_ui_button_group_name(i), Shelf.Collapsed)
self.lock_text(self.is_text_readonly, bForce)
bFull = len(self.shelf_data) == Shelf.MAXIMUM_ICON_COUNT
self.data.set_visibility(self.ui_drop_at_last_aka, "Collapsed" if bFull else "Visible")
self.data.set_visibility(self.ui_drop_is_full_aka, "Visible" if bFull else "Collapsed" )
def lock_text(self, bLock, bForce=False):
if self.is_text_readonly != bLock or bForce:
for i in range(Shelf.MAXIMUM_ICON_COUNT):
self.data.set_text_read_only(self.get_ui_text_name(i), bLock)
self.data.set_color_and_opacity(self.get_ui_text_name(i), [1,1,1,1] if bLock else [1,0,0,1])
self.data.set_visibility(self.get_ui_text_name(i), "HitTestInvisible" if bLock else "Visible" )
self.is_text_readonly = bLock
def get_ui_button_group_name(self, index):
return f"ButtonGroup_{index}"
def get_ui_text_name(self, index):
return f"Txt_{index}"
def get_ui_img_name(self, index):
return f"Img_{index}"
def on_close(self):
self.save_data()
def get_data_path(self):
return os.path.join(os.path.dirname(__file__), "saved_shelf.json")
def load_data(self):
saved_file_path = self.get_data_path()
if os.path.exists(saved_file_path):
return ShelfData.load(saved_file_path)
else:
return ShelfData()
def save_data(self):
# fetch text from UI
for i, shortcut in enumerate(self.shelf_data.shortcuts):
shortcut.text = self.data.get_text(self.get_ui_text_name(i))
saved_file_path = self.get_data_path()
if self.shelf_data != None:
ShelfData.save(self.shelf_data, saved_file_path)
else:
unreal.log_warning("data null")
def clear_shelf(self):
self.shelf_data.clear()
self.update_ui()
def set_item_to_shelf(self, index, shelf_item):
if index >= len(self.shelf_data):
self.shelf_data.add(shelf_item)
else:
self.shelf_data.set(index, shelf_item)
self.update_ui()
# add shortcuts
def add_py_code_shortcut(self, index, py_code):
shelf_item = ShelfItem(icon="", drop_type=ShelfItem.ITEM_TYPE_PY_CMD)
shelf_item.py_cmd = py_code
shelf_item.text=py_code[:3]
self.set_item_to_shelf(index, shelf_item)
def add_chameleon_shortcut(self, index, chameleon_json):
short_name = os.path.basename(chameleon_json)
if short_name.lower().startswith("chameleon") and len(short_name) > 9:
short_name = short_name[9:]
shelf_item = ShelfItem(icon="", drop_type=ShelfItem.ITEM_TYPE_CHAMELEON)
shelf_item.chameleon_json = chameleon_json
shelf_item.text = short_name[:3]
self.set_item_to_shelf(index, shelf_item)
def add_actors_shortcut(self, index, actor_names):
shelf_item = ShelfItem(icon="", drop_type=ShelfItem.ITEM_TYPE_ACTOR)
shelf_item.actors = actor_names
shelf_item.text = shelf_item.actors[0][:3] if shelf_item.actors else ""
shelf_item.text += str(len(shelf_item.actors))
self.set_item_to_shelf(index, shelf_item)
def add_assets_shortcut(self, index, assets):
shelf_item = ShelfItem(icon="", drop_type=ShelfItem.ITEM_TYPE_ASSETS)
shelf_item.assets = assets
if assets:
first_asset = unreal.load_asset(assets[0])
if first_asset:
shelf_item.text = f"{first_asset.get_name()[:3]}{str(len(shelf_item.assets)) if len(shelf_item.assets)>1 else ''}"
else:
shelf_item.text = "None"
else:
shelf_item.text = ""
self.set_item_to_shelf(index, shelf_item)
def add_folders_shortcut(self, index, folders):
shelf_item = ShelfItem(icon="", drop_type=ShelfItem.ITEM_TYPE_ASSETS_FOLDER)
shelf_item.folders = folders
if folders:
shelf_item.text = f"{(os.path.basename(folders[0]))[:3]}{str(len(folders)) if len(folders)>1 else ''}"
else:
shelf_item.text = ""
self.set_item_to_shelf(index, shelf_item)
def get_dropped_by_type(self, *args, **kwargs):
py_cmd = kwargs.get("text", "")
file_names = kwargs.get("files", None)
if file_names:
json_files = [n for n in file_names if n.lower().endswith(".json")]
chameleon_json = json_files[0] if json_files else ""
else:
chameleon_json = ""
actors = kwargs.get("actors", [])
assets = kwargs.get("assets", [])
folders = kwargs.get("assets_folders", [])
return py_cmd, chameleon_json, actors, assets, folders
def on_drop(self, id, *args, **kwargs):
print(f"OnDrop: id:{id} {kwargs}")
py_cmd, chameleon_json, actors, assets, folders = self.get_dropped_by_type(*args, **kwargs)
if chameleon_json:
self.add_chameleon_shortcut(id, chameleon_json)
elif py_cmd:
self.add_py_code_shortcut(id, py_cmd)
elif actors:
self.add_actors_shortcut(id, actors)
elif assets:
self.add_assets_shortcut(id, assets)
elif folders:
self.add_folders_shortcut(id, folders)
else:
print("Drop python snippet, chameleon json, actors or assets.")
def on_drop_last(self, *args, **kwargs):
print(f"on drop last: {args}, {kwargs}")
if len(self.shelf_data) <= Shelf.MAXIMUM_ICON_COUNT:
self.on_drop(len(self.shelf_data) + 1, *args, **kwargs)
def select_actors(self, actor_names):
actors = [unreal.PythonBPLib.find_actor_by_name(name) for name in actor_names]
unreal.PythonBPLib.select_none()
for i, actor in enumerate(actors):
if actor:
unreal.PythonBPLib.select_actor(actor, selected=True, notify=True, force_refresh= i == len(actors)-1)
def select_assets(self, assets):
exists_assets = [asset for asset in assets if unreal.EditorAssetLibrary.does_asset_exist(asset)]
unreal.PythonBPLib.set_selected_assets_by_paths(exists_assets)
def select_assets_folders(self, assets_folders):
print(f"select_assets_folders: {assets_folders}")
unreal.PythonBPLib.set_selected_folder(assets_folders)
def on_button_click(self, id):
shortcut = self.shelf_data.shortcuts[id]
if not shortcut:
unreal.log_warning("shortcut == None")
return
if shortcut.drop_type == ShelfItem.ITEM_TYPE_PY_CMD:
eval(shortcut.py_cmd)
elif shortcut.drop_type == ShelfItem.ITEM_TYPE_CHAMELEON:
unreal.ChameleonData.launch_chameleon_tool(shortcut.chameleon_json)
elif shortcut.drop_type == ShelfItem.ITEM_TYPE_ACTOR:
self.select_actors(shortcut.actors) # do anything what you want
elif shortcut.drop_type == ShelfItem.ITEM_TYPE_ASSETS:
self.select_assets(shortcut.assets)
elif shortcut.drop_type == ShelfItem.ITEM_TYPE_ASSETS_FOLDER:
self.select_assets_folders(shortcut.folders)
class ShelfItem:
ITEM_TYPE_NONE = 0
ITEM_TYPE_PY_CMD = 1
ITEM_TYPE_CHAMELEON = 2
ITEM_TYPE_ACTOR = 3
ITEM_TYPE_ASSETS = 4
ITEM_TYPE_ASSETS_FOLDER = 5
def __init__(self, drop_type, icon=""):
self.drop_type = drop_type
self.icon = icon
self.py_cmd = ""
self.chameleon_json = ""
self.actors = []
self.assets = []
self.folders = []
self.text = ""
def get_tool_tips(self):
if self.drop_type == ShelfItem.ITEM_TYPE_PY_CMD:
return f"PyCmd: {self.py_cmd}"
elif self.drop_type == ShelfItem.ITEM_TYPE_CHAMELEON:
return f"Chameleon Tools: {os.path.basename(self.chameleon_json)}"
elif self.drop_type == ShelfItem.ITEM_TYPE_ACTOR:
return f"{len(self.actors)} actors: {self.actors}"
elif self.drop_type == ShelfItem.ITEM_TYPE_ASSETS:
return f"{len(self.assets)} actors: {self.assets}"
elif self.drop_type == ShelfItem.ITEM_TYPE_ASSETS_FOLDER:
return f"{len(self.folders)} folders: {self.folders}"
class ShelfData:
def __init__(self):
self.shortcuts = []
def __len__(self):
return len(self.shortcuts)
def add(self, item):
assert isinstance(item, ShelfItem)
self.shortcuts.append(item)
def set(self, index, item):
assert isinstance(item, ShelfItem)
self.shortcuts[index] = item
def clear(self):
self.shortcuts.clear()
@staticmethod
def save(shelf_data, file_path):
with open(file_path, 'w') as f:
f.write(json.dumps(shelf_data, default=lambda o: o.__dict__, sort_keys=True, indent=4))
print(f"Shelf data saved: {file_path}")
@staticmethod
def load(file_path):
if not os.path.exists(file_path):
return None
with open(file_path, 'r') as f:
content = json.load(f)
instance = ShelfData()
instance.shortcuts = []
for item in content["shortcuts"]:
shelf_item = ShelfItem(item["drop_type"], item["icon"])
shelf_item.py_cmd = item["py_cmd"]
shelf_item.chameleon_json = item["chameleon_json"]
shelf_item.text = item["text"]
shelf_item.actors = item["actors"]
shelf_item.assets = item["assets"]
shelf_item.folders = item["folders"]
instance.shortcuts.append(shelf_item)
return instance
|
import unreal
##### Replace RPC assets
rpc_replacement_asset = '/project/'
rpcs_to_replace = [
'Hawthorn',
'Honey_Locust',
'Largetooth_Aspen',
'Lombardy_Poplar',
'Red_Ash',
'Red_Maple',
'Scarlet_Oak'
]
actorSubsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
assetSubsystem = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem)
all_actor_components = actorSubsystem.get_all_level_actors_components()
loaded_asset = assetSubsystem.load_asset(rpc_replacement_asset)
for component in all_actor_components:
if component.component_has_tag("Revit.RPC"):
actor_name = component.get_owner().get_actor_label()
print("Found an RPC component: " + actor_name)
for replacement_key in rpcs_to_replace:
if (actor_name.startswith(replacement_key)):
print("Replacing...")
spawn_location = component.get_owner().get_actor_location()
spawn_rotation = component.get_owner().get_actor_rotation()
# randomize the rotation
spawn_rotation.yaw = unreal.MathLibrary.random_float_in_range(0,360)
# spawn the actor
new_actor = actorSubsystem.spawn_actor_from_object(loaded_asset, spawn_location, spawn_rotation)
new_actor.root_component.set_editor_property("mobility", unreal.ComponentMobility.MOVABLE)
# randomize its scale factor
scale_factor = unreal.MathLibrary.random_float_in_range(0.75,1.25)
world_scale = new_actor.get_actor_scale3d()
world_scale.z = world_scale.z * scale_factor
new_actor.set_actor_scale3d( world_scale )
# make the new actor a child of the RPC actor
new_actor.attach_to_actor( component.get_owner(), "", unreal.AttachmentRule.KEEP_WORLD, unreal.AttachmentRule.KEEP_WORLD, unreal.AttachmentRule.KEEP_WORLD, False )
break
|
# Ref:
# https://github.com/project/.py
import abc
import os
import queue
import sys
import threading
import time
from http import HTTPStatus
# importlib machinery needs to be available for importing client modules
from importlib.machinery import SourceFileLoader
from xmlrpc.server import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer
import unreal
EXECUTION_QUEUE = queue.Queue()
RETURN_VALUE_NAME = 'RPC_SERVER_RETURN_VALUE'
ERROR_VALUE_NAME = 'RPC_SERVER_ERROR_VALUE'
def run_in_main_thread(callable_instance, *args):
"""Runs the provided callable instance in the main thread by added it to a que that
is processed by a recurring event in an integration like a timer.
:param call callable_instance: A callable.
:return: The return value of any call from the client.
"""
# timeout = int(os.environ.get('RPC_TIME_OUT', 60))
globals().pop(RETURN_VALUE_NAME, None)
globals().pop(ERROR_VALUE_NAME, None)
EXECUTION_QUEUE.put((callable_instance, args))
# for attempt in range(timeout * 10):
while True:
if RETURN_VALUE_NAME in globals():
return globals().get(RETURN_VALUE_NAME)
elif ERROR_VALUE_NAME in globals():
raise globals()[ERROR_VALUE_NAME]
else:
time.sleep(0.1)
# if RETURN_VALUE_NAME not in globals():
# raise TimeoutError(
# f'The call "{callable_instance.__name__}" timed out because it hit the timeout limit'
# f' of {timeout} seconds.'
# )
def execute_queued_calls(*extra_args):
"""Runs calls in the execution que till they are gone.
Designed to be passed to a recurring event in an integration like a timer.
"""
while not EXECUTION_QUEUE.empty():
if RETURN_VALUE_NAME not in globals():
callable_instance, args = EXECUTION_QUEUE.get()
try:
globals()[RETURN_VALUE_NAME] = callable_instance(*args)
except Exception as error:
# store the error in the globals and re-raise it
globals()[ERROR_VALUE_NAME] = error
raise error
class AuthenticatedRequestHandler(SimpleXMLRPCRequestHandler):
def is_authorized(self):
"""Checks if the Authorization header matches the key generated by the server.
:returns: Whether the request is authorized.
:rtype: bool
"""
# do not allow requests sent cross site
if self.headers.get('Sec-Fetch-Site') == 'cross-site':
return False
# do not allow requests from another origin
if self.headers.get('Origin'):
return False
return True
def report_401(self):
"""Reports an unauthorized error back to the client."""
self.send_response(HTTPStatus.UNAUTHORIZED)
response = b'Not authorized'
self.send_header('Content-type', 'text/plain')
self.send_header('Content-length', str(len(response)))
self.end_headers()
self.wfile.write(response)
def do_POST(self):
"""Overrides the post method to implement authentication."""
if self.is_authorized():
super(AuthenticatedRequestHandler, self).do_POST()
else:
self.report_401()
class BaseServer(SimpleXMLRPCServer):
def __init__(self, *args, **kwargs):
kwargs['requestHandler'] = AuthenticatedRequestHandler
super(BaseServer, self).__init__(*args, **kwargs)
def serve_until_killed(self):
"""Serves till killed by the client."""
self.quit = False
while not self.quit:
self.handle_request()
class BaseRPCServer:
def __init__(self, name, port, is_thread=False):
"""Initialize the base server.
:param str name: The name of the server.
:param int port: The number of the server port.
:param bool is_thread: Whether the server is encapsulated in a thread.
"""
self.server = BaseServer((os.environ.get('RPC_HOST', '127.0.0.1'), port), logRequests=False, allow_none=True)
self.is_thread = is_thread
self.server.register_function(self.add_new_callable)
self.server.register_function(self.kill)
self.server.register_function(self.is_running)
self.server.register_function(self.set_env)
self.server.register_introspection_functions()
self.server.register_multicall_functions()
unreal.log(f'Started RPC server "{name}" on port {port}')
@staticmethod
def is_running():
"""Responds if the server is running."""
return True
@staticmethod
def set_env(name, value):
"""Sets an environment variable in the server's python environment.
:param str name: The name of the variable.
:param str value: The value.
"""
os.environ[name] = str(value)
def kill(self):
"""Kill the running server from the client.
Only if running in blocking mode.
"""
self.server.quit = True
return True
def add_new_callable(self, callable_name, code, client_system_path, remap_pairs=None):
"""Adds a new callable defined in the client to the server.
:param str callable_name: The name of the function that will be added to the
server.
:param str code: The code of the callable that will be added to the server.
:param list[str] client_system_path: The list of python system paths from
the client.
:param list(tuple) remap_pairs: A list of tuples with first value being the
client python path root and the second being the new server path root. This
can be useful if the client and server are on two different file systems and
the root of the import paths need to be dynamically replaced.
:return str: A response message back to the client.
"""
for path in client_system_path:
# if a list of remap pairs are provided, they will be remapped before being added to the system path
for client_path_root, matching_server_path_root in remap_pairs or []:
if path.startswith(client_path_root):
path = os.path.join(
matching_server_path_root, path.replace(client_path_root, '').replace(os.sep, '/').strip('/')
)
if path not in sys.path:
sys.path.append(path)
# run the function code
exec(code)
callable_instance = locals().copy().get(callable_name)
# grab it from the locals and register it with the server
if callable_instance:
if self.is_thread:
self.server.register_function(self.thread_safe_call(callable_instance), callable_name)
else:
self.server.register_function(callable_instance, callable_name)
return f'The function "{callable_name}" has been successfully registered with the server!'
class BaseRPCServerThread(threading.Thread, BaseRPCServer):
def __init__(self, name, port):
"""Initialize the base rpc server.
:param str name: The name of the server.
:param int port: The number of the server port.
"""
threading.Thread.__init__(self, name=name, daemon=True)
BaseRPCServer.__init__(self, name, port, is_thread=True)
def run(self):
"""Overrides the run method."""
self.server.serve_forever()
@abc.abstractmethod
def thread_safe_call(self, callable_instance, *args):
"""Implements thread safe execution of a call."""
return
class BaseRPCServerManager:
@abc.abstractmethod
def __init__(self):
"""Initialize the server manager.
Note: when this class is subclassed `name`, `port`, `threaded_server_class` need to be defined.
"""
self.server_thread = None
self.server_blocking = None
def start_server_thread(self):
"""Starts the server in a thread."""
self.server_thread = self.threaded_server_class(self.name, self.port)
self.server_thread.start()
def start_server_blocking(self):
"""Starts the server in the main thread, which blocks all other processes.
This can only be killed by the client.
"""
self.server_blocking = BaseRPCServer(self.name, self.port)
self.server_blocking.server.serve_until_killed()
def start(self, threaded=True):
"""Starts the server.
:param bool threaded: Whether to start the server in a thread. If not threaded
it will block all other processes.
"""
# start the server in a thread
if threaded and not self.server_thread:
self.start_server_thread()
# start the blocking server
elif not threaded and not self.server_blocking:
self.start_server_blocking()
else:
unreal.log(f'RPC server "{self.name}" is already running...')
def shutdown(self):
"""Shuts down the server."""
if self.server_thread:
unreal.log(f'RPC server "{self.name}" is shutting down...')
# kill the server in the thread
if self.server_thread:
self.server_thread.server.shutdown()
self.server_thread.join()
unreal.log(f'RPC server "{self.name}" has shutdown')
|
import os
import unreal
from . import helpers
# Dictionary containing default FBX import options
DEFAULT_ASSETS_FBX_IMPORT_OPTIONS = {
"import_materials": True,
"import_textures": True,
"import_as_skeletal": False,
}
# Dictionary containing default FBX export options
DEFAULT_ASSETS_FBX_EXPORT_OPTIONS = {
"ascii": False,
"collision": False,
"level_of_detail": False,
"vertex_color": True,
}
def list_asset_paths(directory="/Game", recursive=True, include_folder=False):
"""
Returns a list of all asset paths within Content Browser.
:param str directory: directory path of the asset we want the list from.
:param bool recursive: whether will be recursive and will look in sub folders.
:param bool include_folder: whether result will include folders name.
:param list(str) or str or None extra_paths: asset path of the asset.
:return: list of all asset paths found.
:rtype: list(str)
"""
return unreal.EditorAssetLibrary.list_assets(
directory, recursive=recursive, include_folder=include_folder
)
def asset_exists(asset_path):
"""
Returns whether given asset path exists.
:param str asset_path: asset path of the asset.
:return: True if asset exist; False otherwise.
:rtype: bool
"""
return unreal.EditorAssetLibrary.does_asset_exist(asset_path)
def get_export_path(asset_path):
"""
Returns path where asset was originally exported.
:param str asset_path: path of the asset
:return: export path.
:rtype: str
"""
return (
get_asset_data(asset_path)
.get_asset()
.get_editor_property("asset_import_data")
.get_first_filename()
)
def get_asset_unique_name(asset_path, suffix=""):
"""
Returns a unique name for an asset in the given path.
:param str asset_path: path of the asset
:param str suffix: suffix to use to generate the unique asset name.
:return: tuple containing asset path and name.
:rtype: tuple(str, str)
"""
return unreal.AssetToolsHelpers.get_asset_tools().create_unique_asset_name(
base_package_name=asset_path, suffix=suffix
)
def rename_asset(asset_path, new_name):
"""
Renames asset with new given name.
:param str asset_path: path of the asset to rename.
:param str new_name: new asset name.
:return: new asset name.
:rtype: str
"""
dirname = os.path.dirname(asset_path)
new_name = dirname + "/" + new_name
unreal.EditorAssetLibrary.rename_asset(asset_path, new_name)
return new_name
def move_assets_to_path(root, name, asset_paths):
"""
Moves/Rename the given list of assets to given destination directory.
:param str root: root of the path (eg. '/Game')
:param str name: name of the destination directory (eg. 'Target')
:param list(str) asset_paths: list of asset paths.
:return: new assets directory.
:rtype: str
"""
created_folder = helpers.create_folder(root, name)
for asset_path in asset_paths:
loaded = unreal.EditorAssetLibrary.load_asset(asset_path)
unreal.EditorAssetLibrary.rename_asset(
asset_path, "{}/{}".format(created_folder, loaded.get_name())
)
return created_folder
def get_assets(assets_path, recursive=False, only_on_disk=False):
"""
Returns all assets located in the given path.
:param str assets_path: path to get assets from.
:param bool recursive: whether to recursively find assets located in given path children folders.
:param bool only_on_disk: whether memory-objects will be ignored. If True, this function will be faster.
:return: assets data for all assets in the given path.
:rtype: list(unreal.AssetData)
"""
asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
return (
asset_registry.get_assets_by_path(
assets_path,
recursive=recursive,
include_only_on_disk_assets=only_on_disk,
)
or list()
)
def get_asset_data(asset_path, only_on_disk=False):
"""
Returns AssetData of the asset located in the given path.
:param str asset_path: path of the asset we want to retrieve data of.
:param bool only_on_disk: whether memory-objects will be ignored. If True, this function will be faster.
:return: data of the asset located in the given path.
:rtype: unreal.AssetData or None
"""
asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
return asset_registry.get_asset_by_object_path(
asset_path, include_only_on_disk_assets=only_on_disk
)
def get_asset_object(asset_path:str) -> unreal.Object:
"""
Returns the Object for the asset at the specific asset_path
:param str asset_path: path of the asset we want to retrieve data of.
:rtype: unreal.Object or None
"""
asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
assets_data = asset_registry.get_assets_by_package_name(
asset_path, include_only_on_disk_assets=False
)
if len(assets_data) != 1:
unreal.log_warning(f"Multiple Asset Objects found: {asset_path}")
return None
return assets_data[0].get_asset()
def get_asset(asset_path, only_on_disk=False):
"""
Returns instance of an existent asset.
:param str asset_path: path of the asset instance we want to get.
:param bool only_on_disk: whether memory-objects will be ignored. If True, this function will be faster.
:return: instance of the asset located in the given path.
:rtype: object or None
"""
asset_data = get_asset_data(asset_path, only_on_disk=only_on_disk)
if not asset_data:
return None
full_name = asset_data.get_full_name()
path = full_name.split(" ")[-1]
return unreal.load_asset(path)
def get_selected_asset_data():
"""
Returns current selected AssetData in Content Browser.
:return: list of selected asset data in Content Browser.
:rtype: list(AssetData)
"""
return unreal.EditorUtilityLibrary.get_selected_asset_data()
def selected_assets(asset_type=None):
"""
Returns current selected asset instances in Content Browser.
:param type(unreal.Class) asset_type: The type of object you want to select. Filters out types that do not match
:return: list of selected asset instances in Content Browser.
:rtype: list(object)
"""
if asset_type:
return unreal.EditorUtilityLibrary.get_selected_assets_of_class(asset_type)
return unreal.EditorUtilityLibrary.get_selected_assets()
def find_all_blueprints_data_assets_of_type(asset_type_name):
"""
Returns a list with all blueprint assets of the given type.
:param str or type asset_type_name: blueprint asset type name.
:return: list of blueprints assets with the given type.
:rtype: list
"""
found_blueprint_data_assets = list()
blueprints = (
unreal.AssetRegistryHelpers.get_asset_registry().get_assets_by_class(
"Blueprint", True
)
)
for blueprint in blueprints:
blueprint_asset = blueprint.get_asset()
bp = unreal.EditorAssetLibrary.load_blueprint_class(
blueprint_asset.get_path_name()
)
bp_type = unreal.get_type_from_class(bp)
if bp_type == asset_type_name or bp_type.__name__ == asset_type_name:
found_blueprint_data_assets.append(blueprint)
return found_blueprint_data_assets
def create_asset(
asset_path="",
unique_name=True,
asset_class=None,
asset_factory=None,
**kwargs
):
"""
Creates a new Unreal asset.
:param str asset_path: path where the asset will be created.
:param bool unique_name: whether to automatically generate a unique name for the asset.
:param class asset_class: class of the asset we want to create.
:param class asset_factory: factory class to use for asset creation.
:param dict kwargs: custom keyword arguments to use by the asset creation factory.
:return: newly created asset instance.
:rtype: object or None
"""
if unique_name:
asset_path, asset_name = get_asset_unique_name(asset_path)
if not asset_exists(asset_path):
path = asset_path.rsplit("/", 1)[0]
name = asset_path.rsplit("/", 1)[1]
return unreal.AssetToolsHelpers.get_asset_tools().create_asset(
asset_name=name,
package_path=path,
asset_class=asset_class,
factory=asset_factory,
**kwargs
)
return unreal.load_asset(asset_path)
def generate_fbx_import_task(
filename,
destination_path,
destination_name=None,
replace_existing=True,
automated=True,
save=True,
fbx_options=None,
):
"""
Creates and configures an Unreal AssetImportTask to import a FBX file.
:param str filename: FBX file to import.
:param str destination_path: Content Browser path where the asset will be placed.
:param str or None destination_name: optional name of the imported asset. If not given, the name will be the
filename without the extension.
:param bool replace_existing: whether to replace existing assets.
:param bool automated: unattended import.
:param bool save: whether to save the file after importing it.
:param dict fbx_options: dictionary containing all the FBX settings to use.
:return: Unreal AssetImportTask that handles the import of the FBX file.
:rtype: unreal.AssetImportTask
"""
task = unreal.AssetImportTask()
task.filename = filename
task.destination_path = destination_path
# By default, task.destination_name is the filename without the extension
if destination_name:
task.destination_name = destination_name
task.replace_existing = replace_existing
task.automated = automated
task.save = save
task.options = unreal.FbxImportUI()
fbx_options = fbx_options or DEFAULT_ASSETS_FBX_IMPORT_OPTIONS
# Skeletal Mesh related import options
as_skeletal = fbx_options.pop("mesh_type_to_import", False)
skeletal_mesh_import_data = fbx_options.pop(
"skeletal_mesh_import_data", dict()
)
if skeletal_mesh_import_data:
sk_import_data = unreal.FbxSkeletalMeshImportData()
for name, value in skeletal_mesh_import_data.items():
try:
sk_import_data.set_editor_property(name, value)
except Exception:
unreal.log_warning(
"Was not possible to set Skeletal Mesh FBX Import property: {}: {}".format(
name, value
)
)
task.options.skeletal_mesh_import_data = sk_import_data
# Base FBX import options
for name, value in fbx_options.items():
try:
task.options.set_editor_property(name, value)
except Exception:
unreal.log_warning(
"Was not possible to set FBX Import property: {}: {}".format(
name, value
)
)
# task.options.static_mesh_import_data.combine_meshes = True
task.options.mesh_type_to_import = unreal.FBXImportType.FBXIT_STATIC_MESH
if as_skeletal:
task.options.mesh_type_to_import = (
unreal.FBXImportType.FBXIT_SKELETAL_MESH
)
if fbx_options.get("skeleton", None) is not None:
task.options.skeleton = unreal.load_asset(fbx_options["skeleton"])
task.options.import_as_skeletal = False
return task
def generate_asset_fbx_export_task(
asset, filename, replace_identical=True, automated=True, fbx_options=None
):
"""
Creates and configures an Unreal AssetExportTask to export a FBX file.
:param str asset: asset we want to export with the task.
:param str filename: FBX file to export.
:param bool replace_identical: whether to replace identical files.
:param bool automated: unattended export.
:param fbx_options: dictionary containing all the FBX settings to use.
:return: Unreal AssetExportTask that handles the export of the FBX file.
:rtype: unreal.AssetExportTask
"""
task = unreal.AssetExportTask()
task.filename = filename
task.replace_identical = replace_identical
task.automated = automated
task.object = asset
task.options = unreal.FbxExportOption()
fbx_options = fbx_options or DEFAULT_ASSETS_FBX_EXPORT_OPTIONS
for name, value in fbx_options.items():
try:
task.options.set_editor_property(name, value)
except Exception:
unreal.log_warning(
"Was not possible to set FBX Export property: {}: {}".format(
name, value
)
)
asset_class = asset.get_class()
exporter = None
if asset_class == unreal.StaticMesh.static_class():
exporter = unreal.StaticMeshExporterFBX()
elif asset_class == unreal.SkeletalMesh.static_class():
exporter = unreal.SkeletalMeshExporterFBX()
if not exporter:
unreal.log_warning(
'Asset Type "{}" has not a compatible exporter!'.format(
asset_class
)
)
return None
task.exporter = exporter
return task
def import_fbx_asset(
filename,
destination_path,
destination_name=None,
save=True,
import_options=None,
):
"""
Imports a FBX into Unreal Content Browser.
:param str filename: FBX file to import.
:param str destination_path: Content Browser path where the asset will be placed.
:param str or None destination_name: optional name of the imported asset. If not given, the name will be the
filename without the extension.
:param bool save: whether to save the file after importing it.
:param dict import_options: dictionary containing all the FBX import settings to use.
:return: path of the imported object.
:rtype: str
"""
tasks = list()
tasks.append(
generate_fbx_import_task(
filename,
destination_path,
destination_name=destination_name,
fbx_options=import_options,
save=save,
)
)
return helpers.get_first_in_list(import_assets(tasks), default="")
def export_fbx_asset(asset, directory, fbx_filename="", export_options=None):
"""
Exports a FBX from Unreal Content Browser.
:param unreal.Object asset: asset to export.
:param str directory: directory where FBX asset will be exported.
:param dict export_options: dictionary containing all the FBX export settings to use.
:return: exported FBX file path.
:rtype: str
"""
fbx_path = helpers.clean_path(
os.path.join(
directory, "{}.fbx".format(fbx_filename or asset.get_name())
)
)
unreal.log(
'Exporting Asset "{}" in following path: "{}"'.format(asset, fbx_path)
)
export_task = generate_asset_fbx_export_task(
asset, fbx_path, fbx_options=export_options
)
if not export_task:
unreal.log_warning(
"Was not possible to generate asset FBX export task"
)
return None
result = unreal.ExporterFBX.run_asset_export_task(export_task)
return fbx_path if result else ""
def import_assets(asset_tasks):
"""
Imports assets from the given asset import tasks.
:param list(unreal.AssetImportTask) asset_tasks: list of import tasks to run.
:return: list of imported asset paths.
:rtype: list(str)
"""
unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks(asset_tasks)
imported_paths = list()
for task in asset_tasks:
unreal.log("Import Task for: {}".format(task.filename))
for object_path in task.imported_object_paths:
unreal.log("Imported object: {}".format(object_path))
imported_paths.append(object_path)
return imported_paths
def get_selected_folders(relative=False):
"""
Returns a list of paths for the folders selected in the Content Browser.
:param bool relative: If true paths will be relative to the Unreal Project. if False, they will be absolute.
:return: list of folder paths
:rtype: list(str)
"""
paths = []
folder_paths = unreal.EditorUtilityLibrary.get_selected_folder_paths()
if relative:
return folder_paths
for idx in range(len(folder_paths)):
project_dir = unreal.Paths.project_dir()
content_dir = unreal.Paths.project_content_dir()
absolute_project_dir = str(unreal.Paths.normalize_directory_name(unreal.Paths.convert_relative_path_to_full(project_dir)))
absolute_content_dir = str(unreal.Paths.normalize_directory_name(unreal.Paths.convert_relative_path_to_full(content_dir)))
relative_folder_path = str(folder_paths[idx])
absolute_folder_path = absolute_content_dir + relative_folder_path.split('Game')[-1]
if unreal.Paths.directory_exists(absolute_folder_path):
paths.append(absolute_folder_path)
return paths
def get_all_by_type(package_name, asset_name, game_asset=True):
"""
Gets a list of all available assets in the engine /game
:param str package_name: Name of the package the asset class exists in
:param str asset_name: Name of the asset type
:param bool game_asset: If false all skeleton meshes will be returned, if true only
the skm's found in /Game
:return: List of assets that match.
:rtype: list(unreal.AssetData)
"""
asset_registery = unreal.AssetRegistryHelpers.get_asset_registry()
asset_path = unreal.TopLevelAssetPath(package_name, asset_name)
assets_found = asset_registery.get_assets_by_class(asset_path)
# Returns all assets, found in all packs(Engine, Virtual Production)
if not game_asset:
return assets_found
# Removes any asset that is not in the Games Project
for idx in reversed(range(len(assets_found))):
skm = assets_found[idx]
if str(skm.package_path).find("Game") != 1:
assets_found.pop(idx)
return assets_found
def get_skeleton_meshes(game_asset=True):
"""
Gets a list of all available skeleton meshes
:param bool game_asset: If false all skeleton meshes will be returned, if true only
the skm's found in /Game
:return: List of Skeletal Meshes
:rtype: list(unreal.AssetData)
"""
return get_all_by_type('/project/', 'SkeletalMesh', game_asset)
def get_skeletons(game_asset=True):
"""
Gets a list of all available skeletons
:param bool game_asset: If false all skeletons will be returned, if true only
the skm's found in /Game
:return: List of Skeletons that exist in Content Browser.
:rtype: list(unreal.AssetData)
"""
return get_all_by_type('/project/', 'Skeleton', game_asset)
def import_fbx_animation(fbx_path, dest_path, anim_sequence_name, skeleton_path):
"""
Imports the fbx file as an Animation Sequence.
:param str fbx_path: Path to the fbx file that will be imported.
:param str dest_path: Location where the AnimationSequence will be generated. eg."/project/"
:param str name: Name of the Animation Sequence in unreal
:param str skeleton_path: Location of the Skeleton file. eg."/project/.Butcher_Skeleton"
:return: List of Asset Path locations, to the newly imported Animation Sequence
:rtype: list(str)
"""
task = unreal.AssetImportTask()
task.filename = fbx_path
task.destination_path = dest_path
task.destination_name = anim_sequence_name
task.replace_existing = True
task.automated = True
task.save = True
task.options = unreal.FbxImportUI()
task.options.import_materials = False
task.options.import_animations = True
task.options.import_as_skeletal = True
task.options.import_mesh = False
task.options.automated_import_should_detect_type = False
task.options.skeleton = unreal.load_asset(skeleton_path)
task.options.mesh_type_to_import = unreal.FBXImportType.FBXIT_ANIMATION
paths = import_assets([task])
return paths
def import_fbx_skeletal_mesh(fbx_path, dest_path, anim_sequence_name, skeleton_path=None):
"""
Imports the fbx file as an Skeletal Mesh.
NOTE: FBX file must contain no animation on the character.
:param str fbx_path: Path to the fbx file that will be imported.
:param str dest_path: Location where the AnimationSequence will be generated. eg."/project/"
:param str name: Name of the Animation Sequence in unreal
:param str skeleton_path: Path to the Skeleton. If populated then this skeleton will be used, instead of generating a new one.
:return: List of Asset Path locations, to the newly imported Animation Sequence
:rtype: list(str)
"""
task = unreal.AssetImportTask()
task.filename = fbx_path
task.destination_path = dest_path
task.destination_name = anim_sequence_name
task.replace_existing = True
task.automated = True
task.save = True
task.options = unreal.FbxImportUI()
task.options.import_mesh = True
task.options.import_as_skeletal = True
task.options.import_materials = True
task.options.import_animations = False
task.options.override_full_name = True
task.options.create_physics_asset = True
task.options.automated_import_should_detect_type = False
# task.options.skeletal_mesh_import_data.set_editor_property('update_skeleton_reference_pose', False)
# task.options.skeletal_mesh_import_data.set_editor_property('use_t0_as_ref_pose', True)
task.options.skeletal_mesh_import_data.set_editor_property('preserve_smoothing_groups', 1)
# task.options.skeletal_mesh_import_data.set_editor_property('import_meshes_in_bone_hierarchy', False)
task.options.skeletal_mesh_import_data.set_editor_property('import_morph_targets', True)
# task.options.skeletal_mesh_import_data.set_editor_property('threshold_position', 0.00002)
# task.options.skeletal_mesh_import_data.set_editor_property('threshold_tangent_normal', 0.00002)
# task.options.skeletal_mesh_import_data.set_editor_property('threshold_uv', 0.000977)
task.options.skeletal_mesh_import_data.set_editor_property('convert_scene', True)
# task.options.skeletal_mesh_import_data.set_editor_property('force_front_x_axis', False)
# task.options.skeletal_mesh_import_data.set_editor_property('convert_scene_unit', False)
task.options.mesh_type_to_import = unreal.FBXImportType.FBXIT_SKELETAL_MESH
if skeleton_path:
task.options.skeleton = unreal.load_asset(skeleton_path)
task.options.import_as_skeletal = False
paths = import_assets([task])
return paths
def get_skeleton_count(path):
"""
Returns the amount of joints in the skeleton
example path : "/project/.Butcher_Skeleton"
"""
skeleton_asset = unreal.EditorAssetLibrary.load_asset(path)
ref_pose = skeleton_asset.get_reference_pose()
bone_names = ref_pose.get_bone_names()
return len(bone_names)
|
import unreal
def log_hello_unreal():
'''
logs hello unreal to the output log in unreal.
'''
unreal.log_warning("hello unreal!")
log_hello_unreal()
|
import unreal
from pathlib import Path
import sys
import os
import shutil
import ast
import types
sys.path.append(str(Path(__file__).parent.parent.parent.resolve()))
from importlib import *
reloads = []
for k, v in sys.modules.items():
if k.startswith("pamux_unreal_tools"):
reloads.append(v)
for module in reloads:
reload(module)
import inspect
# from pamux_unreal_tools.interfaces.IHeightLerpWithTwoHeightMaps import IHeightLerpWithTwoHeightMaps
from pamux_unreal_tools.examples.M_Landscape_Master.interfaces.IBlendTwoMaterialsViaHighOpacityMap import IBlendTwoMaterialsViaHighOpacityMap
from pamux_unreal_tools.examples.M_Landscape_Master.interfaces.IForestGround import IForestGround
from pamux_unreal_tools.tools.code_generators.py_code_generator import *
from pamux_unreal_tools.tools.code_generators.base.method_params import *
from pamux_unreal_tools.utils.types import *
import functools
from typing import Any, Callable
type_to_function_output_map = { "SomeType": "varName" }
class DummyBuilder:
def __init__(self) -> None:
pass
class Nodes:
def __init__(self, builder) -> None:
self.builder = builder
class InterfaceImplementer:
def __init__(self, builder, interface):
self.builder = builder
self.interface = interface
self.function_name = None
self.function_parameters = []
self.function_return = None
self.asset_path = None
self.parameter_name_prefix = None
def parse_interface(self):
signature = inspect.signature(self.interface)
self.function_name = self.interface.__name__
self.field_name = self.function_name[1].lower() + self.function_name[2:]
self.function_parameters = signature.parameters
names = []
for p in signature.parameters:
names.append("'" +str(p) + "'")
if len(names) == 0:
self.function_inputs = ''
else:
self.function_inputs = ', '.join(names)
names = []
if isinstance(signature.return_annotation, types.GenericAlias):
type_str = str(signature.return_annotation)
if type_str.startswith("tuple"):
type_str = type_str[len("tuple["):-1]
for t in type_str.split(','):
t = t.strip()
t = t[t.rindex(".")+1:]
if t.startswith("T"):
function_output_name = t[1].lower() + t[2:]
elif t in type_to_function_output_map.keys():
function_output_name = type_to_function_output_map[t]
else:
function_output_name = t
names.append("'" + function_output_name + "'")
else:
names.append("'" + signature.return_annotation.__name__ + "'")
if len(names) == 0:
self.function_outputs = ''
else:
self.function_outputs = ', '.join(names)
if hasattr(self.interface, "_asset_path"):
self.asset_path = self.interface._asset_path
elif hasattr(self.interface, "_parameter_name_prefix"):
self.parameter_name_prefix = self.interface._parameter_name_prefix
def implement_dependencies_object(self, node_container):
line = f"node_container.{self.field_name} = builder.load_MF(\"{self.asset_path}\", [{self.function_inputs}], [{self.function_outputs}])"
def implement_inputs_object(self, node_container):
# self.albedo = builder.build_FunctionInput("Albedo", 0, TextureObject())
signature = inspect.signature(self.interface)
sort_priority = 0
for p in signature.parameters:
#line = f"node_container.{field_name} = builder.build_FunctionInput(\"{input_name}\", {sort_priority}, {preview}, {use_preview_value_as_default})"
sort_priority += 1
def implement_outputs_object(self, node_container):
pass
def begin_class(self, class_name):
self.codeGen.begin_class(class_name, None)
mps = MethodParams()
mps.append(MethodParam("builder", "ContainerBuilderBase"))
self.codeGen.begin_ctor(class_name, mps)
def end_class(self):
self.codeGen.end_ctor()
self.codeGen.end_class()
def implement(self):
self.parse_interface()
self.codeGen = PyCodeGenerator()
self.codeGen.append_import("unreal")
self.codeGen.append_blank_line()
self.codeGen.append_import_from("pamux_unreal_tools.base.container_builder_base", "ContainerBuilderBase")
self.codeGen.append_blank_line()
node_container = Nodes(self.builder)
self.implement_dependencies_object(node_container)
self.implement_inputs_object(node_container)
self.implement_outputs_object(node_container)
self.codeGen.print_code()
# print(".")
# print(self.asset_path)
# print(self.parameter_name_prefix)
# print(self.function_name)
# print(self.function_parameters)
# print(self.function_return)
# print(".")
# print("******************************************************************")
# print(".")
ii = InterfaceImplementer(DummyBuilder(), IForestGround)
ii.implement()
# class Dependencies:
# def __init__(self, builder: ContainerBuilderBase) -> None:
# self.heightLerpWithTwoHeightMaps = builder.load_MF(
# "/project/",
# [ "Transistion Phase", "Height Texture 1", "Height Texture 2" ],
# [ "Alpha" ])
|
import unreal
src_num :str #Binded value from Widget UI
dst_num :str # Binded value from Widget UI
ar_asset_lists = unreal.EditorUtilityLibrary.get_selected_assets()
if len(ar_asset_lists) > 0 :
for each in ar_asset_lists :
src_asset_path = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(each)
dst_asset_path = src_asset_path.replace(src_num, dst_num)
rename = unreal.EditorAssetLibrary.rename_asset(src_asset_path, dst_asset_path)
#Memory Free here
del ar_asset_lists
del src_num
del dst_num
|
#!/project/ python
# -*- encoding: utf-8 -*-
import unreal
print('uiUntil file exec!!!')
menus = unreal.ToolMenus.get()
rootMenuName = 'LevelEditor.MainMenu'
rootToolBarName = "LevelEditor.LevelEditorToolBar"
def addMainMenu(name,label,tool_tip=""):
'''
为 unreal 添加主菜单
:param name: 主菜单名称
:param label: 主菜单 label
:param tool_tip: 显示 toolTip
:return:
'''
# Get the main menu class
menu = menus.find_menu(rootMenuName)
custom_menu_name = rootMenuName + '.' + name
custom_menu = menus.find_menu(custom_menu_name)
if custom_menu == None:
# Custom menu parameters
owner = menu.get_name()
section_name = 'PythonTools'
# Add and refresh
menu.add_sub_menu(owner, section_name, name, label, tool_tip)
menus.refresh_all_widgets()
unreal.log('{} menu add succesful.'.format(name))
else:
unreal.log_warning('{} menu is exists.'.format(name))
def addSubMenu(main_menu,sub_menu,string_commond,tool_tip=''):
'''
添加子菜单命令
:param main_menu: 父菜单路径
:param sub_menu: 子菜单名称
:param string_commond: 具体执行的命令
:param tool_tip: 帮助信息
:return:
'''
main_menu_name = rootMenuName + '.' + main_menu
menu = menus.find_menu(main_menu_name)
if menu == None:
unreal.log_error('{} main menu is not exists.'.format(main_menu))
return
entry = unreal.ToolMenuEntry(type=unreal.MultiBlockType.MENU_ENTRY)
entry.set_label(sub_menu)
typ = unreal.ToolMenuStringCommandType.PYTHON
entry.set_string_command(typ, "", string_commond)
section_name = ''
menu.add_menu_entry(section_name, entry)
if tool_tip:
entry.set_tool_tip(tool_tip)
menus.refresh_all_widgets()
def removeMenu():
'''
TODO 是否存在移除得命令
:return:
'''
pass
def addToolShelf(toolName,string_commond):
menu = menus.find_menu(rootToolBarName)
# Set the button type and label
entry = unreal.ToolMenuEntry(type=unreal.MultiBlockType.TOOL_BAR_BUTTON)
entry.set_label(toolName)
# Set button command
typ = unreal.ToolMenuStringCommandType.PYTHON
entry.set_string_command(typ, "", string_commond)
# Add and refresh
section_name = 'Settings'
menu.add_menu_entry(section_name, entry)
menus.refresh_all_widgets()
def addIqiyiUI():
addMainMenu('IQIYI', 'IQIYI')
#TODO 后续添加其他工具、子菜单、或者按钮
addSubMenu('IQIYI','mainTest','import main as main,importlib\nimportlib.reload(main)\nmain.mainTest()')
|
import unreal
from Lib import __lib_topaz__ as topaz
import importlib
importlib.reload(topaz)
selected : list = topaz.get_selected_assets() #get selected assets using editorUtilityLib
for staticMesh in selected :
meshNaniteSettings : bool = staticMesh.get_editor_property('nanite_settings')
blendModes = topaz.get_materials_from_staticmesh(staticMesh, True)
is_translucent_exist = topaz.is_translucent_exist(blendModes)
if meshNaniteSettings.enabled == False and not is_translucent_exist :
meshNaniteSettings.enabled = True # On nanite setting
unreal.StaticMeshEditorSubsystem().set_nanite_settings(staticMesh,meshNaniteSettings, apply_changes=True) #apply changes
print('Nanite is Enabled')
else :
print('Nanite is already Enabled or this static mesh contains translucent material.')
|
# Copyright 2020 Tomoaki Yoshida<[email protected]>
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/project/.0/.
#
#
#
# You need following modules to run this script
# + pillow
# + numpy
# + gdal
#
# You can install these modules by running following commands on a posh prompt
# PS> cd /project/ Files\Epic Games\UE_4.25\Engine\Binaries\ThirdParty\Python\Win64
# PS> ./python.exe -m pip install pillow numpy
# GDAL cannot install by this simple method. You need to download whl file from
# https://www.lfd.uci.edu/~gohlke/pythonlibs/#gdal
# and then, install it by the similar command
# PS> ./python.exe -m pip install /project/-2.2.4-cp27-cp27m-win_amd64.whl
#
# You may want to add
# --target="/project/ Files\Epic Games\UE_4.25\Engine\Source\ThirdParty\Python\Win64\Lib\site-packages"
# to each pip install command. Without this --target option, modules will be installed in this folder.
# /project/ Files\Epic Games\UE_4.25\Engine\Binaries\ThirdParty\Python\Win64\Lib\site-packages
import unreal
import gdal
import osr
import os
from PIL import Image, ImageTransform, ImageMath
import numpy as np
import math
al=unreal.EditorAssetLibrary
el=unreal.EditorLevelLibrary
sdir=os.path.dirname(os.path.abspath(__file__))
projdir=os.path.join(sdir,"..","..","..","..")
# Parameters
stepSize=10 # [cm] # landscale cell size
zScale=10 # 100: +/-256 [m], 10: +/-25.6 [m] 1: 256 [cm] # landscape z scale value
zEnhance=1 # optional z scaling factor
zOffset=None # None for z at GeoReference Actor
zClipping=19.0 # Clip lowest height [m] (None for no clipping)
zClipping=-10.0 # Clip lowest height [m] (None for no clipping)
inputGeotiff=os.path.join(projdir,"GeotiffDEM.tif")
inputGeotiff=os.path.join(projdir,"TC_P8_pede_surface_export.tif")
inputGeotiff=os.path.join(projdir,"TC_P8_pede_surface_export-median20_geo.tif")
outputHeightmap=os.path.join(projdir,"heightmap-premedian20.png")
toUEScale=100.*128./zScale # [m]->[cm]->[heightmap unit]
LocalGeotiff=[
{"file":os.path.join(projdir,"TC_P8_pede_elev_divmask-export.tif"),
"zoffset":25.43}
]
# Utilities
# FVector ([deg], [min], [sec]) -> float [deg]
def Decode60(vec):
return ((vec.z/60.)+vec.y)/60.+vec.x;
# float [deg] -> FVector ([deg], [min], [sec])
def Encode60(v):
d=math.floor(v)
m=math.floor((v-d)*60.)
s=(v-d-m/60.)*3600.
return unreal.Vector(d,m,s)
class GeoTIFF:
def __init__(self, file):
self.gt = gdal.Open(file, gdal.GA_ReadOnly)
#self.rast = np.array([self.gt.GetRasterBand(1).ReadAsArray()])
self.image = Image.fromarray(self.gt.GetRasterBand(1).ReadAsArray())
self.src_cs = osr.SpatialReference()
self.dst_cs = osr.SpatialReference()
self.dst_cs.ImportFromWkt(self.gt.GetProjectionRef())
self.setSrcEPSG(6668) # default to JGD2011
# inverse transform from GeoTIFF(UV) to GeoTIFF(Logical)
self.mat = self.gt.GetGeoTransform()
d = 1./(self.mat[5]*self.mat[1]-self.mat[4]*self.mat[2])
self.iaf = np.array([[ self.mat[5],-self.mat[2]],
[-self.mat[4], self.mat[1]]])*d
self.offset = np.array([[self.mat[0]], [self.mat[3]]])
self.af=np.array([[self.mat[1], self.mat[2]],
[self.mat[4], self.mat[5]]])
def setSrcEPSG(self, epsg):
self.src_cs = osr.SpatialReference()
self.src_cs.ImportFromEPSG(epsg)
self.transS2G = osr.CoordinateTransformation(self.src_cs, self.dst_cs)
# Geotiff CS to Interface CS
self.transG2S=osr.CoordinateTransformation(self.dst_cs,self.src_cs)
def getBL(self,uv):
u=uv[0]
v=uv[1]
bl=np.dot(self.af,np.array([[u],[v]]))+self.offset
sbl=self.transG2S.TransformPoint(bl[1][0],bl[0][0])
return (sbl[0],sbl[1])
def getBBoxBL(self):
# Geotiff CS to Interface CS
return (self.getBL((0,0)),self.getBL((self.gt.RasterXSize,self.gt.RasterYSize)))
def sanitizedBounds(self, bbox=None):
if bbox is None:
bbox=self.getBBoxBL()
tl,br=bbox
bmin, bmax = tl[0], br[0]
if bmin>bmax:
bmin, bmax = bmax, bmin
lmin, lmax = tl[1], br[1]
if lmin>lmax:
lmin, lmax = lmax, lmin
return ((bmin,bmax,lmin,lmax))
def getIntersection(self, bboxBL):
bbox=self.sanitizedBounds(bboxBL)
sbbox=self.sanitizedBounds()
bmin=max(bbox[0],sbbox[0])
bmax=min(bbox[1],sbbox[1])
lmin=max(bbox[2],sbbox[2])
lmax=min(bbox[3],sbbox[3])
if lmax < lmin or bmax < bmin: # No intersection
return None
return ((bmax,lmin),(bmin,lmax)) # North-East, South-West
def getUV(self, srcBL):
gtBL = self.transS2G.TransformPoint(srcBL[1], srcBL[0])
bl=np.array([[gtBL[0]],[gtBL[1]]])
uv = np.dot(self.iaf, bl-self.offset)
return (uv[0][0], uv[1][0])
def getLandscapeBBox():
# search for landscape proxy actors
w=el.get_all_level_actors()
theFirst=True
for a in w:
if(a.get_class().get_name().startswith("Landscape") and not a.get_class().get_name().startswith("LandscapeGizmo")):
#print("Landscape Found : "+ a.get_name())
o,box=a.get_actor_bounds(True)
h=o+box
l=o-box
if(theFirst):
lx=l.x
ly=l.y
hx=h.x
hy=h.y
theFirst=False
else:
lx=min(lx,l.x)
ly=min(ly,l.y)
hx=max(hx,h.x)
hy=max(hy,h.y)
print("Landscape bounding box: ({0}, {1} - {2}, {3})".format(lx,ly,hx,hy))
print("Landscape size: {0} x {1}".format(hx-lx,hy-ly))
size=(int((hx-lx)/stepSize+1),int((hy-ly)/stepSize+1))
print("Landscape grid size: {0}".format(size))
return (lx,ly,hx,hy,size)
def getGeoReference():
w=el.get_all_level_actors()
theFirst=True
for a in w:
if(a.get_class().get_name().startswith("GeoReferenceBP")):
print("GeoReference Found")
ref=a
ref.initialize_geo_conv()
return ref
# ----------------------------------------------------------------------------------------
lx,ly,hx,hy,size=getLandscapeBBox()
ref=getGeoReference()
text_label="Projecting coordinates"
nFrames=5
with unreal.ScopedSlowTask(nFrames, text_label) as slow_task:
slow_task.make_dialog(True)
tl=tuple(map(Decode60, ref.get_bl(lx,ly)))
bl=tuple(map(Decode60, ref.get_bl(lx,hy)))
br=tuple(map(Decode60, ref.get_bl(hx,hy)))
tr=tuple(map(Decode60, ref.get_bl(hx,ly)))
print("Reference Quad=tl:{0} bl:{1} br:{2} tr:{3}".format(tl, bl, br, tr))
zo=ref.get_actor_location()
zobl=tuple(map(Decode60,ref.get_bl(zo.x,zo.y)))
print("GeoReference in BL {0} {1}".format(zobl[0], zobl[1]))
print("GeoReference in UE {0}".format(zo))
print(ref.get_xy(Encode60(zobl[0]),Encode60(zobl[1])))
gt=GeoTIFF(inputGeotiff)
tluv=gt.getUV(tl)
bluv=gt.getUV(bl)
bruv=gt.getUV(br)
truv=gt.getUV(tr)
zouv=gt.getUV(zobl)
print("Reference Quad on GeoTIFF image =tl:{0} bl:{1} br:{2} tr:{3}".format(tluv, bluv, bruv, truv))
uvf=tluv+bluv+bruv+truv
tlbl=gt.getBL(tluv)
blbl=gt.getBL(bluv)
trbl=gt.getBL(truv)
brbl=gt.getBL(bruv)
print("Reference Quad returned =tl:{0} bl:{1} br:{2} tr:{3}".format(tlbl, blbl, brbl, trbl))
print("Geotiff BBox = {0}".format(gt.getBBoxBL()))
slow_task.enter_progress_frame(1,"Clipping z range")
print(gt.image.mode)
print(gt.image)
if zClipping is not None:
imageref=Image.new(gt.image.mode,gt.image.size,zClipping)
clippedimg=ImageMath.eval("max(a,b)",a=gt.image,b=imageref)
clippedimg.save(os.path.join(projdir,"Assets","clipped.tif"))
else:
clippedimg=gt.image
print("Geotiff bounds:{0}".format(gt.getBBoxBL()))
for lg in LocalGeotiff:
lgt=GeoTIFF(lg["file"])
print("Local Geotiff bounds:{0}".format(lgt.getBBoxBL()))
isc=gt.getIntersection(lgt.getBBoxBL())
print("{0} intersection {1} ".format(lg["file"],isc))
if True:
slow_task.enter_progress_frame(1,"Transforming image region")
img=clippedimg.transform(size,Image.QUAD,data=uvf,resample=Image.BICUBIC)
img.save(os.path.join(projdir,"transform.tif"))
slow_task.enter_progress_frame(1,"Transforming height values")
# scale to match landscape scaling, and offset to align to GeoReference actor
if zOffset is None:
print(zouv)
zou=min(max(zouv[0],0),clippedimg.size[0])
zov=min(max(zouv[1],0),clippedimg.size[1])
zoff=clippedimg.getpixel((zou,zov))
else:
zoff=zOffset
zos=32768-(zoff*zEnhance-zo.z/100.)*toUEScale # 32768: mid point (height=0)
iarrf=np.array(img.getdata(),dtype="float32")*toUEScale*zEnhance + zos
print(zov)
print(zos)
print(zEnhance)
print(toUEScale)
print(iarrf.dtype)
print(iarrf)
slow_task.enter_progress_frame(1,"Converting to 16bit grayscale")
# convert to uint16 using numpy
# PIL cannot handle this operation because of CLIP16() which limits each pixel value in -32768 to 32767.
# This clipping must be avoided because destination dtype is uint16.
iarrs=np.array(iarrf,dtype="uint16")
slow_task.enter_progress_frame(1,"Saving as {0}".format(os.path.basename(outputHeightmap)))
imgS=Image.frombuffer("I;16",img.size,iarrs.data, "raw", "I;16", 0, 1)
imgS.save(outputHeightmap)
print("Heightmap saved as {0}".format(outputHeightmap))
|
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
|
"""
Updated validate_queue.py using common utilities
"""
import sys
import os
import unreal
# Add the common directory to Python path
script_dir = os.path.dirname(os.path.abspath(__file__))
common_dir = os.path.join(script_dir, 'lib')
if common_dir not in sys.path:
sys.path.append(common_dir)
# Import from common module
from render_queue_validation import validate_movie_render_queue
if __name__ == "__main__":
unreal.log(validate_movie_render_queue())
|
import unreal
editor_utility_subsystem = unreal.get_editor_subsystem(unreal.EditorUtilitySubsystem)
editor_utility_object_path = "/project/.InitScript"
editor_utility_object = unreal.load_asset(editor_utility_object_path)
if editor_utility_object:
editor_utility_subsystem.try_run(editor_utility_object)
print(f"VRMMenu Success: {editor_utility_object_path}")
else:
print(f"VRMMenu Failed: {editor_utility_object_path}")
|
import unreal
anim_seqs = unreal.EditorUtilityLibrary.get_selected_assets()
level_sequence: unreal.LevelSequence = unreal.LevelSequenceEditorBlueprintLibrary.get_current_level_sequence()
def get_anim_section():
for binding in level_sequence.get_bindings():
for track in binding.get_tracks():
if isinstance(track, unreal.MovieSceneSkeletalAnimationTrack):
skeletal_animation_sections = track.get_sections()
print(skeletal_animation_sections[0].params.animation)
return skeletal_animation_sections[0]
anim_iter = iter(anim_seqs)
on_finished_callback = None # 글로벌로 유지
def render_next_anim():
global on_finished_callback
try:
anim_seq = next(anim_iter)
except StopIteration:
print('----All renders finished----')
return
section = get_anim_section()
section.params.animation = anim_seq
directory_path = 'E:/temp/' + anim_seq.get_name()
sequencer_asset_path = '/project/.SQ_ENVCHECk'
capture_settings = unreal.AutomatedLevelSequenceCapture()
capture_settings.level_sequence_asset = unreal.SoftObjectPath(sequencer_asset_path)
capture_settings.set_image_capture_protocol_type(unreal.load_class(None, "/project/.ImageSequenceProtocol_PNG"))
capture_settings.settings.resolution.res_x = 256
capture_settings.settings.resolution.res_y = 256
capture_settings.settings.output_directory = unreal.DirectoryPath(directory_path)
capture_settings.settings.use_custom_frame_rate = True
capture_settings.settings.custom_frame_rate = unreal.FrameRate(12,1)
capture_settings.warm_up_frame_count = 3.0
capture_settings.delay_before_warm_up = 1.0
capture_settings.delay_before_shot_warm_up = 1.0
on_finished_callback = unreal.OnRenderMovieStopped()
on_finished_callback.bind_callable(on_render_movie_finished)
print(f"Rendering {anim_seq.get_name()} to movie...")
unreal.SequencerTools.render_movie(capture_settings, on_finished_callback)
def on_render_movie_finished(success):
print("Movie has finished rendering. Python can now invoke another movie render if needed. Success: " + str(success))
render_next_anim()
# 첫 렌더 시작
render_next_anim()
|
# -*- coding: utf-8 -*-
"""Load Skeletal Meshes form FBX."""
import os
from ayon_core.pipeline import (
get_representation_path,
AYON_CONTAINER_ID
)
from ayon_core.hosts.unreal.api import plugin
from ayon_core.hosts.unreal.api.pipeline import (
AYON_ASSET_DIR,
create_container,
imprint,
)
import unreal # noqa
class SkeletalMeshFBXLoader(plugin.Loader):
"""Load Unreal SkeletalMesh from FBX."""
product_types = {"rig", "skeletalMesh"}
label = "Import FBX Skeletal Mesh"
representations = ["fbx"]
icon = "cube"
color = "orange"
root = AYON_ASSET_DIR
@staticmethod
def get_task(filename, asset_dir, asset_name, replace):
task = unreal.AssetImportTask()
options = unreal.FbxImportUI()
task.set_editor_property('filename', filename)
task.set_editor_property('destination_path', asset_dir)
task.set_editor_property('destination_name', asset_name)
task.set_editor_property('replace_existing', replace)
task.set_editor_property('automated', True)
task.set_editor_property('save', True)
options.set_editor_property(
'automated_import_should_detect_type', False)
options.set_editor_property('import_as_skeletal', True)
options.set_editor_property('import_animations', False)
options.set_editor_property('import_mesh', True)
options.set_editor_property('import_materials', False)
options.set_editor_property('import_textures', False)
options.set_editor_property('skeleton', None)
options.set_editor_property('create_physics_asset', False)
options.set_editor_property(
'mesh_type_to_import',
unreal.FBXImportType.FBXIT_SKELETAL_MESH)
options.skeletal_mesh_import_data.set_editor_property(
'import_content_type',
unreal.FBXImportContentType.FBXICT_ALL)
options.skeletal_mesh_import_data.set_editor_property(
'normal_import_method',
unreal.FBXNormalImportMethod.FBXNIM_IMPORT_NORMALS)
task.options = options
return task
def import_and_containerize(
self, filepath, asset_dir, asset_name, container_name
):
unreal.EditorAssetLibrary.make_directory(asset_dir)
task = self.get_task(
filepath, asset_dir, asset_name, False)
unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks([task])
# Create Asset Container
create_container(container=container_name, path=asset_dir)
def imprint(
self,
folder_path,
asset_dir,
container_name,
asset_name,
representation,
product_type
):
data = {
"schema": "ayon:container-2.0",
"id": AYON_CONTAINER_ID,
"folder_path": folder_path,
"namespace": asset_dir,
"container_name": container_name,
"asset_name": asset_name,
"loader": str(self.__class__.__name__),
"representation": representation["id"],
"parent": representation["versionId"],
"product_type": product_type,
# TODO these should be probably removed
"asset": folder_path,
"family": product_type,
}
imprint(f"{asset_dir}/{container_name}", data)
def load(self, context, name, namespace, options):
"""Load and containerise representation into Content Browser.
Args:
context (dict): application context
name (str): Product name
namespace (str): in Unreal this is basically path to container.
This is not passed here, so namespace is set
by `containerise()` because only then we know
real path.
data (dict): Those would be data to be imprinted.
Returns:
list(str): list of container content
"""
# Create directory for asset and Ayon container
folder_name = context["folder"]["name"]
product_type = context["product"]["productType"]
suffix = "_CON"
asset_name = f"{folder_name}_{name}" if folder_name else f"{name}"
version_entity = context["version"]
# Check if version is hero version and use different name
version = version_entity["version"]
if version < 0:
name_version = f"{name}_hero"
else:
name_version = f"{name}_v{version:03d}"
tools = unreal.AssetToolsHelpers().get_asset_tools()
asset_dir, container_name = tools.create_unique_asset_name(
f"{self.root}/{folder_name}/{name_version}", suffix=""
)
container_name += suffix
if not unreal.EditorAssetLibrary.does_directory_exist(asset_dir):
path = self.filepath_from_context(context)
self.import_and_containerize(
path, asset_dir, asset_name, container_name)
self.imprint(
folder_name,
asset_dir,
container_name,
asset_name,
context["representation"],
product_type
)
asset_content = unreal.EditorAssetLibrary.list_assets(
asset_dir, recursive=True, include_folder=True
)
for a in asset_content:
unreal.EditorAssetLibrary.save_asset(a)
return asset_content
def update(self, container, context):
folder_path = context["folder"]["path"]
folder_name = context["folder"]["name"]
product_name = context["product"]["name"]
product_type = context["product"]["productType"]
version = context["version"]["version"]
repre_entity = context["representation"]
# Create directory for asset and Ayon container
suffix = "_CON"
asset_name = product_name
if folder_name:
asset_name = f"{folder_name}_{product_name}"
# Check if version is hero version and use different name
if version < 0:
name_version = f"{product_name}_hero"
else:
name_version = f"{product_name}_v{version:03d}"
tools = unreal.AssetToolsHelpers().get_asset_tools()
asset_dir, container_name = tools.create_unique_asset_name(
f"{self.root}/{folder_name}/{name_version}", suffix="")
container_name += suffix
if not unreal.EditorAssetLibrary.does_directory_exist(asset_dir):
path = get_representation_path(repre_entity)
self.import_and_containerize(
path, asset_dir, asset_name, container_name)
self.imprint(
folder_path,
asset_dir,
container_name,
asset_name,
repre_entity,
product_type
)
asset_content = unreal.EditorAssetLibrary.list_assets(
asset_dir, recursive=True, include_folder=False
)
for a in asset_content:
unreal.EditorAssetLibrary.save_asset(a)
def remove(self, container):
path = container["namespace"]
parent_path = os.path.dirname(path)
unreal.EditorAssetLibrary.delete_directory(path)
asset_content = unreal.EditorAssetLibrary.list_assets(
parent_path, recursive=False
)
if len(asset_content) == 0:
unreal.EditorAssetLibrary.delete_directory(parent_path)
|
# Copyright Epic Games, Inc. All Rights Reserved.
import os
import unreal
import p4utils
import flow.cmd
import unrealcmd
from peafour import P4
from pathlib import Path
#-------------------------------------------------------------------------------
class _SyncBase(unrealcmd.Cmd):
def _write_p4sync_txt_header(self, out):
out.write("# lines starting with a '#' are comments\n")
out.write("# lines prefixed with '-' are excluded from your sync\n")
out.write("# -.../Android/...\n")
out.write("# -/project/...\n")
out.write("# -*.uasset\n")
#-------------------------------------------------------------------------------
class Sync(_SyncBase):
""" Syncs the current project and engine directories to the given changelist
(or latest if none is provided). If the '--all' option is specified then the
branch will be searched locally for existing .uproject files, scheduling each
one to be synced.
The sync can be filtered with a .p4sync.txt file. Lines prefixed with a '-'
(e.g. "-.../SootySweep/...") will be excluded from the sync and anything
already synced is de-synced. The command will read .p4sync.txt files from two
locations;
1. <branch_root>/.p4sync.txt
2. ~/.ushell/.p4sync.txt (where ~ is USERPROFILE on Windows)
Quick edit the branch's .p4sync.txt file with '.p4 sync edit'. An example
of a .p4sync.txt file is as follows;
# a comment
-.../Android/...
-/project/...
-*.uasset """
changelist = unrealcmd.Arg(-1, "The changelist to sync to ('now' if unspecified)")
noresolve = unrealcmd.Opt(False, "Do not run 'p4 resolve -am' after syncing")
dryrun = unrealcmd.Opt(False, "Only pretend to do the sync")
all = unrealcmd.Opt(False, "Sync all the branch's projects found locally")
addprojs = unrealcmd.Opt("", "Comma-separated names of additional projects to sync")
clobber = unrealcmd.Opt(False, "Clobber writable files when syncing")
nosummary = unrealcmd.Opt(False, "Do not print the result-time summary at the end")
echo = unrealcmd.Opt(False, "Echo depot paths as they are synced")
def complete_addprojs(self, prefix):
# Fake a _local_root
local_root = Path(os.getcwd())
for parent in local_root.parents:
if (parent / "GenerateProjectFiles.bat").is_file():
local_root = parent
break
self._local_root = local_root
# Now we can fetch an approximate context and list it's projects
ue_context = self._try_get_unreal_context()
if not ue_context:
return
branch = ue_context.get_branch()
if not branch:
return
return (x.stem for x in branch.read_projects())
@unrealcmd.Cmd.summarise
def _main_summarised(self):
return self._main_impl()
def main(self):
self._client_spec_restore = None
try:
if self.args.nosummary:
return self._main_impl()
else:
return self._main_summarised()
finally:
try:
if self._client_spec_restore:
print("Restoring client spec")
client_spec = self._client_spec_restore
client_spec["Options"] = client_spec["Options"].replace("clobber", "noclobber")
client_spec["Description"] = client_spec["Description"].replace("{ushell_clobber_patch}", "")
P4.client(i=True).run(input_data=client_spec)
except:
pass
def _setup(self):
self.print_info("Perforce environment")
# Check there's a valid Perforce environment.
username = p4utils.login()
if not p4utils.ensure_p4config():
self.print_warning("Unable to establish a P4CONFIG")
# Get some info about the Perforce environment and show it to the user
info = P4.info().run()
print("Client:", info.clientName)
print(" User:", info.userName)
print("Server:", getattr(info, "proxyAddress", info.serverAddress))
# Inform the user if Perforce didn't find the client.
if info.clientName == "*unknown*":
client_name = p4utils.get_p4_set("P4CLIENT")
_, p4config_name = p4utils.has_p4config(".")
raise EnvironmentError(f"Client '{client_name}' not found. Please check P4CLIENT setting in '{p4config_name}'")
# So that P4.where can succeed we sync one known file first. This also
# ensures we can accomodate an unsynced stream switch.
for x in P4.sync(f"//{info.clientName}/GenerateProjectFiles.bat").read(on_error=False):
pass
# Find the root of the current branch
self.print_info("Discovering branch root")
branch_root = p4utils.get_branch_root(f"//{info.clientName}/project/")
print("Branch root:", branch_root)
# Map branch root somewhere on the local file system
local_root = P4.where(branch_root + "X").path
local_root = local_root[:-1] # to strip 'X'
print("Local root:", local_root)
self._info = info
self._branch_root = branch_root
self._local_root = local_root
def _try_get_unreal_context(self):
try:
ue_context = self.get_unreal_context()
branch = ue_context.get_branch()
# If branch doesn't match os.getcwd() then ditch it
if not (branch and branch.get_dir().samefile(self._local_root)):
raise EnvironmentError
except EnvironmentError:
try:
cwd = os.getcwd()
ue_context = unreal.Context(cwd)
except EnvironmentError:
ue_context = None
return ue_context
def _add_paths(self, syncer):
# Add the set of paths that all syncs should include
syncer.add_path(self._local_root + "*")
syncer.add_path(self._local_root + "Engine/...")
templates = self._local_root + "Templates/..."
if P4.files(templates, m=1).run(on_error=lambda x: None) is not None:
syncer.add_path(templates)
# If we've a valid context by this point we can try and use it.
glob_for_projects = False
self._current_cl = 0
if ue_context := self._try_get_unreal_context():
project = ue_context.get_project()
if self.args.all or not project:
if branch := ue_context.get_branch():
project_count = 0
self.print_info("Syncing all known projects")
for uproj_path in branch.read_projects():
print(uproj_path.stem)
syncer.add_path(str(uproj_path.parent) + "/...")
project_count += 1
# If we have somehow managed to not find any projects then
# fallback to globbing for them.
if not project_count:
print("No projects found via .uprojectdirs")
print("Falling back to a glob")
glob_for_projects = True
else:
# By default the active project is synced
self.print_info("Single project sync")
print("Project:", project.get_name())
syncer.add_path(str(project.get_dir()) + "/...")
# Extra projects
if self.args.addprojs and not self.args.all:
add_projects = self.args.addprojs.replace("/", ",")
add_projects = (x.strip() for x in add_projects.split(","))
add_projects = {x for x in add_projects if x}
known_projects = list(ue_context.get_branch().read_projects())
known_projects = {x.stem.lower():x for x in known_projects}
self.print_info("Additional projects to sync;")
for add_project in add_projects:
print(add_project, ": ", sep="", end="")
add_project = add_project.lower()
if add_project not in known_projects:
print("not found")
continue
add_project = known_projects[add_project]
add_project = add_project.parent
syncer.add_path(str(add_project) + "/...")
print(add_project)
engine_info = ue_context.get_engine().get_info()
self._current_cl = engine_info.get("Changelist", 0)
else:
glob_for_projects = True
if glob_for_projects:
# There does not appear to be a fully formed branch so we will infer
# `--all` here on behalf of the user.
self.print_info("Syncing all projects by **/.uproject")
for uproj_path in Path(self._local_root).glob("**/*.uproject"):
print(uproj_path.stem)
syncer.add_path(str(uproj_path.parent) + "/...")
def _main_impl(self):
self._setup()
# Determine the changelist to sync
sync_cl = self.args.changelist
if sync_cl < 0:
sync_cl = int(P4.changes(self._branch_root + "...", m=1).change)
# Remove "noclobber" from the user's client spec
client = P4.client(o=True).run()
client_spec = client.as_dict()
client_spec.setdefault("Description", "")
if self.args.clobber:
self.print_info("Checking for 'noclobber'")
if "noclobber" in client_spec["Options"]:
client_spec["Options"] = client_spec["Options"].replace("noclobber", "clobber")
client_spec["Description"] += "{ushell_clobber_patch}"
self._client_spec_restore = client_spec.copy()
if not self.args.dryrun or True:
print(f"Patching {client.Client} with 'clobber'")
P4.client(i=True).run(input_data=client_spec)
else:
print("Clobbering is already active")
if not self._client_spec_restore:
if "{ushell_clobber_patch}" in client_spec["Description"]:
if "noclobber" not in client_spec["Options"]:
self._client_spec_restore = client_spec.copy()
# Add the paths we always want to sync
syncer = p4utils.Syncer()
self._add_paths(syncer)
# Load and parse the .p4sync.txt file
self._apply_p4sync_txt(syncer)
version_cl = 0
build_ver_path = self._local_root + "Engine/project/.version"
try:
# Special case to force sync Build.version. It can get easily modified
# without Perforce's knowledge, complicating the sync.
if not self.args.dryrun:
P4.sync(build_ver_path + "@" + str(sync_cl), qf=True).run(on_error=False)
# GO!
self.print_info("Scheduling sync")
print("Changelist:", sync_cl, f"(was {self._current_cl})")
print("Requesting... ", end="")
syncer.schedule(sync_cl)
self.print_info("Syncing")
ok = syncer.sync(dryrun=self.args.dryrun, echo=self.args.echo)
if self.args.dryrun or not ok:
return ok
# Sync succeeded, update cl for build.version even if something goes wrong with resolving
version_cl = sync_cl
# Auto-resolve on behalf of the user.
if not self.args.noresolve:
conflicts = set()
self.print_info("Resolving")
for item in P4.resolve(am=True).read(on_error=False):
path = getattr(item, "fromFile", None)
if not path:
continue
path = path[len(self._branch_root):]
if getattr(item, "how", None):
conflicts.remove(path)
print(path)
else:
conflicts.add(path)
for conflict in conflicts:
print(flow.cmd.text.light_red(conflict))
except KeyboardInterrupt:
print()
self.print_warning(f"Sync interrupted! Writing build.version to CL {version_cl}")
return False
finally:
# Record the synced changelist in Build.version
with open(build_ver_path, "r") as x:
lines = list(x.readlines())
import stat
build_ver_mode = os.stat(build_ver_path).st_mode
os.chmod(build_ver_path, build_ver_mode|stat.S_IWRITE)
with open(build_ver_path, "w") as x:
for line in lines:
if r'"Changelist"' in line:
line = line.split(":", 2)
line = line[0] + f": {version_cl},\n"
elif r'"BranchName"' in line:
line = "\t\"BranchName\": \"X\"\n"
line = line.replace("X", self._branch_root[:-1].replace("/", "+"))
x.write(line)
def _apply_p4sync_txt(self, syncer):
def impl(path):
print("Source:", os.path.normpath(path), end="")
try:
sync_config = open(path, "rt")
print()
except:
print(" ... not found")
return
def read_exclusions():
for line in map(str.strip, sync_config):
if line.startswith("-"): yield line[1:]
elif line.startswith("$-"): yield line[2:]
for i, line in enumerate(read_exclusions()):
view = None
if line.startswith("*."): view = ".../" + line
elif line.startswith("/"): view = line[1:]
elif line.startswith("..."): view = line
print(" %2d" % i, "exclude", end=" ")
if view and (view.count("/") or "/*." in view or view.startswith("*.")):
view = self._branch_root + view
syncer.add_exclude(view)
print(view)
else:
view = view or line
print(flow.cmd.text.light_yellow(view + " (ill-formed)"))
sync_config.close()
self.print_info("Applying .p4sync.txt")
for dir in (self.get_home_dir(), self._local_root):
impl(dir + ".p4sync.txt")
#-------------------------------------------------------------------------------
class Edit(_SyncBase):
""" Opens .p4sync.txt in an editor. The editor is selected from environment
variables P4EDITOR, GIT_EDITOR, and the system default editor. """
def main(self):
username = p4utils.login()
cwd = os.getcwd()
client = p4utils.get_client_from_dir(cwd, username)
if not client:
raise EnvironmentError(f"Unable to establish the clientspec from '{cwd}'")
_, root_dir = client
path = Path(root_dir) / ".p4sync.txt"
if not path.is_file():
with path.open("wt") as out:
self._write_p4sync_txt_header(out)
print("Editing", path)
self.edit_file(path)
|
import unreal
MEL = unreal.MaterialEditingLibrary
from pamux_unreal_tools.base.material_expression.material_expression_container_base import MaterialExpressionContainerBase
class MaterialBase(MaterialExpressionContainerBase):
def __init__(self, unrealAsset: unreal.Material):
super().__init__(unrealAsset,
MEL.create_material_expression,
MEL.delete_all_material_expressions,
MEL.layout_material_expressions,
True)
|
import unreal
al=unreal.EditorAssetLibrary
PM_Mapping=[
("Material'/project/.BogMyrtle_01_Billboard_Mat'",
"PhysicalMaterial'/project/.PM_Vegetation'")
]
for assetRef,pmRef in PM_Mapping:
a=al.load_asset(assetRef)
if not a:
print("fixup_assets.py: {} is not exist.".format(assetRef))
continue
pm=al.load_asset(pmRef)
a.set_editor_property('phys_material',pm)
print("Set phys_material {} on {}".format(pmRef, assetRef))
|
import unreal
import csv
# Path to the CSV file
file_path = "/project/.csv"
# Scale factor for MW to light intensity conversion
scale_factor = 10.0
# Function to create a point light in Unreal Engine
def create_point_light(location, intensity):
# Create a new point light actor
point_light = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.PointLight, location)
# Set the light intensity
point_light.set_editor_property('intensity', intensity)
return point_light
# Open the CSV file and read the data
with open(file_path, 'r') as csvfile:
csvreader = csv.reader(csvfile)
# Skip header row if there is one
next(csvreader)
for row in csvreader:
x, y, z, mw = map(float, row)
location = unreal.Vector(x, y, z)
intensity = mw * scale_factor
create_point_light(location, intensity)
|
import unreal
import importlib
import init_menu
importlib.reload(init_menu)
# ------------ create menu ---------------
if __name__ == '__main__':
init_menu.create_menu()
# ------------ lower idle GPU usage ------------
# (not to be 100%)
unreal.SystemLibrary.execute_console_command(None, "t.MaxFPS 30")
|
# 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()
|
'''
File: 00-main-CatDog_ImagePipeline.py
Author: John Smutny
Date: 03/project/
Description:
Singular file that is executed in an Unreal Engine 4.27 script terminal.
This script will create a class object that will perform various actions
to an UE Editor on the same thread as the UE Editor window and collect
screenshots. This script requires that various UE Assets be already
present in the Editor environment named 'Cat' or 'Dog' in the .uasset name.
The script will collect screenshots of various UE assets from various
CineCameraActor angles and output a .csv file of all images created as
well as what object is in the image based on the .uasset's filename.
cmd: python "< insert path to file>/04_ImagePipeline_01b_onefile.py"
Other Notes:
Please enter all user inputs at the bottom of this script. Such as...
- Desired camera angles
- Desired output path for the collected screenshots (output_path_to_images)
- Absolute file paths for all textures used in the collection.
'''
import os
from datetime import datetime
from math import pi, sin, cos
import unreal
#######################################################
#######################################################
#######################################################
def link_ue_objects():
LOC_POINTS = []
cat_actor_objs = []
dog_actor_objs = []
for y in actors:
name = y.get_name()
if name == "Main_Camera":
# Ensure that the camera Actor is selected for screenshots
cam = y
print("*** DEBUG: Found Camera actor")
if 'CENTER_POINT' == name:
CENTER_POINT = y
print("*** DEBUG: Found CENTER_POINT of the shot")
if 'LOC' in name:
LOC_POINTS.append(y)
print(f"*** DEBUG: Found actor location {name}")
if name == 'Sphere_Brush_StaticMesh':
sphere = y
print("*** DEBUG: Found Sphere object")
if name == 'Floor':
floor = y
print("*** DEBUG: Found Floor object")
if 'Cat' in name or 'cat' in name:
cat_actor_objs.append(y)
print(f"*** DEBUG: Found Cat actor {name}")
if 'Dog' in name:
dog_actor_objs.append(y)
print(f"*** DEBUG: Found Dog actor {name}")
if 'SunSky' in name:
sunsky = y
print(f"*** DEBUG: Found the SunSky actor")
print(f"Cats = {len(cat_actor_objs)}\tDogs = {len(dog_actor_objs)}")
poi_objs = cat_actor_objs + dog_actor_objs
actor_dic = {"level_editor": unreal.EditorLevelLibrary(),
"camera": cam,
"sunsky": sunsky,
"center_point": CENTER_POINT,
"model_locs": LOC_POINTS,
"points_of_interest_obj": poi_objs,
"sphere": sphere,
"floor": floor
}
return actor_dic
def check_user_inputted_UE_assets(material_paths,
material_params,
scene_presets):
for i in range(len(material_paths)):
obj = unreal.load_object(None, material_paths[i])
assert obj
mat_params = obj.get_editor_property("scalar_parameter_values")
mat_param_list = []
for i in range(len(mat_params)):
info = mat_params[i].get_editor_property("parameter_info")
mat_param_list.append(str(info.get_editor_property("name")))
for param in material_params:
if param not in mat_param_list:
raise Exception("*** ERROR: Double check specified Material "
"Instance. Did not find needed MATERIAL_PARAM "
f"{param}. Make sure {param} is in the Material "
"Instance .uasset file.")
for key in scene_presets.keys():
switches = scene_presets[key]
if len(switches) != len(material_params):
raise Exception("*** Error: update PRESET settings. Unequal "
f"dimension for setting index {key}")
#######################################################
def spherical_to_cartisen_deg(rho: int = 0.0,
alpha: float = 0.0,
phi: float = 0.0):
# Convert inputs to radians
alpha = alpha * pi/180
phi = phi * pi/180
# Convert Spherical coordinates to cartesian
x = rho * sin(phi) * cos(alpha)
y = rho * sin(phi) * sin(alpha)
z = rho * cos(phi)
x = round(x, 2)
y = round(y, 2)
z = round(z, 2)
return x, y, z
#######################################################
#######################################################
#######################################################
class MoveCamera(object):
def __init__(self, ue_objs: dict, cam_home, output_path_of_run: str):
# Threading setup
self.in_progress = False
self.frame_count = 0
self.frame_buffer = -1
self.max_frame_count = -1
self.action_count = 0
self.num_actions = -1
self.slate_post_tick_handle = None
# Definition of the class's state-machine
self._state = {"set_new_model": True,
"set_new_scene": False,
"get_snapshots": False,
"shift_to_new_model": False,
"end_of_models_terminate_early": False}
###########
# UE Editor controls
self.editor = ue_objs["level_editor"]
# Camera setup
self.camera_obj = ue_objs["camera"]
self.cam_scene = self.camera_obj.scene_component
self.cam_home = unreal.Vector(x=cam_home[0],
y=cam_home[1],
z=cam_home[2])
# SunSky actor setup
# Properties: TimeZone, SolarTime
self.sunsky = ue_objs["sunsky"]
self.sun_time = None
# Point of Interest for the camera to focus on
self.poi_loc_cp = ue_objs["center_point"]
self.poi_loc_ss = ue_objs["model_locs"]
self.poi_objs = ue_objs["points_of_interest_obj"]
# Scene components
self.material_paths = None
self.material_params = None
self.scene_presets = None
##############
# Output and Debug information
self.debug_current_poi = 0
self.debug_current_angle = 0
self.debug_current_scene = 0
self.debug_current_sun = 0
self.output_path = output_path_of_run
self.log_img_str = "abs_filepath,class\n"
#######################################################
# Setter & Getter methods
#######################################################
def get_status(self):
return self.in_progress
def set_max_frames(self, num_frames):
self.max_frame_count = num_frames
def set_frame_buffer(self, num):
self.frame_buffer = num
def set_num_actions(self, num):
self.num_actions = num
def set_material_paths(self, paths):
self.material_paths = paths
def set_material_params(self, params):
self.material_params = params
def set_scene_presets(self, presets):
self.scene_presets = presets
def set_scene_sun_north_offset(self, north_offset):
self.sun_time = north_offset
#######################################################
# Methods for UE environment setup
#######################################################
def reset_model_locations(self, loc):
dest = loc
start_x = dest.static_mesh_component.relative_location.x
SPACING = 50
for poi in self.poi_objs:
dest_vect = unreal.Vector(
x=start_x,
y=dest.static_mesh_component.relative_location.y,
z=dest.static_mesh_component.relative_location.z)
poi.static_mesh_component.set_editor_property(
"relative_location",
dest_vect)
start_x = start_x + SPACING
unreal.log("*** DEBUG - Reset all model locations to START")
def set_environment(self):
'''
Method that will set the UE environment to a default state.
Specifically
1. setting the camera to the stored HOME coordinates
2. removing camera object tracking
3. resetting sunsky setting
4. resetting all UE models to the START location
5. resetting the internal class state-machine
6. resetting the various debug counts.
:return:
'''
unreal.log("::set_environment()")
# Set initial scene
self.set_scene(self.material_paths,
self.material_params,
self.debug_current_scene)
# Set initial camera location
self.teleport_camera_home(home=self.cam_home)
print(f"HOME Camera location: {self.cam_home}")
track_set = unreal.CameraLookatTrackingSettings(
enable_look_at_tracking=False)
self.camera_obj.set_editor_property("lookat_tracking_settings",
track_set)
# Set the sun lighting
solar_time = self.sun_time[0]
self.sunsky.set_editor_property("SolarTime", 15.0)
self.sunsky.set_editor_property("NorthOffset", solar_time)
# Reset the location of all of the models
self.reset_model_locations(self.poi_loc_ss[0])
# Reset class counts
self.frame_count = 0
self.action_count = 0
self._state["set_new_model"] = True
self._state["set_new_sun_time"] = False
self._state["set_new_scene"] = False
self._state["get_snapshots"] = False
self._state["shift_to_new_model"] = False
self._state["end_of_models_terminate_early"] = False
self.debug_current_poi = 0
self.debug_current_angle = 0
self.debug_current_scene = 0
self.debug_current_sun = 0
#######################################################
# Test Sequences
#######################################################
def start(self, seq: int):
'''
Trigger to begin the screenshot sequence. If the class is set
correctly then a 'tick_callback' interrupt will be created to be
executed on the same thread as the UE Editor (this is on the SAME
thread, not a parallel thread).
:param seq: User specified input as too which sequence to start.
:return:
'''
self.editor.clear_actor_selection_set()
self.editor.set_selected_level_actors([self.camera_obj])
if self.max_frame_count == -1:
raise Exception("ERROR: please set the maximum allowed frame "
"count of this script. Run the MoveCamera class "
"method ... set_max_frames()")
if self.frame_buffer == -1:
raise Exception("ERROR: please set the buffer between actions. "
"The frame buffer allows for adequete time for "
"the UE Editor to update before performing the "
"next script action. If not enough time is "
"allowed, actions will be skipped. Please run the "
"MoveCamera class method ... set_frame_buffer()"
"\n- A good buffer could start at 30")
if self.num_actions == -1:
raise Exception("ERROR: please set the number of expected actions "
"to be performed by this script. Please run the "
"MoveCamera class method ... set_num_actions()")
if self.frame_count != 0:
print("Please wait until first call is done.")
else:
# Create output for run
self.create_output_dir(self.output_path)
if seq == 1:
unreal.log("*** DEBUG: Registering ::tick_01 callback")
self.frame_count = 0
self.slate_post_tick_handle = \
unreal.register_slate_post_tick_callback(self.tick_01)
self.in_progress = True
def tick_01(self, delta_time: float):
'''
This method runs every UE 'tick_callback'. Every tick, the script
checks if the callback should stop (the end of an action sequence) or
continue.
:param delta_time: Not used
:return: NA
'''
# Potentially end the thread
terminate = False
if self.frame_count >= self.max_frame_count:
unreal.log_error("<<<<< Hit max_frame_count. Terminating <<<<<<")
terminate = True
elif self.action_count >= self.num_actions:
unreal.log_error("<<<<< Hit max_num_actions. Terminating <<<<<<")
terminate = True
#######################################################
# Perform Actions at ticks
#######################################################
# 1) Reset at end of actions or as a protective measure
if terminate:
self.set_environment()
self.output_image_csv(path=f"{self.output_path}/{self.output_dir}",
filename="synth-cats_dogs.csv")
# Reset before the end of the thread
self.teleport_camera_home(home=self.cam_home)
self.action_count += 1
unreal.log("Unregister callback")
unreal.unregister_slate_post_tick_callback(
self.slate_post_tick_handle)
self.in_progress = False
# 2) Perform action sequence
elif self.action_count < self.num_actions:
# Only execute actions every 'frame_buffer' frames
if self.frame_count % self.frame_buffer == 0:
try:
terminate = self.run_image_seq1(self.action_count)
except Exception:
unreal.log_error("CAUGHT ERROR: "
f"poi {self.debug_current_poi}, "
f"cam {self.debug_current_angle}, "
f"scene {self.debug_current_scene}, "
f"sun {self.debug_current_sun}")
unreal.log("Unregister callback")
unreal.unregister_slate_post_tick_callback(
self.slate_post_tick_handle)
terminate = True
if terminate:
self.action_count = self.num_actions
self.frame_count += 1
def run_image_seq1(self, screenshot_num):
'''
This is the main action sequence in the image gathering script.
While the script meets all non-terminate conditions, the script will
cycle through the established class state-machine. Thus iterating
through all available options of model, sunsky lighting,
scene preset, and camera angle. After every change, a screenshot is
taken.
Changes occur on a semi-separate thread from the UE4 editor every
processor 'tick'. Every 'tick' a different change occurs so that a
screenshot of every combination of differences can be captured in a
different image.
General State-Machine process
*** Screenshots of all specified angles are taken after each step
1. Move new object to the center of the background stage
2. Change skysun lighting
3. Move object to the END POINT. Check if gone through all models
- If Yes, then change scene preset and repeat step 1.
- If no, then begin at step 1.
:param screenshot_num: used to keep track of how many screen shots
have already been taken
:return: NA - however, several .png screenshots are taken
'''
print(f"---- Performing Action {screenshot_num}")
print(f"*** DEBUG: debug #s: {self.debug_current_poi}/"
f"{self.debug_current_angle}/{self.debug_current_scene}/"
f"{self.debug_current_sun}")
end_of_models_terminate_early = False
if self._state["set_new_model"]:
# Move a new object to the center of the stage
print("*** STATE: set_new_model")
# Move new model to CENTER_POINT
poi = self.poi_objs[self.debug_current_poi]
self.set_obj_loc(poi, self.poi_loc_cp)
# Set camera to focus on the target
self.set_camera_tracking(poi)
self._state["set_new_model"] = False
self._state["get_snapshots"] = True
elif self._state["get_snapshots"]:
# Collect all images specified in angle inputs
# Move Camera
self.step_camera_rotation_seq()
# Log the image
image_name, label = self.create_image_name(
action_num=screenshot_num,
model_num=self.debug_current_poi,
scene_num=self.debug_current_scene,
lighting_num=self.debug_current_sun,
angle_num=self.debug_current_angle)
abs_filepath = f"{self.output_path}/{self.output_dir}/" \
f"images/{image_name}"
self.log_image(abs_filepath=abs_filepath, label=label)
# Take a screenshot
self.take_HighResShot2(abs_filepath=abs_filepath)
self.action_count += 1
if self.debug_current_angle == len(self.ss_cam_locs):
self.debug_current_angle = 0
self._state["get_snapshots"] = False
self._state["set_new_sun_time"] = True
elif self._state["set_new_sun_time"]:
# Change the SunSky lighting
print("*** STATE: set_new_sun_time")
# Iterate the current sun time setting to cycle scene lighting
self.debug_current_sun = self.debug_current_sun + 1
# Only iterate if a setting has not been executed
if self.debug_current_sun < len(self.sun_time):
solar_time = self.sun_time[self.debug_current_sun]
self.sunsky.set_editor_property("NorthOffset", solar_time)
self._state["set_new_sun_time"] = False
self._state["get_snapshots"] = True
else:
self.debug_current_sun = 0
solar_time = self.sun_time[self.debug_current_sun]
self.sunsky.set_editor_property("NorthOffset", solar_time)
self._state["set_new_sun_time"] = False
self._state["shift_to_new_model"] = True
elif self._state["set_new_scene"]:
# Change the preset texture multiplexers to cycle to the next
# preset background, floor, and scene
unreal.log_warning("*** STATE: set_new_scene")
self.debug_current_scene = self.debug_current_scene + 1
self.set_scene(self.material_paths,
self.material_params,
self.debug_current_scene)
self._state["set_new_scene"] = False
self._state["set_new_model"] = True
elif self._state["shift_to_new_model"]:
# Cycle the model used at the center of the stage.
print("*** STATE: shift_to_new_model")
# Decide next action based on how many models are used
# 1) Gone through all models, terminate sequence
# 2) or Move onto the next model, repeat sequence
# 3) or Set a new scene, repeat sequence from first model
if self.debug_current_poi == len(self.poi_objs)\
and self.debug_current_scene == len(self.scene_presets):
self._state["shift_to_new_model"] = False
self._state["end_of_models_terminate_early"] = True
elif self.debug_current_poi < len(self.poi_objs)-1:
# Move current model out of the CENTER POINT
self.set_obj_loc(self.poi_objs[self.debug_current_poi],
self.poi_loc_ss[1])
self.debug_current_poi = self.debug_current_poi + 1
self._state["shift_to_new_model"] = False
self._state["set_new_model"] = True
else:
print("*** DEBUG: attempt to set new scene")
# Move current model out of the CENTER POINT
self.set_obj_loc(self.poi_objs[-1],
self.poi_loc_ss[1])
self.debug_current_poi = 0
# Change Scene
self._state["shift_to_new_model"] = False
self._state["set_new_scene"] = True
elif self._state["end_of_models_terminate_early"]:
end_of_models_terminate_early = True
return end_of_models_terminate_early
#######################################################
# CineCameraActor Methods
#######################################################
def take_HighResShot2(self, abs_filepath):
cmd = f"HighResShot 2 filename=\"{abs_filepath}\""
unreal.SystemLibrary.execute_console_command(
self.editor.get_editor_world(), cmd)
def teleport_camera(self, _x, _y, _z):
'''
Move the camera to the desired cartesian [x, y, z] location.
'''
self.cam_scene.set_relative_location(new_location=[_x, _y, _z],
sweep=False,
teleport=True)
self.cam_scene.set_relative_rotation(new_rotation=[0, 0, 0],
sweep=False,
teleport=True)
# REF: current_loc = self.cam_scene.relative_location
def teleport_camera_home(self, home):
self.teleport_camera(_x=home.x,
_y=home.y,
_z=home.z)
def set_camera_tracking(self, poi_obj):
'''
Set the camera actor to focus at the center point of a particular UE
asset.
:param poi_obj: UE asset that the camera should follow
:return: NA
'''
track_set = unreal.CameraLookatTrackingSettings(
enable_look_at_tracking=True,
actor_to_track=poi_obj,
relative_offset=unreal.Vector(z=50.0))
self.camera_obj.set_editor_property("lookat_tracking_settings",
track_set)
def rotate_camera(self, roll, pitch, yaw):
'''
Rotate the camera as desired if the CameraLookatTrackingSettings is
not enabled. Method will not function if CameraLookatTrackingSettings
is enabled, instead the camera's pitch and yaw will adjust to the
tracked target
(For most cases, there will be 0.0 roll)
'''
pitch = pitch
yaw = yaw
rot = unreal.Rotator(roll=roll, pitch=pitch, yaw=yaw)
self.cam_scene.set_relative_rotation(new_rotation=rot,
sweep=False,
teleport=True)
# REF: current_rot = self.cam_scene.relative_rotation
def step_camera_rotation_seq(self):
'''
Move the camera to the next cartesian location calculated by
the ::calc_cam_cartesian_locs() method.
Rotates the camera in a spherical orbit around an object of Importance.
Every position will take a screenshot.
User defines the locations by giving a list of spherical coordinates
(rho, alpha, phi) that the camera should go too.
'''
if len(self.ss_cam_locs) == 0 or len(self.ss_cam_angles) == 0:
raise Exception("ERROR: Need to calculate camera rotation angels.")
seq_pos = self.debug_current_angle
print(f"---- Performing Camera Action {seq_pos}")
try:
unreal.log(f"*** Rotation seq #{seq_pos}")
cam_loc = self.ss_cam_locs[seq_pos]
cam_rot = self.ss_cam_angles[seq_pos]
# unreal.log(f"*** DEBUG: location = "
# f"{cam_loc[0]}/{cam_loc[1]}/{cam_loc[2]}")
# unreal.log(f"*** DEBUG: angle = {cam_rot}")
self.teleport_camera(_x=cam_loc[0],
_y=cam_loc[1],
_z=cam_loc[2])
self.rotate_camera(roll=cam_rot["roll"],
pitch=cam_rot["pitch"],
yaw=cam_rot["yaw"])
# # Take a screenshot
# self.take_HighResShot2()
self.debug_current_angle = self.debug_current_angle + 1
except IndexError:
unreal.log_warning(f"*** WARN: Attempting too many camera "
f"rotations {self.debug_current_angle}. "
f"Only {len(self.ss_cam_locs)} camera locations are "
f"specified.")
def calc_cam_cartesian_locs(self,
range_rho: list,
range_alpha: list,
range_phi: list):
'''
Method that will calculate the equivalent cartesian coordinates for
the various combinations of camera angles desired (that are in
spherical coordinates).
:param range_rho: list of radial distances the camera should be
from the object
:param range_alpha: list of xy axis angles the camera should be
:param range_phi: list of z-axis angles the camera should be
:return: sets a class list of camera locations
'''
end_cam_locs = []
end_cam_angles = []
for r in range_rho:
for phi in range_phi:
for alpha in range_alpha:
x, y, z = spherical_to_cartisen_deg(rho=r,
alpha=alpha,
phi=phi)
end_cam_locs.append([x, y, z])
end_cam_angles.append({'roll': 0.0,
'pitch': phi,
'yaw': alpha})
if len(end_cam_locs) > 0:
unreal.log_warning("::calc_cam_cartesian_locs() - Camera "
"rotation locations set.")
self.ss_cam_locs = end_cam_locs
else:
unreal.log_error("::calc_cam_cartesian_locs() - WARN: Camera "
"rotations not set!!!!")
self.ss_cam_locs = None
if len(end_cam_angles) > 0:
unreal.log_warning("::calc_cam_cartesian_locs() - Camera "
"rotation angles set.")
self.ss_cam_angles = end_cam_angles
else:
unreal.log_error("::calc_cam_cartesian_locs() - Camera "
"rotations not set!!!!")
self.ss_cam_angles = None
#######################################################
# Object Actor Methods
#######################################################
def set_obj_loc(self, poi_obj, new_loc):
dest_vect = unreal.Vector(
x=new_loc.static_mesh_component.relative_location.x,
y=new_loc.static_mesh_component.relative_location.y,
z=new_loc.static_mesh_component.relative_location.z)
poi_obj.static_mesh_component.set_editor_property("relative_location",
dest_vect)
#######################################################
# Object Material Methods
#######################################################
def set_scene(self, material_paths, material_params, scene_num: int):
# Get the scene settings
key = list(self.scene_presets.keys())[scene_num]
print(f"key: {key} --- num: {scene_num}")
try:
settings = self.scene_presets[key]
except Exception:
unreal.log_error("--- ERROR: Expecting settings to have key "
f"{key}")
return 0
try:
for i in range(len(material_paths)):
for j in range(len(material_params)):
# Set scene
material = material_paths[i]
param = material_params[j]
self.set_param(material, param, settings[j])
self.sunsky.set_editor_property("SolarTime",
self.sun_lighting[self.debug_current_sun])
except Exception:
unreal.log_error("--- ERROR: Tried accessing an undeclared "
f"scene_preset. Current settings = {settings}")
return 0
def set_param(self, mat_path, param_name: str, val: float):
obj = unreal.load_object(None, mat_path)
assert obj
# Set material parameter using MaterialEditingLibrary() methods
editor = unreal.MaterialEditingLibrary()
editor.set_material_instance_scalar_parameter_value(obj, param_name, val)
#######################################################
# log images
#######################################################
def create_output_dir(self, path):
now = datetime.now()
start = now.strftime("%Y_%m_%d-%H_%M_%S")
new_dir = start+"-pipeline"
try:
os.mkdir(f"{path}/{new_dir}")
self.output_dir = new_dir
except OSError as error:
print(error)
def create_image_name(self, action_num,
model_num, scene_num, lighting_num, angle_num):
'''
Method that will design a string for each unique screenshot name.
:return: str - the unique image name
'''
try:
label = "cat" if "Cat" in self.poi_objs[model_num].get_name() \
else "dog"
debug_msg = f"{scene_num}_{model_num}_" \
f"{lighting_num}_{angle_num}"
except Exception:
unreal.log_error("*** ERROR: issue in ::create_image_name().")
image_name = f"{label}_{action_num}-{debug_msg}.png"
return image_name, label
def log_image(self, abs_filepath, label):
'''
Method that will append a string that records all images taken via a
pair {image, label of image}
:param abs_filepath: full path of where the image is
:param label: what is in the image
:return: NA
'''
self.log_img_str = self.log_img_str + f"{abs_filepath},{label}\n"
def output_image_csv(self, path, filename):
'''
Method that will create .csv file log of all taken image screenshots.
:param path: location of the eventual csv
:param filename: name of the eventual csv
:return: creates a csv at the specified path+filename of all taken
images.
'''
try:
f = open(f"{path}/{filename}", "w")
f.write(self.log_img_str)
f.close()
unreal.log_warning(f"Write csv file to {path}")
except NameError:
print(f"**** WARN: Dataframes to {path} was not defined")
#######################################################
#######################################################
#######################################################
if __name__=="__main__":
############################
# User defined Unreal Assets
HOME_PATH = '/project/'
MATERIAL_PATHS = [
HOME_PATH + 'background_select_Mat_Inst.background_select_Mat_Inst',
HOME_PATH + 'scene_select_Mat_Inst.scene_select_Mat_Inst',
HOME_PATH + 'floor_select_Mat_Inst.floor_select_Mat_Inst'
]
SCENE_PRESETS = {
# Multiplexer decoding of material instance parameters to select a texture.
# Switch values are based on LERP nodes, not switches.
# Values must be 0.0 or 1.0
"leaves": [0, 0, 0, 0, 0],
"forest": [1, 0, 0, 0, 0],
"interior01": [0, 0, 1, 0, 0],
"grassland": [0, 1, 1, 0, 0],
"interior02": [0, 0, 0, 0, 1],
"mountain": [0, 0, 0, 1, 1]
}
MATERIAL_PARAMS = ['sw_1a', 'sw_1b', 'sw_2', 'sw_1c', 'sw_3']
# Checks
check_user_inputted_UE_assets(MATERIAL_PATHS,
MATERIAL_PARAMS,
SCENE_PRESETS)
############################
# Operational settings
output_path_to_images = "..\\_data\\cat_dog\\synth"
CAM_HOME = [0, -300, 200]
FRAME_BUFFER = 30
#####
# Valid settings for image collection (in Degrees)
# SUN_NORTH_OFFSET = [ 75 --> 190 ]
# Rho = [ 100 --> 400 ]
# alpha = [ -180 --> 0 ]
# phi = [ 0 --> 90 ]
#
# NOTE:
# Unlit mode
# https://docs.unrealengine.com/4.27/en-US/project/.html?highlight=unlit
SUN_NORTH_OFFSET = [ 190 ]
RANGE_RHO = [200, 240, 290 ]
RANGE_ALPHA = [-140, -105, -95, -85, -75, -55]
RANGE_PHI = [45, 55, 65, 80]
#######################################################
#######################################################
#######################################################
#######################################################
# Start of MAIN()
#######################################################
home_path = HOME_PATH
material_paths = MATERIAL_PATHS
material_params = MATERIAL_PARAMS
#####
# Code to print out all or specific actors in a loaded level
actors = unreal.EditorLevelLibrary().get_all_level_actors()
actor_dic = link_ue_objects()
cam_home = CAM_HOME
test1 = MoveCamera(ue_objs=actor_dic,
cam_home=cam_home,
output_path_of_run=output_path_to_images)
####################################################
# Define test parameters
####################################################
range_rho = RANGE_RHO
range_alpha = RANGE_ALPHA
range_phi = RANGE_PHI
test1.calc_cam_cartesian_locs(range_rho=range_rho,
range_alpha=range_alpha,
range_phi=range_phi)
num_models = len(actor_dic["points_of_interest_obj"])
num_angles = len(range_rho)*len(range_alpha)*len(range_phi)
num_actions = num_models * num_angles * len(SCENE_PRESETS.keys()) * \
len(SUN_NORTH_OFFSET)
num_frames = num_actions * FRAME_BUFFER * 5.0
test1.set_max_frames(num_frames)
test1.set_frame_buffer(FRAME_BUFFER)
test1.set_num_actions(num_actions)
test1.set_material_paths(material_paths)
test1.set_material_params(material_params)
test1.set_scene_presets(SCENE_PRESETS)
test1.set_scene_sun_north_offset(SUN_NORTH_OFFSET)
####################################################
# Execute test for each preset
####################################################
unreal.log_warning("----- START TEST ------")
test1.set_environment()
test1.start(1)
unreal.log_warning("*** DEBUG: PRESET COMPLETE!!!")
|
"""
UEMCP Level Operations - All level and project-related operations
"""
import unreal
from utils import get_all_actors, get_project_info
# Enhanced error handling framework
from utils.error_handling import ProcessingError, TypeRule, handle_unreal_errors, safe_operation, validate_inputs
class LevelOperations:
"""Handles all level and project-related operations."""
@handle_unreal_errors("save_level")
@safe_operation("level")
def save_level(self):
"""Save the current level.
Returns:
dict: Result with success status
Raises:
ProcessingError: If level save operation fails
"""
success = unreal.EditorLevelLibrary.save_current_level()
if not success:
raise ProcessingError("Failed to save level")
return {"message": "Level saved successfully"}
@handle_unreal_errors("get_project_info")
@safe_operation("level")
def get_project_info(self):
"""Get information about the current project.
Returns:
dict: Project information
"""
info = get_project_info()
return info
@validate_inputs({"filter": [TypeRule(str, allow_none=True)], "limit": [TypeRule(int)]})
@handle_unreal_errors("get_level_actors")
@safe_operation("level")
def get_level_actors(self, filter=None, limit=30):
"""Get all actors in the current level.
Args:
filter: Optional text to filter actors
limit: Maximum number of actors to return
Returns:
dict: List of actors with properties
"""
actors = get_all_actors(filter_text=filter, limit=limit)
# Count total actors
editor_actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
all_actors = editor_actor_subsystem.get_all_level_actors()
if filter:
# Count filtered actors
filter_lower = filter.lower()
total_count = sum(
1
for actor in all_actors
if actor
and hasattr(actor, "get_actor_label")
and (
filter_lower in actor.get_actor_label().lower()
or filter_lower in actor.get_class().get_name().lower()
)
)
else:
total_count = len([a for a in all_actors if a and hasattr(a, "get_actor_label")])
return {
"actors": actors,
"totalCount": total_count,
"currentLevel": unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem).get_editor_world().get_name(),
}
@validate_inputs({"showEmpty": [TypeRule(bool)], "maxDepth": [TypeRule(int)]})
@handle_unreal_errors("get_outliner_structure")
@safe_operation("level")
def get_outliner_structure(self, showEmpty=False, maxDepth=10):
"""Get the World Outliner folder structure.
Args:
showEmpty: Whether to show empty folders
maxDepth: Maximum folder depth to display
Returns:
dict: Outliner structure
"""
# Get all actors
editor_actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
all_actors = editor_actor_subsystem.get_all_level_actors()
# Build folder structure
folder_structure, unorganized_actors, organized_count = self._build_folder_structure(all_actors, maxDepth)
# Sort all actors
self._sort_folder_actors(folder_structure)
unorganized_actors.sort()
# Remove empty folders if requested
if not showEmpty:
self._remove_empty_folders(folder_structure)
# Count total folders
total_folders = self._count_folders(folder_structure)
return {
"outliner": {
"folders": folder_structure,
"unorganized": unorganized_actors,
"stats": {
"totalActors": len(all_actors),
"organizedActors": organized_count,
"unorganizedActors": len(unorganized_actors),
"totalFolders": total_folders,
},
},
}
def _build_folder_structure(self, all_actors, maxDepth):
"""Build the folder structure from actors.
Args:
all_actors: List of all actors
maxDepth: Maximum folder depth
Returns:
tuple: (folder_structure, unorganized_actors, organized_count)
"""
folder_structure = {}
unorganized_actors = []
organized_count = 0
for actor in all_actors:
if not self._is_valid_actor(actor):
continue
actor_label = actor.get_actor_label()
folder_path = actor.get_folder_path()
if folder_path:
organized_count += 1
self._add_actor_to_folder_structure(folder_structure, actor_label, str(folder_path), maxDepth)
else:
unorganized_actors.append(actor_label)
return folder_structure, unorganized_actors, organized_count
def _is_valid_actor(self, actor):
"""Check if actor is valid for processing.
Args:
actor: Actor to check
Returns:
bool: True if valid
"""
return actor is not None and hasattr(actor, "get_actor_label")
def _add_actor_to_folder_structure(self, folder_structure, actor_label, folder_path_str, maxDepth):
"""Add an actor to the folder structure.
Args:
folder_structure: The folder structure dictionary
actor_label: Label of the actor
folder_path_str: Folder path as string
maxDepth: Maximum folder depth
"""
parts = folder_path_str.split("/")
current = folder_structure
for i, part in enumerate(parts):
if i >= maxDepth:
break
if part not in current:
current[part] = {"actors": [], "subfolders": {}}
# If this is the last part, add the actor
if i == len(parts) - 1:
current[part]["actors"].append(actor_label)
# Move to subfolder for next iteration
current = current[part]["subfolders"]
def _sort_folder_actors(self, folder_dict):
"""Recursively sort actors in all folders.
Args:
folder_dict: Folder dictionary to sort
"""
for _folder_name, folder_data in folder_dict.items():
if "actors" in folder_data:
folder_data["actors"].sort()
if "subfolders" in folder_data:
self._sort_folder_actors(folder_data["subfolders"])
def _remove_empty_folders(self, folder_dict):
"""Recursively remove empty folders.
Args:
folder_dict: Folder dictionary to clean
"""
to_remove = []
for folder_name, folder_data in folder_dict.items():
# Recursively clean subfolders
if "subfolders" in folder_data:
self._remove_empty_folders(folder_data["subfolders"])
# Check if this folder is empty
if self._is_folder_empty(folder_data):
to_remove.append(folder_name)
# Remove empty folders
for folder_name in to_remove:
del folder_dict[folder_name]
def _is_folder_empty(self, folder_data):
"""Check if a folder is empty.
Args:
folder_data: Folder data dictionary
Returns:
bool: True if folder is empty
"""
has_actors = "actors" in folder_data and len(folder_data["actors"]) > 0
has_subfolders = "subfolders" in folder_data and len(folder_data["subfolders"]) > 0
return not has_actors and not has_subfolders
def _count_folders(self, folder_dict):
"""Recursively count total folders.
Args:
folder_dict: Folder dictionary to count
Returns:
int: Total folder count
"""
count = len(folder_dict)
for folder_data in folder_dict.values():
if "subfolders" in folder_data:
count += self._count_folders(folder_data["subfolders"])
return count
|
import unreal
editor_actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
actors = editor_actor_subsystem.get_all_level_actors()
for actor in actors:
actor_class_name = actor.get_class().get_name()
if actor_class_name.startswith("LandscapeStreamingProxy") or actor_class_name.startswith("LandscapeProxy"):
try:
if actor.has_editor_property("HLODLayer"):
actor.set_editor_property("HLODLayer", None)
unreal.log(f"HLODLayer cleared for {actor.get_name()}")
else:
unreal.log_warning(f"{actor.get_name()} has no HLODLayer property.")
except Exception as e:
unreal.log_warning(f"Failed to reset HLODLayer on {actor.get_name()}: {e}")
|
import unreal
@unreal.uclass()
class UEEditorUtility(unreal.GlobalEditorUtilityBase):
pass
EdUtil = UEEditorUtility()
selectedAssets = EdUtil.get_selected_assets()
for selectedAsset in selectedAssets:
selectedAssets.set_editor_property("BlueprintDisplayName", "Same BP")
selectedAssets.set_editor_property("BlueprintDescription", "This is a blueprint generated by Python or something")
selectedAssets.set_editor_property("BlueprintCategory", "Collectable")
selectedActors = EdUtil.get_selection_set()
for actor in selectedActors:
actor.set_editor_property("canRotate", True)
actor.set_editor_property("bHidden", 1)
actor.set_editor_property("SpriteScale", 2.5)
|
# Copyright 2018 Epic Games, Inc.
# Setup the asset in the turntable level for rendering
import unreal
import os
import sys
def main(argv):
# Import the FBX into Unreal using the unreal_importer script
current_folder = os.path.dirname( __file__ )
if current_folder not in sys.path:
sys.path.append(current_folder)
import unreal_importer
unreal_importer.main(argv[0:2])
fbx_file_path = argv[0]
content_browser_path = argv[1]
turntable_map_path = argv[2]
# Load the turntable map where to instantiate the imported asset
world = unreal.EditorLoadingAndSavingUtils.load_map(turntable_map_path)
if not world:
return
# Find the turntable actor, which is used in the turntable sequence that rotates it 360 degrees
turntable_actor = None
level_actors = unreal.EditorLevelLibrary.get_all_level_actors()
for level_actor in level_actors:
if level_actor.get_actor_label() == "turntable":
turntable_actor = level_actor
break
if not turntable_actor:
return
# Destroy any actors attached to the turntable (attached for a previous render)
for attached_actor in turntable_actor.get_attached_actors():
unreal.EditorLevelLibrary.destroy_actor(attached_actor)
# Derive the imported asset path from the given FBX filename and content browser path
fbx_filename = os.path.basename(fbx_file_path)
asset_name = os.path.splitext(fbx_filename)[0]
asset_path_to_load = content_browser_path + asset_name
# Load the asset to spawn it at origin
asset = unreal.EditorAssetLibrary.load_asset(asset_path_to_load)
if not asset:
return
actor = unreal.EditorLevelLibrary.spawn_actor_from_object(asset, unreal.Vector(0, 0, 0))
# Scale the actor to fit the frame, which is dependent on the settings of the camera used in the turntable sequence
# The scale values are based on a volume that fits safely in the frustum of the camera and account for the frame ratio
# and must be tweaked if the camera settings change
origin, bounds = actor.get_actor_bounds(True)
scale_x = 250 / min(bounds.x, bounds.y)
scale_y = 300 / max(bounds.x, bounds.y)
scale_z = 200 / bounds.z
scale = min(scale_x, scale_y, scale_z)
actor.set_actor_scale3d(unreal.Vector(scale, scale, scale))
# Offset the actor location so that it rotates around its center
origin = origin * scale
actor.set_actor_location(unreal.Vector(-origin.x, -origin.y, -origin.z), False, True)
# Attach the newly spawned actor to the turntable
actor.attach_to_actor(turntable_actor, "", unreal.AttachmentRule.KEEP_WORLD, unreal.AttachmentRule.KEEP_WORLD, unreal.AttachmentRule.KEEP_WORLD, False)
unreal.EditorLevelLibrary.save_current_level()
if __name__ == "__main__":
# Script arguments must be, in order:
# Path to FBX to import
# Unreal content browser path where to store the imported asset
# Unreal content browser path to the turntable map to duplicate and where to spawn the asset
argv = []
if 'UNREAL_SG_FBX_OUTPUT_PATH' in os.environ:
argv.append(os.environ['UNREAL_SG_FBX_OUTPUT_PATH'])
if 'UNREAL_SG_CONTENT_BROWSER_PATH' in os.environ:
argv.append(os.environ['UNREAL_SG_CONTENT_BROWSER_PATH'])
if 'UNREAL_SG_MAP_PATH' in os.environ:
argv.append(os.environ['UNREAL_SG_MAP_PATH'])
if len(argv) == 3:
main(argv)
|
#!-!-!-!-!-!-!-!-!-!-!-!-!-!-#
#####
######## IMPORTS
#####
import unreal
import sys
#ignore my bad structure and code pls. ty sorry.
######## EXIT IF VISAI NOT INSTALLED
#####
if not unreal.Paths.directory_exists(unreal.Paths.project_content_dir()+"Vis/AI"):
print('visai not found. exiting...')
sys.exit(101)
print('vis.py has started')
######## BUILT IN
#####
import os
######## VIS
#####
#import ai_test
try:
import ai_backups
except Exception as e:
print(str(e) + " | This is most likely due to first time start")
print('vis.py - modules imported')
#!-!-!-!-!-!-!-!-!-!-!-!-!-!-#
#####
######## VARIABLES
#####
#!-!-!-!-!-!-!-!-!-!-!-!-!-!-#
#####
######## FUNCTIONS
#####
#!-!-!-!-!-!-!-!-!-!-!-!-!-!-#
#####
######## THE APP
#####
print('vis.py has initialized')
|
import unreal
import re
ar_asset_lists = []
ar_asset_lists = unreal.EditorUtilityLibrary.get_selected_assets()
print (ar_asset_lists[0])
str_selected_asset = ''
if len(ar_asset_lists) > 0 :
str_selected_asset = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(ar_asset_lists[0])
#str_selected_asset = str(ar_asset_lists[0])
print(str_selected_asset)
ar_numbers = re.findall("\d+", str_selected_asset)
i_number = ar_numbers[0]
print(ar_numbers)
print(i_number)
|
import unreal
DO_FOR_ALL = False
if DO_FOR_ALL:
actors = unreal.EditorLevelLibrary.get_all_level_actors()
else:
actors = unreal.EditorLevelLibrary.get_selected_level_actors()
relative_offset = unreal.Vector(30000, 30000, -50000)
for actor in actors:
current_location = actor.get_actor_location()
actor.set_actor_location(current_location + relative_offset, False, False)
|
# Copyright (c) 2023 Max Planck Society
# License: https://bedlam.is.tuebingen.mpg.de/license.html
#
# Create level sequences for specified animations in be_seq.csv file
#
# Required plugins: Python Editor Script Plugin, Editor Scripting, Sequencer Scripting
#
import csv
from dataclasses import dataclass
import re
from math import radians, tan
import sys
import time
import unreal
# Globals
WARMUP_FRAMES = 10 # Needed for proper temporal sampling on frame 0 of animations and raytracing warmup. These frames are rendered out with negative numbers and will be deleted in post render pipeline.
data_root_unreal = "/project/"
clothing_actor_class_path = data_root_unreal + "Core/project/.BE_ClothingOverlayActor_C"
body_root = data_root_unreal + "SMPLX/"
hair_root = data_root_unreal + "Hair/project/"
animation_root = data_root_unreal + "SMPLX_batch01_hand_animations/"
hdri_root = data_root_unreal + "HDRI/4k/"
#hdri_suffix = "_8k"
hdri_suffix = ""
material_body_root = "/project/"
material_clothing_root = data_root_unreal + "Clothing/Materials"
texture_body_root = "/project/"
texture_clothing_overlay_root = data_root_unreal + "Clothing/project/"
material_hidden_name = data_root_unreal + "Core/project/"
bedlam_root = "/project/"
level_sequence_hdri_template = bedlam_root + "LS_Template_HDRI"
level_sequences_root = bedlam_root + "LevelSequences/"
camera_root = bedlam_root + "CameraMovement/"
csv_path = r"/project/.csv"
################################################################################
@dataclass
class SequenceBody:
subject: str
body_path: str
clothing_path: str
hair_path: str
animation_path: str
x: float
y: float
z: float
yaw: float
pitch: float
roll: float
start_frame: int
texture_body: str
texture_clothing: str
texture_clothing_overlay: str
@dataclass
class CameraPose:
x: float
y: float
z: float
yaw: float
pitch: float
roll: float
################################################################################
def add_geometry_cache(level_sequence, sequence_body_index, layer_suffix, start_frame, end_frame, target_object, x, y, z, yaw, pitch, roll, material=None, texture_body_path=None, texture_clothing_overlay_path=None):
"""
Add geometry cache to LevelSequence and setup material.
If material parameter is set then GeometryCacheActor will be spawned and the material will be used.
Otherwise a custom clothing actor (SMPLXClothingActor) will be spawned and the provided texture inputs will be used.
"""
# Spawned GeometryCaches will generate GeometryCacheActors where ManualTick is false by default.
# This will cause the animation to play before the animation section in the timeline and lead to temporal sampling errors
# on the first frame of the animation section.
# To prevent this we need to set ManualTick to true as default setting for the GeometryCacheActor.
# 1. Spawn default GeometryCacheActor template in level
# 2. Set default settings for GeometryCache and ManualTick on it
# 3. Add actor as spawnable to sequence
# 4. Destroy template actor in level
# Note: Conversion from possessable to spawnable currently not available in Python: https://forums.unrealengine.com/project/-to-spawnable-with-python/509827
if texture_clothing_overlay_path is not None:
# Use SMPL-X clothing overlay texture, dynamic material instance will be generated in BE_ClothingOverlayActor Construction Script
clothing_actor_class = unreal.load_class(None, clothing_actor_class_path)
geometry_cache_actor = unreal.get_editor_subsystem(unreal.EditorActorSubsystem).spawn_actor_from_class(clothing_actor_class, unreal.Vector(0,0,0))
geometry_cache_actor.set_editor_property("bodytexture", unreal.SystemLibrary.conv_soft_obj_path_to_soft_obj_ref(unreal.SoftObjectPath(texture_body_path)))
geometry_cache_actor.set_editor_property("clothingtextureoverlay", unreal.SystemLibrary.conv_soft_obj_path_to_soft_obj_ref(unreal.SoftObjectPath(texture_clothing_overlay_path)))
else:
geometry_cache_actor = unreal.get_editor_subsystem(unreal.EditorActorSubsystem).spawn_actor_from_class(unreal.GeometryCacheActor, unreal.Vector(0,0,0))
if material is not None:
geometry_cache_actor.get_geometry_cache_component().set_material(0, material)
geometry_cache_actor.set_actor_label(target_object.get_name())
geometry_cache_actor.get_geometry_cache_component().set_editor_property("looping", False) # disable looping to prevent ghosting on last frame with temporal sampling
geometry_cache_actor.get_geometry_cache_component().set_editor_property("manual_tick", True)
geometry_cache_actor.get_geometry_cache_component().set_editor_property("geometry_cache", target_object)
# Add actor to new layer so that we can later use layer name when generating segmentation masks names.
# Note: We cannot use ObjectIds of type "Actor" since actors which are added via add_spawnable_from_instance() will later use their class names when generating ObjectIds of type Actor.
layer_subsystem = unreal.get_editor_subsystem(unreal.LayersSubsystem)
layer_subsystem.add_actor_to_layer(geometry_cache_actor, f"be_actor_{sequence_body_index:02}_{layer_suffix}")
body_binding = level_sequence.add_spawnable_from_instance(geometry_cache_actor)
unreal.get_editor_subsystem(unreal.EditorActorSubsystem).destroy_actor(geometry_cache_actor) # Delete temporary template actor from level
geometry_cache_track = body_binding.add_track(unreal.MovieSceneGeometryCacheTrack)
geometry_cache_section = geometry_cache_track.add_section()
geometry_cache_section.set_range(start_frame, end_frame)
# TODO properly set Geometry Cache target in geometry_cache_section properties to have same behavior as manual setup
#
# Not working: geometry_cache_section.set_editor_property("GeometryCache", body_object)
# Exception: MovieSceneGeometryCacheTrack: Failed to find property 'GeometryCache' for attribute 'GeometryCache' on 'MovieSceneGeometryCacheTrack'
transform_track = body_binding.add_track(unreal.MovieScene3DTransformTrack)
transform_section = transform_track.add_section()
transform_section.set_start_frame_bounded(False)
transform_section.set_end_frame_bounded(False)
transform_channels = transform_section.get_channels()
transform_channels[0].set_default(x) # location X
transform_channels[1].set_default(y) # location Y
transform_channels[2].set_default(z) # location Z
transform_channels[3].set_default(roll) # roll
transform_channels[4].set_default(pitch) # pitch
transform_channels[5].set_default(yaw) # yaw
return
def add_hair(level_sequence, sequence_body_index, layer_suffix, start_frame, end_frame, hair_path, animation_path, x, y, z, yaw, pitch, roll,):
"""
Add hair attached to animation sequence to LevelSequence.
"""
unreal.log(f" Loading static hair mesh: {hair_path}")
hair_object = unreal.load_object(None, hair_path)
if hair_object is None:
unreal.log_error(" Cannot load mesh")
return False
unreal.log(f" Loading animation sequence: {animation_path}")
animsequence_object = unreal.load_asset(animation_path)
if animsequence_object is None:
unreal.log_error(" Cannot load animation sequence")
return False
# SkeletalMesh'/project/.rp_aaron_posed_002_1038'
animation_path_name = animation_path.split("/")[-1]
animation_path_root = animation_path.replace(animation_path_name, "")
skeletal_mesh_path = animation_path_root + animation_path_name.replace("_Anim", "")
unreal.log(f" Loading skeletal mesh: {skeletal_mesh_path}")
skeletal_mesh_object = unreal.load_asset(skeletal_mesh_path)
if skeletal_mesh_object is None:
unreal.log_error(" Cannot load skeletal mesh")
return False
skeletal_mesh_actor = unreal.get_editor_subsystem(unreal.EditorActorSubsystem).spawn_actor_from_class(unreal.SkeletalMeshActor, unreal.Vector(0,0,0))
skeletal_mesh_actor.set_actor_label(animsequence_object.get_name())
skeletal_mesh_actor.skeletal_mesh_component.set_skeletal_mesh(skeletal_mesh_object)
# Set hidden material to hide the skeletal mesh
material = unreal.EditorAssetLibrary.load_asset(f"Material'{material_hidden_name}'")
if not material:
unreal.log_error('Cannot load hidden material: ' + material_hidden_name)
skeletal_mesh_actor.skeletal_mesh_component.set_material(0, material)
hair_actor = unreal.get_editor_subsystem(unreal.EditorActorSubsystem).spawn_actor_from_class(unreal.StaticMeshActor, unreal.Vector(0,0,0))
hair_actor.set_actor_label(hair_object.get_name())
hair_actor.set_mobility(unreal.ComponentMobility.MOVABLE)
hair_actor.static_mesh_component.set_editor_property("static_mesh", hair_object)
# Add actor to new layer so that we can later use layer name when generating segmentation masks names.
# Note: We cannot use ObjectIds of type "Actor" since actors which are added via add_spawnable_from_instance() will later use their class names when generating ObjectIds of type Actor.
layer_subsystem = unreal.get_editor_subsystem(unreal.LayersSubsystem)
layer_subsystem.add_actor_to_layer(hair_actor, f"be_actor_{sequence_body_index:02}_{layer_suffix}")
# Setup LevelSequence
skeletal_mesh_actor_binding = level_sequence.add_spawnable_from_instance(skeletal_mesh_actor)
hair_actor_binding = level_sequence.add_spawnable_from_instance(hair_actor)
unreal.get_editor_subsystem(unreal.EditorActorSubsystem).destroy_actor(skeletal_mesh_actor) # Delete temporary template actor from level
unreal.get_editor_subsystem(unreal.EditorActorSubsystem).destroy_actor(hair_actor) # Delete temporary template actor from level
anim_track = skeletal_mesh_actor_binding.add_track(unreal.MovieSceneSkeletalAnimationTrack)
anim_section = anim_track.add_section()
anim_section.params.animation = animsequence_object
anim_section.set_range(start_frame, end_frame)
transform_track = skeletal_mesh_actor_binding.add_track(unreal.MovieScene3DTransformTrack)
transform_section = transform_track.add_section()
transform_section.set_start_frame_bounded(False)
transform_section.set_end_frame_bounded(False)
transform_channels = transform_section.get_channels()
transform_channels[0].set_default(x) # location X
transform_channels[1].set_default(y) # location Y
transform_channels[2].set_default(z) # location Z
transform_channels[3].set_default(roll) # roll
transform_channels[4].set_default(pitch) # pitch
transform_channels[5].set_default(yaw) # yaw
# Attach hair to animation
attach_track = hair_actor_binding.add_track(unreal.MovieScene3DAttachTrack)
attach_section = attach_track.add_section() # MovieScene3DAttachSection
animation_binding_id = unreal.MovieSceneObjectBindingID()
animation_binding_id.set_editor_property("Guid", skeletal_mesh_actor_binding.get_id())
attach_section.set_constraint_binding_id(animation_binding_id)
attach_section.set_editor_property("attach_socket_name", "head")
attach_section.set_range(start_frame, end_frame)
return True
def add_transform_track(binding, camera_pose):
transform_track = binding.add_track(unreal.MovieScene3DTransformTrack)
transform_section = transform_track.add_section()
transform_section.set_start_frame_bounded(False)
transform_section.set_end_frame_bounded(False)
transform_channels = transform_section.get_channels()
transform_channels[0].set_default(camera_pose.x) # location X
transform_channels[1].set_default(camera_pose.y) # location Y
transform_channels[2].set_default(camera_pose.z) # location Z
transform_channels[3].set_default(camera_pose.roll) # roll
transform_channels[4].set_default(camera_pose.pitch) # pitch
transform_channels[5].set_default(camera_pose.yaw) # yaw
return
def get_focal_length(cine_camera_component, camera_hfov):
sensor_width = cine_camera_component.filmback.sensor_width
focal_length = sensor_width / (2.0 * tan(radians(camera_hfov)/2))
return focal_length
def add_static_camera(level_sequence, camera_actor, camera_pose, camera_hfov):
"""
Add static camera actor and camera cut track to level sequence.
"""
# Add camera with transform track
camera_binding = level_sequence.add_possessable(camera_actor)
add_transform_track(camera_binding, camera_pose)
"""
transform_track = camera_binding.add_track(unreal.MovieScene3DTransformTrack)
transform_section = transform_track.add_section()
transform_section.set_start_frame_bounded(False)
transform_section.set_end_frame_bounded(False)
transform_channels = transform_section.get_channels()
transform_channels[0].set_default(camera_pose.x) # location X
transform_channels[1].set_default(camera_pose.y) # location Y
transform_channels[2].set_default(camera_pose.z) # location Z
transform_channels[3].set_default(camera_pose.roll) # roll
transform_channels[4].set_default(camera_pose.pitch) # pitch
transform_channels[5].set_default(camera_pose.yaw) # yaw
"""
if camera_hfov is not None:
# Add focal length CameraComponent track to match specified hfov
# Add a cine camera component binding using the component of the camera actor
cine_camera_component = camera_actor.get_cine_camera_component()
camera_component_binding = level_sequence.add_possessable(cine_camera_component)
camera_component_binding.set_parent(camera_binding)
# Add a focal length track and default it to 60
focal_length_track = camera_component_binding.add_track(unreal.MovieSceneFloatTrack)
focal_length_track.set_property_name_and_path('CurrentFocalLength', 'CurrentFocalLength')
focal_length_section = focal_length_track.add_section()
focal_length_section.set_start_frame_bounded(False)
focal_length_section.set_end_frame_bounded(False)
focal_length = get_focal_length(cine_camera_component, camera_hfov)
focal_length_section.get_channels()[0].set_default(focal_length)
camera_cut_track = level_sequence.add_master_track(unreal.MovieSceneCameraCutTrack)
camera_cut_section = camera_cut_track.add_section()
camera_cut_section.set_start_frame(-WARMUP_FRAMES) # Use negative frames as warmup frames
camera_binding_id = unreal.MovieSceneObjectBindingID()
camera_binding_id.set_editor_property("Guid", camera_binding.get_id())
camera_cut_section.set_editor_property("CameraBindingID", camera_binding_id)
return camera_cut_section
def change_binding_end_keyframe_times(binding, new_frame):
for track in binding.get_tracks():
for section in track.get_sections():
for channel in section.get_channels():
channel_keys = channel.get_keys()
if len(channel_keys) > 0:
if len(channel_keys) != 2: # only change end keyframe time if channel has two keyframes
unreal.log_error("WARNING: Channel does not have two keyframes. Not changing last keyframe to sequence end frame.")
else:
end_key = channel_keys[1]
end_key.set_time(unreal.FrameNumber(new_frame))
def add_level_sequence(name, camera_actor, camera_pose, ground_truth_logger_actor, sequence_bodies, sequence_frames, hdri_name, camera_hfov=None, camera_movement="Static", cameraroot_yaw=None, cameraroot_location=None):
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
level_sequence_path = level_sequences_root + name
# Check for existing LevelSequence and delete it to avoid message dialog when creating asset which exists
if unreal.EditorAssetLibrary.does_asset_exist(level_sequence_path):
unreal.log(" Deleting existing old LevelSequence: " + level_sequence_path)
unreal.EditorAssetLibrary.delete_asset(level_sequence_path)
# Generate LevelSequence, either via template (HDRI, camera movement) or from scratch
if hdri_name is not None:
# Duplicate template HDRI LevelSequence
if not unreal.EditorAssetLibrary.does_asset_exist(level_sequence_hdri_template):
unreal.log_error("Cannot find LevelSequence HDRI template: " + level_sequence_hdri_template)
return False
level_sequence = unreal.EditorAssetLibrary.duplicate_asset(level_sequence_hdri_template, level_sequence_path)
hdri_path = f"{hdri_root}{hdri_name}{hdri_suffix}"
unreal.log(f" Loading HDRI: {hdri_path}")
hdri_object = unreal.load_object(None, hdri_path)
if hdri_object is None:
unreal.log_error("Cannot load HDRI")
return False
# Set loaded HDRI as Skylight cubemap in sequencer
for binding in level_sequence.get_possessables():
binding_name = binding.get_name()
if (binding_name == "Skylight"):
for track in binding.get_tracks():
for section in track.get_sections():
for channel in section.get_channels():
channel.set_default(hdri_object)
elif camera_movement != "Static":
# Duplicate template camera LevelSequence
level_sequence_camera_template = f"{camera_root}LS_Camera_{camera_movement}"
if not unreal.EditorAssetLibrary.does_asset_exist(level_sequence_camera_template):
unreal.log_error("Cannot find LevelSequence camera template: " + level_sequence_camera_template)
return False
level_sequence = unreal.EditorAssetLibrary.duplicate_asset(level_sequence_camera_template, level_sequence_path)
else:
level_sequence = unreal.AssetTools.create_asset(asset_tools, asset_name = name, package_path = level_sequences_root, asset_class = unreal.LevelSequence, factory = unreal.LevelSequenceFactoryNew())
# Set frame rate to 30fps
frame_rate = unreal.FrameRate(numerator = 30, denominator = 1)
level_sequence.set_display_rate(frame_rate)
cameraroot_binding = None
if camera_movement == "Static":
# Create new camera
camera_cut_section = add_static_camera(level_sequence, camera_actor, camera_pose, camera_hfov)
else:
# Use existing camera from LevelSequence template
master_track = level_sequence.get_master_tracks()[0]
camera_cut_section = master_track.get_sections()[0]
camera_cut_section.set_start_frame(-WARMUP_FRAMES) # Use negative frames as warmup frames
if camera_movement.startswith("Zoom") or camera_movement.startswith("Orbit"):
# Add camera transform track and set static camera pose
for binding in level_sequence.get_possessables():
binding_name = binding.get_name()
if binding_name == "BE_CineCameraActor_Blueprint":
add_transform_track(binding, camera_pose)
if binding_name == "CameraComponent":
# Set HFOV
focal_length = get_focal_length(camera_actor.get_cine_camera_component(), camera_hfov)
binding.get_tracks()[0].get_sections()[0].get_channels()[0].set_default(focal_length)
if camera_movement.startswith("Zoom"):
if binding_name == "CameraComponent":
# Set end focal length keyframe time to end of sequence
change_binding_end_keyframe_times(binding, sequence_frames)
elif camera_movement.startswith("Orbit"):
if binding_name == "BE_CameraRoot":
cameraroot_binding = binding
change_binding_end_keyframe_times(binding, sequence_frames)
if (cameraroot_yaw is not None) or (cameraroot_location is not None):
cameraroot_actor = camera_actor.get_attach_parent_actor()
if cameraroot_actor is None:
unreal.log_error("Cannot find camera root actor for CineCameraActor")
return False
transform_channels = None
if cameraroot_binding is None:
# Add camera root actor to level sequence
cameraroot_binding = level_sequence.add_possessable(cameraroot_actor)
transform_track = cameraroot_binding.add_track(unreal.MovieScene3DTransformTrack)
transform_section = transform_track.add_section()
transform_section.set_start_frame_bounded(False)
transform_section.set_end_frame_bounded(False)
transform_channels = transform_section.get_channels()
if (cameraroot_yaw is not None):
transform_channels[5].set_default(cameraroot_yaw) # yaw
else:
transform_channels[5].set_default(0.0)
else:
if cameraroot_yaw is not None:
# Add cameraroot to existing keyframed yaw values
transform_channels = cameraroot_binding.get_tracks()[0].get_sections()[0].get_channels()
yaw_channel = transform_channels[5]
channel_keys = yaw_channel.get_keys()
for key in channel_keys:
key.set_value(key.get_value() + cameraroot_yaw)
if cameraroot_location is None:
cameraroot_location = cameraroot_actor.get_actor_location() # Default camera root location is not automatically taken from level actor when adding track via Python
transform_channels[0].set_default(cameraroot_location.x)
transform_channels[1].set_default(cameraroot_location.y)
transform_channels[2].set_default(cameraroot_location.z)
"""
# Get end frame from body sequence
body_object = unreal.load_object(None, body_path)
# Python Alembic import bug in 4.27.1 makes cache longer by one frame
# Example:
# 126 frame sequence gets imported as end_frame=127
# Last frame for Movie Render Queue is (end_frame-1)
# We need to set end_frame 126 to ensure that [0, 125] is rendered out.
end_frame = body_object.end_frame - 1
"""
end_frame = sequence_frames
camera_cut_section.set_end_frame(end_frame)
level_sequence.set_playback_start(-WARMUP_FRAMES) # Use negative frames as warmup frames
level_sequence.set_playback_end(end_frame)
# Add ground truth logger if available and keyframe sequencer frame numbers into Frame variable
if ground_truth_logger_actor is not None:
logger_binding = level_sequence.add_possessable(ground_truth_logger_actor)
frame_track = logger_binding.add_track(unreal.MovieSceneIntegerTrack)
frame_track.set_property_name_and_path('Frame', 'Frame')
frame_track_section = frame_track.add_section()
frame_track_section.set_range(-WARMUP_FRAMES, end_frame)
frame_track_channel = frame_track_section.get_channels()[0]
if WARMUP_FRAMES > 0:
frame_track_channel.add_key(time=unreal.FrameNumber(-WARMUP_FRAMES), new_value=-1)
for frame_number in range (0, end_frame):
frame_track_channel.add_key(time=unreal.FrameNumber(frame_number), new_value=frame_number)
# Add level sequence name
sequence_name_track = logger_binding.add_track(unreal.MovieSceneStringTrack)
sequence_name_track.set_property_name_and_path('SequenceName', 'SequenceName')
sequence_name_section = sequence_name_track.add_section()
sequence_name_section.set_start_frame_bounded(False)
sequence_name_section.set_end_frame_bounded(False)
sequence_name_section.get_channels()[0].set_default(name)
for sequence_body_index, sequence_body in enumerate(sequence_bodies):
body_object = unreal.load_object(None, sequence_body.body_path)
if body_object is None:
unreal.log_error(f"Cannot load body asset: {sequence_body.body_path}")
return False
animation_start_frame = -sequence_body.start_frame
animation_end_frame = sequence_frames
# Check if we use clothing overlay textures instead of textured clothing geometry
if sequence_body.texture_clothing_overlay is not None:
if sequence_body.texture_body.startswith("skin_f"):
gender = "female"
else:
gender = "male"
# Set Soft Object Paths to textures
texture_body_path = f"Texture2D'{texture_body_root}/{gender}/skin/{sequence_body.texture_body}.{sequence_body.texture_body}'"
texture_clothing_overlay_path = f"Texture2D'{texture_clothing_overlay_root}/{sequence_body.texture_clothing_overlay}.{sequence_body.texture_clothing_overlay}'"
add_geometry_cache(level_sequence, sequence_body_index, "body", animation_start_frame, animation_end_frame, body_object, sequence_body.x, sequence_body.y, sequence_body.z, sequence_body.yaw, sequence_body.pitch, sequence_body.roll, None, texture_body_path, texture_clothing_overlay_path)
else:
# Add body
material = None
if sequence_body.texture_body is not None:
material_asset_path = f"{material_body_root}/MI_{sequence_body.texture_body}"
material = unreal.EditorAssetLibrary.load_asset(f"MaterialInstanceConstant'{material_asset_path}'")
if not material:
unreal.log_error(f"Cannot load material: {material_asset_path}")
return False
add_geometry_cache(level_sequence, sequence_body_index, "body", animation_start_frame, animation_end_frame, body_object, sequence_body.x, sequence_body.y, sequence_body.z, sequence_body.yaw, sequence_body.pitch, sequence_body.roll, material)
# Add clothing if available
if sequence_body.clothing_path is not None:
clothing_object = unreal.load_object(None, sequence_body.clothing_path)
if clothing_object is None:
unreal.log_error(f"Cannot load clothing asset: {sequence_body.clothing_path}")
return False
material = None
if sequence_body.texture_clothing is not None:
material_asset_path = f"{material_clothing_root}/{sequence_body.subject}/MI_{sequence_body.subject}_{sequence_body.texture_clothing}"
material = unreal.EditorAssetLibrary.load_asset(f"MaterialInstanceConstant'{material_asset_path}'")
if not material:
unreal.log_error(f"Cannot load material: {material_asset_path}")
return False
add_geometry_cache(level_sequence, sequence_body_index, "clothing", animation_start_frame, animation_end_frame, clothing_object, sequence_body.x, sequence_body.y, sequence_body.z, sequence_body.yaw, sequence_body.pitch, sequence_body.roll, material)
# Add hair
if sequence_body.hair_path is not None:
success = add_hair(level_sequence, sequence_body_index, "hair", animation_start_frame, animation_end_frame, sequence_body.hair_path, sequence_body.animation_path, sequence_body.x, sequence_body.y, sequence_body.z, sequence_body.yaw, sequence_body.pitch, sequence_body.roll)
if not success:
return False
unreal.EditorAssetLibrary.save_asset(level_sequence.get_path_name())
return True
######################################################################
# Main
######################################################################
if __name__ == '__main__':
unreal.log("============================================================")
unreal.log("Running: %s" % __file__)
if len(sys.argv) >= 2:
csv_path = sys.argv[1]
camera_movement = "Static"
if len(sys.argv) >= 3:
camera_movement = sys.argv[2]
start_time = time.perf_counter()
# Find CineCameraActor and BE_GroundTruthLogger in current map
actors = unreal.get_editor_subsystem(unreal.EditorActorSubsystem).get_all_level_actors() # deprecated: unreal.EditorLevelLibrary.get_all_level_actors()
camera_actor = None
ground_truth_logger_actor = None
for actor in actors:
if actor.static_class() == unreal.CineCameraActor.static_class():
camera_actor = actor
elif actor.get_class().get_name() == "BE_GroundTruthLogger_C":
ground_truth_logger_actor = actor
success = True
if camera_actor is None:
unreal.log_error("Cannot find CineCameraActor in current map")
success = False
else:
# Generate LevelSequences for defined sequences in csv file
csv_reader = None
with open(csv_path, mode="r") as csv_file:
csv_reader = csv.DictReader(csv_file)
csv_rows = list(csv_reader) # Convert to list of rows so that we can look ahead, this will skip header
sequence_bodies = []
sequence_name = None
sequence_frames = 0
hdri_name = None
camera_hfov = None
camera_pose = None
cameraroot_yaw = None
cameraroot_location = None
for row_index, row in enumerate(csv_rows):
if row["Type"] == "Comment":
continue
if row["Type"] == "Group":
camera_pose = CameraPose(float(row["X"]), float(row["Y"]), float(row["Z"]), float(row["Yaw"]), float(row["Pitch"]), float(row["Roll"]))
# Parse additional group configuration
values = row["Comment"].split(";")
dict_keys = []
dict_values = []
for value in values:
dict_keys.append(value.split("=")[0])
dict_values.append(value.split("=")[1])
group_config = dict(zip(dict_keys, dict_values))
sequence_name = group_config["sequence_name"]
sequence_frames = int(group_config["frames"])
# Check if HDRI was specified
if "hdri" in group_config:
hdri_name = group_config["hdri"]
else:
hdri_name = None
# Check if camera HFOV was specified
if "camera_hfov" in group_config:
camera_hfov = float(group_config["camera_hfov"])
else:
camera_hfov = None
if "cameraroot_yaw" in group_config:
cameraroot_yaw = float(group_config["cameraroot_yaw"])
else:
cameraroot_yaw = None
if "cameraroot_x" in group_config:
cameraroot_x =float(group_config["cameraroot_x"])
cameraroot_y =float(group_config["cameraroot_y"])
cameraroot_z =float(group_config["cameraroot_z"])
cameraroot_location = unreal.Vector(cameraroot_x, cameraroot_y, cameraroot_z)
unreal.log(f" Generating level sequence: {sequence_name}, frames={sequence_frames}, hdri={hdri_name}, camera_hfov={camera_hfov}")
sequence_bodies = []
continue
if row["Type"] == "Body":
index = int(row["Index"])
body = row["Body"]
x = float(row["X"])
y = float(row["Y"])
z = float(row["Z"])
yaw = float(row["Yaw"])
pitch = float(row["Pitch"])
roll = float(row["Roll"])
# Parse additional body configuration
values = row["Comment"].split(";")
dict_keys = []
dict_values = []
for value in values:
dict_keys.append(value.split("=")[0])
dict_values.append(value.split("=")[1])
body_config = dict(zip(dict_keys, dict_values))
start_frame = 0
if "start_frame" in body_config:
start_frame = int(body_config["start_frame"])
texture_body = None
if "texture_body" in body_config:
texture_body = body_config["texture_body"]
texture_clothing = None
if "texture_clothing" in body_config:
texture_clothing = body_config["texture_clothing"]
texture_clothing_overlay = None
if "texture_clothing_overlay" in body_config:
texture_clothing_overlay = body_config["texture_clothing_overlay"]
hair_path = None
if "hair" in body_config:
if not level_sequence_hdri_template.endswith("_Hair"):
level_sequence_hdri_template += "_Hair"
hair_type = body_config["hair"]
# StaticMesh'/project/.SMPLX_M_Hair_Center_part_curtains'
hair_path = f"StaticMesh'{hair_root}{hair_type}/{hair_type}.{hair_type}'"
match = re.search(r"(.+)_(.+)", body)
if not match:
unreal.log_error(f"Invalid body name pattern: {body}")
success = False
break
subject = match.group(1)
animation_id = match.group(2)
# Body: GeometryCache'/project/.rp_aaron_posed_002_0000'
# Clothing: GeometryCache'/project/.rp_aaron_posed_002_0000_clo'
body_path = f"GeometryCache'{body_root}{subject}/{body}.{body}'"
have_body = unreal.EditorAssetLibrary.does_asset_exist(body_path)
if not have_body:
unreal.log_error("No asset found for body path: " + body_path)
success = False
break
unreal.log(" Processing body: " + body_path)
clothing_path = None
if texture_clothing is not None:
clothing_path = body_path.replace("SMPLX", "Clothing")
clothing_path = clothing_path.replace(animation_id, f"{animation_id}_clo")
have_clothing = unreal.EditorAssetLibrary.does_asset_exist(clothing_path)
if not have_clothing:
unreal.log_error("No asset found for clothing path: " + clothing_path)
success = False
break
unreal.log(" Clothing: " + clothing_path)
animation_path = None
if hair_path is not None:
# AnimSequence'/project/.rp_aaron_posed_002_1000_Anim'
animation_path = f"AnimSequence'{animation_root}{subject}/{body}_Anim.{body}_Anim'"
sequence_body = SequenceBody(subject, body_path, clothing_path, hair_path, animation_path, x, y, z, yaw, pitch, roll, start_frame, texture_body, texture_clothing, texture_clothing_overlay)
sequence_bodies.append(sequence_body)
# Check if body was last item in current sequence
add_sequence = False
if index >= (len(csv_rows) - 1):
add_sequence = True
elif csv_rows[row_index + 1]["Type"] != "Body":
add_sequence = True
if add_sequence:
success = add_level_sequence(sequence_name, camera_actor, camera_pose, ground_truth_logger_actor, sequence_bodies, sequence_frames, hdri_name, camera_hfov, camera_movement, cameraroot_yaw, cameraroot_location)
# Remove added layers used for segmentation mask naming
layer_subsystem = unreal.get_editor_subsystem(unreal.LayersSubsystem)
layer_names = layer_subsystem.add_all_layer_names_to()
for layer_name in layer_names:
if str(layer_name).startswith("be_actor"):
layer_subsystem.delete_layer(layer_name)
if not success:
break
if success:
unreal.log(f"LevelSequence generation finished. Total time: {(time.perf_counter() - start_time):.1f}s")
sys.exit(0)
else:
unreal.log_error(f"LevelSequence generation failed. Total time: {(time.perf_counter() - start_time):.1f}s")
sys.exit(1)
|
# Unreal Python script
# Attempts to fix various issues in Source engine Datasmith
# imports into Unreal
from collections import Counter, defaultdict, OrderedDict
import unreal
import re
import traceback
import os
import json
import csv
import posixpath
import math
from glob import glob
# This is the SCALE / 100 which we set in HammUEr when importing models.
# Source maps are bigger than Sandstorm for whatever reason --
# so we've had to scale things down a bit.
# We *need* this scale to be accurate or the placement of
# objects will be *waaaaay* off if we go by the Origin in
# our imported notes. When spawning an item at the Origin defined
# by an imported note (IE: for nbot_cover notes), we need to
# divide each value (Y, X, Z) by this HAMMUER_SCALE
#
# FYI, the ridiculous number below was found by dividing the location
# specified in a Note actor (IE: 319.99) to the same HammUEr-translated
# point value (IE: 736.116821) in that same object.
# ( *sigh* I hate floats... )
HAMMUER_SCALE = 0.4347000243321434
# REQUIRED! We use the values found in the map.txt files for
# placement of objectives, spawns, ...
GCFSCAPE_EXPORT_DIRECTORY = r"/project/"
BSPSRC_EXPORT_DIRECTORY = r"/project/"
# Regex for VMF parsing
PLANE_SPLIT_RE = re.compile(r'\((.+?)\)')
ARRAY_RE = re.compile(r'([-0-9.]+)')
THREE_NUM_STR_RE = re.compile(r'^[-0-9.]+ [-0-9.]+ [-0-9.]+$')
# A set of actor labels to use for ensuring we
# don't place the same actor multiple times
PLACED_ACTORS = set()
# Shortcuts for creating material node connections
CREATE_EXPRESSION = unreal.MaterialEditingLibrary.create_material_expression
CREATE_CONNECTION = unreal.MaterialEditingLibrary.connect_material_expressions
CONNECT_PROPERTY = unreal.MaterialEditingLibrary.connect_material_property
CONNECT_EXPRESSIONS = unreal.MaterialEditingLibrary.connect_material_expressions
# Use to create material node connections
CHILD_OBJECT_REGEX = re.compile(r".*_\d{3}$")
def isnumeric(value):
try:
float(value)
return True
except:
return False
def num_to_alpha(num):
""" Convert a number > 0 and < 24 into it's Alphabetic equivalent """
num = int(num) # Ensure num is an int
if num < 0:
raise ValueError("wtf? num_to_alpha doesn't like numbers less than 0...")
if num > 24:
raise ValueError("seriously? there's no way you have more than 24 objectives...")
return chr(65 + num)
def get_snake_case(text):
# If world_name contains CamelCase lettering, add an _
# before each uppercase letter following the first letter
# TODO: This is a stupid way to do this, right? *Maybe* fix it .. but ... it *does* work ...
text = "".join(reversed([c if c.islower() else "_%s" % c for c in reversed(text)]))
# If world_name has a leading underscore, remove it
text = text[1:] if text[0] == "_" else text
# Ensure world_name is lowercase
return text.lower()
def cast(object_to_cast=None, object_class=None):
"""
# 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
"""
try:
return object_class.cast(object_to_cast)
except Exception:
return None
def get_all_properties(unreal_class=None):
"""
# Note: Also work using the command : help(unreal.StaticMesh)
# unreal_class: obj : The class you want to know the properties
# return: str List : The available properties (formatted the way you can directly use them to get their values)
"""
return unreal.CppLib.get_all_properties(unreal_class)
def get_all_actors(use_selection=False, actor_class=None, actor_tag=None, world=None):
"""
# use_selection: bool : True if you want to get only the selected actors
# actor_class: class unreal.Actor : The class used to filter the actors. Can be None if you do not want to use this filter
# actor_tag: str : The tag used to filter the actors. Can be None if you do not want to use this filter
# world: obj unreal.World : The world you want to get the actors from. If None, will get the actors from the currently open world.
# return: obj List unreal.Actor : The actors
"""
world = world if world is not None else unreal.EditorLevelLibrary.get_editor_world() # Make sure to have a valid world
if use_selection:
selected_actors = get_selected_actors()
class_actors = selected_actors
if actor_class:
class_actors = [x for x in selected_actors if cast(x, actor_class)]
tag_actors = class_actors
if actor_tag:
tag_actors = [x for x in selected_actors if x.actor_has_tag(actor_tag)]
return [x for x in tag_actors]
elif actor_class:
actors = unreal.GameplayStatics.get_all_actors_of_class(world, actor_class)
tag_actors = actors
if actor_tag:
tag_actors = [x for x in actors if x.actor_has_tag(actor_tag)]
return [x for x in tag_actors]
elif actor_tag:
tag_actors = unreal.GameplayStatics.get_all_actors_with_tag(world, actor_tag)
return [x for x in tag_actors]
else:
actors = unreal.GameplayStatics.get_all_actors_of_class(world, unreal.Actor)
return [x for x in actors]
def select_actors(actors_to_select=[]):
"""
# Note: Will always clear the selection before selecting.
# actors_to_select: obj List unreal.Actor : The actors to select.
"""
unreal.EditorLevelLibrary.set_selected_level_actors(actors_to_select)
def get_selected_actors():
""" return: obj List unreal.Actor : The selected actors in the world """
return unreal.EditorLevelLibrary.get_selected_level_actors()
def actor_contains_material(actor, material_name, containing=False):
""" If this actor is StaticMeshActor and contains a material with
a name beginning with any of the words in the provided words_tuple,
return True -- else return False
"""
if not material_name:
return False
if isinstance(actor, unreal.StaticMeshActor):
static_mesh_component = actor.get_component_by_class(unreal.StaticMeshComponent)
# Skip if there's no static mesh to display
if not static_mesh_component.static_mesh:
return False
# Check if the static mesh has materials -- which we'll fix if applicable
mats = static_mesh_component.get_materials()
if not mats:
return False
# Iterate through all materials found in this static mesh
for mat in mats:
if not mat:
continue
# Check if the name of the current material starts with "tools"
mat_name = mat.get_name()
if not mat_name:
continue
if mat_name.startswith(material_name) or (containing and material_name in mat_name):
return True
# Actor wasn't a StaticMesh -- so we couldn't be sure
# it was a tool. Skip this actor ...
return False
def hide_all_actors_with_material_name(material_name, containing=True):
""" Hide all actors with the specified material (with Undo support) """
matching_actors = list()
with unreal.ScopedEditorTransaction("Hiding Actors (in-game) with Specific Mat") as trans:
# Find all actors with the specified material and add them
# to the "matching_actors" list.
for actor in get_all_actors(actor_class=unreal.StaticMeshActor):
if actor_contains_material(actor, material_name, containing=containing):
print(" - hiding actor: %s" % actor.get_name())
# Hide this specified actor in-game
actor.set_actor_hidden_in_game(True)
# Add this actor to our "matching_actors" list
matching_actors.append(actor)
return matching_actors
def move_actors_to_folder(actors, folder_name):
for actor in actors:
if not actor:
continue
try:
actor.set_folder_path(folder_name)
except Exception as ex:
print(ex)
def main():
# Hide all actors with a material name starting with "player_flesh_mat"
# and return a list of all matching actors
matching_actors = hide_all_actors_with_material_name("_flesh_", containing=True)
# Add all actors in the "actors_to_group" list to an Unreal group
with unreal.ScopedEditorTransaction("Group Mannequins"):
useless_actors_group = unreal.ActorGroupingUtils(name="Mannequins")
useless_actors_group.group_actors(matching_actors)
# Move actors to a folder called "Mannequins"
move_actors_to_folder(matching_actors, "Mannequins")
print("[*] We're done! Actors should be hidden in-game")
# Run main!
main()
|
# coding: utf-8
import unreal
def spawnActor():
actor_class = unreal.EditorAssetLibrary.load_blueprint_class('/project/')
actor_location = unreal.Vector(0.0, 0.0, 0.0)
actor_rotation = unreal.Rotator(0.0, 0.0, 0.0)
unreal.EditorLevelLibrary.spawn_actor_from_class(actor_class, actor_location, actor_rotation)
def deferredSpawnActor():
world = unreal.EditorLevelLibrary.get_editor_world()
actor_class = unreal.EditorAssetLibrary.load_blueprint_class('/project/')
actor_location = unreal.Vector(0.0, 0.0, 0.0)
actor_rotation = unreal.Rotator(0.0, 0.0, 0.0)
actor_scale = unreal.Vector(1.0, 1.0, 1.0)
actor_transform = unreal.Transform(actor_location, actor_rotation, actor_scale)
actor = unreal.EditorCppLib.begin_spawn_actor(world, actor_class, actor_transform)
actor_tags = actor.get_editor_property('tags')
actor_tags.append('My Python Tag')
actor.set_editor_property('tags', actor_tags)
unreal.EditorCppLib.finish_spawn_actor(actor, actor_transform)
# import WorldFunctions as wf
# reload(wf)
# wf.spawnActor()
|
# 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 unreal
import numpy as np
import random
import os
import json
import re
import time
NUM_VARIATIONS = 10
np.random.seed(None)
column_num = 5
class SlotManager:
def column_row_to_index(self, column, row):
x = column * 20 + -40
y = -row * 10
return x, y
def choose_slot(self, column_flag, column_list):
candidate_column = []
for i in range(column_num):
if column_flag[i] == 0:
candidate_column.append(i)
chosen_column = np.random.choice(candidate_column)
candidate_row = []
for i in range(len(column_list[chosen_column])):
if column_list[chosen_column][i] == 0:
candidate_row.append(i)
chosen_row = np.random.choice(candidate_row)
return chosen_column, chosen_row
def update_map(self, chosen_column, chosen_row, column_flag, column_list):
column_flag[chosen_column] = 1
for i in range(len(column_list[chosen_column])):
column_list[chosen_column][i] = 1
# 其他column
if chosen_column == 0:
if chosen_row == 0:
column_list[1][2] = 1
column_list[1][3] = 1
if chosen_row == 1:
column_list[1][3] = 1
if chosen_column == 4:
if chosen_row == 0:
column_list[3][2] = 1
column_list[3][3] = 1
if chosen_row == 1:
column_list[3][3] = 1
if chosen_column == 1:
if chosen_row == 1 or chosen_row == 2:
column_list[0][0] = 1
if chosen_row == 3:
column_list[0][0] = 1
column_list[0][1] = 1
column_flag[0] = 1
if chosen_column == 3:
if chosen_row == 1 or chosen_row == 2:
column_list[4][0] = 1
if chosen_row == 3:
column_list[4][0] = 1
column_list[4][1] = 1
column_flag[4] = 1
return column_flag, column_list
def natural_sort_key(s):
return [int(text) if text.isdigit() else text.lower() for text in re.split('([0-9]+)', s)]
def get_candidate_blocks(bool_map, block_size):
candidate_blocks = []
for i in range(bool_map.shape[0] - block_size):
for j in range(bool_map.shape[1] - block_size):
sub_map = bool_map[int(i - block_size / 2):int(i + block_size / 2), int(j - block_size / 2):int(j + block_size / 2)]
if sub_map.shape[0] != 0 and sub_map.shape[1] != 0 and np.all(sub_map):
candidate_blocks.append((i, j))
# print(f"Found empty space at ({i},{j})")
return candidate_blocks
def update_bool_map(bool_map, block_size, block_position, width=None, height=None):
i, j = block_position
assert bool_map[int(i - block_size / 2):int(i + block_size / 2), int(j - block_size / 2):int(j + block_size / 2)].all()
bool_map[int(i - block_size / 2):int(i + block_size / 2), int(j - block_size / 2):int(j + block_size / 2)] = False
return bool_map
def define_offset_and_path():
offset = {
'mug':
[
[[0, 0, 0, 1], [0, 0, 0]], # 0
[[0, 0, 0, 0.7], [0, 0, 0]], # 1
[[0, 0, 0, 0.05], [0, 0, 0]], # 2
[[0, 0, 0, 0.03], [0, 0, 0]], # 3
[[0, 0, 0, 0.0015], [0, 0, 0]], # 4
[[0, 0, 0, 0.6], [0, 0, 0]], # 5
[[0, 0, 0, 0.035], [0, 0, 0]], # 6
[[0, 0, 0, 0.02], [0, 0, 0]], # 7
[[0, 0, 0, 1], [0, 0, 0]], # 8
[[0, 0, 0, 0.5], [0, 0, 0]], # 9
],
'apple':
[
[[0, 0, 0, 0.6], [0, 0, 0]], # 0
[[0, 0, 0, 1], [0, 0, 0]], # 1
[[0, 0, 0, 0.15], [0, 0, 0]], # 2
[[0, 0, 0, 1], [0, 0, 0]], # 3
[[0, 0, 0, 1], [0, 0, 0]], # 4
[[0, 0, 0, 1], [0, 0, 0]], # 5
[[0, 0, 0, 0.03], [0, 0, 0]], # 6
[[0, 0, 4, 1], [0, 0, 0]], # 7
[[0, 0, 0, 0.001], [0, 0, 0]], # 8
[[0, 0, 0, 0.15], [0, 0, 0]], # 9
],
'notebook':
[
[[0, 0, 0, 0.05], [0, 0, 0]], # 0
[[0, 0, 0, 0.7], [0, 0, 0]], # 1
[[0, 0, 0, 1], [0, 0, 0]], # 2
[[0, 0, 0, 0.7], [0, 0, 0]], # 3
[[0, 0, 2.5, 0.5], [0, 180, 0]], # 4
[[0, 0, 0, 0.04], [0, 0, 0]], # 5
[[0, 0, 2, 0.5], [0, 0, 0]], # 6
[[0, 0, 1, 0.7], [0, 180, 0]], # 7
[[0, 0, 0, 0.8], [0, 0, 0]], # 8
[[0, 0, 0, 0.7], [0, 0, 0]], # 9
],
'clock':
[
[[0, 0, 0, 0.0007], [0, 0, 180]], # 0
[[0, 0, 0, 1], [0, 0, 180]], # 1
[[0, 0, 0, 1], [0, 0, 180]], # 2
[[0, 0, 0, 0.01], [0, 0, 180]], # 3
[[0, 0, 0, 0.5], [0, 0, 180]], # 4
[[0, 0, 0, 0.035], [0, 0, 180]], # 5
[[0, 0, 0, 0.07], [0, 0, 180]], # 6
[[0, 0, 0, 0.4], [0, 0, -90]], # 7
[[0, 0, 0, 6], [0, 0, -90]], # 8
[[0, 0, 0, 2], [0, 0, -90]], # 9
]
}
# print(len(offset['notebook']))
for i in range(NUM_VARIATIONS):
offset['notebook'][i][0] = [item * 1.5 for item in offset['notebook'][i][0]]
objects = [
"mug",
# "notebook",
"apple",
"clock",
]
father_path = "/project/"
object_path_list = {
'mug': [],
# 'notebook': [],
'apple': [],
'clock': [],
}
for this_object in objects:
object_root = father_path + this_object
for i in range(NUM_VARIATIONS):
object_path = object_root + "/" + "variation" + str(i) + "/" + this_object + str(i) + "." + this_object + str(i)
object_path_list[this_object].append(object_path)
return objects, object_path_list, offset
def get_object_actor_dict(objects, actors):
object_actor_dict = {}
for object in objects:
object_actor_dict[object] = {}
for actor in actors:
if actor.get_actor_label()[:-1] in objects:
for object in objects:
if object in actor.get_actor_label():
object_actor_dict[object][actor.get_actor_label()] = actor
return object_actor_dict
def main():
# time.sleep(120)
objects, object_path_list, offset = define_offset_and_path()
save_path = "/project/"
obj_rest_point = unreal.Vector(-500, -500, 0)
obj_rest_rotator = unreal.Rotator(0, 0, 0)
editor_subsystem = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem)
world = editor_subsystem.get_editor_world()
# 0. retrieve all the actors
editor_actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
actors = editor_actor_subsystem.get_all_level_actors()
camera_location_list = [
[0, -58, 93],
]
camera_rotation_list = [
[0, -21.5, 90],
]
light_location = [
[0, -800, 380]
]
light_rotation = [
[0, -21, 90]
]
camera_actors = {}
capture_component = []
RTs = []
object_actor_dict = get_object_actor_dict(objects, actors)
light_actor = None
for actor in actors:
if "camera" in actor.get_actor_label():
camera_actors[actor.get_actor_label()] = actor
if "DirectionalLight" in actor.get_actor_label():
light_actor = actor
# print(object_actor_dict)
for i in range(len(camera_location_list)):
this_cc = camera_actors[f'camera{i}'].get_component_by_class(unreal.SceneCaptureComponent2D)
this_cc.set_editor_property("bCaptureEveryFrame", True)
# this_cc.set_editor_property("b_enable_post_processing", True)
pp_settings = this_cc.get_editor_property("post_process_settings")
pp_settings.override_dynamic_global_illumination_method = True
pp_settings.override_reflection_method = True
# bloom
pp_settings.override_bloom_method = True
pp_settings.override_tone_curve_amount = True
pp_settings.override_auto_exposure_bias = True
pp_settings.auto_exposure_bias = 2.5
capture_component.append(this_cc)
RTs.append(capture_component[i].texture_target)
light_actor.set_actor_location_and_rotation(unreal.Vector(*light_location[0]), unreal.Rotator(*light_rotation[0]), False, False)
# set camera location and rotation
episodes = 100000
counter = 0
existed_episodes = sorted(os.listdir(save_path), key=natural_sort_key)
for i in range(len(camera_location_list)):
camera_actors[f'camera{i}'].set_actor_location_and_rotation(unreal.Vector(*camera_location_list[i]), unreal.Rotator(*camera_rotation_list[i]), False, False)
counter = len(existed_episodes) - 10
if counter < 0:
counter = 0
slot_manager = SlotManager()
while counter < episodes:
keys = {}
for object in objects:
keys[object] = []
for object in objects:
for key in object_actor_dict[object].keys():
keys[object].append(key)
object_actor_dict[object][key].set_actor_location_and_rotation(obj_rest_point, obj_rest_rotator, False, False)
# logic on what objects should on the table
num_in_table = np.random.randint(1, 4)
objects_in_scene = np.random.choice(objects, num_in_table, replace=False)
objects_to_show = []
for object in objects_in_scene:
key_on_table = np.random.choice(keys[object])
idx = int(key_on_table.split(object)[-1])
objects_to_show.append([object, idx, object_actor_dict[object][key_on_table]]) # name, id, actor
# logic of placing objects on the table
column_list = []
for i in range(column_num):
column_list.append([])
column_list[0] = [0, 0]
column_list[1] = [0, 0, 0, 0]
column_list[2] = [0, 0, 0, 0, 0]
column_list[3] = [0, 0, 0, 0]
column_list[4] = [0, 0]
column_flag = np.zeros(column_num)
# create record
record = {}
for object in objects:
record[object] = 0
break_flag = False
for actor in objects_to_show:
this_offset = offset[actor[0]][actor[1]]
location_offset = this_offset[0][:3]
rotation_offset = this_offset[1]
scale_offset = this_offset[0][3]
test_c, test_r = slot_manager.choose_slot(column_flag, column_list)
if test_c is not None and test_r is not None:
column_flag, column_list = slot_manager.update_map(test_c, test_r, column_flag, column_list)
x, y = slot_manager.column_row_to_index(test_c, test_r)
scale = scale_offset * 1.0
if actor[0] == 'clock':
scale = scale_offset * 0.8
x = float(x)
y = float(y)
z = 77 + location_offset[2]
rx, ry, rz = rotation_offset
if actor[0] != 'clock':
rz = rz + np.random.randint(-180, 180)
actor[2].set_actor_location_and_rotation(unreal.Vector(x, y, z), unreal.Rotator(rx, ry, rz), False, False)
actor[2].set_actor_scale3d(unreal.Vector(scale, scale, scale))
# print(actor[0])
record[actor[0]] += 1
# print(f"Placed {actor[0]} {actor[1]} at ({x}, {y}, {z})")
else:
print("No empty space")
break_flag = True
# counter -= 1
if break_flag:
continue
# raise ValueError("No empty space")
# actor[2].set_actor_location_and_rotation(obj_rest_point + unreal.Vector(*location_offset), obj_rest_rotator + unreal.Rotator(*rotation_offset), False, False)
time.sleep(0.1)
# take a snapshot
folder_path = f'{save_path}/episode_{counter}'
for i, RT in enumerate(RTs):
# light_actor.set_actor_location_and_rotation(unreal.Vector(*camera_location_list[i]), unreal.Rotator(*camera_rotation_list[i]), False, False)
capture_component[i].capture_scene()
unreal.RenderingLibrary.export_render_target(world, RT, folder_path, f'camera_{i}.png')
capture_component[i].capture_scene()
unreal.RenderingLibrary.export_render_target(world, RT, folder_path, f'camera_{i}.png')
if i >= 0:
break
with open(os.path.join(folder_path, 'info.json'), 'w') as f:
json.dump(record, f)
obj_rest_point_1 = unreal.Vector(0, 0, 81)
obj_rest_rotator_1 = unreal.Rotator(0, 0, 0)
for object in objects:
for key in object_actor_dict[object].keys():
keys[object].append(key)
object_actor_dict[object][key].set_actor_location_and_rotation(obj_rest_point_1, obj_rest_rotator_1, False, False)
counter += 1
# unreal.SystemLibrary.collect_garbage()
# print("-------------------------")
main()
# print(RT)
|
import unreal
import re
bp_editor_lib = unreal.BlueprintEditorLibrary
asset_lib=unreal.EditorAssetLibrary
editor_util = unreal.EditorUtilityLibrary
sys_lib = unreal.SystemLibrary
actor_subsys = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
selected_actors = actor_subsys.get_selected_level_actors()
selected_assets = editor_util.get_selected_assets()
def get_default_object(asset) -> unreal.Object:
bp_gen_class = unreal.load_object(None, asset.generated_class().get_path_name())
default_object = unreal.get_default_object(bp_gen_class)
return default_object
def get_default_object(asset) -> unreal.Object:
bp_gen_class = unreal.load_object(None, asset.generated_class().get_path_name())
default_object = unreal.get_default_object(bp_gen_class)
return default_object
def get_blueprint_class(path: str) -> unreal.Class:
blueprint_asset = unreal.load_asset(path)
blueprint_class = unreal.load_object(
None, blueprint_asset.generated_class().get_path_name()
)
return blueprint_class
def get_level_instance_from_pla(target_actor:unreal.PackedLevelActor):
"""
对于在关卡中选中的Packed Level Actor,找到对应的Level Instance
"""
# Check if the actor has a Level Instance Component
has_level_instance = False
components = target_actor.get_components_by_class(unreal.SceneComponent)
for component in components:
component_class = component.get_class()
if "LevelInstance" in component_class.get_name():
has_level_instance = True
break
# Add actor to packed_level_actors if it matches any of the criteria
if has_level_instance:
level_instance = bp_editor_lib.get_editor_property(target_actor, name="WorldAsset")
return level_instance
# packed_level_actors.append(target_actor)
else:
unreal.log_warning(f"Actor {target_actor.get_name()} does not have a Level Instance")
return None
def replace_pla_with_level_instance(target_actor:unreal.PackedLevelActor):
"""
将关卡中的Packed Level Actor替换为对应的Level Instance
"""
#检查是否有对应的Level Instance
level_instance = get_level_instance_from_pla(target_actor)
if not level_instance:
return None
location = target_actor.get_actor_location()
rotation = target_actor.get_actor_rotation()
unreal.log(f"Replacing {target_actor.get_actor_label()} with Level Instance {level_instance.get_name()}")
actor_subsys.destroy_actor(target_actor)
# Spawn the LevelInstance actor at the same location/rotation
new_actor = actor_subsys.spawn_actor_from_object(level_instance, location, rotation)
# new_actors.append(new_actor)
return new_actor
# selected_assets = unreal.EditorUtilityLibrary.get_selected_assets()
def create_pla_from_level_instance(target_asset:unreal.PackedLevelActor):
""" 从Level Instance创建新的PLA """
# 检查asset是否为Level Instance类型
if not target_asset.get_class().get_name().endswith("World"):
unreal.log_warning(f"Asset {name} 不是Level Instance,已跳过。")
return None
name = target_asset.get_name()
asset_path_name = target_asset.get_path_name()
target_dir = unreal.Paths.get_path(asset_path_name)
target_name = "BPP_" + name
# Create a Blueprint factory
factory = unreal.BlueprintFactory()
factory.set_editor_property("parent_class", unreal.PackedLevelActor) # Set the parent class
# Get the asset tools
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
# Create the Blueprint asset
blueprint = asset_tools.create_asset(target_name, target_dir, None, factory)
bp_actor = get_default_object(blueprint)
bp_editor_lib.set_editor_property(bp_actor, name="WorldAsset", value=target_asset)
unreal.BlueprintEditorLibrary.compile_blueprint(blueprint)
return bp_actor
def copy_asset_to_dir(asset, target_dir:str):
"""
复制目标asset到指定的新路径,返回新asset的路径
"""
asset_path = asset.get_path_name()
asset_name = asset.get_name()
# 清理路径字符串中的空格和不合法字符,只保留字母、数字、下划线、斜杠
target_dir = re.sub(r'[^a-zA-Z0-9_\/]', '', target_dir.replace(' ', ''))
target_dir = unreal.Paths.normalize_directory_name(target_dir)
new_asset_path = f"{target_dir}/{asset_name}"
new_asset_path=check_file_exist(new_asset_path)
duplicated_asset = asset_lib.duplicate_asset(asset_path, new_asset_path)
if duplicated_asset:
new_asset = duplicated_asset
unreal.log(f"Asset {asset_name} copied to {new_asset.get_path_name()}")
return new_asset
else:
unreal.log_warning(f"Failed to copy asset {asset_name} to {target_dir}")
return None
def check_file_exist(file_path: str) -> str:
""" 检查文件是否存在,并根据已有文件名生成新文件名(递归检查直到不存在为止) """
while asset_lib.does_asset_exist(file_path):
# 拆分路径和文件名
dir_path = unreal.Paths.get_path(file_path)
base_name = unreal.Paths.get_base_filename(file_path)
ext = unreal.Paths.get_extension(file_path)
# 匹配结尾数字
match = re.match(r"^(.*?)(\d+)$", base_name)
if match:
name_part = match.group(1)
num_part_str = match.group(2)
num_part = int(num_part_str) + 1
# 保持原有数字的位数
new_num_part = str(num_part).zfill(len(num_part_str))
new_base_name = f"{name_part}{new_num_part}"
else:
new_base_name = f"{base_name}1"
# 重新组装路径
if ext:
file_path = f"{dir_path}/{new_base_name}.{ext}"
else:
file_path = f"{dir_path}/{new_base_name}"
return file_path
# 在UE WidgetBP中调用以下Functions
def duplicate_packed_level_actors(targets,target_dir:str,type="EDITOR"):
"""复制ContentBrowser中选中的PLA资产 target_dir=项目内目标路径 type='EDITOR" 或 'CONTENTBROWSER' """
level_instances=[]
count=0
if type=="EDITOR":
target_actors=targets
for actor in target_actors:
#检查是否是Level Instance
if actor.get_class().get_name()=="LevelInstance":
level_instance=actor.get_world_asset()
else:
level_instance = get_level_instance_from_pla(actor)
if level_instance is not None:
if level_instance not in level_instances:
level_instances.append(level_instance)
elif type=="CONTENTBROWSER":
target_assets=targets
for asset in target_assets:
if asset.get_class().get_name().endswith("World"):
level_instance=asset
else:
if asset.get_class().get_name() == "Blueprint":
#检查parent class 的类型
bp=get_default_object(asset)
if isinstance(bp,unreal.PackedLevelActor):
level_instance=get_level_instance_from_pla(asset)
if level_instance is not None:
if level_instance not in level_instances:
level_instances.append(level_instance)
if len(level_instances) > 0:
asset_count = len(level_instances)
task_name = "Dulpicating Packed Level Actors"
with unreal.ScopedSlowTask(asset_count, task_name) as slowTask:
slowTask.make_dialog(True)
for instance in level_instances:
new_level_instance=copy_asset_to_dir(instance, target_dir)
create_pla_from_level_instance(new_level_instance)
count+=1
unreal.log(f"已创建{count}个PLA")
def batch_replace_pla_to_level_instance(actors):
"""批量将关卡中的PLA转为LevelInstance"""
count = 0
for actor in actors:
new_actor=replace_pla_with_level_instance(actor)
if new_actor:
count+=1
unreal.log("成功替换了" + str(count) + "个Packed Level Actors为LevelInstance资产")
#Test Function
# duplicate_packed_level_actors(targets=selected_actors,target_dir="/project/",type="EDITOR")
# batch_replace_pla_to_level_instance(selected_actors)
|
# 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)
|
# Copyright Epic Games, Inc. All Rights Reserved
# Built-in
import sys
from pathlib import Path
# Third-party
import unreal
import remote_executor
import mrq_cli
plugin_name = "MoviePipelineDeadline"
# Add the actions path to sys path
actions_path = Path(__file__).parent.joinpath("pipeline_actions").as_posix().lower()
if actions_path not in sys.path:
sys.path.append(actions_path)
from pipeline_actions import render_queue_action
# Register the menu from the render queue actions
render_queue_action.register_menu_action()
# The asset registry may not be fully loaded by the time this is called,
# warn the user that attempts to look assets up may fail
# unexpectedly.
# Look for a custom commandline start key `-waitonassetregistry`. This key
# is used to trigger a synchronous wait on the asset registry to complete.
# This is useful in commandline states where you explicitly want all assets
# loaded before continuing.
asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
if asset_registry.is_loading_assets() and ("-waitonassetregistry" in unreal.SystemLibrary.get_command_line().split()):
unreal.log_warning(
f"Asset Registry is still loading. The {plugin_name} plugin will "
f"be loaded after the Asset Registry is complete."
)
asset_registry.wait_for_completion()
unreal.log(f"Asset Registry is complete. Loading {plugin_name} plugin.")
|
import unreal
from unreal import (
BlendMode,
Material,
MaterialShadingModel,
MaterialInstanceBasePropertyOverrides,
MaterialInstanceConstant,
ParticleModuleRequired,
ParticleScreenAlignment,
ParticleSystem,
ParticleEmitter,
MaterialInterface,
)
# input
particle_system: ParticleSystem
root_path: str
print_log: bool = True
# output
result: bool = True
ALLOWED_SCREEN_ALIGNMENT = ParticleScreenAlignment.PSA_RECTANGLE
particle_name = particle_system.get_name()
particl_path = particle_system.get_path_name()
lod_distances = particle_system.get_editor_property("lod_distances")
lod_len = len(lod_distances)
emitters: list[ParticleEmitter] = particle_system.get_cascade_system_emitters()
for emitter in emitters:
# unreal.log(f"Processing Emitter: {emitter.get_name()}")
for lod_index in range(lod_len):
lod_level = emitter.get_cascade_emitter_lod_level(lod_index)
if lod_level:
required_module: ParticleModuleRequired = (
lod_level.get_lod_level_required_module()
)
if required_module:
screen_alignment: ParticleScreenAlignment
material_interface, screen_alignment, *_ = (
required_module.get_particle_module_required_per_renderer_props()
)
if screen_alignment != ALLOWED_SCREEN_ALIGNMENT:
result = False
if print_log:
unreal.log_warning(
f"""粒子屏幕对齐(ScreenAlignment)方式不合规, 只能使用Rectangle方式:
粒子路径: {particl_path}
LOD Level: {lod_index}
Emitter: {emitter.get_name()}
ScreenAlignment: {screen_alignment}
"""
)
|
"""Util module to query path info"""
import configparser
import unreal
PROJECT_CFG_FOLDER = unreal.Paths.project_config_dir()
EDITOR_CFG_FILE = PROJECT_CFG_FOLDER + "DefaultEditor.ini"
ENGINE_CFG_FILE = PROJECT_CFG_FOLDER + "DefaultEngine.ini"
GAME_CFG_FILE = PROJECT_CFG_FOLDER + "DefaultGame.ini"
INPUT_CFG_FILE = PROJECT_CFG_FOLDER + "DefaultInput.ini"
def get_usd_export_folder():
"""Get the usd export folder from the Editor cfg file."""
section_name = "UsdExport"
key_name= "UsdExportFolderPath"
# Get info from the "DefaultEditor.ini"
config = configparser.ConfigParser()
config.read(EDITOR_CFG_FILE)
try:
# might have to replace the '/' based on the OS.
return config[section_name][key_name]
except KeyError:
unreal.log_error(
f"Error parsing DefaultEditor.ini info for section {section_name} and key {key_name}"
)
return None
def get_otio_export_folder():
"""Get the otio export folder from the Editor cfg file."""
section_name = "UsdExport"
key_name= "OtioExportFolderPath"
# Get info from the "DefaultEditor.ini"
config = configparser.ConfigParser()
config.read(EDITOR_CFG_FILE)
try:
# might have to replace the '/' based on the OS.
return config[section_name][key_name]
except KeyError:
unreal.log_error(
f"Error parsing DefaultEditor.ini info for section {section_name} and key {key_name}"
)
return None
|
import unreal
def ClearAssetGrid(assetGrid):
assetGrid.clear_children()
|
import unreal
import sys
import os
print("=== CREATING CHARACTER SYSTEM IN HEADLESS MODE ===")
try:
# Step 1: Create directories
print("Creating directories...")
unreal.EditorAssetLibrary.make_directory('/project/')
unreal.EditorAssetLibrary.make_directory('/project/')
print("✓ Directories created")
# Step 2: Create Character Blueprint
print("Creating Character Blueprint...")
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
blueprint_factory = unreal.BlueprintFactory()
blueprint_factory.set_editor_property('parent_class', unreal.PaperCharacter)
character_bp = asset_tools.create_asset(
'WarriorCharacter',
'/project/',
unreal.Blueprint,
blueprint_factory
)
if character_bp:
print("✓ Character Blueprint created")
# Configure the Blueprint
default_object = character_bp.get_default_object()
if default_object:
# Set initial animation - PaperCharacter uses GetSprite() method
idle_anim = unreal.EditorAssetLibrary.load_asset('/project/')
if idle_anim:
# Try to get the PaperFlipbookComponent (sprite component)
try:
sprite_comp = default_object.get_sprite()
if sprite_comp:
sprite_comp.set_editor_property('source_flipbook', idle_anim)
print("✓ Set idle animation")
except:
print("Note: Could not set idle animation (Blueprint needs manual setup)")
# Configure movement
movement_comp = default_object.get_character_movement()
if movement_comp:
movement_comp.set_editor_property('max_walk_speed', 300.0)
movement_comp.set_editor_property('jump_z_velocity', 400.0)
movement_comp.set_editor_property('plane_constraint_enabled', True)
movement_comp.set_editor_property('plane_constraint_normal', unreal.Vector(0, 1, 0))
print("✓ Configured movement")
# Save the Blueprint
unreal.EditorAssetLibrary.save_asset(character_bp.get_path_name())
print("✓ Character Blueprint saved")
else:
print("✗ Failed to create Character Blueprint")
# Step 3: Create Game Mode
print("Creating Game Mode...")
gamemode_factory = unreal.BlueprintFactory()
gamemode_factory.set_editor_property('parent_class', unreal.GameModeBase)
gamemode_bp = asset_tools.create_asset(
'WarriorGameMode',
'/project/',
unreal.Blueprint,
gamemode_factory
)
if gamemode_bp:
print("✓ Game Mode created")
# Set default pawn class
default_object = gamemode_bp.get_default_object()
if default_object and character_bp:
character_class = character_bp.get_blueprint_generated_class()
if character_class:
default_object.set_editor_property('default_pawn_class', character_class)
print("✓ Set default pawn class")
# Save the Game Mode
unreal.EditorAssetLibrary.save_asset(gamemode_bp.get_path_name())
print("✓ Game Mode saved")
else:
print("✗ Failed to create Game Mode")
print("✅ CHARACTER SYSTEM CREATION COMPLETED SUCCESSFULLY!")
except Exception as e:
print(f"✗ ERROR: {e}")
import traceback
traceback.print_exc()
# Force exit to prevent hanging
print("Exiting...")
unreal.SystemLibrary.execute_console_command(None, "exit")
|
import unreal
def get_track(u_section):
"""
Get level u_seq track the section belongs
:param u_section: unreal.MovieSceneSection.
:return: unreal.MovieSceneTrack.
"""
return u_section.get_outer()
def get_seq(u_section):
"""
Get level u_seq the section belongs
:param u_section: unreal.MovieSceneSection.
:return: unreal.MovieSceneSequence.
"""
return u_section.get_outermost()
def get_sub_seq(u_section):
"""
Get level u_seq attached to the section
:param u_section: unreal.MovieSceneSection.
:return: unreal.MovieSceneSequence.
"""
return u_section.get_editor_property('SubSequence')
def set_sub_seq(u_section, u_seq):
"""
Attach a level sequence to the track
:param u_section: unreal.MovieSceneSection.
:param u_seq: unreal.MovieSceneSequence.
"""
u_section.set_sequence(u_seq)
def set_range(u_section, start, end):
"""
Set the level u_seq section active range
:param u_section: unreal.MovieSceneSection.
:param start: int. start frame
:param end: int. end frame
"""
if start >= end:
raise ValueError('Start frame cannot be equal/greater than end frame')
u_section.set_end_frame(end)
u_section.set_start_frame(start)
def bind_camera(u_section, u_binding):
"""
Attach a camera binding to the 'Camera Cut' track section
:param u_section: unreal.MovieSceneSection. has to be a section in the
'Camera Cut' track
:param u_binding: unreal.SequencerBindingProxy. the camera actor binding
to attach to the camera cut track section.
"""
u_section.set_camera_binding_id(u_binding.get_binding_id())
def set_skm_anim(u_section, u_anim_seq):
"""
Attach an animation sequence to the 'Skeletal Actor Binding' track's
section
:param u_section: unreal.MovieSceneSection. has to be a section in the
'Skeletal Actor Binding' track
:param u_anim_seq: unreal.AnimSequence.
"""
param = unreal.MovieSceneSkeletalAnimationParams()
param.set_editor_property('animation', u_anim_seq)
# section to house anim
u_section.set_editor_property('params', param)
u_section.set_completion_mode(unreal.MovieSceneCompletionMode.KEEP_STATE)
|
import unreal
for actor in unreal.EditorLevelLibrary.get_selected_level_actors():
if not isinstance(actor,unreal.StaticMeshActor):
continue
component = actor.get_component_by_class(unreal.StaticMeshComponent)
mesh = unreal.EditableMeshFactory.make_editable_mesh(component,0)
poly_count = mesh.get_polygon_count()
print(poly_count)
subd_count = mesh.get_subdivision_count()
print(subd_count)
mesh.set_subdivision_count()
poly_count = mesh.get_polygon_count()
print(poly_count)
subd_count = mesh.get_subdivision_count()
print(subd_count)
preview = mesh.is_previewing_subdivisions()
print(preview)
# mesh.tessellate_polygons([unreal.PolygonID(i) for i in range(poly_count-10)],unreal.TriangleTessellationMode.FOUR_TRIANGLES)
# mesh.tessellate_polygons([unreal.PolygonID(i) for i in range(8)],unreal.TriangleTessellationMode.FOUR_TRIANGLES)
# print(poly_count)
|
import unreal
level = unreal.EditorLevelLibrary.get_editor_world()
all_actors = unreal.GameplayStatics.get_all_actors_of_class(level, unreal.Actor)
for actor in all_actors:
# Get all components attached to the actor
components = actor.get_components_by_class(unreal.ActorComponent)
# Check if the actor has a PCGComponent
has_pcg_component = any(isinstance(component, unreal.PCGComponent) for component in components)
if has_pcg_component:
print(f"Actor '{actor.get_name()}' has a PCGComponent.")
for component in components:
if component.component_has_tag("PCG Generated Component"):
component.destroy_component(component)
#parent_component = component.get_attach_parent()
#if not parent_component:
for component in components:
if isinstance(component, unreal.PCGComponent):
print(f"Actor '{actor.get_name()}' has a PCGComponent.")
component.generate(True)
print(f" Called generate() on PCGComponent of actor '{actor.get_name()}'.")
# # Optional: Select all actors that meet the criteria in the Editor
# actors_to_select = [actor for actor in all_actors if any(isinstance(comp, unreal.PCGComponent) for comp in actor.get_components_by_class(unreal.ActorComponent))]
# unreal.EditorLevelLibrary.set_selected_level_actors(actors_to_select)
|
"""
Core dispatcher for executing dynamic Python commands received from the MCP server.
All specific action functions have been moved to their respective modules:
- util_actions.py
- asset_actions.py
- actor_actions.py
- material_actions.py
"""
import unreal # type: ignore # Suppress linter warning, 'unreal' module is available in UE Python environment
import json
import importlib
import traceback
# Core dispatcher for executing dynamic Python commands received from the MCP server
def execute_action(module_name: str, function_name: str, params: dict) -> str: # Changed args_list: list to params: dict
"""
Dynamically imports and executes the specified function from the given module.
It reloads the module on each call to ensure the latest version is used.
Args:
module_name (str): Name of the module containing the function (e.g., "util_actions", "actor_actions").
function_name (str): Name of the function to call (e.g., "ue_print_message").
params (dict): Dictionary of parameters to pass to the target function.
Returns:
str: JSON-formatted string representing the function's result or an error.
"""
try:
# Ensure the module name is valid and does not try to escape the intended directory
# This is a basic check; more robust sandboxing might be needed depending on security requirements.
if ".." in module_name or "/" in module_name or "\\" in module_name:
raise ValueError(f"Invalid module name: {module_name}. Contains restricted characters.")
# Dynamically import the module.
# Assuming these modules are in the Python path accessible by Unreal.
# For plugins, this usually means Content/Python or subdirectories.
target_module = importlib.import_module(module_name)
# Reload the module to pick up any changes without restarting Unreal.
# This is crucial for development and live updates.
importlib.reload(target_module)
target_function = getattr(target_module, function_name)
# Execute the function
# params is now expected to be a dictionary directly.
# Unpack the dictionary as keyword arguments to the target function.
result_json_str = target_function(**params)
# Validate if the result is indeed a JSON string (basic check)
try:
json.loads(result_json_str) # Try to parse it to ensure it's valid JSON
except json.JSONDecodeError as je:
# If the function didn't return a valid JSON string, wrap this error.
error_detail = f"Function '{module_name}.{function_name}' did not return a valid JSON string. Error: {je}. Returned: {result_json_str[:200]}"
return json.dumps({
"success": False,
"message": error_detail,
"traceback": traceback.format_exc(),
"type": "InvalidReturnFormat"
})
except TypeError as te:
# If result_json_str is not a string-like object (e.g. None)
error_detail = f"Function '{module_name}.{function_name}' returned a non-string type. Error: {te}. Returned type: {type(result_json_str).__name__}"
return json.dumps({
"success": False,
"message": error_detail,
"traceback": traceback.format_exc(),
"type": "InvalidReturnType"
})
return result_json_str # Return the JSON string as is
except ImportError:
return json.dumps({
"success": False,
"message": f"Could not import module '{module_name}'. Ensure it exists and is in Python path.",
"traceback": traceback.format_exc(),
"type": "ImportError"
})
except AttributeError:
return json.dumps({
"success": False,
"message": f"Function '{function_name}' not found in module '{module_name}'.",
"traceback": traceback.format_exc(),
"type": "AttributeError"
})
except ValueError as ve: # Catch specific ValueError from module name check
return json.dumps({
"success": False,
"message": str(ve),
"traceback": traceback.format_exc(),
"type": "ValueError"
})
except Exception as e:
# Catch all other exceptions during function execution
return json.dumps({
"success": False,
"message": f"Exception during execution of '{module_name}.{function_name}': {str(e)}",
"traceback": traceback.format_exc(), # Include traceback for debugging
"type": type(e).__name__
})
# All specific ue_... action functions have been moved to their respective files:
# - util_actions.py
# - asset_actions.py
# - actor_actions.py
# - material_actions.py
|
# Content/project/.py - Using UE settings integration
import unreal
import importlib.util
import os
import sys
import subprocess
import atexit
from utils import logging as log
# Global process handle for MCP server
mcp_server_process = None
def shutdown_mcp_server():
"""Shutdown the MCP server process when Unreal Editor closes"""
global mcp_server_process
if mcp_server_process:
log.log_info("Shutting down MCP server process...")
try:
mcp_server_process.terminate()
mcp_server_process = None
log.log_info("MCP server process terminated successfully")
except Exception as e:
log.log_error(f"Error terminating MCP server: {e}")
def start_mcp_server():
"""Start the external MCP server process"""
global mcp_server_process
try:
# Find our plugin's Python directory
plugin_python_path = None
for path in sys.path:
if "GenerativeAISupport/project/" in path:
plugin_python_path = path
break
if not plugin_python_path:
log.log_error("Could not find plugin Python path")
return False
# Get the mcp_server.py path
mcp_server_path = os.path.join(plugin_python_path, "mcp_server.py")
if not os.path.exists(mcp_server_path):
log.log_error(f"MCP server script not found at: {mcp_server_path}")
return False
# Start the MCP server as a separate process
python_exe = sys.executable
log.log_info(f"Starting MCP server using Python: {python_exe}")
log.log_info(f"MCP server script path: {mcp_server_path}")
# Create a detached process that will continue running
# even if Unreal crashes (we'll handle proper shutdown with atexit)
creationflags = 0
if sys.platform == 'win32':
creationflags = subprocess.CREATE_NEW_PROCESS_GROUP
mcp_server_process = subprocess.Popen(
[python_exe, mcp_server_path],
creationflags=creationflags,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
log.log_info(f"MCP server started with PID: {mcp_server_process.pid}")
# Register cleanup handler to ensure process is terminated when Unreal exits
atexit.register(shutdown_mcp_server)
return True
except Exception as e:
log.log_error(f"Error starting MCP server: {e}")
return False
def initialize_socket_server():
"""
Initialize the socket server if auto-start is enabled in UE settings
"""
auto_start = False
# Get settings from UE settings system
try:
# First get the class reference
settings_class = unreal.load_class(None, '/project/.GenerativeAISupportSettings')
if settings_class:
# Get the settings object using the class reference
settings = unreal.get_default_object(settings_class)
# Log available properties for debugging
log.log_info(f"Settings object properties: {dir(settings)}")
# Check if auto-start is enabled
if hasattr(settings, 'auto_start_socket_server'):
auto_start = settings.auto_start_socket_server
log.log_info(f"Socket server auto-start setting: {auto_start}")
else:
log.log_warning("auto_start_socket_server property not found in settings")
# Try alternative property names that might exist
for prop in dir(settings):
if 'auto' in prop.lower() or 'socket' in prop.lower() or 'server' in prop.lower():
log.log_info(f"Found similar property: {prop}")
else:
log.log_error("Could not find GenerativeAISupportSettings class")
except Exception as e:
log.log_error(f"Error reading UE settings: {e}")
log.log_info("Falling back to disabled auto-start")
# Auto-start if configured
if auto_start:
log.log_info("Auto-starting Unreal Socket Server...")
# Start Unreal Socket Server
try:
# Find our plugin's Python directory
plugin_python_path = None
for path in sys.path:
if "GenerativeAISupport/project/" in path:
plugin_python_path = path
break
if plugin_python_path:
server_path = os.path.join(plugin_python_path, "unreal_socket_server.py")
if os.path.exists(server_path):
# Import and execute the server module
spec = importlib.util.spec_from_file_location("unreal_socket_server", server_path)
server_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(server_module)
log.log_info("Unreal Socket Server started successfully")
# Now start the MCP server
if start_mcp_server():
log.log_info("Both servers started successfully")
else:
log.log_error("Failed to start MCP server")
else:
log.log_error(f"Server file not found at: {server_path}")
else:
log.log_error("Could not find plugin Python path")
except Exception as e:
log.log_error(f"Error starting socket server: {e}")
else:
log.log_info("Unreal Socket Server auto-start is disabled")
# Run initialization when this script is loaded
initialize_socket_server()
|
import unreal
from datetime import date
unreal.EditorDialog.show_message("The title", "The message", unreal.AppMsgType.YES_NO)
today = date.today()
print(f"Today is {today}")
print(unreal.EditorUtilityLibrary().get_selected_assets())
def create_shopping_item(price, name):
return {
"name": name,
"price": price
}
shopping_list = []
shopping_list.append(create_shopping_item(10, "rice"))
shopping_list.append(create_shopping_item(20, "beans"))
print(shopping_list)
|
import sys
import os
import pathlib
import unreal
from PySide2 import QtWidgets, QtUiTools, QtGui
#Import UE python lib
import m2_unreal.observer as observer
import m2_unreal.movie_render as mr
import m2_unreal.config as config
#RELOAD MODULE
import importlib
importlib.reload(observer)
importlib.reload(mr)
WINDOW_NAME = 'M2 - Send Render Job'
UI_FILE_FULLNAME = __file__.replace('.py', '.ui')
class QtWindowSendRenderJobs(QtWidgets.QWidget):
def __init__(self, parent=None):
super(QtWindowSendRenderJobs, self).__init__(parent)
self.aboutToClose = None # This is used to stop the tick when the window is closed
self.widget = QtUiTools.QUiLoader().load(UI_FILE_FULLNAME)
self.widget.setParent(self)
self.setWindowTitle(WINDOW_NAME)
self.setGeometry(100, 100, self.widget.width(), self.widget.height())
self.layout = QtWidgets.QVBoxLayout(self)
self.layout.addWidget(self.widget)
self.setLayout(self.layout)
#Extend list asset to allow multiple selection
self.widget.list_shots.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.widget.asset_filter.textChanged.connect(self.filter_asset)
#QComboBox project_comboBox
self.combobox1 = self.widget.project_comboBox
self.make_projects_list()
self.combobox1.currentIndexChanged.connect(self.combo_sel_change)
self.combobox1.setCurrentIndex(-1)
self.shotsDict = {}
self.preset_combobox = self.widget.preset_comboBox
self.make_presets_list()
self.render_checkbox = self.widget.render_checkBox
self.transfer_checkbox = self.widget.transfer_checkBox
#send render jobs button
self.widget.makeJobsButton.clicked.connect(self.send_render_jobs)
self.widget.episode_list_widget.itemSelectionChanged.connect(self.episode_list_sel_change)
def send_render_jobs(self):
# clean up th queue
mr.cleanup_queue()
self.preset = self.preset_combobox.currentText()
preset_address = f'{config.mp_presets}/{self.preset}.{self.preset}'
user_home_address = os.path.expanduser('~')
self.list = self.widget.list_shots.selectedItems()
output_folders = []
for i in self.list:
shot_name = i.text()
sequencer_name = f'{config.shots_path}/{self.episode}/{shot_name}/{shot_name}_SEQ.{shot_name}_SEQ'
map_name = f'{config.shots_path}/{self.episode}/{shot_name}/{shot_name}.{shot_name}'
# make output folder
output_folder = user_home_address + f'\LIVE\{self.project}\{self.episode}\COMMON\RENDER\{self.project}_{self.episode}_{shot_name}'
folder = pathlib.Path(output_folder)
if not folder.exists ():
os.makedirs(folder)
output_folders.append(output_folder)
mr.make_render_job(shot_name,sequencer_name, map_name,output_folder,preset_address)
# after making the jobs now render them
do_render = self.render_checkbox.isChecked()
do_transfer = self.transfer_checkbox.isChecked()
if do_render:
mr.render_jobs(output_folders,do_transfer)
def filter_asset(self):
text = self.widget.asset_filter.text()
self.widget.list_shots.clear()
for key, value in sorted(self.shotsDict.items()):
if text in key:
self.widget.list_shots.addItem(key)
def make_list_shots(self):
self.shotsDict = observer.make_shot_list(self.project, self.episode)
self.widget.list_shots.clear()
for key, value in sorted(self.shotsDict.items()):
self.widget.list_shots.addItem(key)
def make_projects_list(self):
proj_list = observer.make_project_dict()
for proj in proj_list:
self.combobox1.addItem(proj)
def make_episode_list(self):
if self.project != None:
episode_list = observer.make_episodes_list(self.project)
self.widget.episode_list_widget.clear()
for epl in episode_list:
self.widget.episode_list_widget.addItem(epl)
def combo_sel_change(self):
self.project = self.combobox1.currentText()
self.episode = self.widget.episode_list_widget.currentItem()
if self.project != '':
unreal.log('Import shot list of project : ' + self.project)
self.make_episode_list()
self.make_list_shots()
def episode_list_sel_change(self):
self.project = self.combobox1.currentText()
selected_items = self.episode = self.widget.episode_list_widget.selectedItems()
if len(selected_items) > 0:
self.episode = self.widget.episode_list_widget.selectedItems()[0].text()
else:
self.episode = ''
self.make_list_shots()
def make_presets_list(self):
presets_list = observer.get_presets_list()
print(presets_list)
self.preset_combobox.addItems(presets_list)
app = None
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
widget = QtWindowSendRenderJobs()
widget.show()
unreal.parent_external_window_to_slate(widget.winId())
|
# Copyright Epic Games, Inc. All Rights Reserved
# Built-In
import os
import re
import json
import traceback
from collections import OrderedDict
# External
import unreal
from deadline_service import get_global_deadline_service_instance
from deadline_job import DeadlineJob
from deadline_utils import get_deadline_info_from_preset
@unreal.uclass()
class MoviePipelineDeadlineRemoteExecutor(unreal.MoviePipelineExecutorBase):
"""
This class defines the editor implementation for Deadline (what happens when you
press 'Render (Remote)', which is in charge of taking a movie queue from the UI
and processing it into something Deadline can handle.
"""
# The queue we are working on, null if no queue has been provided.
pipeline_queue = unreal.uproperty(unreal.MoviePipelineQueue)
job_ids = unreal.uproperty(unreal.Array(str))
# A MoviePipelineExecutor implementation must override this.
@unreal.ufunction(override=True)
def execute(self, pipeline_queue):
"""
This is called when the user presses Render (Remote) in the UI. We will
split the queue up into multiple jobs. Each job will be submitted to
deadline separately, with each shot within the job split into one Deadline
task per shot.
"""
unreal.log(f"Asked to execute Queue: {pipeline_queue}")
unreal.log(f"Queue has {len(pipeline_queue.get_jobs())} jobs")
# Don't try to process empty/null Queues, no need to send them to
# Deadline.
if not pipeline_queue or (not pipeline_queue.get_jobs()):
self.on_executor_finished_impl()
return
# The user must save their work and check it in so that Deadline
# can sync it.
dirty_packages = []
dirty_packages.extend(
unreal.EditorLoadingAndSavingUtils.get_dirty_content_packages()
)
dirty_packages.extend(
unreal.EditorLoadingAndSavingUtils.get_dirty_map_packages()
)
# Sometimes the dialog will return `False`
# even when there are no packages to save. so we are
# being explict about the packages we need to save
if dirty_packages:
if not unreal.EditorLoadingAndSavingUtils.save_dirty_packages_with_dialog(
True, True
):
message = (
"One or more jobs in the queue have an unsaved map/content. "
"{packages} "
"Please save and check-in all work before submission.".format(
packages="\n".join(dirty_packages)
)
)
unreal.log_error(message)
unreal.EditorDialog.show_message(
"Unsaved Maps/Content", message, unreal.AppMsgType.OK
)
self.on_executor_finished_impl()
return
# Make sure all the maps in the queue exist on disk somewhere,
# unsaved maps can't be loaded on the remote machine, and it's common
# to have the wrong map name if you submit without loading the map.
has_valid_map = (
unreal.MoviePipelineEditorLibrary.is_map_valid_for_remote_render(
pipeline_queue.get_jobs()
)
)
if not has_valid_map:
message = (
"One or more jobs in the queue have an unsaved map as "
"their target map. "
"These unsaved maps cannot be loaded by an external process, "
"and the render has been aborted."
)
unreal.log_error(message)
unreal.EditorDialog.show_message(
"Unsaved Maps", message, unreal.AppMsgType.OK
)
self.on_executor_finished_impl()
return
self.pipeline_queue = pipeline_queue
deadline_settings = unreal.get_default_object(
unreal.MoviePipelineDeadlineSettings
)
# Arguments to pass to the executable. This can be modified by settings
# in the event a setting needs to be applied early.
# In the format of -foo -bar
# commandLineArgs = ""
command_args = []
# Append all of our inherited command line arguments from the editor.
in_process_executor_settings = unreal.get_default_object(
unreal.MoviePipelineInProcessExecutorSettings
)
inherited_cmds = in_process_executor_settings.inherited_command_line_arguments
# Sanitize the commandline by removing any execcmds that may
# have passed through the commandline.
# We remove the execcmds because, in some cases, users may execute a
# script that is local to their editor build for some automated
# workflow but this is not ideal on the farm. We will expect all
# custom startup commands for rendering to go through the `Start
# Command` in the MRQ settings.
inherited_cmds = re.sub(
".*(?P<cmds>-execcmds=[\s\S]+[\'\"])",
"",
inherited_cmds
)
command_args.extend(inherited_cmds.split(" "))
command_args.extend(
in_process_executor_settings.additional_command_line_arguments.split(
" "
)
)
command_args.extend(
["-nohmd", "-windowed", f"-ResX=1280", f"-ResY=720"]
)
# Get the project level preset
project_preset = deadline_settings.default_job_preset
# Get the job and plugin info string.
# Note:
# Sometimes a project level default may not be set,
# so if this returns an empty dictionary, that is okay
# as we primarily care about the job level preset.
# Catch any exceptions here and continue
try:
project_job_info, project_plugin_info = get_deadline_info_from_preset(job_preset=project_preset)
except Exception:
pass
deadline_service = get_global_deadline_service_instance()
for job in self.pipeline_queue.get_jobs():
unreal.log(f"Submitting Job `{job.job_name}` to Deadline...")
try:
# Create a Deadline job object with the default project level
# job info and plugin info
deadline_job = DeadlineJob(project_job_info, project_plugin_info)
deadline_job_id = self.submit_job(
job, deadline_job, command_args, deadline_service
)
except Exception as err:
unreal.log_error(
f"Failed to submit job `{job.job_name}` to Deadline, aborting render. \n\tError: {str(err)}"
)
unreal.log_error(traceback.format_exc())
self.on_executor_errored_impl(None, True, str(err))
unreal.EditorDialog.show_message(
"Submission Result",
f"Failed to submit job `{job.job_name}` to Deadline with error: {str(err)}. "
f"See log for more details.",
unreal.AppMsgType.OK,
)
self.on_executor_finished_impl()
return
if not deadline_job_id:
message = (
f"A problem occurred submitting `{job.job_name}`. "
f"Either the job doesn't have any data to submit, "
f"or an error occurred getting the Deadline JobID. "
f"This job status would not be reflected in the UI. "
f"Check the logs for more details."
)
unreal.log_warning(message)
unreal.EditorDialog.show_message(
"Submission Result", message, unreal.AppMsgType.OK
)
return
else:
unreal.log(f"Deadline JobId: {deadline_job_id}")
self.job_ids.append(deadline_job_id)
# Store the Deadline JobId in our job (the one that exists in
# the queue, not the duplicate) so we can match up Movie
# Pipeline jobs with status updates from Deadline.
job.user_data = deadline_job_id
# Now that we've sent a job to Deadline, we're going to request a status
# update on them so that they transition from "Ready" to "Queued" or
# their actual status in Deadline. self.request_job_status_update(
# deadline_service)
message = (
f"Successfully submitted {len(self.job_ids)} jobs to Deadline. JobIds: {', '.join(self.job_ids)}. "
f"\nPlease use Deadline Monitor to track render job statuses"
)
unreal.log(message)
unreal.EditorDialog.show_message(
"Submission Result", message, unreal.AppMsgType.OK
)
# Set the executor to finished
self.on_executor_finished_impl()
@unreal.ufunction(override=True)
def is_rendering(self):
# Because we forward unfinished jobs onto another service when the
# button is pressed, they can always submit what is in the queue and
# there's no need to block the queue.
# A MoviePipelineExecutor implementation must override this. If you
# override a ufunction from a base class you don't specify the return
# type or parameter types.
return False
def submit_job(self, job, deadline_job, command_args, deadline_service):
"""
Submit a new Job to Deadline
:param job: Queued job to submit
:param deadline_job: Deadline job object
:param list[str] command_args: Commandline arguments to configure for the Deadline Job
:param deadline_service: An instance of the deadline service object
:returns: Deadline Job ID
:rtype: str
"""
# Get the Job Info and plugin Info
# If we have a preset set on the job, get the deadline submission details
try:
job_info, plugin_info = get_deadline_info_from_preset(job_preset_struct=job.get_deadline_job_preset_struct_with_overrides())
# Fail the submission if any errors occur
except Exception as err:
raise RuntimeError(
f"An error occurred getting the deadline job and plugin "
f"details. \n\tError: {err} "
)
# check for required fields in pluginInfo
if "Executable" not in plugin_info:
raise RuntimeError("An error occurred formatting the Plugin Info string. \n\tMissing \"Executable\" key")
elif not plugin_info["Executable"]:
raise RuntimeError(f"An error occurred formatting the Plugin Info string. \n\tExecutable value cannot be empty")
if "ProjectFile" not in plugin_info:
raise RuntimeError("An error occurred formatting the Plugin Info string. \n\tMissing \"ProjectFile\" key")
elif not plugin_info["ProjectFile"]:
raise RuntimeError(f"An error occurred formatting the Plugin Info string. \n\tProjectFile value cannot be empty")
# Update the job info with overrides from the UI
if job.batch_name:
job_info["BatchName"] = job.batch_name
if hasattr(job, "comment") and not job_info.get("Comment"):
job_info["Comment"] = job.comment
if not job_info.get("Name") or job_info["Name"] == "Untitled":
job_info["Name"] = job.job_name
if job.author:
job_info["UserName"] = job.author
if unreal.Paths.is_project_file_path_set():
# Trim down to just "Game.uproject" instead of absolute path.
game_name_or_project_file = (
unreal.Paths.convert_relative_path_to_full(
unreal.Paths.get_project_file_path()
)
)
else:
raise RuntimeError(
"Failed to get a project name. Please set a project!"
)
# Create a new queue with only this job in it and save it to disk,
# then load it, so we can send it with the REST API
new_queue = unreal.MoviePipelineQueue()
new_job = new_queue.duplicate_job(job)
duplicated_queue, manifest_path = unreal.MoviePipelineEditorLibrary.save_queue_to_manifest_file(
new_queue
)
# Convert the queue to text (load the serialized json from disk) so we
# can send it via deadline, and deadline will write the queue to the
# local machines on job startup.
serialized_pipeline = unreal.MoviePipelineEditorLibrary.convert_manifest_file_to_string(
manifest_path
)
# Loop through our settings in the job and let them modify the command
# line arguments/params.
new_job.get_configuration().initialize_transient_settings()
# Look for our Game Override setting to pull the game mode to start
# with. We start with this game mode even on a blank map to override
# the project default from kicking in.
game_override_class = None
out_url_params = []
out_command_line_args = []
out_device_profile_cvars = []
out_exec_cmds = []
for setting in new_job.get_configuration().get_all_settings():
out_url_params, out_command_line_args, out_device_profile_cvars, out_exec_cmds = setting.build_new_process_command_line_args(
out_url_params,
out_command_line_args,
out_device_profile_cvars,
out_exec_cmds,
)
# Set the game override
if setting.get_class() == unreal.MoviePipelineGameOverrideSetting.static_class():
game_override_class = setting.game_mode_override
# This triggers the editor to start looking for render jobs when it
# finishes loading.
out_exec_cmds.append("py mrq_rpc.py")
# Convert the arrays of command line args, device profile cvars,
# and exec cmds into actual commands for our command line.
command_args.extend(out_command_line_args)
if out_device_profile_cvars:
# -dpcvars="arg0,arg1,..."
command_args.append(
'-dpcvars="{dpcvars}"'.format(
dpcvars=",".join(out_device_profile_cvars)
)
)
if out_exec_cmds:
# -execcmds="cmd0,cmd1,..."
command_args.append(
'-execcmds="{cmds}"'.format(cmds=",".join(out_exec_cmds))
)
# Add support for telling the remote process to wait for the
# asset registry to complete synchronously
command_args.append("-waitonassetregistry")
# Build a shot-mask from this sequence, to split into the appropriate
# number of tasks. Remove any already-disabled shots before we
# generate a list, otherwise we make unneeded tasks which get sent to
# machines
shots_to_render = []
for shot_index, shot in enumerate(new_job.shot_info):
if not shot.enabled:
unreal.log(
f"Skipped submitting shot {shot_index} in {job.job_name} "
f"to server due to being already disabled!"
)
else:
shots_to_render.append(shot.outer_name)
# If there are no shots enabled,
# "these are not the droids we are looking for", move along ;)
# We will catch this later and deal with it
if not shots_to_render:
unreal.log_warning("No shots enabled in shot mask, not submitting.")
return
# Divide the job to render by the chunk size
# i.e {"O": "my_new_shot"} or {"0", "shot_1,shot_2,shot_4"}
chunk_size = int(job_info.get("ChunkSize", 1))
shots = {}
frame_list = []
for index in range(0, len(shots_to_render), chunk_size):
shots[str(index)] = ",".join(shots_to_render[index : index + chunk_size])
frame_list.append(str(index))
job_info["Frames"] = ",".join(frame_list)
# Get the current index of the ExtraInfoKeyValue pair, we will
# increment the index, so we do not stomp other settings
extra_info_key_indexs = set()
for key in job_info.keys():
if key.startswith("ExtraInfoKeyValue"):
_, index = key.split("ExtraInfoKeyValue")
extra_info_key_indexs.add(int(index))
# Get the highest number in the index list and increment the number
# by one
current_index = max(extra_info_key_indexs) + 1 if extra_info_key_indexs else 0
# Put the serialized Queue into the Job data but hidden from
# Deadline UI
job_info[f"ExtraInfoKeyValue{current_index}"] = f"serialized_pipeline={serialized_pipeline}"
# Increment the index
current_index += 1
# Put the shot info in the job extra info keys
job_info[f"ExtraInfoKeyValue{current_index}"] = f"shot_info={json.dumps(shots)}"
current_index += 1
# Set the job output directory override on the deadline job
if hasattr(new_job, "output_directory_override"):
if new_job.output_directory_override.path:
job_info[f"ExtraInfoKeyValue{current_index}"] = f"output_directory_override={new_job.output_directory_override.path}"
current_index += 1
# Set the job filename format override on the deadline job
if hasattr(new_job, "filename_format_override"):
if new_job.filename_format_override:
job_info[f"ExtraInfoKeyValue{current_index}"] = f"filename_format_override={new_job.filename_format_override}"
current_index += 1
# Build the command line arguments the remote machine will use.
# The Deadline plugin will provide the executable since it is local to
# the machine. It will also write out queue manifest to the correct
# location relative to the Saved folder
# Get the current commandline args from the plugin info
plugin_info_cmd_args = [plugin_info.get("CommandLineArguments", "")]
if not plugin_info.get("ProjectFile"):
project_file = plugin_info.get("ProjectFile", game_name_or_project_file)
plugin_info["ProjectFile"] = project_file
# This is the map included in the plugin to boot up to.
project_cmd_args = [
f"MoviePipelineEntryMap?game={game_override_class.get_path_name()}"
]
# Combine all the compiled arguments
full_cmd_args = project_cmd_args + command_args + plugin_info_cmd_args
# Remove any duplicates in the commandline args and convert to a string
full_cmd_args = " ".join(list(OrderedDict.fromkeys(full_cmd_args))).strip()
unreal.log(f"Deadline job command line args: {full_cmd_args}")
# Update the plugin info with the commandline arguments
plugin_info.update(
{
"CommandLineArguments": full_cmd_args,
"CommandLineMode": "false",
}
)
deadline_job.job_info = job_info
deadline_job.plugin_info = plugin_info
# Submit the deadline job
return deadline_service.submit_job(deadline_job)
# TODO: For performance reasons, we will skip updating the UI and request
# that users use a different mechanism for checking on job statuses.
# This will be updated once we have a performant solution.
|
"""
Integration tests for unreal-blender-mcp system.
"""
import os
import sys
import json
import asyncio
import unittest
import tempfile
from typing import Dict, Any, List, Tuple
from tests.integration.test_config import (
get_test_script_path,
TEST_SCENARIOS
)
from tests.integration.connections import (
ping_blender,
ping_unreal,
ping_mcp,
execute_script_file,
execute_cross_platform_workflow,
send_mcp_message,
ConnectionError
)
class IntegrationTests(unittest.TestCase):
"""Integration tests for the unreal-blender-mcp system."""
@classmethod
def setUpClass(cls):
"""Set up the test environment."""
# Ensure all components are running
try:
asyncio.run(cls.check_services())
except ConnectionError as e:
print(f"Service check failed: {e}")
print("Please ensure all components (MCP, Blender, Unreal) are running")
sys.exit(1)
@classmethod
async def check_services(cls):
"""Check if all required services are running."""
tasks = [
ping_blender(),
ping_unreal(),
ping_mcp()
]
blender_alive, unreal_alive, mcp_alive = await asyncio.gather(*tasks)
if not blender_alive:
raise ConnectionError("Blender server is not running")
if not unreal_alive:
raise ConnectionError("Unreal Engine server is not running")
if not mcp_alive:
raise ConnectionError("MCP server is not running")
def test_blender_connection(self):
"""Test connection to Blender."""
result = asyncio.run(ping_blender())
self.assertTrue(result, "Failed to connect to Blender")
def test_unreal_connection(self):
"""Test connection to Unreal Engine."""
result = asyncio.run(ping_unreal())
self.assertTrue(result, "Failed to connect to Unreal Engine")
def test_mcp_connection(self):
"""Test connection to MCP server."""
result = asyncio.run(ping_mcp())
self.assertTrue(result, "Failed to connect to MCP server")
def test_blender_create_cube(self):
"""Test creating a cube in Blender."""
script_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'test_data', 'create_cube.py')
result = asyncio.run(execute_script_file(script_path, 'blender'))
self.assertEqual(result.get('status'), 'success', f"Failed to create cube: {result.get('message')}")
self.assertEqual(result.get('object_name'), 'TestCube')
def test_blender_create_material(self):
"""Test creating a material in Blender."""
script_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'test_data', 'create_material.py')
result = asyncio.run(execute_script_file(script_path, 'blender'))
self.assertEqual(result.get('status'), 'success', f"Failed to create material: {result.get('message')}")
self.assertEqual(result.get('material_name'), 'TestMaterial')
def test_unreal_create_actor(self):
"""Test creating an actor in Unreal Engine."""
script_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'test_data', 'create_actor.py')
result = asyncio.run(execute_script_file(script_path, 'unreal'))
self.assertEqual(result.get('status'), 'success', f"Failed to create actor: {result.get('message')}")
self.assertEqual(result.get('actor_label'), 'TestCube')
def test_unreal_create_blueprint(self):
"""Test creating a blueprint in Unreal Engine."""
script_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'test_data', 'create_blueprint.py')
result = asyncio.run(execute_script_file(script_path, 'unreal'))
self.assertEqual(result.get('status'), 'success', f"Failed to create blueprint: {result.get('message')}")
self.assertEqual(result.get('blueprint_name'), 'TestBlueprint')
def test_cross_platform_workflow(self):
"""Test cross-platform workflow (export from Blender, import to Unreal)."""
blender_script_path = os.path.join(
os.path.dirname(os.path.dirname(__file__)),
'test_data',
'export_from_blender.py'
)
unreal_script_path = os.path.join(
os.path.dirname(os.path.dirname(__file__)),
'test_data',
'import_to_unreal.py'
)
result = asyncio.run(execute_cross_platform_workflow(blender_script_path, unreal_script_path))
self.assertEqual(result.get('status'), 'success', f"Cross-platform workflow failed: {result.get('message')}")
self.assertEqual(result.get('blender_result', {}).get('object_name'), 'ExportSphere')
self.assertEqual(result.get('unreal_result', {}).get('asset_name'), 'ImportedSphere')
def test_mcp_blender_tool_execution(self):
"""Test executing a Blender tool through the MCP server."""
message = {
"type": "tool_call",
"tool": "mcp_blender_create_primitive",
"args": {
"type": "CUBE",
"location": [0, 0, 0],
"color": [1, 0, 0]
}
}
result = asyncio.run(send_mcp_message(message))
self.assertEqual(result.get('status'), 'success', f"MCP Blender tool execution failed: {result.get('message')}")
def test_mcp_unreal_tool_execution(self):
"""Test executing an Unreal tool through the MCP server."""
message = {
"type": "tool_call",
"tool": "mcp_unreal_execute_code",
"args": {
"code": """
import unreal
actor_location = unreal.Vector(0, 0, 0)
actor_rotation = unreal.Rotator(0, 0, 0)
cube = unreal.EditorLevelLibrary.spawn_actor_from_class(
unreal.StaticMeshActor,
actor_location,
actor_rotation
)
print(f"Created actor: {cube.get_name()}")
"""
}
}
result = asyncio.run(send_mcp_message(message))
self.assertEqual(result.get('status'), 'success', f"MCP Unreal tool execution failed: {result.get('message')}")
if __name__ == '__main__':
unittest.main()
|
# Copyright (c) <2021> Side Effects Software Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. The name of Side Effects Software may not be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import math
import unreal
@unreal.uclass()
class CurveInputExample(unreal.PlacedEditorUtilityBase):
# Use a FProperty to hold the reference to the API wrapper we create in
# run_curve_input_example
_asset_wrapper = unreal.uproperty(unreal.HoudiniPublicAPIAssetWrapper)
@unreal.ufunction(meta=dict(BlueprintCallable=True, CallInEditor=True))
def run_curve_input_example(self):
# Get the API instance
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
# Ensure we have a running session
if not api.is_session_valid():
api.create_session()
# Load our HDA uasset
example_hda = unreal.load_object(None, '/project/.copy_to_curve_1_0')
# Create an API wrapper instance for instantiating the HDA and interacting with it
wrapper = api.instantiate_asset(example_hda, instantiate_at=unreal.Transform())
if wrapper:
# Pre-instantiation is the earliest point where we can set parameter values
wrapper.on_pre_instantiation_delegate.add_function(self, '_set_initial_parameter_values')
# Jumping ahead a bit: we also want to configure inputs, but inputs are only available after instantiation
wrapper.on_post_instantiation_delegate.add_function(self, '_set_inputs')
# Jumping ahead a bit: we also want to print the outputs after the node has cook and the plug-in has processed the output
wrapper.on_post_processing_delegate.add_function(self, '_print_outputs')
self.set_editor_property('_asset_wrapper', wrapper)
@unreal.ufunction(params=[unreal.HoudiniPublicAPIAssetWrapper], meta=dict(CallInEditor=True))
def _set_initial_parameter_values(self, in_wrapper):
""" Set our initial parameter values: disable upvectorstart and set the scale to 0.2. """
# Uncheck the upvectoratstart parameter
in_wrapper.set_bool_parameter_value('upvectoratstart', False)
# Set the scale to 0.2
in_wrapper.set_float_parameter_value('scale', 0.2)
# Since we are done with setting the initial values, we can unbind from the delegate
in_wrapper.on_pre_instantiation_delegate.remove_function(self, '_set_initial_parameter_values')
@unreal.ufunction(params=[unreal.HoudiniPublicAPIAssetWrapper], meta=dict(CallInEditor=True))
def _set_inputs(self, in_wrapper):
""" Configure our inputs: input 0 is a cube and input 1 a helix. """
# Create an empty geometry input
geo_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPIGeoInput)
# Load the cube static mesh asset
cube = unreal.load_object(None, '/project/.Cube')
# Set the input object array for our geometry input, in this case containing only the cube
geo_input.set_input_objects((cube, ))
# Set the input on the instantiated HDA via the wrapper
in_wrapper.set_input_at_index(0, geo_input)
# Create a curve input
curve_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPICurveInput)
# Create a curve wrapper/helper
curve_object = unreal.HoudiniPublicAPICurveInputObject(curve_input)
# Make it a Nurbs curve
curve_object.set_curve_type(unreal.HoudiniPublicAPICurveType.NURBS)
# Set the points of the curve, for this example we create a helix
# consisting of 100 points
curve_points = []
for i in range(100):
t = i / 20.0 * math.pi * 2.0
x = 100.0 * math.cos(t)
y = 100.0 * math.sin(t)
z = i
curve_points.append(unreal.Transform([x, y, z], [0, 0, 0], [1, 1, 1]))
curve_object.set_curve_points(curve_points)
# Set the curve wrapper as an input object
curve_input.set_input_objects((curve_object, ))
# Copy the input data to the HDA as node input 1
in_wrapper.set_input_at_index(1, curve_input)
# unbind from the delegate, since we are done with setting inputs
in_wrapper.on_post_instantiation_delegate.remove_function(self, '_set_inputs')
@unreal.ufunction(params=[unreal.HoudiniPublicAPIAssetWrapper], meta=dict(CallInEditor=True))
def _print_outputs(self, in_wrapper):
""" Print the outputs that were generated by the HDA (after a cook) """
num_outputs = in_wrapper.get_num_outputs()
print('num_outputs: {}'.format(num_outputs))
if num_outputs > 0:
for output_idx in range(num_outputs):
identifiers = in_wrapper.get_output_identifiers_at(output_idx)
print('\toutput index: {}'.format(output_idx))
print('\toutput type: {}'.format(in_wrapper.get_output_type_at(output_idx)))
print('\tnum_output_objects: {}'.format(len(identifiers)))
if identifiers:
for identifier in identifiers:
output_object = in_wrapper.get_output_object_at(output_idx, identifier)
output_component = in_wrapper.get_output_component_at(output_idx, identifier)
is_proxy = in_wrapper.is_output_current_proxy_at(output_idx, identifier)
print('\t\tidentifier: {}'.format(identifier))
print('\t\toutput_object: {}'.format(output_object.get_name() if output_object else 'None'))
print('\t\toutput_component: {}'.format(output_component.get_name() if output_component else 'None'))
print('\t\tis_proxy: {}'.format(is_proxy))
print('')
def run():
# Spawn CurveInputExample and call run_curve_input_example
curve_input_example_actor = unreal.EditorLevelLibrary.spawn_actor_from_class(CurveInputExample.static_class(), unreal.Vector.ZERO, unreal.Rotator())
curve_input_example_actor.run_curve_input_example()
if __name__ == '__main__':
run()
|
import unreal
from pathlib import Path
from typing import Tuple
from CommonFunctions import *
from HardsurfacePropPrefabFix import *
string_lib = unreal.StringLibrary()
system_lib = unreal.SystemLibrary()
decal_suffix = "_Decal"
mesh_folder_name = "Meshes"
selected_assets = unreal.EditorUtilityLibrary.get_selected_assets()
# 路径构建
asset_pathname = selected_assets[0].get_path_name()
asset_path = Path(asset_pathname).parent
# 处理所选asset不在meshes下的情况
if string_lib.contains(str(asset_path), "\\Meshes") is True:
asset_path_split = string_lib.split(
source_string=str(asset_path), str="\\" + mesh_folder_name
)
else:
asset_path_split = string_lib.split(source_string=str(asset_path), str="\\")
level_path = string_lib.replace(asset_path_split[0], from_="\\", to="/")
asset_subpath = string_lib.replace(asset_path_split[1], from_="\\", to="/")
# 处理所选asset在meshes子目录下的情况,把subpath的值从 /AAA 变成 AAA/
if string_lib.starts_with(asset_subpath, "/") is True:
asset_subpath_t = string_lib.split(asset_subpath, "/")
asset_subpath = asset_subpath_t[1] + "/"
def add_subobject(
subsystem: unreal.SubobjectDataSubsystem,
blueprint: unreal.Blueprint,
new_class,
name: str,
) -> Tuple[unreal.SubobjectDataHandle, unreal.Object]:
root_data_handle: unreal.SubobjectDataHandle = (
subsystem.k2_gather_subobject_data_for_blueprint(context=blueprint)[0]
)
sub_handle, fail_reason = subsystem.add_new_subobject(
params=unreal.AddNewSubobjectParams(
parent_handle=root_data_handle,
new_class=new_class,
blueprint_context=blueprint,
)
)
if not fail_reason.is_empty():
raise Exception(
"ERROR from sub_object_subsystem.add_new_subobject: {fail_reason}"
)
subsystem.rename_subobject(handle=sub_handle, new_name=unreal.Text(name))
# subsystem.attach_subobject(owner_handle=root_data_handle, child_to_add_handle=sub_handle)
BFL = unreal.SubobjectDataBlueprintFunctionLibrary
obj: object = BFL.get_object(BFL.get_data(sub_handle))
return sub_handle, obj
def load_mesh(path: str) -> unreal.StaticMesh:
asset = unreal.EditorAssetLibrary.load_asset(path)
if not isinstance(asset, unreal.StaticMesh):
raise Exception("Failed to load StaticMesh from {path}")
return asset
def make_prop_blueprint(
mesh_path: str,
mesh_name: str,
prefab_path: str,
prefab_name: str,
parent_bp_path: str,
):
# PhysicsActor: unreal.Name = unreal.Name("PhysicsActor")
BaseCollision = unreal.Name("CamToHiddenMesh") #"CamToHiddenMesh"可以实现相机穿透功能,使用Actor Tag"Camera_NoHide" 屏蔽
DecalCollision = unreal.Name("NoCollision")
parent_class = Blueprint.get_blueprint_class(parent_bp_path)
basemesh_path = mesh_path + mesh_name
decalmesh_path = mesh_path + mesh_name + "_Decal"
factory = unreal.BlueprintFactory()
# this works, the saved blueprint is derived from Actor
factory.set_editor_property(name="parent_class", value=parent_class)
# make the blueprint
asset_tools: unreal.AssetTools = unreal.AssetToolsHelpers.get_asset_tools()
asset = asset_tools.create_asset(
asset_name=prefab_name,
package_path=prefab_path,
asset_class=None,
factory=factory,
)
if not isinstance(asset, unreal.Blueprint):
raise Exception("Failed to create blueprint asset")
blueprint = asset # noqa
bp_actor = Blueprint.get_default_object(blueprint)
base_mesh = load_mesh(path=basemesh_path)
if isinstance(base_mesh, unreal.StaticMesh):
bp_editor_lib.set_editor_property(bp_actor, name="Base", value=base_mesh)
setBaseMesh(base_mesh)
if unreal.EditorAssetLibrary.does_asset_exist(decalmesh_path) is True:
decal_mesh = load_mesh(path=decalmesh_path)
if isinstance(decal_mesh, unreal.StaticMesh):
bp_editor_lib.set_editor_property(bp_actor, name="Decal", value=decal_mesh)
setDecalMesh(decal_mesh)
def make_prop_prefabs(target_assets, prefab_folder, use_subfolder, parent_asset_path):
count = 0
if (
string_lib.contains(str(asset_path), "\\" + mesh_folder_name) is True
): # 检查asset是否在//Meshes路径下
for asset in target_assets:
mesh_name = asset.get_name()
aclass = asset.get_class()
asset_class = system_lib.get_class_display_name(aclass)
# 修正widget中textbox输入的prefab路径
if string_lib.ends_with(prefab_folder, "/") is not True:
prefab_folder = prefab_folder + "/"
# prefab目标路径
if use_subfolder is True:
prefab_path = level_path + prefab_folder + asset_subpath
else:
prefab_path = level_path + prefab_folder
# Mesh路径
mesh_path = level_path + "/" + mesh_folder_name + "/" + asset_subpath
if asset_class != "StaticMesh":
unreal.log_warning(
"{} is not static mesh,skipped | 不是StaticMesh,跳过".format(
mesh_name
)
)
else:
if decal_suffix not in mesh_name:
prefab_name_parts = mesh_name.split("_")
prefab_name_start = "BP_"
prefab_name_body = prefab_name_parts[1]
prefab_name_end = "_SM"
prefab_name = prefab_name_start + prefab_name_body + prefab_name_end
if (
unreal.EditorAssetLibrary.does_asset_exist(
prefab_path + prefab_name
)
is False
):
count += 1
unreal.log(
"{}:{} ==> {} | 创建Prefab".format(
count, mesh_name, prefab_name
)
)
make_prop_blueprint(
mesh_path=mesh_path,
mesh_name=mesh_name,
prefab_path=prefab_path,
prefab_name=prefab_name,
parent_bp_path=parent_asset_path,
)
else:
unreal.log_warning(
"Target blueprint {} already exists, skipped | 目标BP已存在,跳过".format(
prefab_name
)
)
else:
unreal.log_warning(mesh_name + " is decal mesh,skipped | 跳过Decal")
unreal.log("{} blueprint created. | 成功创建{}个蓝图".format(count, count))
else:
unreal.log_error(
"Seclected asset nor in /{}, stopped | 所选物体不在 /{} 下, 操作停止".format(
mesh_folder_name, mesh_folder_name
)
)
|
import random
import re
import os
import unreal
from datetime import datetime
from typing import Optional, Callable
def clean_sequencer(level_sequence):
bindings = level_sequence.get_bindings()
for b in bindings:
# b_display_name = str(b.get_display_name())
# if "Camera" not in b_display_name:
# b.remove()
b.remove()
def select_random_asset(assets_path, asset_class=None, predicate:Optional[Callable]=None):
eal = unreal.EditorAssetLibrary()
assets = eal.list_assets(assets_path)
if asset_class is not None:
filtered_assets = []
for asset in assets:
try:
asset_name = os.path.splitext(asset)[0]
if eal.find_asset_data(asset_name).asset_class_path.asset_name == asset_class:
filtered_assets.append(asset)
except:
continue
assets = filtered_assets
if predicate is not None:
filtered_assets = []
for asset in assets:
if predicate(asset):
filtered_assets.append(asset)
assets = filtered_assets
selected_asset_path = random.choice(assets)
return selected_asset_path
def spawn_actor(asset_path, location=unreal.Vector(0.0, 0.0, 0.0)):
# spawn actor into level
obj = unreal.load_asset(asset_path)
rotation = unreal.Rotator(0, 0, 0)
actor = unreal.EditorLevelLibrary.spawn_actor_from_object(object_to_use=obj,
location=location,
rotation=rotation)
actor.set_actor_scale3d(unreal.Vector(1.0, 1.0, 1.0))
# actor.get_editor_property('render_component').set_editor_property('cast_shadow', self.add_sprite_based_shadow)
return actor
def add_animation_to_actor(spawnable_actor, animation_path):
# Get the skeleton animation track class
anim_track = spawnable_actor.add_track(unreal.MovieSceneSkeletalAnimationTrack)
# Add a new animation section
animation_section = anim_track.add_section()
# Set the skeletal animation asset
animation_asset = unreal.load_asset(animation_path)
animation_section.params.animation = animation_asset
# Set the Section Range
frame_rate = 30 # level_sequence.get_frame_rate()
start_frame = 0
end_frame = animation_asset.get_editor_property('sequence_length') * frame_rate.numerator / frame_rate.denominator
animation_section.set_range(start_frame, end_frame)
def find_relevant_assets(level_sequence):
camera_re = re.compile("SuperCineCameraActor_([0-9]+)")
target_point_re = re.compile("TargetPoint_([0-9]+)")
cameras = {}
target_points = {}
skylight = None
# hdri_backdrop = None
#all_actors = unreal.get_editor_subsystem(unreal.EditorActorSubsystem).get_all_level_actors()
# ues = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem)
# current_world = ues.get_editor_world()
# bound_objects = unreal.SequencerTools().get_bound_objects(current_world, level_sequence, level_sequence.get_bindings(), level_sequence.get_playback_range())
# for b_obj in bound_objects:
# for actor1 in b_obj.bound_objects:
# print(actor1.get_name())
# if 'CineCamera' in actor1.get_name():
# camera = actor1
# break
all_actors = unreal.get_editor_subsystem(unreal.EditorActorSubsystem).get_all_level_actors()
for actor in all_actors:
label = actor.get_actor_label()
name = actor.get_name()
# if 'HDRIBackdrop' in actor.get_name():
# hdri_backdrop = actor
camera_matches = camera_re.search(label)
target_point_matches = target_point_re.search(label)
if camera_matches is not None:
cameras[camera_matches.group(1)] = actor
if target_point_matches is not None:
target_points[target_point_matches.group(1)] = actor
if 'SkyLight' in name:
skylight = actor
# return camera, hdri_backdrop
return cameras, target_points, skylight
def random_hdri(hdri_backdrop):
selected_hdri_path = select_random_asset('/project/')
hdri_texture = unreal.load_asset(selected_hdri_path)
hdri_backdrop.set_editor_property('cubemap', hdri_texture)
def random_cubemap(skylight):
cubemap_path = select_random_asset('/project/', asset_class='TextureCube')
cubemap_asset = unreal.load_asset(cubemap_path)
if cubemap_asset is not None:
# Access the skylight component
skylight_comp = skylight.get_editor_property('light_component')
# Assign the new cubemap
skylight_comp.set_editor_property('cubemap', cubemap_asset)
# Update the skylight to apply the new cubemap
skylight_comp.recapture_sky()
def bind_camera_to_level_sequence(level_sequence, camera, character_location, start_frame=0, num_frames=0, move_radius=500):
# Get the Camera Cuts track manually
camera_cuts_track = None
for track in level_sequence.get_tracks():
if track.get_class() == unreal.MovieSceneCameraCutTrack.static_class():
camera_cuts_track = track
break
if camera_cuts_track is None:
print("No Camera Cuts track found.")
return
# Find the section (usually only one for camera cuts)
sections = camera_cuts_track.get_sections()
for section in sections:
if isinstance(section, unreal.MovieSceneCameraCutSection):
# Replace the camera binding
camera_binding = level_sequence.add_possessable(camera)
camera_binding_id = level_sequence.get_binding_id(camera_binding)
# Set the new camera binding to the camera cut section
section.set_camera_binding_id(camera_binding_id)
print("Camera cut updated to use:", camera.get_name())
# Add Transform Track
transform_track = camera_binding.add_track(unreal.MovieScene3DTransformTrack)
transform_section = transform_track.add_section()
transform_section.set_range(start_frame, start_frame + num_frames)
# Get transform channels
channels = transform_section.get_all_channels()
loc_x_channel = channels[0]
loc_y_channel = channels[1]
loc_z_channel = channels[2]
# Get original camera location as center point
#center_location = camera.get_actor_location()
center_location = character_location + unreal.Vector(0.0, 0.0, 100.0) # Offset to avoid ground collision
# Generate random keyframes
# frames = sorted(random.sample(range(start_frame+1, start_frame+num_frames-1), num_keyframes-2))
frames = [start_frame, start_frame+num_frames]
# Add keyframes
for frame in frames:
# Randomize location around the center within a radius
random_location = center_location + unreal.Vector(
random.uniform(-move_radius, move_radius),
random.uniform(-move_radius, move_radius),
random.uniform(-move_radius/2, move_radius/2)
)
frame_number = unreal.FrameNumber(frame)
# Add location keys
loc_x_channel.add_key(frame_number, random_location.x)
loc_y_channel.add_key(frame_number, random_location.y)
loc_z_channel.add_key(frame_number, random_location.z)
def add_actor_to_layer(actor, layer_name="character"):
layer_subsystem = unreal.get_editor_subsystem(unreal.LayersSubsystem)
# Add the actor to the specified layer, if it doesn't exist, add_actor_to_layer will create it
layer_subsystem.add_actor_to_layer(actor, layer_name)
def render(output_path, start_frame=0, num_frames=0, mode="rgb"):
subsystem = unreal.get_editor_subsystem(unreal.MoviePipelineQueueSubsystem)
pipelineQueue = subsystem.get_queue()
# delete all jobs before rendering
for job in pipelineQueue.get_jobs():
pipelineQueue.delete_job(job)
ues = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem)
current_world = ues.get_editor_world()
map_name = current_world.get_path_name()
job = pipelineQueue.allocate_new_job(unreal.MoviePipelineExecutorJob)
job.set_editor_property('map', unreal.SoftObjectPath(map_name))
job.set_editor_property('sequence', unreal.SoftObjectPath('/project/'))
# This is already set (because we duplicated the main queue) but this is how you set what sequence is rendered for this job
job.author = "Voia"
job.job_name = "Synthetic Data"
# Example of configuration loading
if mode == 'rgb':
newConfig = unreal.load_asset("/project/")
elif mode == 'normals':
# This is the normals configuration, which will render normals in the alpha channel
newConfig = unreal.load_asset("/project/")
else:
newConfig = unreal.load_asset("/project/")
# This is how you set the configuration for the job. You can also create a new configuration if you want.
job.set_configuration(newConfig)
# Now we can configure the job. Calling find_or_add_setting_by_class is how you add new settings or find the existing one.
outputSetting = job.get_configuration().find_or_add_setting_by_class(unreal.MoviePipelineOutputSetting)
outputSetting.output_resolution = unreal.IntPoint(1920, 1080) # HORIZONTAL
outputSetting.file_name_format = "Image.{render_pass}.{frame_number}"
outputSetting.flush_disk_writes_per_shot = True # Required for the OnIndividualShotFinishedCallback to get called.
outputSetting.output_directory = unreal.DirectoryPath(path=f'{output_path}/{mode}')
use_custom_playback_range = num_frames > 0
outputSetting.use_custom_playback_range = use_custom_playback_range
outputSetting.custom_start_frame = start_frame
outputSetting.custom_end_frame = start_frame + num_frames
renderPass = job.get_configuration().find_or_add_setting_by_class(unreal.MoviePipelineDeferredPassBase)
# remove default
jpg_settings = job.get_configuration().find_setting_by_class(unreal.MoviePipelineImageSequenceOutput_JPG)
job.get_configuration().remove_setting(jpg_settings)
# if cs_709:
# set_709_color_space(job)
png_settings = job.get_configuration().find_or_add_setting_by_class(unreal.MoviePipelineImageSequenceOutput_PNG)
#png_settings.set_editor_property('write_alpha', False)
# set render presets for given location
# set_render_presets(self.rendering_stage, render_presets)
job.get_configuration().initialize_transient_settings()
# render...
error_callback = unreal.OnMoviePipelineExecutorErrored()
def movie_error(pipeline_executor, pipeline_with_error, is_fatal, error_text):
unreal.log(pipeline_executor)
unreal.log(pipeline_with_error)
unreal.log(is_fatal)
unreal.log(error_text)
error_callback.add_callable(movie_error)
def movie_finished(pipeline_executor, success):
unreal.log('movie finished')
unreal.log(pipeline_executor)
unreal.log(success)
# unreal.log(self.rendering_stage)
# TODO: call render again with normals configuration
if mode == 'rgb':
png_settings.set_editor_property('write_alpha', False)
render(output_path=output_path, mode="normals")
elif mode == 'normals':
png_settings.set_editor_property('write_alpha', True)
render(output_path=output_path, mode="rgb_alpha")
# elif mode == 'rgb_alpha':
# unreal.SystemLibrary.quit_editor()
finished_callback = unreal.OnMoviePipelineExecutorFinished()
finished_callback.add_callable(movie_finished)
unreal.log("Starting Executor")
# executor = subsystem.render_queue_with_executor(unreal.MoviePipelinePIEExecutor)
global executor
executor = unreal.MoviePipelinePIEExecutor(subsystem)
# if executor:
executor.set_editor_property('on_executor_errored_delegate', error_callback)
executor.set_editor_property('on_executor_finished_delegate', finished_callback)
subsystem.render_queue_with_executor_instance(executor)
if __name__ == '__main__':
# get sequencer and clean it (keep only camera) ······· ``
level_sequence = unreal.EditorAssetLibrary.load_asset('/project/.RenderSequencer')
clean_sequencer(level_sequence)
# assumin a single camera and a single hdri
#camera, hdri_backdrop = find_relevant_assets()
cameras, target_points, skylight = find_relevant_assets(level_sequence)
# find the intersect of keys
random_keys = [k for k in cameras.keys() if k in target_points.keys()]
random_key = random.choice(random_keys)
# random_key = random_keys[0]
camera = cameras[random_key]
target_point = target_points[random_key]
# # hdri
# random_hdri(hdri_backdrop)
# skylight
random_cubemap(skylight)
location = target_point.get_actor_location()
# location = unreal.Vector(-990, -290, 0.0)
# # character
# selected_skeletal_mesh_path = select_random_asset('/project/', asset_class='SkeletalMesh')
# selected_skeletal_mesh_path = select_random_asset('/project/', asset_class='SkeletalMesh')
# print(selected_skeletal_mesh_path)
# #exit()
# actor = spawn_actor(asset_path=selected_skeletal_mesh_path, location=location)
# spawnable_actor = level_sequence.add_spawnable_from_instance(actor)
# # animation (Selected random animation)
# selected_animation_path = select_random_asset('/project/')
# selected_animation_path = select_random_asset('/project/')
# add_animation_to_actor(spawnable_actor, animation_path=selected_animation_path)
selected_skeletal_mesh_path = select_random_asset('/project/', asset_class='SkeletalMesh')
a_pose_animation_name = os.path.splitext(selected_skeletal_mesh_path)[-1] + "_Anim"
def not_a_pose_animation(asset:str):
return not asset.endswith(a_pose_animation_name)
baked_animation_directory_path = os.path.dirname(selected_skeletal_mesh_path)
selected_animation_path = select_random_asset(baked_animation_directory_path, asset_class="AnimSequence", predicate=not_a_pose_animation)
print(f"Skeletal Mesh: {selected_skeletal_mesh_path}")
print(f"Animation: {selected_animation_path}")
#exit()
actor = spawn_actor(asset_path=selected_skeletal_mesh_path, location=location)
#spawnable_actor = level_sequence.add_spawnable_from_instance(actor)
add_actor_to_layer(actor, layer_name="character")
spawnable_actor = level_sequence.add_spawnable_from_instance(actor)
add_animation_to_actor(spawnable_actor, animation_path=selected_animation_path)
# delete the original import (keeping only the spawnable actor)
unreal.get_editor_subsystem(unreal.EditorActorSubsystem).destroy_actor(actor)
bind_camera_to_level_sequence(level_sequence, camera, location, start_frame=0, num_frames=300, move_radius=800)
unreal.log(f"Selected character and animation: {selected_skeletal_mesh_path}, {selected_animation_path}")
# this will render two passes (first is rgb following by normals)
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
render(output_path="/project/" + timestamp + "\\", mode="rgb")
|
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
import os
import unreal
import configparser
from deadline.unreal_logger import get_logger
from deadline.unreal_perforce_utils import exceptions
logger = get_logger()
_SOURCE_CONTROL_INI_RELATIVE_PATH = "Saved/project/.ini"
_CONFIGURE_PERFORCE_MESSAGE = (
"Please, configure Source Control plugin to use Perforce during the submission"
)
def validate_source_control_file(sc_file: str) -> str:
"""
Check if SourceControlSettings.ini file exists
:param sc_file: Path to the SourceControlSettings.ini file
:return: Path to the SourceControlSettings.ini file
:raises FileNotFoundError: If SourceControlSettings.ini file does not exist
"""
if not os.path.exists(sc_file):
raise FileNotFoundError(
f"SourceControlSettings.ini not found: {sc_file}. "
f"Check if Unreal Source Control is enabled, relaunch the project and try again."
)
return sc_file
def validate_has_section(
sc_settings: configparser.ConfigParser,
section_name: str,
) -> configparser.ConfigParser:
"""
Validate that the given configparser object has the specified section.
:param sc_settings: A configparser object containing the source control settings.
:param section_name: The name of the section to validate.
:return: The configparser object if the section is found.
:raises KeyError: If the section is not found in the configparser object.
"""
if not sc_settings.has_section(section_name):
raise KeyError(f"{section_name} section not found in {_SOURCE_CONTROL_INI_RELATIVE_PATH}")
return sc_settings
def validate_has_option(
sc_settings: configparser.ConfigParser,
section_name: str,
option_name: str,
) -> configparser.ConfigParser:
"""
Validate that the given configparser object has the specified option in the specified section.
:param sc_settings: A configparser object containing the source control settings.
:param section_name: The name of the section to validate.
:param option_name: The name of the option to check for within the section.
:return: The configparser object if the option is found in the specified section.
:raises KeyError: If the option is not found in the specified section of the configparser object.
"""
try:
sc_settings.get(section_name, option_name)
except configparser.NoOptionError:
raise KeyError(
f"{section_name} section does not contain '{option_name}' setting "
f"in {_SOURCE_CONTROL_INI_RELATIVE_PATH}"
)
return sc_settings
def validate_provider(sc_settings: configparser.ConfigParser) -> configparser.ConfigParser:
"""
Check if SourceControlSettings.ini file Provider is "Perforce"
:param sc_settings: A configparser object containing the source control settings.
:return: The configparser object if the settings are valid.
:raises ValueError: If the settings are not valid.
"""
section_name = "SourceControl.SourceControlSettings"
option_name = "Provider"
validate_has_option(sc_settings, section_name, option_name)
provider = sc_settings.get(section_name, option_name)
if provider != "Perforce":
raise ValueError(
f"{section_name}.{option_name} = {provider}. "
f"Can't get Perforce connection settings. {_CONFIGURE_PERFORCE_MESSAGE}"
f""
)
return sc_settings
def validate_perforce_source_control_settings(
sc_settings: configparser.ConfigParser,
) -> configparser.ConfigParser:
"""
Check if SourceControlSettings.ini has the valid Perforce connection settings.
Raises an errors if there are any missing keys or values for Port, User and Workspace
:param sc_settings: A configparser object containing the source control settings.
:return: The configparser object if the settings are valid.
:raises KeyError: If the settings are not valid.
"""
section_name = "PerforceSourceControl.PerforceSourceControlSettings"
expected_keys = {"Port", "UserName", "Workspace"}
missed_keys: set[str] = {
k for k in expected_keys if not sc_settings.has_option(section_name, k)
}
if missed_keys:
raise KeyError(
"Some keys are missed in PerforceSourceControl.PerforceSourceControlSettings. "
f"Expected: {expected_keys}. Actual: {expected_keys - missed_keys}. "
f"{_CONFIGURE_PERFORCE_MESSAGE}"
)
missed_values: set[str] = {k for k in expected_keys if not sc_settings.get(section_name, k)}
if missed_values:
raise ValueError(
f"Some parameters is unfilled in PerforceSourceControl.PerforceSourceControlSettings: "
f"{missed_values}. "
f"{_CONFIGURE_PERFORCE_MESSAGE}"
)
return sc_settings
def get_connection_settings_from_ue_source_control() -> dict[str, str]:
"""
Parse /project/.ini file inside project's directory
and return dictionary with Port, User and Workspace
:return: P4 connection settings as dictionary (port, user, workspace)
:rtype: dict[str, str]
"""
if not unreal.SourceControl.is_available():
raise exceptions.UnrealSourceControlNotAvailableError(
f"Unreal Source Control is not available. {_CONFIGURE_PERFORCE_MESSAGE}"
)
project_dir = os.path.dirname(
unreal.Paths.convert_relative_path_to_full(unreal.Paths.get_project_file_path())
).replace("\\", "/")
source_control_ini = f"{project_dir}/{_SOURCE_CONTROL_INI_RELATIVE_PATH}"
validate_source_control_file(source_control_ini)
config = configparser.ConfigParser()
config.read(source_control_ini)
validate_has_section(config, "SourceControl.SourceControlSettings")
validate_provider(config)
perforce_section_name = "PerforceSourceControl.PerforceSourceControlSettings"
validate_has_section(config, perforce_section_name)
validate_perforce_source_control_settings(config)
connection_settings = {
"port": config.get(perforce_section_name, "Port"),
"user": config.get(perforce_section_name, "UserName"),
"workspace": config.get(perforce_section_name, "Workspace"),
}
logger.info(f"UE Source Control connection settings for Perforce: {connection_settings}")
return connection_settings
|
import unreal
__anim_notify_name__ = "ChangeState"
__anim_sequence_dir__ = "/project/"
__anim_sequence_lists__ = unreal.EditorAssetLibrary.list_assets(__anim_sequence_dir__)
__anim_assets_lists__ = []
for i in __anim_sequence_lists__:
__anim_assets_lists__.append(unreal.EditorAssetLibrary.load_asset(i))
for i in __anim_assets_lists__:
/project/
|
# coding: utf-8
from asyncio.windows_events import NULL
import unreal
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-vrm")
parser.add_argument("-rig")
parser.add_argument("-meta")
args = parser.parse_args()
print(args.vrm)
reg = unreal.AssetRegistryHelpers.get_asset_registry();
##
rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints()
print(rigs)
for r in rigs:
s:str = r.get_path_name()
ss:str = args.rig
if (s.find(ss) < 0):
print("no rig")
else:
rig = r
#rig = rigs[10]
hierarchy = unreal.ControlRigBlueprintLibrary.get_hierarchy(rig)
h_con = hierarchy.get_controller()
r_con = rig.get_controller()
graph = r_con.get_graph()
node = graph.get_nodes()
for e in hierarchy.get_controls(True):
h_con.remove_element(e)
for e in hierarchy.get_nulls(True):
h_con.remove_element(e)
boneCount = 0
for e in hierarchy.get_bones():
p = hierarchy.get_first_parent(e)
print('===')
print(e)
print(p)
t = unreal.Transform()
s = unreal.RigControlSettings()
s.shape_visible = False
v = unreal.RigControlValue()
shape_t = unreal.Transform(location=[0.0, 0.0, 0.0], rotation=[0.0, 0.0, 0.0], scale=[0.001, 0.001, 0.001])
if (boneCount == 0):
n = h_con.add_null("{}_s".format(e.name), unreal.RigElementKey(), t)
c = h_con.add_control(e.name, n, s, v)
t = hierarchy.get_global_transform(n)
hierarchy.set_global_transform(c, t, True)
hierarchy.set_control_shape_transform(c, shape_t, True)
else:
p.type = unreal.RigElementType.CONTROL
n = h_con.add_null("{}_s".format(e.name), p, t)
c = h_con.add_control(e.name, n, s, v)
t = hierarchy.get_global_transform(n)
hierarchy.set_global_transform(c, t, True)
hierarchy.set_control_shape_transform(c, shape_t, True)
if ("{}".format(e.name) == "head"):
parent = c
n = h_con.add_null("eye_l_s", parent, t)
c = h_con.add_control("eye_l", n, s, v)
t = hierarchy.get_global_transform(n)
hierarchy.set_global_transform(c, t, True)
hierarchy.set_control_shape_transform(c, shape_t, True)
n = h_con.add_null("eye_r_s", parent, t)
c = h_con.add_control("eye_r", n, s, v)
t = hierarchy.get_global_transform(n)
hierarchy.set_global_transform(c, t, True)
hierarchy.set_control_shape_transform(c, shape_t, True)
boneCount += 1
|
# coding: utf-8
import unreal
import random
import time
def executeSlowTask():
quantity_steps_in_slow_task = 10
with unreal.ScopedSlowTask(quantity_steps_in_slow_task, 'My Slow Task Text ...') as slow_task:
slow_task.make_dialog(True)
for x in range(quantity_steps_in_slow_task):
if slow_task.should_cancel():
break
slow_task.enter_progress_frame(1, 'My Slow Task Text ...' + str(x) + ' / ' + str(quantity_steps_in_slow_task))
# Execute slow logic
deferredSpawnActor()
time.sleep(1)
def deferredSpawnActor():
world = unreal.EditorLevelLibrary.get_editor_world()
# ! blueprint actor
actor_class = unreal.EditorAssetLibrary.load_blueprint_class('/project/')
actor_location = unreal.Vector(random.uniform(0.0, 2000.0), random.uniform(0.0, 2000.0), 0.0)
actor_rotation = unreal.Rotator(random.uniform(0.0, 360.0), random.uniform(0.0, 360.0), random.uniform(0.0, 360.0))
actor_scale = unreal.Vector(random.uniform(0.1, 2.0), random.uniform(0.1, 2.0), random.uniform(0.1, 2.0))
actor_transform = unreal.Transform(actor_location, actor_rotation, actor_scale)
# ! "GameplayStatics.begin_spawning_actor_from_class()" is deprecated. Use BeginDeferredActorSpawnFromClass instead.
# actor = unreal.GameplayStatics.begin_spawning_actor_from_class(world, actor_class, actor_transform)
# unreal.GameplayStatics.finish_spawning_actor(actor, actor_transform)
actor = unreal.EditorCppLib.begin_spawn_actor(world, actor_class, actor_transform)
unreal.EditorCppLib.finish_spawn_actor(actor, actor_transform)
# import EditorFunction_1 as ef
# reload(ef)
# ef.executeSlowTask()
|
# 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()
|
# Unreal Python script
# Attempts to fix various issues in Source engine Datasmith
# imports into Unreal
from collections import Counter, defaultdict, OrderedDict
import sys
import unreal
import re
import traceback
import os
import json
import csv
import posixpath
import math
from glob import glob
def spawn_blueprint_actor(asset_path='', label=None, actor_location=None, actor_rotation=None,
local_rotation=None, actor_scale=None, properties={}, hidden=False):
"""
# path: str : Blueprint class path
# actor_location: obj unreal.Vector : The actor location
# actor_rotation: obj unreal.Rotator : The actor rotation
# actor_location: obj unreal.Vector : The actor scale
# world: obj unreal.World : The world in which you want to spawn the actor. If None, will spawn in the currently open world.
# properties: dict : The properties you want to set before the actor is spawned. These properties will be taken into account in the Construction Script
# return: obj unreal.Actor : The spawned actor
"""
if actor_location:
actor_location = actor_location if isinstance(actor_location, unreal.Vector) else unreal.Vector(*actor_location)
if actor_rotation:
actor_rotation = actor_rotation if isinstance(actor_rotation, unreal.Rotator) else unreal.Rotator(*actor_rotation)
# Attempt to find the specified Blueprint class
actor_class = unreal.EditorAssetLibrary.load_blueprint_class(asset_path)
# Spawn the blueprint class!
actor = unreal.EditorLevelLibrary.spawn_actor_from_class(
actor_class, location=actor_location, rotation=actor_rotation)
if not actor:
print("[!] Failed to spawn actor: %s" % label)
return None
# If "actor_rotation" is actuall a Vector and not a Rotator,
# we'll assume the caller wanted to add local rotation
if local_rotation:
actor.add_actor_local_rotation(local_rotation, sweep=False, teleport=True)
if actor_scale:
actor.set_actor_scale3d(actor_scale)
if label:
actor.set_actor_label(label)
if hidden:
actor.set_actor_hidden_in_game(hidden)
# Edit Properties
for x in properties:
actor.set_editor_property(x, properties[x])
return actor
def actor_contains_material_starting_with(actor, material_name):
""" If this actor is StaticMeshActor and contains a material with
a name beginning with any of the words in the provided material_name,
return True -- else return False
"""
if not material_name:
return False
if isinstance(actor, unreal.StaticMeshActor):
static_mesh_component = actor.get_component_by_class(unreal.StaticMeshComponent)
# Skip if there's no static mesh to display
if not static_mesh_component.static_mesh:
return False
# Check if the static mesh has materials -- which we'll fix if applicable
mats = static_mesh_component.get_materials()
if not mats:
return False
# Iterate through all materials found in this static mesh
for mat in mats:
if not mat:
continue
# Check if the name of the current material starts with "tools"
mat_name = mat.get_name()
if not mat_name:
continue
if mat_name.startswith(material_name):
return True
# Actor wasn't a StaticMesh or no materials matched
return False
def get_selected_actors():
""" return: obj List unreal.Actor : The selected actors in the world """
return unreal.EditorLevelLibrary.get_selected_level_actors()
def point_actor_down(actor):
# Reset actor rotation; which points down by default
actor.set_actor_rotation(unreal.Rotator(0,-90,0), True)
def main():
prop = "prop_target_metal_"
with unreal.ScopedEditorTransaction("Select Specific Meshes") as trans:
for actor in unreal.EditorLevelLibrary.get_all_level_actors():
if isinstance(actor, unreal.StaticMeshActor):
static_mesh_component = actor.get_component_by_class(unreal.StaticMeshComponent)
# Skip if there's no static mesh to display
if not static_mesh_component.static_mesh:
continue
# Check if this static mesh is named whatever we
# specified in our mesh_name variable
mesh_name = static_mesh_component.static_mesh.get_name()
if not mesh_name.startswith(prop):
continue
# 1. Spawn new BP_Prop_Target with same transform as actor
new_actor_label = actor.get_actor_label() + "_REPLACEMENT"
actor_location = actor.get_actor_location()
actor_rotation = actor.get_actor_rotation()
new_target = spawn_blueprint_actor("/project/",
label=new_actor_label,
actor_location=actor_location,
actor_rotation=actor_rotation,
actor_scale=actor.get_actor_scale3d(),
properties=dict())
# 2. Replace BP_Prop_Target's mesh with actor mesh
new_target_smc = actor.get_component_by_class(unreal.StaticMeshComponent)
new_target_smc.set_static_mesh(static_mesh_component.static_mesh)
# 3. Delete actor
unreal.EditorLevelLibrary.destroy_actor(actor)
main()
|
# -*- coding: utf-8 -*-
"""Loader for published alembics."""
from ayon_core.pipeline import AYON_CONTAINER_ID
from ayon_core.lib import EnumDef
from ayon_unreal.api import plugin
from ayon_unreal.api.pipeline import (
create_container,
imprint,
format_asset_directory,
UNREAL_VERSION,
get_dir_from_existing_asset
)
from ayon_core.settings import get_current_project_settings
import unreal # noqa
class PointCacheAlembicLoader(plugin.Loader):
"""Load Point Cache from Alembic"""
product_types = {"model", "pointcache"}
label = "Import Alembic Point Cache"
representations = {"abc"}
icon = "cube"
color = "orange"
abc_conversion_preset = "maya"
loaded_asset_dir = "{folder[path]}/{product[name]}_{version[version]}"
loaded_asset_name = "{folder[name]}_{product[name]}_{version[version]}_{representation[name]}" # noqa
show_dialog = False
@classmethod
def apply_settings(cls, project_settings):
super(PointCacheAlembicLoader, cls).apply_settings(project_settings)
# Apply import settings
unreal_settings = project_settings["unreal"]["import_settings"]
cls.abc_conversion_preset = unreal_settings["abc_conversion_preset"]
cls.loaded_asset_dir = unreal_settings["loaded_asset_dir"]
cls.loaded_asset_name = unreal_settings["loaded_asset_name"]
cls.show_dialog = unreal_settings["show_dialog"]
@classmethod
def get_options(cls, contexts):
return [
EnumDef(
"abc_conversion_preset",
label="Alembic Conversion Preset",
items={
"3dsmax": "3dsmax",
"maya": "maya",
"custom": "custom"
},
default=cls.abc_conversion_preset
)
]
@staticmethod
def get_task(
filename, asset_dir, asset_name, replace,
frame_start=None, frame_end=None, loaded_options=None
):
task = unreal.AssetImportTask()
options = unreal.AbcImportSettings()
gc_settings = unreal.AbcGeometryCacheSettings()
conversion_settings = unreal.AbcConversionSettings()
sampling_settings = unreal.AbcSamplingSettings()
abc_conversion_preset = loaded_options.get("abc_conversion_preset")
if abc_conversion_preset == "maya":
if UNREAL_VERSION.major >= 5 and UNREAL_VERSION.minor >= 4:
conversion_settings = unreal.AbcConversionSettings(
preset=unreal.AbcConversionPreset.MAYA)
else:
conversion_settings = unreal.AbcConversionSettings(
preset=unreal.AbcConversionPreset.CUSTOM,
flip_u=False, flip_v=True,
rotation=[90.0, 0.0, 0.0],
scale=[1.0, -1.0, 1.0])
elif abc_conversion_preset == "3dsmax":
if UNREAL_VERSION.major >= 5:
conversion_settings = unreal.AbcConversionSettings(
preset=unreal.AbcConversionPreset.MAX)
else:
conversion_settings = unreal.AbcConversionSettings(
preset=unreal.AbcConversionPreset.CUSTOM,
flip_u=False, flip_v=True,
rotation=[0.0, 0.0, 0.0],
scale=[1.0, -1.0, 1.0])
else:
data = get_current_project_settings()
preset = (
data["unreal"]["import_settings"]["custom"]
)
conversion_settings = unreal.AbcConversionSettings(
preset=unreal.AbcConversionPreset.CUSTOM,
flip_u=preset["flip_u"],
flip_v=preset["flip_v"],
rotation=[
preset["rot_x"],
preset["rot_y"],
preset["rot_z"]
],
scale=[
preset["scl_x"],
preset["scl_y"],
preset["scl_z"]
]
)
task.set_editor_property('filename', filename)
task.set_editor_property('destination_path', asset_dir)
task.set_editor_property('destination_name', asset_name)
task.set_editor_property('replace_existing', replace)
task.set_editor_property(
'automated', not loaded_options.get("show_dialog"))
task.set_editor_property('save', True)
options.set_editor_property(
'import_type', unreal.AlembicImportType.GEOMETRY_CACHE)
options.sampling_settings.frame_start = frame_start
options.sampling_settings.frame_end = frame_end
gc_settings.set_editor_property('flatten_tracks', False)
if frame_start is not None:
sampling_settings.set_editor_property('frame_start', frame_start)
if frame_end is not None:
sampling_settings.set_editor_property('frame_end', frame_end)
options.geometry_cache_settings = gc_settings
options.conversion_settings = conversion_settings
options.sampling_settings = sampling_settings
task.options = options
return task
def import_and_containerize(
self, filepath, asset_dir, asset_name, container_name,
frame_start, frame_end, loaded_options
):
task = None
if not unreal.EditorAssetLibrary.does_asset_exist(
f"{asset_dir}/{asset_name}"):
task = self.get_task(
filepath, asset_dir, asset_name, False,
frame_start, frame_end,
loaded_options=loaded_options
)
unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks([task])
if not unreal.EditorAssetLibrary.does_asset_exist(
f"{asset_dir}/{container_name}"):
# Create Asset Container
create_container(container=container_name, path=asset_dir)
return asset_dir
def imprint(
self,
folder_path,
asset_dir,
container_name,
asset_name,
representation,
frame_start,
frame_end,
product_type,
project_name,
layout
):
data = {
"schema": "ayon:container-2.0",
"id": AYON_CONTAINER_ID,
"namespace": asset_dir,
"container_name": container_name,
"asset_name": asset_name,
"loader": str(self.__class__.__name__),
"representation": representation["id"],
"parent": representation["versionId"],
"frame_start": frame_start,
"frame_end": frame_end,
"product_type": product_type,
"folder_path": folder_path,
# TODO these should be probably removed
"family": product_type,
"asset": folder_path,
"project_name": project_name,
"layout": layout
}
imprint(f"{asset_dir}/{container_name}", data)
def load(self, context, name, namespace, options):
"""Load and containerise representation into Content Browser.
Args:
context (dict): application context
name (str): Product name
namespace (str): in Unreal this is basically path to container.
This is not passed here, so namespace is set
by `containerise()` because only then we know
real path.
data (dict): Those would be data to be imprinted.
Returns:
list(str): list of container content
"""
# Create directory for asset and Ayon container
folder_entity = context["folder"]
folder_path = folder_entity["path"]
folder_attributes = folder_entity["attrib"]
suffix = "_CON"
path = self.filepath_from_context(context)
asset_root, asset_name = format_asset_directory(
context, self.loaded_asset_dir, self.loaded_asset_name
)
tools = unreal.AssetToolsHelpers().get_asset_tools()
asset_dir, container_name = tools.create_unique_asset_name(
asset_root, suffix="")
frame_start = folder_attributes.get("frameStart")
frame_end = folder_attributes.get("frameEnd")
# If frame start and end are the same, we increase the end frame by
# one, otherwise Unreal will not import it
if frame_start == frame_end:
frame_end += 1
container_name += suffix
should_use_layout = options.get("layout", False)
# Get existing asset dir if possible, otherwise import & containerize
if should_use_layout and (
existing_asset_dir := get_dir_from_existing_asset(
asset_dir, asset_name)
):
asset_dir = existing_asset_dir
else:
loaded_options = {
"abc_conversion_preset": options.get(
"abc_conversion_preset", self.abc_conversion_preset),
"show_dialog": options.get("show_dialog", self.show_dialog),
}
asset_dir = self.import_and_containerize(
path, asset_dir, asset_name, container_name,
frame_start, frame_end, loaded_options
)
self.imprint(
folder_path,
asset_dir,
container_name,
asset_name,
context["representation"],
frame_start,
frame_end,
context["product"]["productType"],
context["project"]["name"],
should_use_layout
)
asset_content = unreal.EditorAssetLibrary.list_assets(
asset_dir, recursive=True, include_folder=True
)
for a in asset_content:
unreal.EditorAssetLibrary.save_asset(a)
return asset_content
def update(self, container, context):
# Create directory for folder and Ayon container
folder_path = context["folder"]["path"]
product_type = context["product"]["productType"]
repre_entity = context["representation"]
asset_dir = container["namespace"]
suffix = "_CON"
path = self.filepath_from_context(context)
asset_root, asset_name = format_asset_directory(
context, self.loaded_asset_dir, self.loaded_asset_name
)
tools = unreal.AssetToolsHelpers().get_asset_tools()
asset_dir, container_name = tools.create_unique_asset_name(
asset_root, suffix="")
frame_start = int(container.get("frame_start"))
frame_end = int(container.get("frame_end"))
container_name += suffix
should_use_layout = container.get("layout", False)
# Get existing asset dir if possible, otherwise import & containerize
if should_use_layout and (
existing_asset_dir := get_dir_from_existing_asset(
asset_dir, asset_name)
):
asset_dir = existing_asset_dir
else:
loaded_options = {
"abc_conversion_preset": self.abc_conversion_preset,
"show_dialog": self.show_dialog,
}
asset_dir = self.import_and_containerize(
path, asset_dir, asset_name, container_name,
frame_start, frame_end, loaded_options)
self.imprint(
folder_path,
asset_dir,
container_name,
asset_name,
repre_entity,
frame_start,
frame_end,
product_type,
context["project"]["name"],
should_use_layout
)
asset_content = unreal.EditorAssetLibrary.list_assets(
asset_dir, recursive=True, include_folder=False
)
for a in asset_content:
unreal.EditorAssetLibrary.save_asset(a)
def remove(self, container):
path = container["namespace"]
if unreal.EditorAssetLibrary.does_directory_exist(path):
unreal.EditorAssetLibrary.delete_directory(path)
|
# 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()
|
import unreal
import math
import random
import os
import csv
seqs= []
def checkshottype():
with open('/project/.txt','r') as f:
print(f.readline())
# def createSeq():
# asset_reg = unreal.AssetRegistryHelpers.get_asset_registry()
# all_seqs = asset_reg.get_assets_by_path('/project/')
# if len(all_seqs) == 0:
# shotNum = '0'
# elif len(all_seqs) ==1:
# shotNum = '1'
# elif len(all_seqs)==2:
# shotNum = '2'
# elif len(all_seqs)==3:
# shotNum = '3'
# else:
# shotNum = '4'
# at = unreal.AssetToolsHelpers.get_asset_tools()
# seq_names = shotNum
# seq = at.create_asset(
# asset_name= seq_names,
# package_path='/project/',
# asset_class=unreal.LevelSequence,
# factory=unreal.LevelSequenceFactoryNew(),
# )
# randStart = random.randrange(40,70)
# seq.set_playback_start(randStart)
# seq.set_playback_end(randStart+30)
# alex_bind = seq.add_possessable(alex)
# anim_track = alex_bind.add_track(unreal.MovieSceneSkeletalAnimationTrack)
# anim_section = anim_track.add_section()
# anim_section.set_range(0,150)
# anim_section.params.animation = alexAnims()
# for cam in cams:
# cam_binding = seq.add_possessable(cam)
# unreal.LevelSequenceEditorBlueprintLibrary.open_level_sequence(seq)
# def randomCam(str):
# if str=='medium':
# distance_offset = 300
# elif str=='closeup':
# distance_offset = 100
# elif str=='wide':
# distance_offset = 1000
# # cam = unreal.CineCameraActor()
# for cam in cams:
# vertCount = 1000
# step=2*math.pi/vertCount
# theta = random.randrange(0,vertCount)
# theta *= step
# x = math.cos(theta) * distance_offset
# y = math.sin(theta) * distance_offset
# #centerStage = unreal.Vector(0,0,0)
# camLoc=unreal.Vector(x,y,random.randrange(100,170))
# camLoc.y += random.randrange(-50,50)
# camLoc.x += random.randrange(-35,35)
# camLoc.z +=random.randrange(10,100)
# #camRot = ueMath.find_look_at_rotation(camLoc,centerStage)
# #camRot.pitch = 0
# #print(cam.get_editor_property('lookat_tracking_settings'))
# #print(type(actor))
# #cam.set_editor_property('lookat_tracking_settings',trackingSettings)
# #return camLoc,camRot
# cam.set_actor_location(camLoc,False,False)
# alignTracking()
def alignTracking():
allactors = unreal.EditorLevelLibrary().get_all_level_actors()
alex = None
attach = None
cams = []
for actor in allactors:
if actor.get_class().get_name()=='SkeletalMeshActor':
alex = actor
elif actor.get_class().get_name()=="CineCameraActor":
cams.append(actor)
elif actor.get_name()=='StaticMeshActor_0':
attach = actor
for cam in cams:
trackingSettings = unreal.CameraLookatTrackingSettings()
trackingSettings.set_editor_property('enable_look_at_tracking',True)
trackingSettings.set_editor_property("actor_to_track",attach)
trackingSettings.set_editor_property('look_at_tracking_interp_speed',10)
cam.lookat_tracking_settings = trackingSettings
def alexAnims():
asset_reg = unreal.AssetRegistryHelpers.get_asset_registry()
all_anims = asset_reg.get_assets_by_path('/project/')
randomElement = random.choice(all_anims)
split_path = randomElement.get_full_name().split('.')
anim_path = "/"+split_path[1].split('/',1)[1]
anim_path = unreal.EditorAssetLibrary.load_asset(anim_path)
return anim_path
# def camSelection(selection):
# cam=None
# if selection == 1:
# cam=0
# elif selection == 2:
# cam=2
# elif selection == 3:
# cam=1
# elif selection == 4:
# cam=0
# else:
# print('error')
# print(cam)
# savepos = cams[cam].get_actor_location()
# data = [savepos.x,savepos.y,savepos.z]
# with open('/project/.csv','a',newline='') as f:
# writer = csv.writer(f)
# writer.writerow(data)
# def makeFinalFilm():
# at = unreal.AssetToolsHelpers.get_asset_tools()
# campos=[]
# splitcampos=[]
# with open('/project/.csv','r') as f:
# camchoicespos = csv.reader(f,delimiter=',')
# next(camchoicespos)
# for row in f:
# campos.append(row)
# for pos in campos:
# splitcampos.append(pos.split(','))
# asset_reg = unreal.AssetRegistryHelpers.get_asset_registry()
# all_seqs = asset_reg.get_assets_by_path('/project/')
# masterseq = at.create_asset(
# asset_name= 'finalFilm',
# package_path='/project/',
# asset_class=unreal.LevelSequence,
# factory=unreal.LevelSequenceFactoryNew(),
# )
# masterseq.set_playback_start(0)
# masterseq.set_playback_end(600)
# for i, cam in enumerate(cams):
# cam_binding = masterseq.add_possessable(cam)
# camloc = unreal.Vector(float(splitcampos[i][0]),float(splitcampos[i][1]),float(splitcampos[i][2]))
# cam.set_actor_location(camloc,False,False)
# cameracutsTrack = masterseq.add_master_track(unreal.MovieSceneCameraCutTrack)
# cameracutsSection = cameracutsTrack.add_section()
# if i == 0:
# cameracutsSection.set_range(0,150)
# if i == 1:
# cameracutsSection.set_range(150,300)
# if i == 2:
# cameracutsSection.set_range(300,450)
# if i == 3:
# cameracutsSection.set_range(450,600)
# camBindingID = unreal.MovieSceneObjectBindingID()
# camBindingID.set_editor_property('guid',cam_binding.get_id())
# cameracutsSection.set_camera_binding_id(camBindingID)
# shottrack = masterseq.add_master_track(unreal.MovieSceneCinematicShotTrack)
# shotsection = shottrack.add_section()
# if i == 0:
# shotsection.set_range(0,150)
# if i == 1:
# shotsection.set_range(150,300)
# if i == 2:
# shotsection.set_range(300,450)
# if i == 3:
# shotsection.set_range(450,600)
# split_path = all_seqs[i].get_full_name().split('.')
# seq = "/"+split_path[1].split('/',1)[1]
# seqload = unreal.EditorAssetLibrary.load_asset(seq)
# shot = shotsection.set_sequence(seqload)
# unreal.LevelSequenceEditorBlueprintLibrary.open_level_sequence(masterseq)
def makeFilmBasedOnUserCamLoc():
allactors = unreal.EditorLevelLibrary().get_all_level_actors()
alex = None
for actor in allactors:
if actor.get_class().get_name()=='SkeletalMeshActor':
alex = actor
at = unreal.AssetToolsHelpers.get_asset_tools()
camposarray = readingCamPosCSV()
masterseq = at.create_asset(
asset_name= 'userFilm',
package_path='/project/',
asset_class=unreal.LevelSequence,
factory=unreal.LevelSequenceFactoryNew(),
)
playback_start = 0
playback_end = 600
masterseq.set_playback_start(playback_start)
masterseq.set_playback_end(playback_end)
alex_bind = masterseq.add_possessable(alex)
anim_track = alex_bind.add_track(unreal.MovieSceneSkeletalAnimationTrack)
anim_section = anim_track.add_section()
anim_section.set_range(playback_start,playback_end)
alexAnim3Shot = unreal.EditorAssetLibrary().load_asset('/project/')
anim_section.params.animation= alexAnim3Shot
cameracutsTrack = masterseq.add_master_track(unreal.MovieSceneCameraCutTrack)
shotlength = playback_end/len(camposarray)
start = 0
for i in range(len(camposarray)):
cam = unreal.CineCameraActor()
end = start+shotlength
camLoc = unreal.Vector(float(camposarray[i][0]),float(camposarray[i][1]),float(camposarray[i][2]))
cam = unreal.EditorLevelLibrary().spawn_actor_from_object(cam,camLoc,unreal.Rotator(0,0,0))
cam_binding = masterseq.add_possessable(cam)
cameracutsSection = cameracutsTrack.add_section()
cameracutsSection.set_range(start,end)
camBindingID = unreal.MovieSceneObjectBindingID()
camBindingID.set_editor_property('guid',cam_binding.get_id())
cameracutsSection.set_camera_binding_id(camBindingID)
start=end
alignTracking()
unreal.LevelSequenceEditorBlueprintLibrary.open_level_sequence(masterseq)
def makeFinalFilmBasedOnShotList():
allactors = unreal.EditorLevelLibrary().get_all_level_actors()
alex = None
for actor in allactors:
if actor.get_class().get_name()=='SkeletalMeshActor':
alex = actor
at = unreal.AssetToolsHelpers.get_asset_tools()
shotlist = readingShotTypes()
del shotlist[-1]
masterseq = at.create_asset(
asset_name= 'cnnFilm',
package_path='/project/',
asset_class=unreal.LevelSequence,
factory=unreal.LevelSequenceFactoryNew(),
)
playback_start = 0
playback_end = 600
masterseq.set_playback_start(playback_start)
masterseq.set_playback_end(playback_end)
alex_bind = masterseq.add_possessable(alex)
anim_track = alex_bind.add_track(unreal.MovieSceneSkeletalAnimationTrack)
anim_section = anim_track.add_section()
anim_section.set_range(playback_start,playback_end)
alexAnim3Shot = unreal.EditorAssetLibrary().load_asset('/project/')
anim_section.params.animation= alexAnim3Shot
cameracutsTrack = masterseq.add_master_track(unreal.MovieSceneCameraCutTrack)
shotlength = playback_end/len(shotlist)
start = 0
cl=0
m=0
w=0
for i in range(len(shotlist)):
if shotlist[i]=='closeup':
cl+=1
elif shotlist[i] =='medium':
m+=1
elif shotlist[i]=='wide':
w+=1
end = start+shotlength
cam = randomCam2(shotlist[i])
cam_binding = masterseq.add_possessable(cam)
cameracutsSection = cameracutsTrack.add_section()
cameracutsSection.set_range(start,end)
camBindingID = unreal.MovieSceneObjectBindingID()
camBindingID.set_editor_property('guid',cam_binding.get_id())
cameracutsSection.set_camera_binding_id(camBindingID)
start=end
alignTracking()
unreal.LevelSequenceEditorBlueprintLibrary.open_level_sequence(masterseq)
print(cl,m,w)
def randomCam2(str):
cam=unreal.CineCameraActor()
if str=='medium':
distance_offset = 300
elif str=='closeup':
distance_offset = 100
elif str=='wide':
distance_offset = 1000
vertCount = 1000
step=2*math.pi/vertCount
theta = random.randrange(0,vertCount)
theta *= step
x = math.cos(theta) * distance_offset
y = math.sin(theta) * distance_offset
camLoc=unreal.Vector(x,y,random.randrange(100,170))
camLoc.y += random.randrange(-50,50)
camLoc.x += random.randrange(-35,35)
camLoc.z +=random.randrange(10,100)
camrot = unreal.Rotator(0,0,0)
camspawn = unreal.EditorLevelLibrary().spawn_actor_from_object(cam,camLoc,camrot)
return camspawn
def readingShotTypes():
with open('/project/.txt','r') as f:
shots = f.readline()
shotlist = shots.split(',')
return shotlist
def readingCamPosCSV():
campos = []
splitcampos = []
with open('/project/.csv','r') as f:
camchoicespos = csv.reader(f,delimiter=',')
next(camchoicespos)
for row in f:
campos.append(row)
for pos in campos:
splitcampos.append(pos.strip().split(','))
return splitcampos
|
from .. import (shelf_core
)
import logging
import unreal
@unreal.uclass()
class LogWidget(unreal.VerticalBox):
edit_box = unreal.uproperty(unreal.PythonMultiLineEditableTextBox)
def _post_init(self):
filter_layout = unreal.HorizontalBox()
filter_menu = unreal.MenuAnchor()
#self.filter_menu.get_editor_property("on_get_menu_content_event").bind_callable(self.init_filter_menu)
filter_btn = shelf_core.create_button("Filter", icon_path=shelf_core.Utl.get_full_icon_path("filter.png"))
filter_btn.set_background_color(unreal.LinearColor())
#self.filter_btn.widget_style.normal.outline_settings.width = 0
filter_menu.set_content(filter_btn)
filter_layout.add_child_to_horizontal_box(filter_menu)
self.edit_box = unreal.PythonMultiLineEditableTextBox()
self.edit_box.read_only = True
self.add_child_to_vertical_box(filter_layout)
slot = self.add_child_to_vertical_box(self.edit_box)
slot.size.size_rule = unreal.SlateSizeRule.FILL
def write(self, log_type, text):
if log_type == logging.WARNING:
R = G = 1
B = 0
elif log_type == logging.ERROR:
R = 1
B = G = 0
else:
R = G = B = 1
if text[-1] == "\n":
text = text[0:-1]
text = f"<PythonRichText FontColor=\"R={R} G={G} B={B}\">{text}</>"
self.edit_box.set_text(str(self.edit_box.get_text()) + "\n" + text)
class LogToolHandle(shelf_core.StackWidgetHandle):
instance = True
order = 0.1
support_tool = ["日志"]
fill = True
def __init__(self, entity):
self.background_color = unreal.LinearColor()
super().__init__(entity)
self.__expand_area_map = {
""
}
#base_controll.create_logger("ToolShelf", self)
def setup(self):
self._root_widget = LogWidget()
shelf_core.ToolShelfLogger.set_default_output(self._root_widget)
shelf_core.ToolShelfLogger.create_logger("ToolShelf")
|
import json
import unreal
from actor.background import load_all_backgrounds
from actor.camera import Camera
from actor.level import Level
from actor.metahuman import MetaHuman
import utils.utils as utils
from utils.utils import MetaHumanAssets
from utils.pose import generate_pose_filter_uniform_from_dict, lower_c, lower_r, lower_l, upper_c, upper_r, upper_l
PATH_MAIN = "/project/"
metahuman = MetaHuman(MetaHumanAssets.jake_id)
for iteration in range(1):
NUM_ANIMATION = 100
GAP_ANIMATION = 30
keys_agregation = [{"frame": t, "camera": {}, "metahuman": {}} for t in range((NUM_ANIMATION-1)*(GAP_ANIMATION+1) + 1)]
dict_key = {}
dict_key.update(lower_c)
dict_key.update(lower_r)
dict_key.update(lower_l)
dict_key.update(upper_c)
dict_key.update(upper_r)
dict_key.update(upper_l)
# Initialize level sequence
level = Level(f'seq_{iteration}')
#camera = Camera()
# light1 = PointLight()
# light2 = PointLight()
# level.add_actor(camera)
# level.add_actor(light1)
# level.add_actor(light2)
level.add_actor(metahuman)
# light1.add_key_random(0, offset=[0., 0., 180.])
# light2.add_key_random(0, offset=[0., 0., 180.])
# keys_camera = camera.add_key_random(0, distance=50, offset=[0., 0., 165.])
# Generate animation
with unreal.ScopedSlowTask(NUM_ANIMATION, "Generate Animation") as slow_task:
slow_task.make_dialog(can_cancel=True)
key_metahuman_prec = None
# keys_camera_prec = None
for k in range(NUM_ANIMATION):
slow_task.enter_progress_frame(work=1.0, desc=f'Generate Animation {k}/{NUM_ANIMATION}')
if slow_task.should_cancel():
break
frame_time = k*(GAP_ANIMATION + 1)
key_metahuman = generate_pose_filter_uniform_from_dict(dict_key) #generate_pose_filter(10)
metahuman.add_key_fast(key_metahuman, frame_time)
keys_agregation[frame_time]['metahuman'] = key_metahuman
if key_metahuman_prec: # and keys_camera_prec:
interp_keys_metahuman = utils.linear_interp_keys(key_metahuman_prec, key_metahuman, GAP_ANIMATION)
# interp_keys_camera = utils.linear_interp_keys(keys_camera_prec, keys_camera, GAP_ANIMATION)
frame_time_prec = (k-1)*(GAP_ANIMATION + 1) + 1
for t in range(GAP_ANIMATION):
keys_agregation[frame_time_prec + t]['metahuman'] = interp_keys_metahuman[t]
# keys_agregation[frame_time_prec + t]['camera'] = interp_keys_camera[t]
key_metahuman_prec = key_metahuman
# keys_camera_prec = keys_camera
else:
key_metahuman_prec = key_metahuman
# keys_camera_prec = keys_camera
# metahuman.add_keys(keys_metahuman, frames_time)
level.update_level_sequence(0, (NUM_ANIMATION-1)*(GAP_ANIMATION+1) + 1)
metahuman.change_interpmode(unreal.RichCurveInterpMode.RCIM_LINEAR)
level.save_level()
level.close_level()
# Save keys
with open(PATH_MAIN + f"keys_seq_{iteration}.json", 'w') as file:
json.dump(keys_agregation, file, indent=4)
|
"""Logging configuration for the batch face importer package."""
import logging
import unreal
class UnrealLogger:
"""Custom logger that integrates with Unreal Engine's logging system."""
def __init__(self, name="BatchFaceImporter"):
"""Initialize logger with name and default settings."""
self.logger = logging.getLogger(name)
self.logger.setLevel(logging.INFO)
# Add Unreal output handler
unreal_handler = UnrealLogHandler()
unreal_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
self.logger.addHandler(unreal_handler)
# Add console output handler for development
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
self.logger.addHandler(console_handler)
class UnrealLogHandler(logging.Handler):
"""Handler that routes Python logging to Unreal's logging system."""
def emit(self, record):
"""Emit a log record to Unreal's logging system."""
try:
msg = self.format(record)
if record.levelno >= logging.ERROR:
unreal.log_error(msg)
elif record.levelno >= logging.WARNING:
unreal.log_warning(msg)
else:
unreal.log(msg)
except Exception as e:
# Fallback to print if logging fails
print(f"Logging failed: {str(e)}")
print(f"Original message: {record.getMessage()}")
def setup_logger(name="BatchFaceImporter", level=logging.INFO):
"""Set up and return a logger instance with the specified configuration."""
logger = UnrealLogger(name).logger
logger.setLevel(level)
return logger
# Create global logger instance
logger = setup_logger()
def update_log_level(level):
"""Update the log level of the global logger."""
logger.setLevel(level)
def log_error(message):
"""Convenience function for logging errors."""
logger.error(message)
def log_warning(message):
"""Convenience function for logging warnings."""
logger.warning(message)
def log_info(message):
"""Convenience function for logging info messages."""
logger.info(message)
def log_debug(message):
"""Convenience function for logging debug messages."""
logger.debug(message)
|
# 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()
|
import unreal
from pathlib import Path
from typing import List
def get_assets_in_folder(content_folder: str, recursive: bool =False) -> List[unreal.Object]:
"""
Get assets in the given content folder.
Args:
content_folder (str): The path where this asset is located in the project. i.e. '/project/'
recursive (bool, optional): Whether to search all folders under that path. Defaults to False.
Returns:
List[unreal.Object]: A list of assets.
"""
assets = []
asset_library = unreal.EditorAssetLibrary()
for asset_path in asset_library.list_assets(content_folder, recursive=recursive, include_folder=False):
asset = unreal.load_asset(asset_path)
if asset:
assets.append(asset)
return assets
def create_asset(
asset_path: str,
asset_class: unreal.Class,
asset_factory: unreal.Factory,
unique_name: bool = True
) -> unreal.Object:
"""
Creates a new unreal asset.
Args:
asset_path (str): The project path to the asset.
asset_class (unreal.Class): The unreal asset class.
asset_factory (unreal.Factory): The unreal factory.
unique_name (bool, optional): Whether or not to check if the name
is unique before creating the asset. Defaults to True.
Returns:
unreal.Object: The created asset.
"""
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
if unique_name:
asset_path, _ = asset_tools.create_unique_asset_name(
base_package_name=asset_path,
suffix=''
)
path, name = asset_path.rsplit("/", 1)
return asset_tools.create_asset(
asset_name=name,
package_path=path,
asset_class=asset_class,
factory=asset_factory
)
def copy_asset_to_folder(
asset_path: str,
content_folder: str,
overwrite: bool = False,
post_fix: str = ''
) -> unreal.Object:
"""
Copy the assets to the given content folder.
Args:
asset_path (str): The path to the asset.
content_folder (str): The path where the asset will be copied to.
overwrite (bool): Whether to overwrite the asset if it already exists.
Returns:
unreal.Object | None: The copied asset.
"""
asset_subsystem = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem)
asset_name = asset_path.split('/')[-1]
asset = unreal.load_asset(asset_path)
if not asset:
raise FileExistsError(f"Asset {asset_path} does not exist.")
destination_path = f'{content_folder}/{asset_name}{post_fix}'
if asset_subsystem.does_asset_exist(destination_path) and not overwrite: # type: ignore
return unreal.load_asset(destination_path)
duplicated_asset = unreal.EditorAssetLibrary.duplicate_asset(
source_asset_path=asset_path,
destination_asset_path=destination_path
)
return duplicated_asset
|
import unreal
# Create all assets and objects we'll use
lvs = unreal.VariantManagerLibrary.create_level_variant_sets_asset("LVS", "/Game/")
lvs_actor = unreal.VariantManagerLibrary.create_level_variant_sets_actor(lvs)
if lvs is None or lvs_actor is None:
print "Failed to spawn either the LevelVariantSets asset or the LevelVariantSetsActor!"
quit()
# Create a variant set and add it to lvs
var_set1 = unreal.VariantSet()
var_set1.set_display_text("My VariantSet")
lvs.add_variant_set(var_set1)
# Create a variant and add it to var_set1
var1 = unreal.Variant()
var1.set_display_text("Variant 1")
var_set1.add_variant(var1)
# Create a test actor and add it to var1. The test actor has almost all possible types of capturable properties
location = unreal.Vector()
rotation = unreal.Rotator()
test_actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.VariantManagerTestActor, location, rotation)
var1.add_actor_binding(test_actor)
capturable_props = unreal.VariantManagerLibrary.get_capturable_properties(test_actor)
captured_props = []
print "Capturable properties for actor '" + test_actor.get_actor_label() + "':"
for prop in capturable_props:
print "\t" + prop
# All test properties are named like 'Captured____Property'
# The check here avoids capturing generic Actor properties like 'Can be Damaged'
if str(prop).startswith('Captured') and str(prop).endswith('Property'):
new_prop = var1.capture_property(test_actor, prop)
captured_props.append(new_prop)
for prop in captured_props:
type_str = prop.get_property_type_string()
# Set a value for a property depending on its type
if type_str == "bool":
prop.set_value_bool(True)
elif type_str == "int":
prop.set_value_int(2)
elif type_str == "float":
prop.set_value_float(2.0)
elif type_str == "object":
cube = unreal.EditorAssetLibrary.load_asset("StaticMesh'/project/.Cube'")
prop.set_value_object(cube)
elif type_str == "strint":
prop.set_value_string("new string")
elif type_str == "rotator":
prop.set_value_rotator(unreal.Rotator(11, 12, 13))
elif type_str == "color":
prop.set_value_color(unreal.Color(21, 22, 23, 24))
elif type_str == "linear_color":
prop.set_value_linear_color(unreal.LinearColor(0.31, 0.32, 0.33, 0.34))
elif type_str == "vector":
prop.set_value_vector(unreal.Vector(41, 42, 43))
elif type_str == "quat":
prop.set_value_quat(unreal.Quat(0.51, 0.52, 0.53, 0.54))
elif type_str == "vector4":
prop.set_value_vector4(unreal.Vector4(6.1, 6.2, 6.3, 6.4))
elif type_str == "Vector2D":
prop.set_value_vector2d(unreal.Vector2D(7.1, 7.2))
elif type_str == "int_Point":
prop.set_value_int_point(unreal.IntPoint(81, 82))
# Easier to print using getattr
for prop in captured_props:
type_str = prop.get_property_type_string()
print(getattr(prop, "get_value_" + type_str)())
|
import unreal
# instances of unreal classes
editor_level_lib = unreal.EditorLevelLibrary()
editor_filter_lib = unreal.EditorFilterLibrary()
# get all level actors and filter by StaticMeshActor
level_actors = editor_level_lib.get_all_level_actors()
static_mesh_actors = editor_filter_lib.by_class(level_actors, unreal.StaticMeshActor)
deleted = 0
for actor in static_mesh_actors:
actor_name = actor.get_fname()
# get the static mesh through the static mesh component
actor_mesh_comp = actor.static_mesh_component
actor_mesh = actor_mesh_comp.static_mesh
is_valid_actor = actor_mesh != None
# if mesh not valid, destroy
if not is_valid_actor:
actor.destroy_actor()
deleted += 1
unreal.log("The Mesh Component of Actor {} is invalid and was deleted".format(actor_name))
unreal.log("Deleted {} Actors with invalid Mesh Component".format(deleted))
|
import unreal
def create_data_asset(asset_class, package_path, asset_name, properties=None):
"""
Crea un Data Asset in Unreal Engine.
:param asset_class: Classe del Data Asset (es. unreal.MyDataAsset)
:param package_path: Percorso del pacchetto (es. "/project/")
:param asset_name: Nome dell'asset (es. "MyDataAssetInstance")
:param properties: Dizionario di proprietà da impostare sull'asset (opzionale)
:return: Il Data Asset creato o None se già esiste.
"""
asset_full_path = f"{package_path}/{asset_name}"
# Controlla se l'asset esiste già
if unreal.EditorAssetLibrary.does_asset_exist(asset_full_path):
print(f"L'asset '{asset_full_path}' esiste già!")
return None
# Crea il Data Asset
factory = unreal.DataAssetFactory()
asset = unreal.AssetToolsHelpers.get_asset_tools().create_asset(
asset_name,
package_path,
asset_class,
factory
)
if asset and properties:
# Imposta le proprietà fornite
for key, value in properties.items():
asset.set_editor_property(key, value)
# Salva l'asset
unreal.EditorAssetLibrary.save_asset(asset_full_path)
print(f"Data Asset creato: {asset_full_path}")
return asset
# Esempio di utilizzo
if __name__ == "__main__":
asset_class = unreal.MyDataAsset # Sostituisci con la tua classe C++
package_path = "/project/"
asset_name = "MyDataAssetInstance"
properties = {
"Value": 42,
"Name": "My Example Data"
}
create_data_asset(asset_class, package_path, asset_name, properties)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.