text
stringlengths
15
267k
# coding: utf-8 u""" Qt 管理Windowモジュール """ import sys import os import inspect from yurlungur.core import env def main_window(): """ >>> import sys, yurlungur >>> app = yurlungur.Qt.QtWidgets.QApplication(sys.argv) >>> ptr = yurlungur.Qt.main_window() >>> view = yurlungur.Qt.QtWidgets.QMainWindow(ptr) >>> yurlungur.Qt.show(view) >>> sys.exit(app.exec_()) :return: """ import yurlungur app_name = yurlungur.application.__name__ if app_name == "maya.cmds": from yurlungur.user.Qt import QtCompat from maya import OpenMayaUI window = OpenMayaUI.MQtUtil.mainWindow() if sys.version_info[0] < 3: ptr = long(window) else: ptr = int(window) return QtCompat.wrapInstance(ptr, QWidget) if app_name == "sd.api": from yurlungur.adapters import substance_designer return substance_designer.qt.getMainWindow() if app_name == "hou": import hou return hou.qt.mainWindow() if app_name == "nuke": return QApplication.activeWindow() if app_name == "fusion": try: import fusionscript except ImportError: import PeyeonScript as fusionscript fusion = fusionscript.scriptapp('Fusion') return fusion.GetMainWindow() if app_name == "substance_painter": import substance_painter return substance_painter.ui.get_main_window() if app_name == "pymxs": try: import qtmax return qtmax.GetQMaxMainWindow() except ImportError: import MaxPlus return MaxPlus.QtHelpers_GetQmaxMainWindow() return None def show(view): """ >>> view = yurlungur.Qt.QtWidgets.QWidget() >>> yurlungur.Qt.show(view) :param view: :return: """ # try: # view.deleteLater() # except: # logger.pprint(view) def show_(view): __dark_view(view) if env.Max(): __protect_show(view) elif env.Unreal(): import unreal unreal.parent_external_window_to_slate(view.winId()) else: view.show() from yurlungur.user import Qt if not Qt.QtWidgets.QApplication.instance(): app = Qt.QtWidgets.QApplication(sys.argv) show_(view) sys.exit(app.exec_()) else: show_(view) class __GCProtector(object): widgets = [] def __protect_show(w): from yurlungur.user import Qt w.setWindowFlags(Qt.QtCore.Qt.WindowStaysOnTopHint) w.show() __GCProtector.widgets.append(w) def __dark_view(view): local = os.path.dirname(os.path.dirname(inspect.currentframe().f_code.co_filename)) with open(local + "/project/.css") as f: view.setStyleSheet("".join(f.readlines()))
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
# 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, os 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_Skeletal/" geometry_cache_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_skeletal_mesh_for_pov(level_sequence, sequence_body_index, start_frame, end_frame, skeletal_mesh_path, skeletal_animation_path, x, y, z, yaw, pitch, roll): """ 为POV相机添加隐藏的SkeletalMesh用于骨骼绑定 """ # 调试:打印路径并检查资产是否存在 skeletal_mesh_asset_path = skeletal_mesh_path.split("'")[1] animation_asset_path = skeletal_animation_path.split("'")[1] unreal.log(f"DEBUG: Trying to load skeletal mesh: {skeletal_mesh_asset_path}") unreal.log(f"DEBUG: Asset exists? {unreal.EditorAssetLibrary.does_asset_exist(skeletal_mesh_asset_path)}") unreal.log(f"DEBUG: Trying to load animation: {animation_asset_path}") unreal.log(f"DEBUG: Asset exists? {unreal.EditorAssetLibrary.does_asset_exist(animation_asset_path)}") # 调试:列出目录中的所有资产 import_dir = "/".join(skeletal_mesh_asset_path.split("/")[:-1]) unreal.log(f"DEBUG: Assets in directory {import_dir}:") all_assets = unreal.EditorAssetLibrary.list_assets(import_dir) for asset in all_assets: if "skel" in asset.lower(): unreal.log(f" Found skeletal asset: {asset}") # 加载SkeletalMesh和Animation skeletal_mesh_object = unreal.load_asset(skeletal_mesh_path.split("'")[1]) animation_object = unreal.load_asset(skeletal_animation_path.split("'")[1]) unreal.log(f"DEBUG: SkeletalMesh loaded successfully: {skeletal_mesh_object.get_name()}") skeleton = skeletal_mesh_object.skeleton unreal.log(f"DEBUG: Skeleton loaded successfully: {skeleton.get_name()}") if skeletal_mesh_object is None or animation_object is None: unreal.log_error(f"Cannot load skeletal mesh or animation: {skeletal_mesh_path}, {skeletal_animation_path}") return None # 创建隐藏的SkeletalMeshActor 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(f"{skeletal_mesh_object.get_name()}_POV") skeletal_mesh_actor.skeletal_mesh_component.set_skeletal_mesh(skeletal_mesh_object) # 设置为隐藏 skeletal_mesh_actor.set_actor_hidden_in_game(False) # 临时设为可见 skeletal_mesh_actor.skeletal_mesh_component.set_visibility(True) unreal.log(f"DEBUG: Animation length: {animation_object.sequence_length} seconds") #unreal.log(f"DEBUG: Animation frame count: {animation_object.get_number_of_sampling_keys()}") # 添加到序列 skeletal_binding = level_sequence.add_spawnable_from_instance(skeletal_mesh_actor) unreal.get_editor_subsystem(unreal.EditorActorSubsystem).destroy_actor(skeletal_mesh_actor) # 添加动画轨道 anim_track = skeletal_binding.add_track(unreal.MovieSceneSkeletalAnimationTrack) anim_section = anim_track.add_section() anim_section.params.animation = animation_object anim_section.set_range(start_frame, end_frame) # 设置位置和旋转 transform_track = skeletal_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 skeletal_binding 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 body_binding 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, pov_camera=False): 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 camera_cut_section = None if not pov_camera: 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) else: # --- new pov logic --- unreal.log(f" Setting up POV camera for sequence {name}") 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) 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) end_frame = sequence_frames if camera_cut_section: 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) pov_host_binding = None pov_skeletal_binding = None 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}'" body_binding=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) if pov_camera and sequence_body_index == 0: pov_host_binding = body_binding if hasattr(sequence_body, 'skeletal_mesh_path') and sequence_body.skeletal_mesh_path: pov_skeletal_binding = add_skeletal_mesh_for_pov( level_sequence, sequence_body_index, animation_start_frame, animation_end_frame, sequence_body.skeletal_mesh_path, sequence_body.skeletal_animation_path, sequence_body.x, sequence_body.y, sequence_body.z, sequence_body.yaw, sequence_body.pitch, sequence_body.roll ) visibility_track = body_binding.add_track(unreal.MovieSceneVisibilityTrack) visibility_section = visibility_track.add_section() visibility_section.set_range(-WARMUP_FRAMES, end_frame) visibility_section.get_channels()[0].set_default(False) else: unreal.log_warning("POV mode enabled but skeletal mesh paths not available") 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 body_binding=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) if pov_camera and sequence_body_index == 0: pov_host_binding = body_binding if hasattr(sequence_body, 'skeletal_mesh_path') and sequence_body.skeletal_mesh_path: pov_skeletal_binding = add_skeletal_mesh_for_pov( level_sequence, sequence_body_index, animation_start_frame, animation_end_frame, sequence_body.skeletal_mesh_path, sequence_body.skeletal_animation_path, sequence_body.x, sequence_body.y, sequence_body.z, sequence_body.yaw, sequence_body.pitch, sequence_body.roll ) visibility_track = body_binding.add_track(unreal.MovieSceneVisibilityTrack) visibility_section = visibility_track.add_section() visibility_section.set_range(-WARMUP_FRAMES, end_frame) visibility_section.get_channels()[0].set_default(False) else: unreal.log_warning("POV mode enabled but skeletal mesh paths not available") # 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 if pov_host_binding is not None: # 关键改动:将相机创建为Spawnable,而不是使用Possessable camera_binding = level_sequence.add_spawnable_from_class(unreal.CineCameraActor) camera_binding.set_name("POVCineCamera") # 设置POV相机的HFOV if camera_hfov is not None: focal_length_track = camera_binding.add_track(unreal.MovieSceneFloatTrack) focal_length_track.set_property_name_and_path('CineCameraComponent.CurrentFocalLength', 'CineCameraComponent.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) source_cine_component = camera_actor.get_cine_camera_component() if source_cine_component: focal_length = get_focal_length(source_cine_component, camera_hfov) focal_length_section.get_channels()[0].set_default(focal_length) else: unreal.log_warning("Could not get CineCameraComponent from source camera actor to calculate focal length. HFOV will not be set.") if pov_skeletal_binding: # 添加附加轨道,这是定位的核心 attach_track = camera_binding.add_track(unreal.MovieScene3DAttachTrack) attach_section = attach_track.add_section() # 关键修复:先设置绑定ID,再设置范围(与hair函数保持一致) skeletal_binding_id = unreal.MovieSceneObjectBindingID() skeletal_binding_id.set_editor_property("Guid", pov_skeletal_binding.get_id()) attach_section.set_constraint_binding_id(skeletal_binding_id) attach_section.set_editor_property("attach_socket_name", "head") # 最后设置范围 attach_section.set_range(-WARMUP_FRAMES, end_frame) unreal.log(f" POV camera attached to 'head' bone on SkeletalMesh") # 关键修复:设置附加偏移,而不是使用Transform轨道 # 这样可以避免Transform轨道覆盖Attach效果 pov_offset_location = unreal.Vector(15.0, 0.0, 10.0) # X向前, Y向右, Z向上 pov_offset_rotation = unreal.Rotator(0.0, 0.0, 0.0) # Roll, Pitch, Yaw #attach_section.set_editor_property("attach_location", pov_offset_location) #attach_section.set_editor_property("attach_rotation", pov_offset_rotation) #unreal.log(f" POV camera attached to 'head' bone with offset {pov_offset_location}") # 移除Transform轨道 - 这是关键修复! # 不再添加Transform轨道,避免与Attach轨道冲突 # 将Camera Cut轨道的相机设置为我们刚绑定的Spawnable相机 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) 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 pov_camera = False 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 # check if is POV camera if "pov_camera" in group_config and group_config["pov_camera"] == "true": pov_camera = True else: pov_camera = False 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' if pov_camera: # POV模式:加载SkeletalMesh和Animation unreal.log(" POV mode enabled, using SkeletalMesh and Animation") skeletal_mesh_path = f"SkeletalMesh'{body_root}{subject}/{body}.{body}'" skeletal_animation_path = f"AnimSequence'{body_root}{subject}/{body}.{body}_Animation'" # 同时也需要GeometryCache用于渲染 body_path = f"GeometryCache'{geometry_cache_body_root}{subject}/{body}.{body}'" else: # 非POV模式:只使用GeometryCache body_path = f"GeometryCache'{geometry_cache_body_root}{subject}/{body}.{body}'" skeletal_mesh_path = None skeletal_animation_path = None 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) if pov_camera: sequence_body.skeletal_mesh_path = skeletal_mesh_path sequence_body.skeletal_animation_path = skeletal_animation_path else: sequence_body.skeletal_mesh_path = None sequence_body.skeletal_animation_path = None 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, pov_camera) # 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)
#!/project/ python3 """ Automated City Builder - Creates full Birmingham city via UE5 automation No grand scaling. Just code that works. """ import subprocess import time def build_birmingham_city(): """Automate creation of complete Birmingham city""" print("🏗️ Building Birmingham city automatically...") # UE5 Python script for city automation city_builder_script = ''' import unreal import random print("🚀 Starting automated Birmingham city builder...") # City building parameters BUILDINGS_PER_BLOCK = 8 CITY_BLOCKS = 10 BUILDING_SPACING = 2000 # UE5 units (20 meters) # Your existing building files building_templates = [ "Building_Examples_1", "building_02", "building_03", "building_04", "building_05" ] editor_util = unreal.EditorLevelLibrary() print(f"📋 Generating {CITY_BLOCKS * CITY_BLOCKS * BUILDINGS_PER_BLOCK} buildings...") building_count = 0 for block_x in range(CITY_BLOCKS): for block_y in range(CITY_BLOCKS): for building_slot in range(BUILDINGS_PER_BLOCK): # Pick random building template template_name = random.choice(building_templates) asset_path = f"/project/{template_name}" try: # Load building mesh static_mesh = unreal.EditorAssetLibrary.load_asset(asset_path) if static_mesh: # Calculate position in city grid x_pos = block_x * BUILDING_SPACING + (building_slot % 4) * 500 y_pos = block_y * BUILDING_SPACING + (building_slot // 4) * 500 z_pos = 0 # Spawn building location = unreal.Vector(x_pos, y_pos, z_pos) actor = editor_util.spawn_actor_from_object(static_mesh, location) if actor: # Add slight rotation variety rotation = unreal.Rotator(0, random.uniform(-15, 15), 0) actor.set_actor_rotation(rotation) # Add height variety scale = unreal.Vector(1.0, 1.0, random.uniform(0.8, 1.5)) actor.set_actor_scale3d(scale) # Add CesiumGlobeAnchor for geographic positioning anchor = actor.add_component_by_class(unreal.CesiumGlobeAnchorComponent) building_count += 1 if building_count % 50 == 0: print(f"✅ Generated {building_count} buildings...") except Exception as e: print(f"⚠️ Skipped building: {e}") print(f"🌪️ Birmingham city complete: {building_count} buildings generated") print("📍 City positioned at Birmingham coordinates") ''' # Send script to UE5 applescript = f''' tell application "System Events" tell application process "UnrealEditor" set frontmost to true delay 1 -- Open Python console keystroke "ctrl" using {{control down, command down}} keystroke "p" delay 2 -- Clear console key code 51 using command down delay 0.5 -- Execute city builder set the clipboard to "{city_builder_script.replace('"', '\\"')}" keystroke "v" using command down delay 1 key code 36 delay 2 end tell end tell ''' try: print("🤖 Sending city builder automation to UE5...") subprocess.run(['osascript', '-e', applescript], check=True) print("✅ City builder automation sent") print("🏙️ Birmingham city generation in progress...") return True except subprocess.CalledProcessError as e: print(f"❌ Automation failed: {e}") return False if __name__ == "__main__": print("🏙️ BIRMINGHAM AUTOMATED CITY BUILDER") print("=" * 50) print("📋 Generates complete city using existing building templates") print("🎯 Grid-based layout with variety and geographic positioning") print("") success = build_birmingham_city() if success: print("") print("✅ CITY AUTOMATION COMPLETE") print("🏗️ Check UE5 for city generation progress") print("📊 Birmingham ready for damage report visualization") else: print("❌ CITY AUTOMATION FAILED")
from __future__ import annotations import os import unreal VSCODE_DEBUG_SERVER_ENV_VAR = "vscode_debugpy_server_port" def is_debugpy_installed() -> bool: """ Tries to import debugpy to check if it is installed. """ try: import debugpy return True except ModuleNotFoundError: return False def install_debugpy() -> bool: """ Installs debugpy using the current Unreal Python interpreter. """ import subprocess python_exe = unreal.get_interpreter_executable_path() if not python_exe: return False debugpy_install_args = [python_exe, "-m", "pip", "install", "debugpy"] env = os.environ.copy() env["PYTHONNOUSERSITE"] = "1" try: result = subprocess.run(debugpy_install_args, capture_output=True, check=True, text=True, env=env) unreal.log(result.stdout) unreal.log(result.stderr) except subprocess.CalledProcessError as e: unreal.log_error(f"Failed to install debugpy: {e}") unreal.log_error(e.stdout) unreal.log_error(e.stderr) except Exception as e: unreal.log_error(f"Failed to install debugpy: {e}") # Make sure the installation was successful by trying to import debugpy import debugpy return True def start_debugpy_server(port: int) -> bool: """ Starts a debugpy server on the specified port """ import debugpy python_exe = unreal.get_interpreter_executable_path() if not python_exe: return False debugpy.configure(python=python_exe) debugpy.listen(port) os.environ[VSCODE_DEBUG_SERVER_ENV_VAR] = str(port) return True def get_current_debugpy_port() -> int: """ Returns the current debugpy server port or -1 if it is not set """ return int(os.environ.get(VSCODE_DEBUG_SERVER_ENV_VAR, -1))
import unreal import math # instances of unreal classes editor_util = unreal.EditorUtilityLibrary() # get the selected assets selected_assets = editor_util.get_selected_assets() num_assets = len(selected_assets) not_pow = 0 for asset in selected_assets: asset_name = asset.get_fname() asset_path = asset.get_path_name() try: x_size = asset.blueprint_get_size_x() y_size = asset.blueprint_get_size_y() # check if both values are power of two is_x_valid = math.log(x_size, 2).is_integer() is_y_valid = math.log(y_size, 2).is_integer() if not is_x_valid or not is_y_valid: unreal.log("{} is not power of two({}, {})".format(asset_name, x_size, y_size)) unreal.log("It's path is {}".format(asset_path)) not_pow +=1 except Exception as err: unreal.log("{} is not a Texture - {}".format(asset_name, err)) unreal.log("{} checked, {} textures found problematic".format(num_assets, not_pow))
import unreal import sys from PySide2 import QtWidgets, QtUiTools, QtGui #Import UE python lib #import ui.qwidget_import_asset as q_import_asset # RELOAD MODULE import importlib sys.path.append('C:/project/') sys.path.append('C:/project/') sys.path.append('C:/project/') WINDOW_NAME = 'M2 - Menu' UI_FILE_FULLNAME = __file__.replace('.py', '.ui') class QtWindowImport(QtWidgets.QWidget): def __init__(self, parent=None): super(QtWindowImport, self).__init__(parent) self.aboutToClose = None # This is used to stop the tick when the window is closed self.widget = QtUiTools.QUiLoader().load(UI_FILE_FULLNAME) self.widget.setParent(self) self.setWindowTitle(WINDOW_NAME) self.setGeometry(100, 100, self.widget.width(), self.widget.height()) self.layout = QtWidgets.QVBoxLayout(self) self.layout.addWidget(self.widget) self.setLayout(self.layout) # importAssetButton self.widget.importAssetButton.clicked.connect(self.importAssetButton) # importAnimsButton self.widget.importAnimsButton.clicked.connect(self.importAnimButton) # setShotButton self.widget.setShotButton.clicked.connect(self.setShotButton) # make render jobs button self.widget.sendRenderButton.clicked.connect(self.makeRenderJobsButton) # export to meme self.widget.exportMemeButton.clicked.connect(self.exportMemeButton) # importLodButton self.widget.importLodButton.clicked.connect(self.importLodButton) # export set button self.widget.exportSetButton.clicked.connect(self.exportSetButton) # turntable button self.widget.makeTurntableButton.clicked.connect(self.makeTurntableButton) def importAssetButton(self): #import ui.qwidget_import_asset as q_import_asset #importlib.reload(q_import_asset) import ui.q_global_import_asset as q_import_asset importlib.reload(q_import_asset) def importAnimButton(self): import ui.q_import_anim as q_import_anim importlib.reload(q_import_anim) def setShotButton(self): import ui.q_set_shot as q_setShot importlib.reload(q_setShot) def makeRenderJobsButton(self): import ui.q_send_render_jobs as q_render importlib.reload(q_render) def exportMemeButton(self): import ui.q_export_to_meme as q_exp_meme importlib.reload(q_exp_meme) def importLodButton(self): import ui.q_import_lods as q_importlod importlib.reload(q_importlod) def exportSetButton(self): import ui.q_export_set as q_export_set importlib.reload(q_export_set) def makeTurntableButton(self): import ui.q_make_turntable as q_make_turntable importlib.reload(q_make_turntable) app = None if not QtWidgets.QApplication.instance(): app = QtWidgets.QApplication(sys.argv) widget = QtWindowImport() widget.show() unreal.parent_external_window_to_slate(widget.winId())
# -*- coding: utf-8 -*- """Load FBX with animations.""" import os import json import unreal from unreal import EditorAssetLibrary from unreal import MovieSceneSkeletalAnimationTrack from unreal import MovieSceneSkeletalAnimationSection from ayon_core.pipeline.context_tools import get_current_project_folder 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 import pipeline as unreal_pipeline class AnimationFBXLoader(plugin.Loader): """Load Unreal SkeletalMesh from FBX.""" product_types = {"animation"} label = "Import FBX Animation" representations = ["fbx"] icon = "cube" color = "orange" def _process(self, path, asset_dir, asset_name, instance_name): automated = False actor = None task = unreal.AssetImportTask() task.options = unreal.FbxImportUI() if instance_name: automated = True # Old method to get the actor # actor_name = 'PersistentLevel.' + instance_name # actor = unreal.EditorLevelLibrary.get_actor_reference(actor_name) actors = unreal.EditorLevelLibrary.get_all_level_actors() for a in actors: if a.get_class().get_name() != "SkeletalMeshActor": continue if a.get_actor_label() == instance_name: actor = a break if not actor: raise Exception(f"Could not find actor {instance_name}") skeleton = actor.skeletal_mesh_component.skeletal_mesh.skeleton task.options.set_editor_property('skeleton', skeleton) if not actor: return None folder_entity = get_current_project_folder(fields=["attrib.fps"]) task.set_editor_property('filename', path) task.set_editor_property('destination_path', asset_dir) task.set_editor_property('destination_name', asset_name) task.set_editor_property('replace_existing', False) task.set_editor_property('automated', automated) task.set_editor_property('save', False) # set import options here task.options.set_editor_property( 'automated_import_should_detect_type', False) task.options.set_editor_property( 'original_import_type', unreal.FBXImportType.FBXIT_SKELETAL_MESH) task.options.set_editor_property( 'mesh_type_to_import', unreal.FBXImportType.FBXIT_ANIMATION) task.options.set_editor_property('import_mesh', False) task.options.set_editor_property('import_animations', True) task.options.set_editor_property('override_full_name', True) task.options.anim_sequence_import_data.set_editor_property( 'animation_length', unreal.FBXAnimationLengthImportType.FBXALIT_EXPORTED_TIME ) task.options.anim_sequence_import_data.set_editor_property( 'import_meshes_in_bone_hierarchy', False) task.options.anim_sequence_import_data.set_editor_property( 'use_default_sample_rate', False) task.options.anim_sequence_import_data.set_editor_property( 'custom_sample_rate', folder_entity.get("attrib", {}).get("fps")) task.options.anim_sequence_import_data.set_editor_property( 'import_custom_attribute', True) task.options.anim_sequence_import_data.set_editor_property( 'import_bone_tracks', True) task.options.anim_sequence_import_data.set_editor_property( 'remove_redundant_keys', False) task.options.anim_sequence_import_data.set_editor_property( 'convert_scene', True) unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks([task]) asset_content = EditorAssetLibrary.list_assets( asset_dir, recursive=True, include_folder=True ) animation = None for a in asset_content: imported_asset_data = EditorAssetLibrary.find_asset_data(a) imported_asset = unreal.AssetRegistryHelpers.get_asset( imported_asset_data) if imported_asset.__class__ == unreal.AnimSequence: animation = imported_asset break if animation: animation.set_editor_property('enable_root_motion', True) actor.skeletal_mesh_component.set_editor_property( 'animation_mode', unreal.AnimationMode.ANIMATION_SINGLE_NODE) actor.skeletal_mesh_component.animation_data.set_editor_property( 'anim_to_play', animation) return animation def load(self, context, name, namespace, options=None): """ Load and containerise representation into Content Browser. This is two step process. First, import FBX to temporary path and then call `containerise()` on it - this moves all content to new directory and then it will create AssetContainer there and imprint it with metadata. This will mark this path as container. 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. This is not used now, data are imprinted by `containerise()`. Returns: list(str): list of container content """ # Create directory for asset and Ayon container root = "/project/" folder_path = context["folder"]["path"] hierarchy = folder_path.lstrip("/").split("/") folder_name = hierarchy.pop(-1) product_type = context["product"]["productType"] suffix = "_CON" asset_name = f"{folder_name}_{name}" if folder_name else f"{name}" tools = unreal.AssetToolsHelpers().get_asset_tools() asset_dir, container_name = tools.create_unique_asset_name( f"{root}/Animations/{folder_name}/{name}", suffix="") ar = unreal.AssetRegistryHelpers.get_asset_registry() _filter = unreal.ARFilter( class_names=["World"], package_paths=[f"{root}/{hierarchy[0]}"], recursive_paths=False) levels = ar.get_assets(_filter) master_level = levels[0].get_asset().get_path_name() hierarchy_dir = root for h in hierarchy: hierarchy_dir = f"{hierarchy_dir}/{h}" hierarchy_dir = f"{hierarchy_dir}/{folder_name}" _filter = unreal.ARFilter( class_names=["World"], package_paths=[f"{hierarchy_dir}/"], recursive_paths=True) levels = ar.get_assets(_filter) level = levels[0].get_asset().get_path_name() unreal.EditorLevelLibrary.save_all_dirty_levels() unreal.EditorLevelLibrary.load_level(level) container_name += suffix EditorAssetLibrary.make_directory(asset_dir) path = self.filepath_from_context(context) libpath = path.replace(".fbx", ".json") with open(libpath, "r") as fp: data = json.load(fp) instance_name = data.get("instance_name") animation = self._process(path, asset_dir, asset_name, instance_name) asset_content = EditorAssetLibrary.list_assets( hierarchy_dir, recursive=True, include_folder=False) # Get the sequence for the layout, excluding the camera one. sequences = [a for a in asset_content if (EditorAssetLibrary.find_asset_data(a).get_class() == unreal.LevelSequence.static_class() and "_camera" not in a.split("/")[-1])] ar = unreal.AssetRegistryHelpers.get_asset_registry() for s in sequences: sequence = ar.get_asset_by_object_path(s).get_asset() possessables = [ p for p in sequence.get_possessables() if p.get_display_name() == instance_name] for p in possessables: tracks = [ t for t in p.get_tracks() if (t.get_class() == MovieSceneSkeletalAnimationTrack.static_class())] for t in tracks: sections = [ s for s in t.get_sections() if (s.get_class() == MovieSceneSkeletalAnimationSection.static_class())] for s in sections: s.params.set_editor_property('animation', animation) # Create Asset Container unreal_pipeline.create_container( container=container_name, path=asset_dir) 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": context["representation"]["id"], "parent": context["representation"]["versionId"], "folder_path": folder_path, "product_type": product_type, # TODO these shold be probably removed "asset": folder_path, "family": product_type } unreal_pipeline.imprint(f"{asset_dir}/{container_name}", data) imported_content = EditorAssetLibrary.list_assets( asset_dir, recursive=True, include_folder=False) for a in imported_content: EditorAssetLibrary.save_asset(a) unreal.EditorLevelLibrary.save_current_level() unreal.EditorLevelLibrary.load_level(master_level) def update(self, container, context): repre_entity = context["representation"] folder_name = container["asset_name"] source_path = get_representation_path(repre_entity) folder_entity = get_current_project_folder(fields=["attrib.fps"]) destination_path = container["namespace"] task = unreal.AssetImportTask() task.options = unreal.FbxImportUI() task.set_editor_property('filename', source_path) task.set_editor_property('destination_path', destination_path) # strip suffix task.set_editor_property('destination_name', folder_name) task.set_editor_property('replace_existing', True) task.set_editor_property('automated', True) task.set_editor_property('save', True) # set import options here task.options.set_editor_property( 'automated_import_should_detect_type', False) task.options.set_editor_property( 'original_import_type', unreal.FBXImportType.FBXIT_SKELETAL_MESH) task.options.set_editor_property( 'mesh_type_to_import', unreal.FBXImportType.FBXIT_ANIMATION) task.options.set_editor_property('import_mesh', False) task.options.set_editor_property('import_animations', True) task.options.set_editor_property('override_full_name', True) task.options.anim_sequence_import_data.set_editor_property( 'animation_length', unreal.FBXAnimationLengthImportType.FBXALIT_EXPORTED_TIME ) task.options.anim_sequence_import_data.set_editor_property( 'import_meshes_in_bone_hierarchy', False) task.options.anim_sequence_import_data.set_editor_property( 'use_default_sample_rate', False) task.options.anim_sequence_import_data.set_editor_property( 'custom_sample_rate', folder_entity.get("attrib", {}).get("fps")) task.options.anim_sequence_import_data.set_editor_property( 'import_custom_attribute', True) task.options.anim_sequence_import_data.set_editor_property( 'import_bone_tracks', True) task.options.anim_sequence_import_data.set_editor_property( 'remove_redundant_keys', False) task.options.anim_sequence_import_data.set_editor_property( 'convert_scene', True) skeletal_mesh = EditorAssetLibrary.load_asset( container.get('namespace') + "/" + container.get('asset_name')) skeleton = skeletal_mesh.get_editor_property('skeleton') task.options.set_editor_property('skeleton', skeleton) # do import fbx and replace existing data unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks([task]) container_path = f'{container["namespace"]}/{container["objectName"]}' # update metadata unreal_pipeline.imprint( container_path, { "representation": repre_entity["id"], "parent": repre_entity["versionId"], }) asset_content = EditorAssetLibrary.list_assets( destination_path, recursive=True, include_folder=True ) for a in asset_content: EditorAssetLibrary.save_asset(a) def remove(self, container): path = container["namespace"] parent_path = os.path.dirname(path) EditorAssetLibrary.delete_directory(path) asset_content = EditorAssetLibrary.list_assets( parent_path, recursive=False, include_folder=True ) if len(asset_content) == 0: EditorAssetLibrary.delete_directory(parent_path)
import unreal import sys # https://docs.unrealengine.com/5.0/en-US/project/.html?highlight=create_asset#unreal.AssetTools.create_asset def create_material_instance(parent_material, asset_path, new_asset_name): # Create the child material asset_tools = unreal.AssetToolsHelpers.get_asset_tools() material_factory = unreal.MaterialInstanceConstantFactoryNew() new_asset = asset_tools.create_asset(new_asset_name, asset_path, None, material_factory) # Assign its parent unreal.MaterialEditingLibrary.set_material_instance_parent(new_asset, parent_material) return new_asset selected_materials = unreal.EditorUtilityLibrary.get_selected_assets() if not selected_materials or len(selected_materials) != 1: unreal.EditorDialog.show_message("Error", "Select one material in the Content Browser and run the script", unreal.AppMsgType.OK) sys.exit() create_material_instance(selected_materials[0], "/project/", "MaterialInstanceTest")
from typing import Dict, Any import unreal import json def get_project_info() -> Dict[str, dict]: project_info = {} project_info["project_name"] = ( unreal.Paths.get_project_file_path().split("/")[-1].replace(".uproject", "") if unreal.Paths.get_project_file_path() else "Unknown" ) project_info["project_directory"] = unreal.Paths.project_dir() project_info["engine_version"] = unreal.SystemLibrary.get_engine_version() # Asset registry analysis asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() all_assets = asset_registry.get_all_assets() # Asset summary total_assets = len(all_assets) asset_locations = {} input_actions = [] input_mappings = [] game_modes = [] characters = [] experiences = [] weapons = [] maps = [] for asset in all_assets: asset_name = str(asset.asset_name) package_path = str(asset.package_path) # Count by location location = package_path.split("/")[1] if "/" in package_path else "Root" asset_locations[location] = asset_locations.get(location, 0) + 1 asset_name_lower = asset_name.lower() full_path = f"{package_path}/{asset_name}" if asset_name.startswith("IA_"): input_actions.append(full_path) elif asset_name.startswith("IMC_"): input_mappings.append(full_path) elif "gamemode" in asset_name_lower: game_modes.append(full_path) elif ( any(term in asset_name_lower for term in ["hero", "character"]) and "b_" in asset_name_lower ): characters.append(full_path) elif "experience" in asset_name_lower and "ui" not in package_path.lower(): experiences.append(full_path) elif any(term in asset_name_lower for term in ["weapon", "wid_"]): weapons.append(full_path) elif asset_name.startswith("L_"): maps.append(full_path) project_info["total_assets"] = total_assets project_info["asset_locations"] = dict( sorted(asset_locations.items(), key=lambda x: x[1], reverse=True)[:10] ) # system project_info["enhanced_input_enabled"] = True project_info["input_actions"] = input_actions[:10] project_info["input_mappings"] = input_mappings[:10] project_info["input_actions_count"] = len(input_actions) project_info["input_mappings_count"] = len(input_mappings) # assets project_info["game_modes"] = game_modes[:5] project_info["characters"] = characters[:5] project_info["experiences"] = experiences[:5] project_info["weapons"] = weapons[:10] project_info["maps"] = maps[:10] # capabilities project_info["gameplay_ability_system"] = True project_info["modular_gameplay"] = True project_info["python_scripting"] = True project_info["networking"] = True # info project_info["total_maps"] = len(maps) project_info["total_weapons"] = len(weapons) project_info["total_experiences"] = len(experiences) return project_info def main(): project_data = get_project_info() print(json.dumps(project_data, indent=2)) if __name__ == "__main__": main()
# Copyright (c) <2021> Side Effects Software Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. The name of Side Effects Software may not be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN # NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ Example script that instantiates an HDA using the API and then setting some parameter values after instantiation but before the first cook. """ import unreal _g_wrapper = None def get_test_hda_path(): return '/project/.pig_head_subdivider_v01' def get_test_hda(): return unreal.load_object(None, get_test_hda_path()) def on_post_instantiation(in_wrapper): print('on_post_instantiation') # in_wrapper.on_post_instantiation_delegate.remove_callable(on_post_instantiation) # Set some parameters to create instances and enable a material in_wrapper.set_bool_parameter_value('add_instances', True) in_wrapper.set_int_parameter_value('num_instances', 8) in_wrapper.set_bool_parameter_value('addshader', True) def run(): # get the API singleton api = unreal.HoudiniPublicAPIBlueprintLib.get_api() global _g_wrapper # instantiate an asset with auto-cook enabled _g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform()) # Bind on_post_instantiation (before the first cook) callback to set parameters _g_wrapper.on_post_instantiation_delegate.add_callable(on_post_instantiation) if __name__ == '__main__': run()
# Copyright Epic Games, Inc. All Rights Reserved. import os import unreal #------------------------------------------------------------------------------- class PlatformBase(unreal.Platform): name = "Linux" autosdk_name = "Linux_x64" env_var = "LINUX_MULTIARCH_ROOT" def _get_version_ue4(self): dot_cs = self.get_unreal_context().get_engine().get_dir() dot_cs /= "Source/project/.cs" return Platform._get_version_helper_ue4(dot_cs, "ExpectedSDKVersion") def _get_version_ue5(self): dot_cs = "Source/project/" version = self._get_version_helper_ue5(dot_cs + ".Versions.cs") return version or self._get_version_helper_ue5(dot_cs + ".cs") def _get_cook_form(self, target): if target == "game": return "Linux" if self.get_unreal_context().get_engine().get_version_major() > 4 else "LinuxNoEditor" if target == "client": return "LinuxClient" if target == "server": return "LinuxServer" #------------------------------------------------------------------------------- class Platform(PlatformBase): def _read_env(self): env_var = PlatformBase.env_var value = os.getenv(env_var) if value: yield env_var, value return version = self.get_version() extras_dir = self.get_unreal_context().get_engine().get_dir() / "Extras" for suffix in ("AutoSDK/", "ThirdPartyNotUE/SDKs/"): value = extras_dir / suffix / f"HostLinux/Linux_x64/{version}/" if (value / "x86_64-unknown-linux-gnu/bin").is_dir(): yield env_var, value return yield env_var, f"Linux_x64/{version}/" def _launch(self, exec_context, stage_dir, binary_path, args): if stage_dir: base_dir = binary_path.replace("\\", "/").split("/") base_dir = "/".join(base_dir[-4:-1]) base_dir = stage_dir + base_dir if not os.path.isdir(base_dir): raise EnvironmentError(f"Failed to find base directory '{base_dir}'") args = (*args, "-basedir=" + base_dir) ue_context = self.get_unreal_context() engine_dir = ue_context.get_engine().get_dir() engine_bin_dir = str(engine_dir / "Binaries/Linux") if ld_lib_path := os.getenv("LD_LIBRARY_PATH"): ld_lib_path += ":" + str(engine_bin_dir) else: ld_lib_path = str(engine_bin_dir) env = exec_context.get_env() env["LD_LIBRARY_PATH"] = ld_lib_path cmd = exec_context.create_runnable(binary_path, *args) cmd.launch() return True
import unreal import os import json #constants DEFAULT_IO_TEMP_DIR = r"/project/" BL_FLAG = "Blender" BL_NEW = "NewActor" BL_DEL = "Removed" editor_subsys= unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem) level_subsys = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem) actor_subsys= unreal.get_editor_subsystem(unreal.EditorActorSubsystem) # unreal.EditorAssetSubsystem.set_dirty_flag editor_util = unreal.EditorUtilityLibrary 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_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_actor_type(actor, class_name): """ 获取Actor的更有意义的类型描述。 Args: actor: Actor对象 class_name: Actor的类名 Returns: str: 更有意义的类型描述 """ # 检查是否是常见的Actor类型 if class_name == "StaticMeshActor": return "StaticMesh" elif class_name == "SkeletalMeshActor": return "SkeletalMesh" elif class_name == "CameraActor": return "Camera" elif class_name == "DirectionalLight": return "DirectionalLight" elif class_name == "PointLight": return "PointLight" elif class_name == "SpotLight": return "SpotLight" elif class_name == "SkyLight": return "SkyLight" elif class_name == "ReflectionCapture": return "ReflectionCapture" elif class_name == "PackedLevelActor": return "PackedLevel" elif class_name == "LevelInstance": return "LevelInstance" # 检查是否是蓝图Actor if "_C" in class_name: # 尝试获取父类 try: parent_class = actor.get_class().get_super_class() if parent_class: parent_name = parent_class.get_name() if parent_name == "Actor": # 如果父类是Actor,尝试检查组件 return get_actor_type_from_components(actor, class_name) else: # 返回父类名称 return f"Blueprint ({parent_name})" except: pass # 如果无法获取更多信息,至少标记为蓝图 return "Blueprint" # 默认返回原始类名 return class_name def get_actor_type_from_components(actor, class_name): """ 通过检查Actor的组件来确定其类型。 Args: actor: Actor对象 class_name: Actor的类名 Returns: str: 基于组件的类型描述 """ try: # 获取所有组件 components = actor.get_components_by_class(unreal.SceneComponent) # 检查是否有StaticMeshComponent static_mesh_components = [c for c in components if c.get_class().get_name() == "StaticMeshComponent"] if static_mesh_components: return "Blueprint (StaticMesh)" # 检查是否有SkeletalMeshComponent skeletal_mesh_components = [c for c in components if c.get_class().get_name() == "SkeletalMeshComponent"] if skeletal_mesh_components: return "Blueprint (SkeletalMesh)" # 检查是否有CameraComponent camera_components = [c for c in components if c.get_class().get_name() == "CameraComponent"] if camera_components: return "Blueprint (Camera)" # 检查是否有LightComponent light_components = [c for c in components if "LightComponent" in c.get_class().get_name()] if light_components: return "Blueprint (Light)" except: pass # 如果无法确定具体类型,返回通用蓝图类型 return "Blueprint" def is_transform_close(actor, location, rotation, scale, tol=0.01): actor_transform = actor.get_actor_transform() loc = actor_transform.translation rot = actor_transform.rotation.rotator() scl = actor_transform.scale3d def is_close(a, b, tol=tol): return abs(a - b) < tol loc_match = ( is_close(loc.x, location.get("x", 0)) and is_close(loc.y, location.get("y", 0)) and is_close(loc.z, location.get("z", 0)) ) rot_match = ( is_close(rot.roll, rotation.get("x", 0)) and is_close(rot.pitch, rotation.get("y", 0)) and is_close(rot.yaw, rotation.get("z", 0)) ) scl_match = ( is_close(scl.x, scale.get("x", 1)) and is_close(scl.y, scale.get("y", 1)) and is_close(scl.z, scale.get("z", 1)) ) return loc_match and rot_match and scl_match def get_level_asset(type="EDITOR"): """ 获取Level Asset type='EDITOR' 时输出当前打开的Level的World对象 type='CONTENTBROWSER' 时输出在Content Browser中选中的Level """ if type == "EDITOR": # 获取当前打开的Level current_level = level_subsys.get_current_level() # 从Level获取World对象 if current_level: outer = current_level.get_outer() if outer: if outer.get_class().get_name() == "World": # print(f"Current Active Level Asset: {outer}") return outer if type == "CONTENTBROWSER": level_assets=[] editor_util = unreal.EditorUtilityLibrary selected_assets = editor_util.get_selected_assets() for asset in selected_assets: #检查是否是LevelAsset asset_class = asset.get_class().get_name() if asset_class=="World": level_assets.append(asset) return level_assets def export_level_to_fbx(level_asset,output_path): """ 导出Level到指定的FBX文件路径。 Args: level_asset: World对象或Level对象 output_path (str): 导出的FBX文件的完整路径,包括文件名和扩展名(.fbx)。 Returns: str: 成功导出后返回FBX文件的完整路径,否则返回None。 """ # 确保输出目录存在 if not os.path.exists(output_path): os.makedirs(output_path) print(f"创建输出目录: {output_path}") if level_asset is None: print("错误: level_asset 为 None") return None current_level = level_asset print(f"Export object: {current_level}") print(f"Export object class: {current_level.get_class().get_name()}") # 如果传入的是Level对象,尝试获取World对象 if current_level.get_class().get_name() == "Level": print("检测到Level对象,尝试获取对应的World对象...") world = get_level_asset(type="EDITOR") if world: current_level = world print(f"使用World对象: {current_level}") else: print("警告: 无法获取World对象,将尝试使用Level对象导出") level_name = current_level.get_name() # 设置导出选项 export_options = unreal.FbxExportOption() # 这里可以根据需要设置更多的导出选项,例如: export_options.export_source_mesh=True export_options.vertex_color = False export_options.level_of_detail = False export_options.collision = False # 构建完整的输出文件路径 fbx_file_path = os.path.join(output_path, f"{level_name}.fbx") print(f"导出路径: {fbx_file_path}") # 导出Level到FBX export_task = unreal.AssetExportTask() export_task.object = current_level export_task.filename = fbx_file_path export_task.automated = True export_task.prompt = False export_task.options = export_options # 使用正确的导出器 fbx_exporter = unreal.LevelExporterFBX() export_task.exporter = fbx_exporter # 执行导出任务 result = fbx_exporter.run_asset_export_task(export_task) # 检查导出结果 if result: print(f"✓ 成功导出 Level: {level_name} 到 {fbx_file_path}") # 验证文件是否存在 if os.path.exists(fbx_file_path): file_size = os.path.getsize(fbx_file_path) print(f" 文件大小: {file_size} bytes") return fbx_file_path else: print(f" 警告: 导出报告成功但文件不存在!") return None else: print(f"✗ 导出 Level 失败: {level_name}") return None def export_current_level_json(output_path): """ 导出当前关卡的世界信息和所有Actor的信息到JSON文件。 Actor信息包括Transform, 类型, FName和FGuid。 """ try: # 1. 获取当前编辑器世界和关卡信息 main_level=editor_subsys.get_editor_world() current_level = level_subsys.get_current_level() if current_level: print(current_level) level_asset = current_level.get_outer() if not current_level: # outer = current_level.get_outer(): unreal.log_error("无法获取当前编辑器世界。请确保在编辑器中打开了一个关卡。") return main_level_path = main_level.get_path_name() level_asset_path = level_asset.get_path_name() print (f"当前关卡: {level_asset_path}") # 使用关卡名作为文件名(去除路径和前缀,使其更简洁) level_name_for_file = unreal.SystemLibrary.get_object_name(level_asset).replace(" ", "_") # print (f"关卡名: {level_name_for_file}") unreal.log(f"开始导出关卡: {level_asset.get_name()}") # 2. 获取当前活动子关卡中的所有Actor # 使用get_actors_from_level方法,只获取特定关卡中的Actor all_actors = [] all_actors = actor_subsys.get_all_level_actors() # 过滤出属于当前关卡的Actor if level_asset_path != main_level_path: filtered_actors = [] for actor in all_actors: if actor and actor.get_level() == current_level: filtered_actors.append(actor) all_actors = filtered_actors unreal.log(f"通过过滤获取到 {len(all_actors)} 个属于当前关卡的Actor") else: unreal.log(f"当前关卡为主关卡,不进行过滤,获取到{len(all_actors)}个Actor") actors_data = [] # 3. 遍历所有Actor并提取信息 for actor in all_actors: # print(actor.get_actor_label()) if actor is None: # 避免处理无效的actor continue actor_info = {} # Actor FName (对象实例名) actor_info["name"] = str(actor.get_actor_label()) actor_info["fname"] = str(actor.get_fname()) # Actor FGuid (全局唯一ID) actor_guid = actor.actor_guid actor_info["fguid"] = str(actor_guid) # Actor 类型 (类名) actor_class = actor.get_class() class_name = actor_class.get_name() if actor_class else "Unknown" # 获取更有意义的类型信息 actor_type = get_actor_type(actor, class_name) actor_info["class"] = class_name # 保留原始类名 actor_info["actor_type"] = actor_type # 添加更有意义的类型描述 # Actor Transform transform = actor.get_actor_transform() location = transform.translation # unreal.Vector rotation = transform.rotation.rotator() # unreal.Rotator scale = transform.scale3d # unreal.Vector actor_info["transform"] = { "location": {"x": location.x, "y": location.y, "z": location.z}, "rotation": {"x": rotation.roll,"y": rotation.pitch, "z": rotation.yaw}, "scale": {"x": scale.x, "y": scale.y, "z": scale.z} } actors_data.append(actor_info) # 4. 组织最终的JSON数据 level_export_data = { "main_level": main_level_path, "level_path": level_asset_path, "level_name_for_file": level_name_for_file, "export_path": output_path, "actor_count": len(actors_data), "actors": actors_data } # 5. 定义输出路径并写入JSON文件 if not os.path.exists(output_path): os.makedirs(output_path) print(f"创建输出目录: {output_path}") file_path = os.path.join(output_path, f"{level_name_for_file}.json") with open(file_path, 'w', encoding='utf-8') as f: json.dump(level_export_data, f, indent=4, ensure_ascii=False) unreal.log(f"成功导出关卡数据到: {file_path}") return file_path except Exception as e: unreal.log_error(f"导出关卡数据时发生错误: {e}") import traceback unreal.log_error(traceback.format_exc()) return None def import_json(file_path): """ 1. 从json导入数据 2. 检查json的关卡是否与目前打开的关卡一致(根据main_level和level_path校验是否同一个关卡) 3. 检查json里actor的transform是否与level中actor的transform一致(根据name, fname和guid校验是否同一个actor) 4. 如果json里有新actor,根据guid,创建一个actor,根据transform,设置actor的位置,旋转,缩放 """ # 1. 读取JSON文件 if not os.path.exists(file_path): unreal.log_error(f"找不到JSON文件: {file_path}") return with open(file_path, 'r', encoding='utf-8') as f: json_data = json.load(f) unreal.log(f"成功读取JSON文件: {file_path}") # 2. 校验关卡 main_level = editor_subsys.get_editor_world() level_asset = get_level_asset(type="EDITOR") main_level_path = main_level.get_path_name() level_asset_path = level_asset.get_path_name() json_main_level = json_data.get("main_level", "") json_level_path = json_data.get("level_path", "") if main_level_path != json_main_level or level_asset_path != json_level_path: unreal.log_error("JSON中的关卡与当前打开的关卡不一致,导入终止。") return # 3. 获取当前关卡所有Actor,建立fname映射 all_actors = actor_subsys.get_all_level_actors() fname_to_actor = {} match_count = 0 for actor in all_actors: if hasattr(actor, "get_fname"): actor_fname = str(actor.get_fname()) actor_name = str(actor.get_actor_label()) fname_to_actor[actor_fname] = actor match_count += 1 print(f"matched count: {match_count}") # print(fname_to_actor) # 4. 遍历JSON中的actors json_actors_data = json_data.get("actors", []) # 先遍历一遍,收集需要处理的对象到不同列表 bl_new_list = [] # 存储需要新建的actor信息 bl_del_list = [] # 存储需要删除的actor信息 other_ops = [] # 存储其他需要同步transform的actor信息 for actor_info in json_actors_data: guid = actor_info.get("fguid") name = actor_info.get("name") fname = actor_info.get("fname") actor_type = actor_info.get("actor_type") blender_flag = actor_info.get(BL_FLAG, None) if "Light" in actor_type: # 忽略灯光 continue transform_data = actor_info.get("transform", {}) location = transform_data.get("location", {}) rotation = transform_data.get("rotation", {}) scale = transform_data.get("scale", {}) # 分类收集BL_NEW、BL_DEL和其他操作 if blender_flag == BL_NEW: bl_new_list.append((actor_info, location, rotation, scale)) elif blender_flag == BL_DEL: bl_del_list.append((actor_info, actor_type, name)) else: other_ops.append((actor_info, location, rotation, scale)) # 先统一处理所有BL_NEW,避免被提前删除 for actor_info, location, rotation, scale in bl_new_list: name = actor_info.get("name") fname = actor_info.get("fname") actor_type = actor_info.get("actor_type") name_exists = False same_type = False # 检查场景中是否有同名actor for a in fname_to_actor.values(): if a.get_actor_label() == name: name_exists = True a_type = get_actor_type(a, a.get_class().get_name()) if a_type == actor_type: same_type = True # 只修改transform new_transform = unreal.Transform( unreal.Vector(location.get("x", 0), location.get("y", 0), location.get("z", 0)), unreal.Rotator(rotation.get("x", 0), rotation.get("y", 0), rotation.get("z", 0)), unreal.Vector(scale.get("x", 1), scale.get("y", 1), scale.get("z", 1)) ) a.set_actor_transform(new_transform, sweep=False, teleport=True) unreal.log(f"已更新同名Actor: {name} 的Transform") break # 如果是新Actor且没有找到同名同类型的actor if not name_exists or not same_type: # fname找原资源并复制 src_actor = None for a in fname_to_actor.values(): if str(a.get_fname()) == fname: src_actor = a break if src_actor: # 复制actor new_actor = actor_subsys.duplicate_actor(src_actor) if new_actor: new_actor.set_actor_label(name) new_transform = unreal.Transform( unreal.Vector(location.get("x", 0), location.get("y", 0), location.get("z", 0)), unreal.Rotator(rotation.get("x", 0), rotation.get("y", 0), rotation.get("z", 0)), unreal.Vector(scale.get("x", 1), scale.get("y", 1), scale.get("z", 1)) ) new_actor.set_actor_transform(new_transform, sweep=False, teleport=True) unreal.log(f"已新增Blender新Actor: {name} 并设置Transform") else: unreal.log_error(f"无法复制原Actor: {name}") else: unreal.log_error(f"找不到原资源Actor用于复制: {name}") # 再统一处理所有BL_DEL,确保不会提前删除新建目标 for actor_info, actor_type, name in bl_del_list: # 检查场景中是否有同名actor且类型一致 for a in fname_to_actor.values(): if a.get_actor_label() == name: a_type = get_actor_type(a, a.get_class().get_name()) if a_type == actor_type: # 找到匹配的actor,删除它 unreal.log(f"删除Actor: {name} (类型: {actor_type})") a.destroy_actor() break # 最后处理其他操作(如transform同步) for actor_info, location, rotation, scale in other_ops: name = actor_info.get("name") fname = actor_info.get("fname") actor_type = actor_info.get("actor_type") actor = None # 只有当 fname 和 name 都匹配时才认为是同一个 actor if fname in fname_to_actor: candidate = fname_to_actor[fname] if candidate.get_actor_label() == name: actor = candidate if actor: # 检查transform是否一致 if not is_transform_close(actor, location, rotation, scale): new_transform = unreal.Transform( unreal.Vector(location.get("x", 0), location.get("y", 0), location.get("z", 0)), unreal.Rotator(rotation.get("x", 0), rotation.get("y", 0), rotation.get("z", 0)), unreal.Vector(scale.get("x", 1), scale.get("y", 1), scale.get("z", 1)) ) actor.set_actor_transform(new_transform, sweep=False, teleport=True) unreal.log(f"已更新Actor: {name} 的Transform") # unreal.EditorLevelLibrary.editor_screen_refresh() unreal.log("关卡数据导入完成。") return # 主执行部分 def ubio_export(): json_path=export_current_level_json(DEFAULT_IO_TEMP_DIR) level_asset = get_level_asset(type="EDITOR") if level_asset: fbx_path=export_level_to_fbx(level_asset, DEFAULT_IO_TEMP_DIR) else: print("无法获取Level资产") # print(f"导出名字不匹配,请检查") def ubio_import(): main_level=editor_subsys.get_editor_world() level_asset=get_level_asset(type="EDITOR") level_asset_path = level_asset.get_path_name() # print (f"当前关卡: {level_asset_path}") level_name_for_file = unreal.SystemLibrary.get_object_name(level_asset).replace(" ", "_") json_path=DEFAULT_IO_TEMP_DIR+"\\"+level_name_for_file+".json" print(f"从{json_path}导入") import_json(json_path) # ubio_import()
import unreal ar_asset_lists = unreal.EditorUtilityLibrary.get_selected_assets() ar_selected_0 = ar_asset_lists[0] for each in ar_asset_lists : import_data_selected = each.get_editor_property("asset_import_data") frame_rate_data = import_data_selected.get_editor_property("custom_sample_rate") using_default_sample_rate = import_data_selected.get_editor_property("use_default_sample_rate") import_data_selected.set_editor_property("use_default_sample_rate", False) import_data_selected.set_editor_property("custom_sample_rate", 60)
#!/project/ python # -*- coding: utf-8 -*- # # SequencerFunctions.py # @Author : () # @Link : # @Date : 2019/project/ 下午6:40:43 # unreal.MovieSceneSequence # https://api.unrealengine.com/project/.html # unreal.LevelSequence # https://api.unrealengine.com/project/.html # unreal.SequencerBindingProxy # https://api.unrealengine.com/project/.html import unreal # 创建LevelSequence资源。 ''' Summary: 在指定目录下创建具有给定名称的 level sequence 。这是一个如何创建 level sequence 资源的示例, 如何将当前映射中的对象添加到序列中,以及如何创建一些示例绑定/etc。 Creates a level sequence with the given name under the specified directory. This is an example of how to create Level Sequence assets, how to add objects from the current map into the sequence and how to create some example bindings/etc. Params: asset_name - Name of the resulting asset, ie: "MyLevelSequence" 所得资产的名称,即:"MyLevelSequence" package_path - Name of the package path to put the asest into, ie: "/project/" 要将asest放入的包路径的名称 Returns: The created LevelSequence asset. 创建LevelSequence资源。 ''' def create_level_sequence(asset_name, package_path = '/project/'): # 创建LevelSequence资源 sequence = unreal.AssetToolsHelpers.get_asset_tools().create_asset(asset_name, package_path, unreal.LevelSequence, unreal.LevelSequenceFactoryNew()) # 获取定序器,并添加 actor ,返回 actor 绑定的代理 # sequence_path: str : The level sequence asset path 关卡定序器资产路径 # actor: obj unreal.Actor : The actor you want to add into (or get from) the sequence asset 要添加到序列资源中(或从序列资源中获取)的 actor # return: obj unreal.SequencerBindingProxy : The actor binding 绑定的 actor def getOrAddPossessableInSequenceAsset(sequence_path='', actor=None): sequence_asset = unreal.LevelSequence.cast(unreal.load_asset(sequence_path)) # 绑定 sequence 资产 possessable = sequence_asset.add_possessable(object_to_possess=actor) # 添加 actor 资产到 sequence return possessable # 向 actor 绑定的代理,添加动画 # animation_path: str : The animation asset path 动画资源路径 # possessable: obj unreal.SequencerBindingProxy : The actor binding you want to add the animation on 要添加动画的 actor 绑定 # return: obj unreal.SequencerBindingProxy : The actor binding 绑定的 actor def addSkeletalAnimationTrackOnPossessable(animation_path='', possessable=None): # Get Animation 获取动画 animation_asset = unreal.AnimSequence.cast(unreal.load_asset(animation_path)) params = unreal.MovieSceneSkeletalAnimationParams() # 电影场景骨骼动画参数 params.set_editor_property('Animation', animation_asset) # Add track 添加轨道 animation_track = possessable.add_track(track_type=unreal.MovieSceneSkeletalAnimationTrack) # 添加轨道,类型为动画类型 # Add section 添加动画片段 animation_section = animation_track.add_section() animation_section.set_editor_property('Params', params) animation_section.set_range(0, animation_asset.get_editor_property('sequence_length')) def addSkeletalAnimationTrackOnActor_EXAMPLE(): sequence_path = '/project/' actor_path = '/project/' animation_path = '/project/' actor_in_world = unreal.GameplayStatics.get_all_actors_of_class(unreal.EditorLevelLibrary.get_editor_world(), unreal.SkeletalMeshActor)()[0] possessable_in_sequence = getOrAddPossessableInSequenceAsset(sequence_path, actor_path) addSkeletalAnimationTrackOnPossessable(animation_path, possessable_in_sequence) if __name__ == "__main__": create_level_sequence('MyLevelSequence')
import unreal AssetTools = unreal.AssetToolsHelpers.get_asset_tools() MaterialEditLibrary = unreal.MaterialEditingLibrary EditorAssetLibrary = unreal.EditorAssetLibrary # Create 2D texture param and connect to BASE COLOR masterMaterial = AssetTools.create_asset("M_Master", "/project/", unreal.Material, unreal.MaterialFactoryNew()) baseColorTextureParam = MaterialEditLibrary.create_material_expression(masterMaterial, unreal.MaterialExpressionTextureSampleParameter, -384, -200) MaterialEditLibrary.connect_material_property(baseColorTextureParam, "RGB", unreal.MaterialProperty.MP_BASE_COLOR) # Create 2D texture param and connect to ROUGHNESS roughnessTextureParam = MaterialEditLibrary.create_material_expression(masterMaterial, unreal.MaterialExpressionTextureSampleParameter, -384, -200) MaterialEditLibrary.connect_material_property(roughnessTextureParam, "RGB", unreal.MaterialProperty.MP_ROUGHNESS) # Create constant value and connect to SPECULAR specularTextureParam = MaterialEditLibrary.create_material_expression(masterMaterial, unreal.MaterialExpressionConstant, -125, 70) specularTextureParam.set_editor_property("R", 0.3) MaterialEditLibrary.connect_material_property(specularTextureParam, "", unreal.MaterialProperty.MP_SPECULAR) # Create 2D texture param and connect to NORMAL normalTextureParam = MaterialEditLibrary.create_material_expression(masterMaterial, unreal.MaterialExpressionTextureSampleParameter, -125, -25) MaterialEditLibrary.connect_material_property(normalTextureParam, "RGB", unreal.MaterialProperty.MP_NORMAL) # Create 2D texture param and connect to METALLIC metalTextureParam = MaterialEditLibrary.create_material_expression(masterMaterial, unreal.MaterialExpressionTextureSampleParameter, -125, -25) MaterialEditLibrary.connect_material_property(metalTextureParam, "RGB", unreal.MaterialProperty.MP_METALLIC) # Create 2D texture param and connect to AO aoTextureParam = MaterialEditLibrary.create_material_expression(masterMaterial, unreal.MaterialExpressionTextureSampleParameter, -125, -25) MaterialEditLibrary.connect_material_property(aoTextureParam, "RGB", unreal.MaterialProperty.MP_AMBIENT_OCCLUSION) EditorAssetLibrary.save_asset("/project/", True)
# Copyright (c) 2023 Max Planck Society # License: https://bedlam.is.tuebingen.mpg.de/license.html # # Import clothing textures and generate MaterialInstances # import os from pathlib import Path import sys import time import unreal DATA_ROOT = r"/project/" DATA_ROOT_UNREAL = "/project/" MASTER_MATERIAL_PATH = "/project/" def import_textures(texture_paths): master_material = unreal.EditorAssetLibrary.load_asset(f"Material'{MASTER_MATERIAL_PATH}'") if not master_material: unreal.log_error(f"Cannot load master material: {MASTER_MATERIAL_PATH}") return False for texture_path in texture_paths: unreal.log(f"Processing {texture_path}") # Check if texture is already imported # clothing_abc\rp_aaron_posed_002\clothing_textures\texture_01\texture_01_diffuse_1001.png subject_name = texture_path.parent.parent.parent.name texture_name = texture_path.parent.name import_tasks = [] # Diffuse texture texture_asset_name = f"T_{subject_name}_{texture_name}_diffuse" texture_asset_dir = f"{DATA_ROOT_UNREAL}/{subject_name}" texture_asset_path = f"{texture_asset_dir}/{texture_asset_name}" if unreal.EditorAssetLibrary.does_asset_exist(texture_asset_path): unreal.log(" Skipping. Already imported: " + texture_asset_path) else: unreal.log(" Importing: " + texture_asset_path) task = unreal.AssetImportTask() task.set_editor_property("filename", str(texture_path)) task.set_editor_property("destination_name", texture_asset_name) task.set_editor_property("destination_path", texture_asset_dir) task.set_editor_property('save', True) import_tasks.append(task) # Normal texture normal_texture_path = texture_path.parent / texture_path.name.replace("diffuse", "normal") normal_texture_asset_name = f"T_{subject_name}_{texture_name}_normal" normal_texture_asset_path = f"{texture_asset_dir}/{normal_texture_asset_name}" if unreal.EditorAssetLibrary.does_asset_exist(normal_texture_asset_path): unreal.log(" Skipping. Already imported: " + normal_texture_asset_path) else: unreal.log(" Importing: " + normal_texture_asset_path) task = unreal.AssetImportTask() task.set_editor_property("filename", str(normal_texture_path)) task.set_editor_property("destination_name", normal_texture_asset_name) task.set_editor_property("destination_path", texture_asset_dir) task.set_editor_property('save', True) import_tasks.append(task) # Import diffuse and normal textures unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks(import_tasks) # Load diffuse and normal textures texture_asset = unreal.EditorAssetLibrary.load_asset(f"Texture2D'{texture_asset_path}'") if not texture_asset: unreal.log_error(f"Cannot load texture: {texture_asset_path}") return False normal_texture_asset = unreal.EditorAssetLibrary.load_asset(f"Texture2D'{normal_texture_asset_path}'") if not texture_asset: unreal.log_error(f"Cannot load texture: {normal_texture_asset_path}") return False # Create MaterialInstance material_instance_name = f"MI_{subject_name}_{texture_name}" material_instance_dir = texture_asset_dir material_instance_path = f"{material_instance_dir}/{material_instance_name}" if unreal.EditorAssetLibrary.does_asset_exist(material_instance_path): unreal.log(" Skipping. MaterialInstance exists: " + material_instance_path) else: unreal.log(f" Creating MaterialInstance: {material_instance_path}") material_instance = unreal.AssetToolsHelpers.get_asset_tools().create_asset(asset_name=material_instance_name, package_path=material_instance_dir, asset_class=unreal.MaterialInstanceConstant, factory=unreal.MaterialInstanceConstantFactoryNew()) unreal.MaterialEditingLibrary.set_material_instance_parent(material_instance, master_material) unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value(material_instance, 'BaseColor', texture_asset) unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value(material_instance, 'Normal', normal_texture_asset) return True ###################################################################### # Main ###################################################################### if __name__ == "__main__": unreal.log("============================================================") unreal.log("Running: %s" % __file__) # Build import list import_texture_paths = sorted(Path(DATA_ROOT).rglob("*diffuse*.png")) import_textures(import_texture_paths)
# Copyright Epic Games, Inc. All Rights Reserved # Built-in import sys from pathlib import Path from deadline_utils import get_editor_deadline_globals from deadline_service import DeadlineService # Third-party import unreal plugin_name = "DeadlineService" # Add the actions path to sys path actions_path = Path(__file__).parent.joinpath("service_actions").as_posix() if actions_path not in sys.path: sys.path.append(actions_path) # 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.") # Create a global instance of the deadline service. This is useful for # unreal classes that are not able to save the instance as an # attribute on the class. Because the Deadline Service is a singleton, # any new instance created from the service module will return the global # instance deadline_globals = get_editor_deadline_globals() try: deadline_globals["__deadline_service_instance__"] = DeadlineService() except Exception as err: raise RuntimeError(f"An error occurred creating a Deadline service instance. \n\tError: {str(err)}") from service_actions import submit_job_action # Register the menu from the render queue actions submit_job_action.register_menu_action()
""" Unreal Engine FBX Skeletal Mesh Import Benchmark Too # Path to Maya batch executable (use mayabatch.exe for command-line operations) maya_executable: str = "/project/" # Linux path # Cache directory - update this to match your cache location cache_dir: str = "/project/-scripts/cache" # Linux pathis script benchmarks the import performance of FBX skeletal meshes into Unreal Engine, with optional triangulation using Maya. Key features: - Class-based architecture for maintainability - Separates triangulation timing from pure import timing - Uses mayabatch.exe for Maya automation (not GUI maya.exe) - Disables Unreal's automatic triangulation to measure only Maya triangulation - Comprehensive logging with script identification - Cache directory organization for temporary files Recent fixes: - Maya executable path corrected from maya.exe to mayabatch.exe - Unreal FBX import configured to disable automatic triangulation - Enhanced mesh import data settings to preserve Maya triangulation - Script path resolution updated to use cache directory """ # Run this in Unreal Console # exec(open("C:/project/-scripts/project/.py").read()) import shutil import subprocess import time from pathlib import Path from typing import List, Optional from dataclasses import dataclass from enum import Enum import unreal class LogLevel(Enum): """Log level enumeration""" INFO = "info" WARNING = "warning" ERROR = "error" @dataclass class BenchmarkConfig: """Configuration class for benchmark settings""" # IMPORTANT: Change this path to the folder containing your FBX files fbx_source_folder: str = "P:/project/" # Destination folder for imported assets within Unreal project import_destination: str = "/project/" # Enable triangulation of FBX files before import triangulate_mesh: bool = True # Path to Maya batch executable (use mayabatch.exe for command-line operations) maya_executable: str = "C:/Program Files/project/.exe" # Cache directory - update this to match your cache location cache_dir: str = "Z:/project/" # Derived paths @property def working_dir(self) -> Path: return Path(self.cache_dir) / "fbx_working" @property def maya_triangulate_script(self) -> Path: # Script is actually in the unreal_benchmark directory, not cache return Path("Z:/project/-scripts/unreal_benchmark") / "maya_fbx_triangulate.py" # Process timeouts maya_timeout: int = 300 # 5 minutes maya_version_check_timeout: int = 30 class Logger: """Unified logging interface for Unreal Engine""" @staticmethod def log(message: str, level: LogLevel = LogLevel.INFO) -> None: """Log a message with specified level""" if level == LogLevel.INFO: unreal.log(message) elif level == LogLevel.WARNING: unreal.log_warning(message) elif level == LogLevel.ERROR: unreal.log_error(message) class MayaChecker: """Handles Maya availability checking""" def __init__(self, config: BenchmarkConfig): self.config = config self._is_available: Optional[bool] = None @property def is_available(self) -> bool: """Check if Maya is available and cache the result""" if self._is_available is None: self._is_available = self._check_maya_availability() return self._is_available def _check_maya_availability(self) -> bool: """Check if Maya executable is available""" Logger.log(f"🔍 [MayaChecker] Checking Maya availability at: {self.config.maya_executable}") try: # Use -v flag instead of --version (Maya doesn't support --version properly) result = subprocess.run( [self.config.maya_executable, "-v"], capture_output=True, text=True, timeout=self.config.maya_version_check_timeout, ) if result.returncode == 0: Logger.log("✅ [MayaChecker] Maya is available - version check passed") Logger.log(f"🔍 [MayaChecker] Maya version output: {result.stdout.strip()}") return True else: Logger.log(f"❌ [MayaChecker] Maya version check failed with return code: {result.returncode}") if result.stderr: Logger.log(f"🔍 [MayaChecker] Maya stderr: {result.stderr}") if result.stdout: Logger.log(f"🔍 [MayaChecker] Maya stdout: {result.stdout}") return False except FileNotFoundError: Logger.log(f"❌ [MayaChecker] Maya executable not found at: {self.config.maya_executable}") return False except subprocess.TimeoutExpired: Logger.log(f"⏱️ [MayaChecker] Maya version check timed out after {self.config.maya_version_check_timeout}s") return False except subprocess.SubprocessError as e: Logger.log(f"❌ [MayaChecker] Maya subprocess error: {e}") return False class MayaTriangulator: """Handles FBX triangulation using Maya""" def __init__(self, config: BenchmarkConfig, maya_checker: MayaChecker): self.config = config self.maya_checker = maya_checker def triangulate_fbx(self, input_path: Path, output_path: Path) -> bool: """ Triangulates mesh in FBX file using Maya batch mode Args: input_path: Path to input FBX file output_path: Path to output triangulated FBX file Returns: True if successful, False otherwise """ Logger.log(f"🔧 [MayaTriangulator] Processing: {input_path.name}") Logger.log(f"🔧 [MayaTriangulator] Maya available: {self.maya_checker.is_available}") Logger.log(f"🔧 [MayaTriangulator] Script path: {self.config.maya_triangulate_script}") Logger.log(f"🔧 [MayaTriangulator] Script exists: {self.config.maya_triangulate_script.exists()}") if not self.maya_checker.is_available: Logger.log("⚠️ [MayaTriangulator] Maya not available, copying original file", LogLevel.WARNING) return self._copy_original(input_path, output_path) if not self.config.maya_triangulate_script.exists(): Logger.log( f"❌ [MayaTriangulator] Maya triangulation script not found: {self.config.maya_triangulate_script}", LogLevel.ERROR, ) return self._copy_original(input_path, output_path) Logger.log("🚀 [MayaTriangulator] Starting Maya triangulation process") return self._run_maya_triangulation(input_path, output_path) def _copy_original(self, input_path: Path, output_path: Path) -> bool: """Copy original file without triangulation""" Logger.log("📁 [MayaTriangulator] Copying file without triangulation") Logger.log(f"📁 [MayaTriangulator] From: {input_path}") Logger.log(f"📁 [MayaTriangulator] To: {output_path}") try: shutil.copy2(input_path, output_path) Logger.log(f"✅ [MayaTriangulator] Successfully copied: {input_path.name} -> {output_path.name}") return True except Exception as e: Logger.log(f"❌ [MayaTriangulator] Failed to copy file {input_path}: {e}", LogLevel.ERROR) return False def _run_maya_triangulation(self, input_path: Path, output_path: Path) -> bool: """Execute Maya triangulation process""" try: # Convert paths to strings with proper Windows formatting script_path = str(self.config.maya_triangulate_script).replace('\\', '/') input_path_str = str(input_path).replace('\\', '/') output_path_str = str(output_path).replace('\\', '/') cmd = [ self.config.maya_executable, "-batch", "-command", f"python(\"exec(open('{script_path}').read()); " f"triangulate_fbx_in_maya('{input_path_str}', '{output_path_str}')\")", ] Logger.log(f"🚀 [MayaTriangulator] Executing Maya command: {input_path.name}") Logger.log(f"🔍 [MayaTriangulator] Maya executable: {self.config.maya_executable}") Logger.log(f"🔍 [MayaTriangulator] Script: {script_path}") Logger.log(f"🔍 [MayaTriangulator] Input: {input_path_str}") Logger.log(f"🔍 [MayaTriangulator] Output: {output_path_str}") Logger.log(f"⏱️ [MayaTriangulator] Timeout: {self.config.maya_timeout}s") result = subprocess.run(cmd, capture_output=True, text=True, timeout=self.config.maya_timeout) Logger.log(f"🔍 [MayaTriangulator] Maya return code: {result.returncode}") Logger.log(f"🔍 [MayaTriangulator] Output file exists: {output_path.exists()}") if result.stdout: Logger.log(f"📝 [MayaTriangulator] Maya stdout: {result.stdout}") if result.stderr: Logger.log(f"🔍 [MayaTriangulator] Maya stderr: {result.stderr}") if result.returncode == 0 and output_path.exists(): Logger.log(f"✅ [MayaTriangulator] Successfully triangulated: {input_path.name}") return True else: Logger.log(f"❌ [MayaTriangulator] Maya triangulation failed for {input_path}", LogLevel.ERROR) Logger.log("📁 [MayaTriangulator] Falling back to copying original file") return self._copy_original(input_path, output_path) except subprocess.TimeoutExpired: Logger.log(f"⏱️ [MayaTriangulator] Maya triangulation timed out for {input_path}", LogLevel.ERROR) return self._copy_original(input_path, output_path) except Exception as e: Logger.log(f"❌ [MayaTriangulator] Error running Maya triangulation for {input_path}: {e}", LogLevel.ERROR) return self._copy_original(input_path, output_path) class FileProcessor: """Handles file operations and processing""" def __init__(self, config: BenchmarkConfig, triangulator: MayaTriangulator): self.config = config self.triangulator = triangulator def setup_working_directory(self) -> None: """Create working directory if it doesn't exist""" self.config.working_dir.mkdir(parents=True, exist_ok=True) def cleanup_working_directory(self) -> None: """Clean up the working directory after processing""" try: if self.config.working_dir.exists(): shutil.rmtree(self.config.working_dir) Logger.log("Cleaned up working directory") except Exception as e: Logger.log(f"Failed to clean up working directory: {e}", LogLevel.WARNING) def find_fbx_files(self, source_folder: Path) -> List[str]: """Find all FBX files in the source folder""" if not source_folder.is_dir(): return [] return [f.name for f in source_folder.iterdir() if f.suffix.lower() == ".fbx"] def process_fbx_files(self, source_folder: Path, fbx_files: List[str]) -> tuple[List[Path], float]: """ Process FBX files by copying and optionally triangulating them Args: source_folder: Source directory containing FBX files fbx_files: List of FBX filenames to process Returns: Tuple of (processed file paths, triangulation time in seconds) """ self.setup_working_directory() processed_files = [] Logger.log("🔄 Starting file processing phase...") triangulation_start = time.time() for fbx_file in fbx_files: source_path = source_folder / fbx_file processed_path = self._process_single_file(source_path) if processed_path: processed_files.append(processed_path) else: Logger.log(f"Failed to process: {fbx_file}", LogLevel.ERROR) triangulation_time = time.time() - triangulation_start if self.config.triangulate_mesh: Logger.log( f"✅ File processing complete: {len(processed_files)} files processed in {triangulation_time:.4f}s" ) else: Logger.log(f"✅ File copying complete: {len(processed_files)} files copied in {triangulation_time:.4f}s") return processed_files, triangulation_time def _process_single_file(self, source_path: Path) -> Optional[Path]: """Process a single FBX file""" if self.config.triangulate_mesh: return self._triangulate_file(source_path) else: return self._copy_file(source_path) def _triangulate_file(self, source_path: Path) -> Optional[Path]: """Triangulate a single FBX file""" base_name = source_path.stem # Check if actual triangulation will happen will_triangulate = self.triangulator.maya_checker.is_available and self.config.maya_triangulate_script.exists() if will_triangulate: processed_name = f"{base_name}_triangulated.fbx" Logger.log(f"Triangulating: {source_path.name}") else: processed_name = source_path.name Logger.log(f"Copying (Maya unavailable): {source_path.name}") dest_path = self.config.working_dir / processed_name if self.triangulator.triangulate_fbx(source_path, dest_path): return dest_path return None def _copy_file(self, source_path: Path) -> Optional[Path]: """Copy a single FBX file without triangulation""" dest_path = self.config.working_dir / source_path.name try: shutil.copy2(source_path, dest_path) Logger.log(f"Copied: {source_path.name}") return dest_path except Exception as e: Logger.log(f"Failed to copy {source_path.name}: {e}", LogLevel.ERROR) return None class UnrealImportOptions: """Handles Unreal Engine import options configuration""" @staticmethod def create_skeletal_mesh_options() -> unreal.FbxImportUI: """ Creates and configures import options for skeletal mesh Materials/textures are disabled to focus benchmark on mesh processing CRITICAL: Unreal's triangulation is DISABLED to ensure we only test Maya triangulation """ options = unreal.FbxImportUI() # General settings options.set_editor_property("import_as_skeletal", True) 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("import_animations", False) # Skeletal mesh specific settings skeletal_mesh_import_data = options.get_editor_property("skeletal_mesh_import_data") skeletal_mesh_import_data.set_editor_property("import_morph_targets", True) skeletal_mesh_import_data.set_editor_property("update_skeleton_reference_pose", False) Logger.log("🔍 [UnrealImport] Configured FBX import with triangulation DISABLED") return options @staticmethod def create_import_task(filename: str, destination_path: str, options: unreal.FbxImportUI) -> unreal.AssetImportTask: """Create an asset import task for a single file""" task = unreal.AssetImportTask() task.set_editor_property("filename", filename) task.set_editor_property("destination_path", destination_path) task.set_editor_property("options", options) task.set_editor_property("replace_existing", True) task.set_editor_property("save", False) # Don't save for pure benchmark task.set_editor_property("automated", True) # Prevent dialogs return task @dataclass class BenchmarkResults: """Container for benchmark results""" triangulation_enabled: bool maya_available: bool original_files_found: int files_processed: int files_imported: int triangulation_time: float import_time: float @property def total_time(self) -> float: """Total time including triangulation and import""" return self.triangulation_time + self.import_time @property def average_triangulation_time(self) -> float: """Calculate average triangulation time per file""" return self.triangulation_time / self.files_processed if self.files_processed > 0 else 0.0 @property def average_import_time(self) -> float: """Calculate average import time per file""" return self.import_time / self.files_imported if self.files_imported > 0 else 0.0 def print_summary(self) -> None: """Print simplified benchmark results summary""" actual_triangulation = self.triangulation_enabled and self.maya_available success_rate = (self.files_imported / self.original_files_found * 100) if self.original_files_found > 0 else 0 print("\n" + "=" * 50) print(" FBX IMPORT BENCHMARK RESULTS") print("=" * 50) # Core results print(f"📊 Files: {self.files_imported}/{self.original_files_found} imported ({success_rate:.1f}%)") print(f"⚡ Import Time: {self.import_time:.3f}s ({self.average_import_time:.3f}s/file)") # Processing details if actual_triangulation: print(f"🔧 Triangulation: {self.triangulation_time:.3f}s ({self.average_triangulation_time:.3f}s/file)") print(f"📈 Total Time: {self.total_time:.3f}s") elif self.triangulation_enabled and not self.maya_available: print(f"📁 File Copy: {self.triangulation_time:.3f}s (Maya unavailable)") print(f"🚀 Throughput: {(self.files_imported / self.import_time):.2f} files/second") print("=" * 50) # Also log to Unreal for console visibility Logger.log( f"🎯 [Benchmark] Import: {self.import_time:.3f}s | Files: {self.files_imported} | Rate: {self.average_import_time:.3f}s/file" ) class FBXBenchmarkRunner: """Main benchmark runner orchestrating the entire process""" def __init__(self, config: BenchmarkConfig): self.config = config self.maya_checker = MayaChecker(config) self.triangulator = MayaTriangulator(config, self.maya_checker) self.file_processor = FileProcessor(config, self.triangulator) def run(self) -> BenchmarkResults: """Execute the complete benchmark process""" Logger.log("🚀 [FBXBenchmark] Starting FBX Skeletal Mesh Import Benchmark...") Logger.log("📊 [FBXBenchmark] This benchmark measures PURE IMPORT performance (triangulation is separate)") Logger.log(f"🔍 [FBXBenchmark] Maya triangulation script: {self.config.maya_triangulate_script}") self._log_initial_status() # Validate source folder source_folder = Path(self.config.fbx_source_folder) if not source_folder.is_dir(): Logger.log(f"Source folder not found: {source_folder}", LogLevel.ERROR) Logger.log("Please update the fbx_source_folder in the configuration.", LogLevel.ERROR) return self._create_failed_results() # Find FBX files fbx_files = self.file_processor.find_fbx_files(source_folder) if not fbx_files: Logger.log(f"No .fbx files found in {source_folder}", LogLevel.WARNING) return self._create_failed_results() Logger.log(f"Found {len(fbx_files)} FBX files to process") # Process files (triangulation phase) processed_files, triangulation_time = self.file_processor.process_fbx_files(source_folder, fbx_files) if not processed_files: Logger.log("No files were successfully processed", LogLevel.ERROR) return self._create_failed_results() # Import into Unreal (pure import benchmark) Logger.log("🚀 Starting pure import benchmark phase...") import_results = self._import_to_unreal(processed_files) # Cleanup self.file_processor.cleanup_working_directory() # Create and return results results = BenchmarkResults( triangulation_enabled=self.config.triangulate_mesh, maya_available=self.maya_checker.is_available, original_files_found=len(fbx_files), files_processed=len(processed_files), files_imported=import_results["imported_count"], triangulation_time=triangulation_time, import_time=import_results["import_time"], ) results.print_summary() return results def _log_initial_status(self) -> None: """Log initial status of Maya and triangulation""" Logger.log(f"🔍 [FBXBenchmark] Configuration check - Triangulation enabled: {self.config.triangulate_mesh}") Logger.log("🔍 [FBXBenchmark] Maya availability check starting...") if self.config.triangulate_mesh and self.maya_checker.is_available: Logger.log( "⚙️ [FBXBenchmark] Triangulation: ENABLED - Maya available (files will be triangulated before import)" ) elif self.config.triangulate_mesh and not self.maya_checker.is_available: Logger.log( "⚠️ [FBXBenchmark] Triangulation: ENABLED but Maya unavailable - files will be copied without triangulation" ) else: Logger.log("⚙️ [FBXBenchmark] Triangulation: DISABLED - files will be copied as-is") Logger.log("⏱️ [FBXBenchmark] Import timing will measure ONLY the Unreal import phase for accurate benchmarking") def _create_failed_results(self) -> BenchmarkResults: """Create results object for failed benchmark""" return BenchmarkResults( triangulation_enabled=self.config.triangulate_mesh, maya_available=self.maya_checker.is_available, original_files_found=0, files_processed=0, files_imported=0, triangulation_time=0.0, import_time=0.0, ) def _import_to_unreal(self, processed_files: List[Path]) -> dict: """Import processed files into Unreal Engine - measures pure import time only""" asset_tools = unreal.AssetToolsHelpers.get_asset_tools() import_options = UnrealImportOptions.create_skeletal_mesh_options() # Create import tasks all_tasks = [] for processed_file in processed_files: processed_file_path = processed_file.as_posix() task = UnrealImportOptions.create_import_task( processed_file_path, self.config.import_destination, import_options ) all_tasks.append(task) Logger.log(f"⚡ Executing pure import benchmark for {len(all_tasks)} files...") # Execute import - THIS IS THE PURE IMPORT BENCHMARK start_time = time.time() asset_tools.import_asset_tasks(all_tasks) end_time = time.time() import_time = end_time - start_time # Count successful imports imported_count = 0 for task in all_tasks: if task.get_editor_property("imported_object_paths"): imported_count += 1 filename = Path(task.get_editor_property("filename")).name Logger.log(f"✅ Successfully imported: {filename}") else: filename = Path(task.get_editor_property("filename")).name Logger.log(f"❌ Failed to import: {filename}", LogLevel.ERROR) Logger.log(f"🎯 Pure import benchmark complete: {imported_count}/{len(all_tasks)} files in {import_time:.4f}s") return {"imported_count": imported_count, "import_time": import_time} def main() -> None: """Main function to execute the benchmark""" # Create configuration - modify these values as needed config = BenchmarkConfig() # Initialize and run benchmark runner = FBXBenchmarkRunner(config) results = runner.run() # Results are automatically printed in the run method return results # Execute the main function if __name__ == "__main__": main() else: # For direct execution in Unreal Python console 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()
# Copyright Epic Games, Inc. All Rights Reserved # Third party import unreal # Internal from .base_menu_action import BaseActionMenuEntry class DeadlineToolBarMenu(object): """ Class for Deadline Unreal Toolbar menu """ TOOLBAR_NAME = "Deadline" TOOLBAR_OWNER = "deadline.toolbar.menu" PARENT_MENU = "LevelEditor.MainMenu" SECTION_NAME = "deadline_section" def __init__(self): """Constructor""" # Keep reference to tool menus from Unreal self._tool_menus = None # Keep track of all the action menus that have been registered to # Unreal. Without keeping these around, the Unreal GC will remove the # menu objects and break the in-engine menu self.menu_entries = [] self._top_level_menu = f"{self.PARENT_MENU}.{self.TOOLBAR_NAME}" self._initialize_toolbar() # Set up a shutdown callback for when python is existing to cleanly # clear the menus unreal.register_python_shutdown_callback(self._shutdown) @property def _unreal_tools_menu(self): """Get Unreal Editor Tool menu""" if not self._tool_menus or self._tool_menus is None: self._tool_menus = unreal.ToolMenus.get() return self._tool_menus def _initialize_toolbar(self): """Initialize our custom toolbar with the Editor""" tools_menu = self._unreal_tools_menu # Create the custom menu and add it to Unreal Main Menu main_menu = tools_menu.extend_menu(self.PARENT_MENU) # Create the submenu object main_menu.add_sub_menu( self.TOOLBAR_OWNER, "", self.TOOLBAR_NAME, self.TOOLBAR_NAME ) # Register the custom deadline menu to the Editor Main Menu tools_menu.register_menu( self._top_level_menu, "", unreal.MultiBoxType.MENU, False ) def _shutdown(self): """Method to call when the editor is shutting down""" # Unregister all menus owned by the integration self._tool_menus.unregister_owner_by_name(self.TOOLBAR_OWNER) # Clean up all the menu instances we are tracking del self.menu_entries[:] def register_submenu( self, menu_name, callable_method, label_name=None, description=None ): """ Register a menu to the toolbar. Note: This currently creates a flat submenu in the Main Menu :param str menu_name: The name of the submenu :param object callable_method: A callable method to execute on menu activation :param str label_name: Nice Label name to display the menu :param str description: Description of the menu. This will eb displayed in the tooltip """ # Get an instance of a custom `unreal.ToolMenuEntryScript` class # Wrap it in a try except block for instances where # the unreal module has not loaded yet. try: entry = BaseActionMenuEntry( callable_method, parent=self ) menu_entry_name = menu_name.replace(" ", "") entry.init_entry( self.TOOLBAR_OWNER, f"{self._top_level_menu}.{menu_entry_name}", menu_entry_name, label_name or menu_name, tool_tip=description or "" ) # Add the entry to our tracked list self.menu_entries.append(entry) # Get the registered top level menu menu = self._tool_menus.find_menu(self._top_level_menu) # Add the entry object to the menu menu.add_menu_entry_object(entry) except Exception as err: raise RuntimeError( "Its possible unreal hasn't loaded yet. Here's the " "error that occurred: {err}".format(err=err) )
import unreal actorLocation = unreal.Vector(0, 0, 0) pointLight = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.PointLight, actorLocation) pointLight.set_actor_label("key_light")
# -*- coding: utf-8 -*- import time import unreal from Utilities.Utils import Singleton import random import os class ChameleonSketch(metaclass=Singleton): def __init__(self, jsonPath): self.jsonPath = jsonPath self.data = unreal.PythonBPLib.get_chameleon_data(self.jsonPath) self.ui_names = ["SMultiLineEditableTextBox", "SMultiLineEditableTextBox_2"] self.debug_index = 1 self.ui_python_not_ready = "IsPythonReadyImg" self.ui_python_is_ready = "IsPythonReadyImgB" self.ui_is_python_ready_text = "IsPythonReadyText" print ("ChameleonSketch.Init") def mark_python_ready(self): print("set_python_ready call") self.data.set_visibility(self.ui_python_not_ready, "Collapsed") self.data.set_visibility(self.ui_python_is_ready, "Visible") self.data.set_text(self.ui_is_python_ready_text, "Python Path Ready.") def get_texts(self): for name in self.ui_names: n = self.data.get_text(name) print(f"name: {n}") def set_texts(self): for name in self.ui_names: self.data.set_text(name, ["AAA", "BBB", "CCC", "DDD", "EEE", "FFF"][random.randint(0, 5)]) def set_text_one(self): self.data.set_text(self.ui_names[self.debug_index], ["AAA", "BBB", "CCC", "DDD", "EEE", "FFF"][random.randint(0, 5)] ) def get_text_one(self): print(f"name: {self.data.get_text(self.ui_names[self.debug_index])}") def tree(self): print(time.time()) names = [] parent_indices = [] name_to_index = dict() for root, folders, files in os.walk(r"/project/"): root_name = os.path.basename(root) if root not in name_to_index: name_to_index[root] = len(names) parent_indices.append(-1 if not names else name_to_index[os.path.dirname(root)]) names.append(root_name) parent_id = name_to_index[root] for items in [folders, files]: for item in items: names.append(item) parent_indices.append(parent_id) print(len(names)) self.data.set_tree_view_items("TreeViewA", names, parent_indices) print(time.time())
from typing import Dict, Any import unreal import json def get_world_outliner() -> Dict[str, Any]: world = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem).get_editor_world() if not world: return {"error": "No world loaded"} # Get all actors in the current level all_actors = unreal.get_editor_subsystem( unreal.EditorActorSubsystem ).get_all_level_actors() outliner_data = { "world_name": world.get_name(), "total_actors": len(all_actors), "actors": [], } for actor in all_actors: try: actor_info = { "name": actor.get_name(), "class": actor.get_class().get_name(), "location": { "x": actor.get_actor_location().x, "y": actor.get_actor_location().y, "z": actor.get_actor_location().z, }, "rotation": { "pitch": actor.get_actor_rotation().pitch, "yaw": actor.get_actor_rotation().yaw, "roll": actor.get_actor_rotation().roll, }, "scale": { "x": actor.get_actor_scale3d().x, "y": actor.get_actor_scale3d().y, "z": actor.get_actor_scale3d().z, }, "is_hidden": actor.is_hidden_ed(), "folder_path": str(actor.get_folder_path()) if hasattr(actor, "get_folder_path") else None, } components = actor.get_components_by_class(unreal.ActorComponent) if components: actor_info["components"] = [ comp.get_class().get_name() for comp in components[:5] ] outliner_data["actors"].append(actor_info) except Exception as e: continue outliner_data["actors"].sort(key=lambda x: x["name"]) return outliner_data def main(): outliner_data = get_world_outliner() print(json.dumps(outliner_data, indent=2)) if __name__ == "__main__": main()
# This script describes a generic use case for the variant manager import unreal # Create all assets and objects we'll use lvs = unreal.VariantManagerLibrary.create_level_variant_sets_asset("LVS", "/Game/") lvs_actor = unreal.VariantManagerLibrary.create_level_variant_sets_actor(lvs) if lvs is None or lvs_actor is None: print "Failed to spawn either the LevelVariantSets asset or the LevelVariantSetsActor!" quit() var_set1 = unreal.VariantSet() var_set1.set_display_text("My VariantSet") var_set2 = unreal.VariantSet() var_set2.set_display_text("VariantSet we'll delete") var1 = unreal.Variant() var1.set_display_text("Variant 1") var2 = unreal.Variant() var2.set_display_text("Variant 2") var3 = unreal.Variant() var3.set_display_text("Variant 3") var4 = unreal.Variant() var4.set_display_text("Variant 4") var5 = unreal.Variant() var5.set_display_text("Variant 5") # Adds the objects to the correct parents lvs.add_variant_set(var_set1) var_set1.add_variant(var1) var_set1.add_variant(var2) var_set1.add_variant(var3) var_set1.add_variant(var4) var_set1.add_variant(var5) # Spawn a simple cube static mesh actor cube = unreal.EditorAssetLibrary.load_asset("StaticMesh'/project/.Cube'") spawned_actor = None if cube: location = unreal.Vector() rotation = unreal.Rotator() spawned_actor = unreal.EditorLevelLibrary.spawn_actor_from_object(cube, location, rotation) spawned_actor.set_actor_label("Cube Actor") else: print "Failed to find Cube asset!" if spawned_actor is None: print "Failed to spawn an actor for the Cube asset!" quit() # Bind spawned_actor to all our variants var1.add_actor_binding(spawned_actor) var2.add_actor_binding(spawned_actor) var3.add_actor_binding(spawned_actor) var4.add_actor_binding(spawned_actor) var5.add_actor_binding(spawned_actor) capturable_props = unreal.VariantManagerLibrary.get_capturable_properties(spawned_actor) print "Capturable properties for actor '" + spawned_actor.get_actor_label() + "':" for prop in capturable_props: print "\t" + prop # Capture all available properties on Variant 1 for prop in capturable_props: var1.capture_property(spawned_actor, prop) # Capture just materials on Variant 2 just_mat_props = (p for p in capturable_props if "Material[" in p) for prop in just_mat_props: var2.capture_property(spawned_actor, prop) # Capture just relative location on Variant 4 just_rel_loc = (p for p in capturable_props if "Relative Location" in p) rel_loc_props = [] for prop in just_rel_loc: captured_prop = var4.capture_property(spawned_actor, prop) rel_loc_props.append(captured_prop) # Store a property value on Variant 4 rel_loc_prop = rel_loc_props[0] print rel_loc_prop.get_full_display_string() spawned_actor.set_actor_relative_location(unreal.Vector(100, 200, 300), False, False) rel_loc_prop.record() # Move the target actor to some other position spawned_actor.set_actor_relative_location(unreal.Vector(500, 500, 500), False, False) # Can switch on the variant, applying the recorded value of all its properties to all # of its bound actors var4.switch_on() # Cube will be at 100, 200, 300 after this # Apply the recorded value from just a single property rel_loc_prop.apply() # Get the relative rotation property rel_rot = [p for p in capturable_props if "Relative Rotation" in p][0] # Remove objects lvs.remove_variant_set(var_set2) lvs.remove_variant_set(var_set2) var_set1.remove_variant(var3) var5.remove_actor_binding(spawned_actor) var1.remove_captured_property_by_name(spawned_actor, rel_rot)
# 未完成:将模型的材质贴图所有的颜色信息写入到顶点颜色中 import unreal selected_assets = unreal.EditorUtilityLibrary().get_selected_assets() if selected_assets: static_mesh = selected_assets[0] static_materials = static_mesh.static_materials # Array of MaterialInterface material_number = len(static_materials) unreal.log(material_number) material_array = [] base_color_array = [] for i in range(material_number): # TODO:Material Instance Constant # TODO:Material Instance Dynamic有啥区别?同时看一下L_unreal.py中关于材质的内容 material_array.append(static_materials[i].material_interface.get_name()) base_color_array.append(unreal.MaterialEditingLibrary.get_material_instance_vector_parameter_value(static_materials[i].material_interface, 'BaseColor')) unreal.log(base_color_array) # if len(static_materials) == 2: # # 获取两个材质的Base Color颜色 # material_1 = static_materials[0] # material_2 = static_materials[1] # # 获取材质实例并提取Base Color颜色 # base_color_1 = unreal.MaterialEditingLibrary.get_material_instance_property(material_1, 'BaseColor') # base_color_2 = unreal.MaterialEditingLibrary.get_material_instance_property(material_2, 'BaseColor') # # 获取StaticMesh的顶点数据 # mesh = static_mesh.get_mesh() # # 设置顶点颜色 # vertices = mesh.get_vertices() # # 假设顶点可以根据材质插槽进行分组(你可能需要根据UV或材质插槽的实际情况来分配) # num_vertices = len(vertices) # mid_point = num_vertices // 2 # 将顶点分成两半,前一半是材质1,后一半是材质2 # # 对前半部分顶点应用第一个材质颜色 # for i in range(mid_point): # vertices[i].set_color(base_color_1) # # 对后半部分顶点应用第二个材质颜色 # for i in range(mid_point, num_vertices): # vertices[i].set_color(base_color_2) # # 保存修改 # static_mesh.save() # else: # unreal.SystemLibrary.print_string(None, "该静态网格没有两个材质插槽。")
import unreal file_a = "/project/.fbx" file_b = "/project/.fbx" imported_scenes_path = "/project/" print 'Preparing import options...' advanced_mesh_options = unreal.DatasmithStaticMeshImportOptions() advanced_mesh_options.set_editor_property('max_lightmap_resolution', unreal.DatasmithImportLightmapMax.LIGHTMAP_512) advanced_mesh_options.set_editor_property('min_lightmap_resolution', unreal.DatasmithImportLightmapMin.LIGHTMAP_64) advanced_mesh_options.set_editor_property('generate_lightmap_u_vs', True) advanced_mesh_options.set_editor_property('remove_degenerates', True) base_options = unreal.DatasmithImportBaseOptions() base_options.set_editor_property('include_geometry', True) base_options.set_editor_property('include_material', True) base_options.set_editor_property('include_light', True) base_options.set_editor_property('include_camera', True) base_options.set_editor_property('include_animation', True) base_options.set_editor_property('static_mesh_options', advanced_mesh_options) base_options.set_editor_property('scene_handling', unreal.DatasmithImportScene.CURRENT_LEVEL) base_options.set_editor_property('asset_options', []) # Not used vred_options = unreal.DatasmithVREDImportOptions() vred_options.set_editor_property('merge_nodes', False) vred_options.set_editor_property('optimize_duplicated_nodes', False) vred_options.set_editor_property('import_var', True) vred_options.set_editor_property('var_path', "") vred_options.set_editor_property('import_light_info', True) vred_options.set_editor_property('light_info_path', "") vred_options.set_editor_property('import_clip_info', True) vred_options.set_editor_property('clip_info_path', "") vred_options.set_editor_property('textures_dir', "") vred_options.set_editor_property('import_animations', True) vred_options.set_editor_property('intermediate_serialization', unreal.DatasmithVREDIntermediateSerializationType.DISABLED) vred_options.set_editor_property('colorize_materials', False) vred_options.set_editor_property('generate_lightmap_u_vs', False) vred_options.set_editor_property('import_animations', True) # Direct import to scene and assets: print 'Importing directly to scene...' unreal.VREDLibrary.import_(file_a, imported_scenes_path, base_options, None, True) #2-stage import step 1: print 'Parsing to scene object...' scene = unreal.DatasmithVREDSceneElement.construct_datasmith_scene_from_file(file_b, imported_scenes_path, base_options, vred_options) print 'Resulting datasmith scene: ' + str(scene) print '\tProduct name: ' + str(scene.get_product_name()) print '\tMesh actor count: ' + str(len(scene.get_all_mesh_actors())) print '\tLight actor count: ' + str(len(scene.get_all_light_actors())) print '\tCamera actor count: ' + str(len(scene.get_all_camera_actors())) print '\tCustom actor count: ' + str(len(scene.get_all_custom_actors())) print '\tMaterial count: ' + str(len(scene.get_all_materials())) print '\tAnimNode count: ' + str(len(scene.get_all_anim_nodes())) print '\tAnimClip count: ' + str(len(scene.get_all_anim_clips())) print '\tExtra light info count: ' + str(len(scene.get_all_extra_lights_info())) print '\tVariant count: ' + str(len(scene.get_all_variants())) # Modify one of the AnimNodes # Warning: The AnimNode nested structure is all USTRUCTs, which are value types, and the Array accessor returns # a copy. Meaning something like anim_nodes[0].name = 'new_name' will set the name on the COPY of anim_nodes[0] anim_nodes = scene.get_all_anim_nodes() if len(anim_nodes) > 0: node_0 = anim_nodes[0] old_name = node_0.name print 'Anim node old name: ' + old_name node_0.name += '_MODIFIED' modified_name = node_0.name print 'Anim node modified name: ' + modified_name anim_nodes[0] = node_0 scene.set_all_anim_nodes(anim_nodes) # Check modification new_anim_nodes = scene.get_all_anim_nodes() print 'Anim node retrieved modified name: ' + new_anim_nodes[0].name assert new_anim_nodes[0].name == modified_name, "Node modification didn't work!" # Restore to previous state node_0 = new_anim_nodes[0] node_0.name = old_name new_anim_nodes[0] = node_0 scene.set_all_anim_nodes(new_anim_nodes) # 2-stage import step 2: print 'Importing assets and actors...' result = scene.import_scene() print 'Import results: ' print '\tImported actor count: ' + str(len(result.imported_actors)) print '\tImported mesh count: ' + str(len(result.imported_meshes)) print '\tImported level sequences: ' + str([a.get_name() for a in result.animations]) print '\tImported level variant sets asset: ' + str(result.level_variant_sets.get_name()) if result.import_succeed: print 'Import succeeded!' else: print 'Import failed!'
# -*- coding: utf-8 -*- """ 打开 metahuman 项目执行脚本 需要启用 Sequencer Scripting 插件 """ # Import future modules from __future__ import absolute_import from __future__ import division from __future__ import print_function __author__ = "timmyliang" __email__ = "[email protected]" __date__ = "2022-06-24 18:07:09" # Import built-in modules from collections import defaultdict import json import os import math # Import local modules import unreal DIR = os.path.dirname(os.path.abspath(__file__)) DATA_PATH = r"/project/.json" def unreal_progress(tasks, label="进度", total=None): total = total if total else len(tasks) with unreal.ScopedSlowTask(total, label) as task: task.make_dialog(True) for i, item in enumerate(tasks): if task.should_cancel(): break task.enter_progress_frame(1, "%s %s/%s" % (label, i, total)) yield item def main(): # NOTE: 读取 sequence sequence = unreal.load_asset( "/project/.NewLevelSequence" ) # NOTE: 收集 sequence 里面所有的 binding binding_dict = defaultdict(list) for binding in sequence.get_bindings(): binding_dict[binding.get_name()].append(binding) with open(DATA_PATH, "r") as rf: key_data = json.load(rf) # NOTE: 遍历命名为 Face 的 binding for binding in unreal_progress(binding_dict.get("ABP_headmesh", []), "导入 Face 数据"): # NOTE: 获取关键帧 channel 数据 keys_dict = {} for track in binding.get_tracks(): for section in track.get_sections(): for channel in unreal_progress(section.get_channels(), "导入关键帧"): channel_name = channel.get_name() if not channel_name.startswith("CTRL_"): continue channel_name = channel_name.rsplit("_", 1)[0] key_list = key_data.get(channel_name) if not key_list: continue for frame_data in key_list: frame = frame_data.get("frame") value = frame_data.get("value") sub_frame, frame = math.modf(frame_data.get("frame")) channel.add_key(unreal.FrameNumber(frame), value, sub_frame) if __name__ == "__main__": main()
# SPDX-FileCopyrightText: 2018-2025 Xavier Loux (BleuRaven) # # SPDX-License-Identifier: GPL-3.0-or-later # ---------------------------------------------- # Blender For UnrealEngine # https://github.com/project/-For-UnrealEngine-Addons # ---------------------------------------------- from typing import TYPE_CHECKING, Dict, Any import unreal from . import import_module_unreal_utils # Since 5.1 MovieSceneBindingProxy replace SequencerBindingProxy. use_movie_scene = import_module_unreal_utils.get_unreal_version() > (5,1,0) sequencer_scripting_active = import_module_unreal_utils.sequencer_scripting_active() if sequencer_scripting_active: def get_sequencer_framerate(denominator = 1, numerator = 24) -> unreal.FrameRate: """ Adjusts the given frame rate to be compatible with Unreal Engine Sequencer. Ensures the denominator and numerator are integers over zero and warns if the input values are adjusted. Parameters: - denominator (float): The original denominator value. - numerator (float): The original numerator value. Returns: - unreal.FrameRate: The adjusted frame rate object. """ # Ensure denominator and numerator are at least 1 and int 32 new_denominator = max(round(denominator), 1) new_numerator = max(round(numerator), 1) myFFrameRate = unreal.FrameRate(numerator=new_numerator, denominator=new_denominator) if denominator != new_denominator or numerator != new_numerator: message = ('WARNING: Frame rate denominator and numerator must be an int32 over zero.\n' 'Float denominator and numerator is not supported in Unreal Engine Sequencer.\n\n' f'- Before: Denominator: {denominator}, Numerator: {numerator}\n' f'- After: Denominator: {new_denominator}, Numerator: {new_numerator}') import_module_unreal_utils.show_warning_message("Frame Rate Adjustment Warning", message) return myFFrameRate def get_section_all_channel(section: unreal.MovieSceneSection): if import_module_unreal_utils.get_unreal_version() >= (5,0,0): return section.get_all_channels() else: return section.get_channels() def AddSequencerSectionTransformKeysByIniFile(section: unreal.MovieSceneSection, track_dict: Dict[str, Any]): for key in track_dict.keys(): value = track_dict[key] # (x,y,z x,y,z x,y,z) frame = unreal.FrameNumber(int(key)) get_section_all_channel(section)[0].add_key(frame, value["location_x"]) get_section_all_channel(section)[1].add_key(frame, value["location_y"]) get_section_all_channel(section)[2].add_key(frame, value["location_z"]) get_section_all_channel(section)[3].add_key(frame, value["rotation_x"]) get_section_all_channel(section)[4].add_key(frame, value["rotation_y"]) get_section_all_channel(section)[5].add_key(frame, value["rotation_z"]) get_section_all_channel(section)[6].add_key(frame, value["scale_x"]) get_section_all_channel(section)[7].add_key(frame, value["scale_y"]) get_section_all_channel(section)[8].add_key(frame, value["scale_z"]) def AddSequencerSectionDoubleVectorKeysByIniFile(section, track_dict: Dict[str, Any]): for key in track_dict.keys(): value = track_dict[key] # (x,y,z x,y,z x,y,z) frame = unreal.FrameNumber(int(key)) get_section_all_channel(section)[0].add_key(frame, value["x"]) get_section_all_channel(section)[1].add_key(frame, value["y"]) def AddSequencerSectionFloatKeysByIniFile(section, track_dict: Dict[str, Any]): for key in track_dict.keys(): frame = unreal.FrameNumber(int(key)) value = track_dict[key] get_section_all_channel(section)[0].add_key(frame, value) def AddSequencerSectionBoolKeysByIniFile(section, track_dict: Dict[str, Any]): for key in track_dict.keys(): frame = unreal.FrameNumber(int(key)) value = track_dict[key] get_section_all_channel(section)[0].add_key(frame, value) def create_new_sequence() -> unreal.LevelSequence: factory = unreal.LevelSequenceFactoryNew() asset_tools = unreal.AssetToolsHelpers.get_asset_tools() seq = asset_tools.create_asset_with_dialog('MySequence', '/Game', None, factory) if seq is None: return 'ERROR: level sequencer factory_create fail' return seq def Sequencer_add_new_camera(seq: unreal.LevelSequence, camera_target_class = unreal.CineCameraActor, camera_name = "MyCamera", is_spawnable_camera = False): #Create bindings if is_spawnable_camera: ''' I preffer create an level camera an convert to spawnable than use seq.add_spawnable_from_class() Because with seq.add_spawnable_from_class() it not possible to change actor name an add create camera_component_binding. Need more control in the API. ''' # Create camera temp_camera_actor = unreal.EditorLevelLibrary().spawn_actor_from_class(camera_target_class, unreal.Vector(0, 0, 0), unreal.Rotator(0, 0, 0), transient=True) temp_camera_actor.set_actor_label(camera_name) # Add camera to sequencer temp_camera_binding = seq.add_possessable(temp_camera_actor) if isinstance(temp_camera_actor, unreal.CineCameraActor): camera_component_binding = seq.add_possessable(temp_camera_actor.get_cine_camera_component()) elif isinstance(temp_camera_actor, unreal.CameraActor): camera_component_binding = seq.add_possessable(temp_camera_actor.camera_component) else: camera_component_binding = seq.add_possessable(temp_camera_actor.get_component_by_class(unreal.CameraComponent)) # Convert to spawnable camera_binding = seq.add_spawnable_from_instance(temp_camera_actor) camera_component_binding.set_parent(camera_binding) temp_camera_binding.remove() #Clean old camera temp_camera_actor.destroy_actor() else: # Create possessable camera camera_actor = unreal.EditorLevelLibrary().spawn_actor_from_class(camera_target_class, unreal.Vector(0, 0, 0), unreal.Rotator(0, 0, 0)) camera_actor.set_actor_label(camera_name) camera_binding = seq.add_possessable(camera_actor) camera_component_binding = seq.add_possessable(camera_actor.get_cine_camera_component()) if import_module_unreal_utils.get_unreal_version() >= (4,26,0): camera_binding.set_display_name(camera_name) else: pass return camera_binding, camera_component_binding def update_sequencer_camera_tracks(seq: unreal.LevelSequence, camera_binding, camera_component_binding, camera_tracks: Dict[str, Any]): if TYPE_CHECKING: if use_movie_scene: camera_binding: unreal.MovieSceneBindingProxy camera_component_binding: unreal.MovieSceneBindingProxy else: camera_binding: unreal.SequencerBindingProxy camera_component_binding: unreal.SequencerBindingProxy # Transform transform_track = camera_binding.add_track(unreal.MovieScene3DTransformTrack) transform_section = transform_track.add_section() transform_section.set_end_frame_bounded(False) transform_section.set_start_frame_bounded(False) AddSequencerSectionTransformKeysByIniFile(transform_section, camera_tracks['ue_camera_transform']) # Focal Length TrackFocalLength = camera_component_binding.add_track(unreal.MovieSceneFloatTrack) TrackFocalLength.set_property_name_and_path('Current Focal Length', 'CurrentFocalLength') sectionFocalLength = TrackFocalLength.add_section() sectionFocalLength.set_end_frame_bounded(False) sectionFocalLength.set_start_frame_bounded(False) AddSequencerSectionFloatKeysByIniFile(sectionFocalLength, camera_tracks['camera_focal_length']) # Sensor Width TrackSensorWidth = camera_component_binding.add_track(unreal.MovieSceneFloatTrack) TrackSensorWidth.set_property_name_and_path('Sensor Width (Filmback)', 'Filmback.SensorWidth') sectionSensorWidth = TrackSensorWidth.add_section() sectionSensorWidth.set_end_frame_bounded(False) sectionSensorWidth.set_start_frame_bounded(False) AddSequencerSectionFloatKeysByIniFile(sectionSensorWidth, camera_tracks['ue_camera_sensor_width']) # Sensor Height TrackSensorHeight = camera_component_binding.add_track(unreal.MovieSceneFloatTrack) TrackSensorHeight.set_property_name_and_path('Sensor Height (Filmback)', 'Filmback.SensorHeight') sectionSensorHeight = TrackSensorHeight.add_section() sectionSensorHeight.set_end_frame_bounded(False) sectionSensorHeight.set_start_frame_bounded(False) AddSequencerSectionFloatKeysByIniFile(sectionSensorHeight, camera_tracks['ue_camera_sensor_height']) # Focus Distance TrackFocusDistance = camera_component_binding.add_track(unreal.MovieSceneFloatTrack) if import_module_unreal_utils.get_unreal_version() >= (4,24,0): TrackFocusDistance.set_property_name_and_path('Manual Focus Distance (Focus Settings)', 'FocusSettings.ManualFocusDistance') else: TrackFocusDistance.set_property_name_and_path('Current Focus Distance', 'ManualFocusDistance') sectionFocusDistance = TrackFocusDistance.add_section() sectionFocusDistance.set_end_frame_bounded(False) sectionFocusDistance.set_start_frame_bounded(False) AddSequencerSectionFloatKeysByIniFile(sectionFocusDistance, camera_tracks['camera_focus_distance']) # Current Aperture TracknAperture = camera_component_binding.add_track(unreal.MovieSceneFloatTrack) TracknAperture.set_property_name_and_path('Current Aperture', 'CurrentAperture') sectionAperture = TracknAperture.add_section() sectionAperture.set_end_frame_bounded(False) sectionAperture.set_start_frame_bounded(False) AddSequencerSectionFloatKeysByIniFile(sectionAperture, camera_tracks['camera_aperture']) if camera_tracks['camera_type'] == "ARCHVIS": # MovieSceneDoubleVectorTrack not supported in Unreal Engine 5.0 and older if import_module_unreal_utils.get_unreal_version() >= (5,0,0): # Camera Shift X/Y TrackArchVisShift = camera_component_binding.add_track(unreal.MovieSceneDoubleVectorTrack) TrackArchVisShift.set_property_name_and_path('Manual Correction (Shift)', 'ProjectionOffset') TrackArchVisShift.set_num_channels_used(2) SectionArchVisShift = TrackArchVisShift.add_section() SectionArchVisShift.set_end_frame_bounded(False) SectionArchVisShift.set_start_frame_bounded(False) AddSequencerSectionDoubleVectorKeysByIniFile(SectionArchVisShift, camera_tracks['archvis_camera_shift']) # Disable auto correct perspective TrackArchVisCorrectPersp = camera_component_binding.add_track(unreal.MovieSceneBoolTrack) TrackArchVisCorrectPersp.set_property_name_and_path('Correct Perspective (Auto)', 'bCorrectPerspective') SectionArchVisCorrectPersp = TrackArchVisCorrectPersp.add_section() start_frame = unreal.FrameNumber(int(camera_tracks['frame_start'])) get_section_all_channel(SectionArchVisCorrectPersp)[0].add_key(start_frame, False) # Spawned tracksSpawned = camera_binding.find_tracks_by_exact_type(unreal.MovieSceneSpawnTrack) if len(tracksSpawned) > 0: sectionSpawned = tracksSpawned[0].get_sections()[0] AddSequencerSectionBoolKeysByIniFile(sectionSpawned, camera_tracks['camera_spawned']) # @TODO Need found a way to set this values... #camera_component.set_editor_property('aspect_ratio', camera_tracks['desired_screen_ratio']) #Projection mode supported since UE 4.26. #camera_component.set_editor_property('projection_mode', camera_tracks['projection_mode']) #camera_component.set_editor_property('ortho_width', camera_tracks['ortho_scale']) #camera_component.lens_settings.set_editor_property('min_f_stop', camera_tracks['ue_lens_minfstop']) #camera_component.lens_settings.set_editor_property('max_f_stop', camera_tracks['ue_lens_maxfstop'])
# Copyright Epic Games, Inc. All Rights Reserved """ Thinkbox Deadline REST API service plugin used to submit and query jobs from a Deadline server """ # Built-in import json import logging import platform from getpass import getuser from threading import Thread, Event # Internal from deadline_job import DeadlineJob from deadline_http import DeadlineHttp from deadline_enums import DeadlineJobState, DeadlineJobStatus, HttpRequestType from deadline_utils import get_editor_deadline_globals from deadline_command import DeadlineCommand # Third-party import unreal logger = logging.getLogger("DeadlineService") logger.setLevel(logging.INFO) class _Singleton(type): """ Singleton metaclass for the Deadline service """ # ------------------------------------------------------------------------------------------------------------------ # Class Variables _instances = {} # ------------------------------------------------------------------------------------------------------------------ # Magic Methods def __call__(cls, *args, **kwargs): """ Determines the initialization behavior of this class """ if cls not in cls._instances: cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] # TODO: Make this a native Subsystem in the editor class DeadlineService(metaclass=_Singleton): """ Singleton class to handle Deadline submissions. We are using a singleton class as there is no need to have multiple instances of the service. This allows job queries and submissions to be tracked by a single entity and be a source of truth on the client about all jobs created in the current session. """ # ------------------------------------------------------------------------------------------------------------------ # Magic Methods def __init__(self, host=None, auto_start_job_updates=False, service_update_interval=1.0): """ Deadline service class for submitting jobs to deadline and querying data from deadline :param str host: Deadline host :param bool auto_start_job_updates: This flag auto starts processing jobs when the service is initialized tracked by the service :param float service_update_interval: Interval(seconds) for job update frequency. Default is 2.0 seconds """ # Track a dictionary of jobs registered with the service. This dictionary contains job object instance ID and a # reference to the job instance object and deadline job ID. # i.e {"instance_object_id": {"object": <job class instance>, "job_id": 0001 or None}} self._current_jobs = {} self._submitted_jobs = {} # Similar to the current jobs, this tracks all jobs submitted self._failed_jobs = set() self._completed_jobs = set() # This flag determines if the service should deregister a job when it fails on the server self.deregister_job_on_failure = True # Thread execution variables self._event_thread = None self._exit_auto_update = False self._update_thread_event = Event() self._service_update_interval = service_update_interval # A timer for executing job update functions on an interval self._event_timer_manager = self.get_event_manager() self._event_handler = None # Use DeadlineCommand by defaut self._use_deadline_command = self._get_use_deadline_cmd() # True # TODO: hardcoded for testing, change to project read setting # Get/Set service host self._host = host or self._get_deadline_host() # Get deadline https instance self._http_server = DeadlineHttp(self.host) if auto_start_job_updates: self.start_job_updates() # ------------------------------------------------------------------------------------------------------------------ # Public Properties @property def pools(self): """ Returns the current list of pools found on the server :return: List of pools on the server """ return self._get_pools() @property def groups(self): """ Returns the current list of groups found on the server :return: List of groups on the server """ return self._get_groups() @property def use_deadline_command(self): """ Returns the current value of the use deadline command flag :return: True if the service uses the deadline command, False otherwise """ return self._use_deadline_command @use_deadline_command.setter def use_deadline_command(self, value): """ Sets the use deadline command flag :param value: True if the service uses the deadline command, False otherwise """ self._use_deadline_command = value @property def host(self): """ Returns the server url used by the service :return: Service url """ return self._host @host.setter def host(self, value): """ Set the server host on the service :param value: host value """ self._host = value # When the host service is updated, get a new connection to that host self._http_server = DeadlineHttp(self._host) @property def current_jobs(self): """ Returns the global current jobs tracked by the service :return: List of Jobs tracked by the service """ return [value["object"] for value in self._current_jobs.values()] @property def failed_jobs(self): """ Returns the failed jobs tracked by the service :return: List of failed Jobs tracked by the service """ return self._failed_jobs @property def completed_jobs(self): """ Returns the completed jobs tracked by the service :return: List of completed Jobs tracked by the service """ return self._completed_jobs # ------------------------------------------------------------------------------------------------------------------ # Protected Methods def _get_pools(self): """ This method updates the set of pools tracked by the service """ if self._get_use_deadline_cmd(): # if self._use_deadline_command: return DeadlineCommand().get_pools() else: response = self.send_http_request( HttpRequestType.GET, "api/pools", headers={'Content-Type': 'application/json'} ) return json.loads(response.decode('utf-8')) def _get_groups(self): """ This method updates the set of groups tracked by the service """ if self._get_use_deadline_cmd(): # if self._use_deadline_command: return DeadlineCommand().get_groups() else: response = self.send_http_request( HttpRequestType.GET, "api/groups", headers={'Content-Type': 'application/json'} ) return json.loads(response.decode('utf-8')) def _register_job(self, job_object, deadline_job_id=None): """ This method registers the job object with the service :param DeadlineJob job_object: Deadline Job object :param str deadline_job_id: ID of job returned from the server """ # Set the job Id on the job. The service # should be allowed to set this protected property on the job object as this property should natively # not be allowed to be set externally job_object._job_id = deadline_job_id job_data = { str(id(job_object)): { "object": job_object, "job_id": deadline_job_id } } self._submitted_jobs.update(job_data) self._current_jobs.update(job_data) def _deregister_job(self, job_object): """ This method removes the current job object from the tracked jobs :param DeadlineJob job_object: Deadline job object """ if str(id(job_object)) in self._current_jobs: self._current_jobs.pop(str(id(job_object)), f"{job_object} could not be found") def _update_tracked_job_by_status(self, job_object, job_status, update_job=False): """ This method moves the job object from the tracked list based on the current job status :param DeadlineJob job_object: Deadline job object :param DeadlineJobStatus job_status: Deadline job status :param bool update_job: Flag to update the job object's status to the passed in job status """ # Convert the job status into the appropriate enum. This will raise an error if the status enum does not exist. # If a valid enum is passed into this function, the enum is return job_status = job_object.get_job_status_enum(job_status) # If the job has an unknown status, remove it from the currently tracked jobs by the service. Note we are not # de-registering failed jobs unless explicitly set, that's because a failed job can be re-queued and # completed on the next try. # So we do not want to preemptively remove this job from the tracked jobs by the service. if job_status is DeadlineJobStatus.UNKNOWN: self._deregister_job(job_object) self._failed_jobs.add(job_object) elif job_status is DeadlineJobStatus.COMPLETED: self._deregister_job(job_object) self._completed_jobs.add(job_object) elif job_status is DeadlineJobStatus.FAILED: if self.deregister_job_on_failure: self._deregister_job(job_object) self._failed_jobs.add(job_object) if update_job: job_object.job_status = job_status # ------------------------------------------------------------------------------------------------------------------ # Public Methods def send_http_request(self, request_type, api_url, payload=None, fields=None, headers=None, retries=0): """ This method is used to upload or receive data from the Deadline server. :param HttpRequestType request_type: HTTP request verb. i.e GET/project/ :param str api_url: URL relative path queries. Example: /jobs , /pools, /jobs?JobID=0000 :param payload: Data object to POST/PUT to Deadline server :param dict fields: Request fields. This is typically used in files and binary uploads :param dict headers: Header data for request :param int retries: The number of retries to attempt before failing request. Defaults to 0. :return: JSON object response from the server """ # Make sure we always have the most up-to-date host if not self.host or (self.host != self._get_deadline_host()): self.host = self._get_deadline_host() try: response = self._http_server.send_http_request( request_type, api_url, payload=payload, fields=fields, headers=headers, retries=retries ) except Exception as err: raise DeadlineServiceError(f"Communication with {self.host} failed with err: \n{err}") else: return response def submit_job(self, job_object): """ This method submits the tracked job to the Deadline server :param DeadlineJob job_object: Deadline Job object :returns: Deadline `JobID` if an id was returned from the server """ self._validate_job_object(job_object) logger.debug(f"Submitting {job_object} to {self.host}..") if str(id(job_object)) in self._current_jobs: logger.warning(f"{job_object} has already been added to the service") # Return the job ID of the submitted job return job_object.job_id job_id = None job_data = job_object.get_submission_data() # Set the job data to return the job ID on submission job_data.update(IdOnly="true") # Update the job data to include the user and machine submitting the job # Update the username if one is not supplied if "UserName" not in job_data["JobInfo"]: # NOTE: Make sure this matches the expected naming convention by the server else the user will get # permission errors on job submission # Todo: Make sure the username convention matches the username on the server job_data["JobInfo"].update(UserName=getuser()) job_data["JobInfo"].update(MachineName=platform.node()) self._validate_job_info(job_data["JobInfo"]) if self._get_use_deadline_cmd(): # if self._use_deadline_command: # Submit the job to the Deadline server using the Deadline command # Todo: Add support for the Deadline command job_id = DeadlineCommand().submit_job(job_data) else: # Submit the job to the Deadline server using the HTTP API try: response = self.send_http_request( HttpRequestType.POST, "api/jobs", payload=json.dumps(job_data).encode('utf-8'), headers={'Content-Type': 'application/json'} ) except DeadlineServiceError as exp: logger.error( f"An error occurred submitting {job_object} to Deadline host `{self.host}`.\n\t{str(exp)}" ) self._failed_jobs.add(job_object) else: try: response = json.loads(response.decode('utf-8')) # If an error occurs trying to decode the json data, most likely an error occurred server side thereby # returning a string instead of the data requested. # Raise the decoded error except Exception as err: raise DeadlineServiceError(f"An error occurred getting the server dat/project/{response.decode('utf-8')}") job_id = response.get('_id', None) if not job_id: logger.warning( f"No JobId was returned from the server for {job_object}. " f"The service will not be able to get job details for this job!" ) else: # Register the job with the service. self._register_job(job_object, job_id) logger.info(f"Submitted `{job_object.job_name}` to Deadline. JobID: {job_id}") return job_id def get_job_details(self, job_object): """ This method gets the job details for the Deadline job :param DeadlineJob job_object: Custom Deadline job object :return: Job details object returned from the server. Usually a Json object """ self._validate_job_object(job_object) if str(id(job_object)) not in self._current_jobs: logger.warning( f"{job_object} is currently not tracked by the service. The job has either not been submitted, " f"its already completed or there was a problem with the job!" ) elif not job_object.job_id: logger.error( f"There is no JobID for {job_object}!" ) else: try: job_details = self._http_server.get_job_details(job_object.job_id) except (Exception, RuntimeError): # If an error occurred, most likely the job does not exist on the server anymore. Mark the job as # unknown self._update_tracked_job_by_status(job_object, DeadlineJobStatus.UNKNOWN, update_job=True) else: # Sometimes Deadline returns a status with a parenthesis after the status indicating the number of tasks # executing. We only care about the status here so lets split the number of tasks out. self._update_tracked_job_by_status(job_object, job_details["Job"]["Status"].split()[0]) return job_details def send_job_command(self, job_object, command): """ Send a command to the Deadline server for the job :param DeadlineJob job_object: Deadline job object :param dict command: Command to send to the Deadline server :return: Returns the response from the server """ self._validate_job_object(job_object) if not job_object.job_id: raise RuntimeError("There is no Deadline job ID to send this command for.") try: response = self._http_server.send_job_command( job_object.job_id, command ) except Exception as exp: logger.error( f"An error occurred getting the command result for {job_object} from Deadline host {self.host}. " f"\n{exp}" ) return "Fail" else: if response != "Success": logger.error(f"An error occurred executing command for {job_object}. \nError: {response}") return "Fail" return response def change_job_state(self, job_object, state): """ This modifies a submitted job's state on the Deadline server. This can be used in job orchestration. For example a job can be submitted as suspended/pending and this command can be used to update the state of the job to active after submission. :param DeadlineJob job_object: Deadline job object :param DeadlineJobState state: State to set the job :return: Submission results """ self._validate_job_object(job_object) # Validate jobs state if not isinstance(state, DeadlineJobState): raise ValueError(f"`{state}` is not a valid state.") return self.send_job_command(job_object, {"Command": state.value}) def start_job_updates(self): """ This method starts an auto update on jobs in the service. The purpose of this system is to allow the service to automatically update the job details from the server. This allows you to submit a job from your implementation and periodically poll the changes on the job as the service will continuously update the job details. Note: This function must explicitly be called or the `auto_start_job_updates` flag must be passed to the service instance for this functionality to happen. """ # Prevent the event from being executed several times in succession if not self._event_handler: if not self._event_thread: # Create a thread for the job update function. This function takes the current list of jobs # tracked by the service. The Thread owns an instance of the http connection. This allows the thread # to have its own pool of http connections separate from the main service. A thread event is passed # into the thread which allows the process events from the timer to reactivate the function. The # purpose of this is to prevent unnecessary re-execution while jobs are being processed. # This also allows the main service to stop function execution within the thread and allow it to cleanly # exit. # HACK: For some odd reason, passing an instance of the service into the thread seems to work as # opposed to passing in explicit variables. I would prefer explicit variables as the thread does not # need to have access to the entire service object # Threading is used here as the editor runs python on the game thread. If a function call is # executed on an interval (as this part of the service is designed to do), this will halt the editor # every n interval to process the update event. A separate thread for processing events allows the # editor to continue functions without interfering with the editor # TODO: Figure out a way to have updated variables in the thread vs passing the whole service instance self._event_thread = Thread( target=self._update_all_jobs, args=(self,), name="deadline_service_auto_update_thread", daemon=True ) # Start the thread self._event_thread.start() else: # If the thread is stopped, restart it. if not self._event_thread.is_alive(): self._event_thread.start() def process_events(): """ Function ran by the tick event for monitoring function execution inside of the auto update thread. """ # Since the editor ticks at a high rate, this monitors the current state of the function execution in # the update thread. When a function is done executing, this resets the event on the function. logger.debug("Processing current jobs.") if self._update_thread_event.is_set(): logger.debug("Job processing complete, restarting..") # Send an event to tell the thread to start the job processing loop self._update_thread_event.clear() # Attach the thread executions to a timer event self._event_timer_manager.on_timer_interval_delegate.add_callable(process_events) # Start the timer on an interval self._event_handler = self._event_timer_manager.start_timer(self._service_update_interval) # Allow the thread to stop when a python shutdown is detected unreal.register_python_shutdown_callback(self.stop_job_updates) def stop_job_updates(self): """ This method stops the auto update thread. This method should be explicitly called to stop the service from continuously updating the current tracked jobs. """ if self._event_handler: # Remove the event handle to the tick event self.stop_function_timer(self._event_timer_manager, self._event_handler) self._event_handler = None if self._event_thread and self._event_thread.is_alive(): # Force stop the thread self._exit_auto_update = True # immediately stop the thread. Do not wait for jobs to complete. self._event_thread.join(1.0) # Usually if a thread is still alive after a timeout, then something went wrong if self._event_thread.is_alive(): logger.error("An error occurred closing the auto update Thread!") # Reset the event, thread and tick handler self._update_thread_event.set() self._event_thread = None def get_job_object_by_job_id(self, job_id): """ This method returns the job object tracked by the service based on the deadline job ID :param job_id: Deadline job ID :return: DeadlineJob object :rtype DeadlineJob """ job_object = None for job in self._submitted_jobs.values(): if job_id == job["job_id"]: job_object = job["object"] break return job_object # ------------------------------------------------------------------------------------------------------------------ # Static Methods @staticmethod def _validate_job_info(job_info): """ This method validates the job info dictionary to make sure the information provided meets a specific standard :param dict job_info: Deadline job info dictionary :raises ValueError """ # validate the job info plugin settings if "Plugin" not in job_info or (not job_info["Plugin"]): raise ValueError("No plugin was specified in the Job info dictionary") @staticmethod def _get_use_deadline_cmd(): """ Returns the deadline command flag settings from the unreal project settings :return: Deadline command settings unreal project """ try: # This will be set on the deadline editor project settings deadline_settings = unreal.get_default_object(unreal.DeadlineServiceEditorSettings) # Catch any other general exceptions except Exception as exc: unreal.log( f"Caught Exception while getting use deadline command flag. Error: {exc}" ) else: return deadline_settings.deadline_command @staticmethod def _get_deadline_host(): """ Returns the host settings from the unreal project settings :return: Deadline host settings unreal project """ try: # This will be set on the deadline editor project settings deadline_settings = unreal.get_default_object(unreal.DeadlineServiceEditorSettings) # Catch any other general exceptions except Exception as exc: unreal.log( f"Caught Exception while getting deadline host. Error: {exc}" ) else: return deadline_settings.deadline_host @staticmethod def _validate_job_object(job_object): """ This method ensures the object passed in is of type DeadlineJob :param DeadlineJob job_object: Python object :raises: RuntimeError if the job object is not of type DeadlineJob """ # Using type checking instead of isinstance to prevent cyclical imports if not isinstance(job_object, DeadlineJob): raise DeadlineServiceError(f"Job is not of type DeadlineJob. Found {type(job_object)}!") @staticmethod def _update_all_jobs(service): """ This method updates current running job properties in a thread. :param DeadlineService service: Deadline service instance """ # Get a Deadline http instance inside for this function. This function is expected to be executed in a thread. deadline_http = DeadlineHttp(service.host) while not service._exit_auto_update: while not service._update_thread_event.is_set(): # Execute the job update properties on the job object for job_object in service.current_jobs: logger.debug(f"Updating {job_object} job properties") # Get the job details for this job and update the job details on the job object. The service # should be allowed to set this protected property on the job object as this property should # natively not be allowed to be set externally try: if job_object.job_id: job_object.job_details = deadline_http.get_job_details(job_object.job_id) # If a job fails to get job details, log it, mark it unknown except Exception as err: logger.exception(f"An error occurred getting job details for {job_object}:\n\t{err}") service._update_tracked_job_by_status( job_object, DeadlineJobStatus.UNKNOWN, update_job=True ) # Iterate over the jobs and update the tracked jobs by the service for job in service.current_jobs: service._update_tracked_job_by_status(job, job.job_status) service._update_thread_event.set() @staticmethod def get_event_manager(): """ Returns an instance of an event timer manager """ return unreal.DeadlineServiceTimerManager() @staticmethod def start_function_timer(event_manager, function, interval_in_seconds=2.0): """ Start a timer on a function within an interval :param unreal.DeadlineServiceTimerManager event_manager: Unreal Deadline service timer manager :param object function: Function to execute :param float interval_in_seconds: Interval in seconds between function execution. Default is 2.0 seconds :return: Event timer handle """ if not isinstance(event_manager, unreal.DeadlineServiceTimerManager): raise TypeError( f"The event manager is not of type `unreal.DeadlineServiceTimerManager`. Got {type(event_manager)}" ) event_manager.on_timer_interval_delegate.add_callable(function) return event_manager.start_timer(interval_in_seconds) @staticmethod def stop_function_timer(event_manager, time_handle): """ Stops the timer event :param unreal.DeadlineServiceTimerManager event_manager: Service Event manager :param time_handle: Time handle returned from the event manager """ event_manager.stop_timer(time_handle) class DeadlineServiceError(Exception): """ General Exception class for the Deadline Service """ pass def get_global_deadline_service_instance(): """ This method returns an instance of the service from the interpreter globals. :return: """ # This behavior is a result of unreal classes not able to store python object # directly on the class due to limitations in the reflection system. # The expectation is that uclass's that may not be able to store the service # as a persistent attribute on a class can use the global service instance. # BEWARE!!!! # Due to the nature of the DeadlineService being a singleton, if you get the # current instance and change the host path for the service, the connection will # change for every other implementation that uses this service deadline_globals = get_editor_deadline_globals() if '__deadline_service_instance__' not in deadline_globals: deadline_globals["__deadline_service_instance__"] = DeadlineService() return deadline_globals["__deadline_service_instance__"]
# -*- coding: utf-8 -*- """ Hidden UI Window to parent to. """ # mca python imports import sys # PySide2 imports from PySide2.QtWidgets import QApplication # software specific imports import unreal # mca python imports from mca.common.pyqt import common_windows from mca.common import log logger = log.MCA_LOGGER class MATUnrealWindow(common_windows.MCAMainWindow): def __init__(self, title='UE_Window', ui_path=None, version='1.0.0', style=None, parent=None): super().__init__(title=title, ui_path=ui_path, version=version, style=style, parent=parent) app = None if not QApplication.instance(): app = QApplication(sys.argv) try: unreal.parent_external_window_to_slate(int(self.winId())) sys.exit(app.exec_()) except Exception as e: print(e) class MATUnrealTestWindow(common_windows.MCAMainWindow): def __init__(self, title='UE_TestWindow', ui_path=None, version='1.0.0', style=None, parent=None): super().__init__(title=title, ui_path=ui_path, version=version, style=style, parent=parent) app = None if not QApplication.instance(): app = QApplication(sys.argv) try: window = self unreal.parent_external_window_to_slate(int(window.winId())) sys.exit(app.exec_()) except Exception as e: print(e)
# Copyright (c) <2021> Side Effects Software Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. The name of Side Effects Software may not be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN # NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ An example script that instantiates an HDA that contains a TOP network. After the HDA itself has cooked (in on_post_process) we iterate over all TOP networks in the HDA and print their paths. Auto-bake is then enabled for PDG and the TOP networks are cooked. """ import os import unreal _g_wrapper = None def get_test_hda_path(): return '/project/.pdg_pighead_grid_2_0' def get_test_hda(): return unreal.load_object(None, get_test_hda_path()) def get_hda_directory(): """ Attempt to get the directory containing the .hda files. This is /project/. In newer versions of UE we can use ``unreal.SystemLibrary.get_system_path(asset)``, in older versions we manually construct the path to the plugin. Returns: (str): the path to the example hda directory or ``None``. """ if hasattr(unreal.SystemLibrary, 'get_system_path'): return os.path.dirname(os.path.normpath( unreal.SystemLibrary.get_system_path(get_test_hda()))) else: plugin_dir = os.path.join( os.path.normpath(unreal.Paths.project_plugins_dir()), 'Runtime', 'HoudiniEngine', 'Content', 'Examples', 'hda' ) if not os.path.exists(plugin_dir): plugin_dir = os.path.join( os.path.normpath(unreal.Paths.engine_plugins_dir()), 'Runtime', 'HoudiniEngine', 'Content', 'Examples', 'hda' ) if not os.path.exists(plugin_dir): return None return plugin_dir def delete_instantiated_asset(): global _g_wrapper if _g_wrapper: result = _g_wrapper.delete_instantiated_asset() _g_wrapper = None return result else: return False def on_pre_instantiation(in_wrapper): print('on_pre_instantiation') # Set the hda_directory parameter to the directory that contains the # example .hda files hda_directory = get_hda_directory() print('Setting "hda_directory" to {0}'.format(hda_directory)) in_wrapper.set_string_parameter_value('hda_directory', hda_directory) # Cook the HDA (not PDG yet) in_wrapper.recook() def on_post_bake(in_wrapper, success): # in_wrapper.on_post_bake_delegate.remove_callable(on_post_bake) print('bake complete ... {}'.format('success' if success else 'failed')) def on_post_process(in_wrapper): print('on_post_process') # in_wrapper.on_post_processing_delegate.remove_callable(on_post_process) # Iterate over all PDG/TOP networks and nodes and log them print('TOP networks:') for network_path in in_wrapper.get_pdgtop_network_paths(): print('\t{}'.format(network_path)) for node_path in in_wrapper.get_pdgtop_node_paths(network_path): print('\t\t{}'.format(node_path)) # Enable PDG auto-bake (auto bake TOP nodes after they are cooked) in_wrapper.set_pdg_auto_bake_enabled(True) # Bind to PDG post bake delegate (called after all baking is complete) in_wrapper.on_post_pdg_bake_delegate.add_callable(on_post_bake) # Cook the specified TOP node in_wrapper.pdg_cook_node('topnet1', 'HE_OUT_PIGHEAD_GRID') def run(): # get the API singleton api = unreal.HoudiniPublicAPIBlueprintLib.get_api() global _g_wrapper # instantiate an asset, disabling auto-cook of the asset _g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform(), enable_auto_cook=False) # Bind to the on pre instantiation delegate (before the first cook) and # set parameters _g_wrapper.on_pre_instantiation_delegate.add_callable(on_pre_instantiation) # Bind to the on post processing delegate (after a cook and after all # outputs have been generated in Unreal) _g_wrapper.on_post_processing_delegate.add_callable(on_post_process) if __name__ == '__main__': run()
# Copyright (C) 2024 Louis Vottero [email protected] All rights reserved. from vtool import util from vtool import util_file import os # this module should not use python 37 features to keep compatibility. # some of these commands could be used to query unreal information outside of unreal. if util.in_unreal: import unreal def get_project_directory(): game_dir = unreal.Paths.project_content_dir() game_dir = util_file.get_dirname(game_dir) return game_dir def get_custom_library_path(): vetala = util_file.get_vetala_directory() library_path = util_file.join_path(vetala, 'unreal_lib') library_path = util_file.join_path(library_path, 'library') if util_file.exists(library_path): return library_path def create_static_mesh_asset(asset_name, package_path): # Create a new Static Mesh object static_mesh_factory = unreal.EditorStaticMeshFactoryNew() new_static_mesh = unreal.AssetToolsHelpers.get_asset_tools().create_asset(asset_name, package_path, unreal.ControlRig, static_mesh_factory) # Save the new asset unreal.AssetToolsHelpers.get_asset_tools().save_asset(new_static_mesh) # Return the newly created Static Mesh object return new_static_mesh def create_control_rig_shape_library(filepath, path='/project/'): asset_path = path asset_name = 'vetala_shape_library' # Create an instance of the ControlRigShapeLibraryFactory factory = unreal.ControlRigShapeLibraryFactory() # Use the AssetTools module to create the new asset asset_tools = unreal.AssetToolsHelpers.get_asset_tools() shape_library_asset = asset_tools.create_asset( asset_name, asset_path, unreal.ControlRigShapeLibrary, factory ) return shape_library_asset def add_static_meshes_to_library(shape_library_inst, mesh_paths): pass def is_of_type(filepath, type_name): asset_data = unreal.EditorAssetLibrary.find_asset_data(filepath) if asset_data: if asset_data.asset_class_path.asset_name == type_name: return True return False def get_asset_data_instance(filepath): asset_data = unreal.EditorAssetLibrary.find_asset_data(filepath) return asset_data def get_asset_data_asset(asset_data_instance): inst = asset_data_instance.get_asset() return inst def get_instance_type(asset_data_instance): return asset_data_instance.asset_class_path.asset_name def is_instance_of_type(asset_data_instance, type_name): if asset_data_instance.asset_class_path.asset_name == type_name: return True return False def is_skeletal_mesh(filepath): return is_of_type(filepath, 'SkeletalMesh') def is_control_rig(filepath): return is_of_type(filepath, 'ControlRigBlueprint') def open_unreal_window(instance): if isinstance(instance, unreal.AssetData): instance = get_asset_data_asset(instance) unreal.AssetEditorSubsystem().open_editor_for_assets([instance]) def set_skeletal_mesh(filepath): util.set_env('VETALA_CURRENT_PROCESS_SKELETAL_MESH', filepath) mesh = get_skeletal_mesh_object(filepath) control_rigs = find_associated_control_rigs(mesh) return control_rigs[0] # create_control_rig_from_skeletal_mesh(mesh) def get_skeletal_mesh(): path = os.environ.get('VETALA_CURRENT_PROCESS_SKELETAL_MESH') return path def get_skeletal_mesh_object(asset_path): mesh = unreal.load_object(name=asset_path, outer=None) return mesh def get_control_rig_object(asset_path): rig = unreal.load_object(name=asset_path, outer=None) return rig def get_content_data(asset_path): game_dir = get_project_directory() asset_paths = unreal.EditorAssetLibrary.list_assets(asset_path, recursive=True) found = [] for path in asset_paths: package_name = path.split('.') package_name = package_name[0] full_path = unreal.Paths.convert_relative_path_to_full(path) full_path = util_file.join_path(game_dir, full_path) util.show(package_name) found.append(package_name) return found def find_associated_control_rigs(skeletal_mesh_object): path = skeletal_mesh_object.get_path_name() path = util_file.get_dirname(path) asset_paths = unreal.EditorAssetLibrary.list_assets(path, recursive=True) control_rigs = [] for asset_path in asset_paths: package_name = asset_path.split('.') package_name = package_name[0] if is_control_rig(package_name): control_rigs.append(package_name) found = None if control_rigs: found = [unreal.load_object(name=control_rigs[0], outer=None)] return found def get_unreal_content_process_path(): project_path = os.environ.get('VETALA_PROJECT_PATH') process_path = util_file.get_current_vetala_process_path() rel_path = util_file.remove_common_path_simple(project_path, process_path) content_path = util_file.join_path('/project/', rel_path) return content_path def get_unreal_control_shapes(): shapes = ['Arrow2', 'Arrow4', 'Arrow', 'Box', 'Circle', 'Diamond', 'HalfCircle', 'Hexagon', 'Octagon', 'Pyramid', 'QuarterCircle', 'RoundedSquare', 'RoundedTriangle', 'Sphere', 'Square', 'Star4', 'Triangle', 'Wedge'] sub_names = ['Thin', 'Thick', 'Solid'] found = [] # TODO: Refactor and use itertools. for shape in shapes: for name in sub_names: found.append(shape + '_' + name) defaults = ['None', 'Default'] found = defaults + found return found
import unreal from unreal_global import * unreal.log("""@ #################### Unreal Init Script #################### """) import unreal_startup
import unreal import json ##Intances classes of unreal engine editor_util = unreal.EditorUtilityLibrary() system_lib = unreal.SystemLibrary() ##prefix mapping prefix_mapping = {} with open("/project/.json", "r") as json_file: prefix_mapping = json.loads(json_file.read()) ##get selected assets selected_assets = editor_util.get_selected_assets() num_assets = len(selected_assets) prefixed = 0 for asset in selected_assets: #get the class instance and clear text name asset_name = system_lib.get_object_name(asset) asset_class = asset.get_class() class_name = system_lib.get_class_display_name(asset_class) #get the prefix for the given class class_prefix = prefix_mapping.get(class_name, None) if class_prefix is None: unreal.log_warning("No mapping fo asset {} of type {}".format(asset_name, class_name)) continue if not asset_name.startswith(class_prefix): #rename the asset and add the prefix new_name = class_prefix + asset_name editor_util.rename_asset(asset, new_name) prefixed += 1 unreal.log("Prefixed {} of type {} with {}".format(asset_name, class_name, class_prefix)) else: unreal.log("Asset {} of type {} is already prefixed with {}".format(asset_name, class_name, class_prefix)) unreal.log("Prefixed {} of {}".format(prefixed, num_assets))
import unreal import numpy as np import random import os import json import re import time NUM_VARIATIONS = 10 np.random.seed(None) 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, 2, 1], [0, 0, 0]], # 0 # [[0, 0, 4.2, 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, 4, 4.5, 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, 2.7, 0.6], [0, 0, 0]], # 0 # [[0, 0, 3, 1], [0, 0, 0]], # 1 # [[0, 0, 3, 0.15], [0, 0, 0]], # 2 # [[0, 0, 3, 1], [0, 0, 0]], # 3 # [[0, 0, 0, 1], [0, 0, 0]], # 4 # [[0, 0, 3, 1], [0, 0, 0]], # 5 # [[6, 13.5, -27, 0.03], [0, 0, 0]], # 6 # [[0, 0, 3, 1], [0, 0, 0]], # 7 # [[0, 0, 0, 0.001], [0, 0, 0]], # 8 # [[27, 0, -3, 0.15], [0, 0, 0]], # 9 # ], # 'notebook': # [ # [[-5, -12, 0, 0.05], [0, 0, 0]], # 0 # [[0, -5, 0, 0.4], [0, 0, 0]], # 1 # [[0, 0, 0, 1], [0, 0, 0]], # 2 # [[0, 0, 0, 0.7], [0, 0, 0]], # 3 # [[0, 0, 0, 0.5], [-90, 0, 0]], # 4 # [[0, 0, 0, 0.0004], [0, 0, 60]], # 5 # [[-13, -2.5, 2, 0.5], [0, 0, 0]], # 6 # [[6, 0, 0, 0.7], [0, 90, 0]], # 7 # [[8, 0, 0, 0.8], [0, 90, 0]], # 8 # [[0, 0, 0, 0.7], [0, 0, 0]], # 9 # ] # } 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, 3, 0.03], [0, 0, 0]], # 6 [[0, 0, 0, 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.4], [0, 0, 0]], # 1 [[0, 0, 0, 1], [0, 0, 0]], # 2 [[0, 0, 0, 0.7], [0, 0, 0]], # 3 [[0, 0, 0, 0.5], [0, 0, 0]], # 4 [[0, 0, 0, 0.04], [0, 0, 0]], # 5 [[0, 0, 0, 0.5], [0, 0, 0]], # 6 [[0, 0, 0, 0.7], [0, 180, 0]], # 7 [[0, 0, 0, 0.8], [0, 0, 0]], # 8 [[0, 0, 0, 0.7], [0, 0, 0]], # 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", ] father_path = "/project/" object_path_list = { 'mug': [], 'notebook': [], 'apple': [] } 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 = [ # [-120, 0, 200], # [120, 0, 200], # [0, -61, 220], # [0, 61, 220], # [-120, -60, 190], # [120, 60, 190], # [-120, 60, 190], # [120, -60, 190] # ] # camera_rotation_list = [ # [0, -51, 0], # [0, -51, 180], # [0, -65, 90], # [0, -65, -90], # [0, -50, 30], # [0, -50, -150], # [0, -50, -30], # [0, -50, 150] # ] camera_location_list = [ [0, -58, 93], [15, 0, 160], [0, 15, 160], [0, -15, 160], [-120, -60, 190], [120, 60, 190], [-120, 60, 190], [120, -60, 190] ] camera_rotation_list = [ [0, -21.5, 90], [0, -80, 180], [0, -82, 270], [360, -82, 90], [0, -50, 30], [0, -50, -150], [0, -50, -30], [0, -50, 150] ] 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(8): 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) pps = this_cc.get_editor_property("post_process_settings") # pp_settings.override_dynamic_global_illumination_method = True # pp_settings.override_reflection_method = True # # bloom # pp_settings.override_bloom_method = True # pp_settings.override_tone_curve_amount = True # this_cc.set_editor_property("post_process_settings", pp_settings) for attr in dir(pps): if not attr.startswith('_'): if attr.startswith('override_'): # print(f"{attr}: {getattr(pps, attr)}") # set it to True setattr(pps, attr, True) # print(f"{attr}: {getattr(pps, attr)}") this_cc.set_editor_property("post_process_settings", pps) capture_component.append(this_cc) RTs.append(capture_component[i].texture_target) # set camera location and rotation existed_episodes = sorted(os.listdir(save_path), key=natural_sort_key) episodes = 30 counter = 0 while counter < episodes: # if episode_idx < len(existed_episodes) - 5: # 重新生成最后一几个,防止不全 # continue # print(f"Episode {episode_idx}") # set camera location and rotation # print(default_pp_settings) for i in range(8): camera_actors[f'camera{i}'].set_actor_location_and_rotation(unreal.Vector(*camera_location_list[i]), unreal.Rotator(*camera_rotation_list[i]), False, False) # set object location and rotation for object in objects: for i in range(NUM_VARIATIONS): object_actor_dict[object][f'{object}{i}'].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: id_in_table = np.random.randint(0, NUM_VARIATIONS) objects_to_show.append([object, id_in_table, object_actor_dict[object][f'{object}{id_in_table}']]) # name, id, actor # logic of placing objects on the table limits = [[-40, 40], [-40, 40]] height = 77 bool_map = np.bool_(np.ones((60, 60))) block_size = 20 record = { 'mug': 0, 'notebook': 0, 'apple': 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] candidate_blocks = get_candidate_blocks(bool_map, block_size) if candidate_blocks: block_position = random.choice(candidate_blocks) bool_map = update_bool_map(bool_map, block_size, block_position) scale = scale_offset * np.random.choice([1.0, 1.0, 1.0]) x = block_position[0] + limits[0][0] + location_offset[0] * scale y = block_position[1] + limits[1][0] + location_offset[1] * scale z = height + location_offset[2] * scale actor[2].set_actor_location_and_rotation(unreal.Vector(x, y, z), unreal.Rotator(*rotation_offset), 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.5) # 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') if i >= 0: break with open(os.path.join(folder_path, 'info.json'), 'w') as f: json.dump(record, f) counter += 1 # unreal.SystemLibrary.collect_garbage() print("-------------------------") main() # print(RT)
import unreal import sys import os import json from PySide2 import QtUiTools, QtWidgets, QtGui, QtCore class UnrealWidget(QtWidgets.QWidget): """ Create a default tool window. """ # store ref to window to prevent garbage collection window = None def __init__(self, parent=None): """ Import UI and connect components """ super(UnrealWidget, self).__init__(parent) # load the created UI widget self.widgetPath = '/project/-Project\\msccavepipelineandtdproject24-RahulChandra99\\unreal-automation\\GUI\\' self.widget = QtUiTools.QUiLoader().load(self.widgetPath + 'unrealWidget.ui') # path to PyQt .ui file # attach the widget to the instance of this class (aka self) self.widget.setParent(self) # find interactive elements of UI self.btn_close = self.widget.findChild(QtWidgets.QPushButton, 'btn_close') # assign clicked handler to buttons # self.btn_close.clicked.connect(self.closewindow) # find interactive elements of UI # project setup tools UI self.line_parentfolder = self.widget.findChild(QtWidgets.QLineEdit, 'line_parentfolder') self.btn_createfolderstruc = self.widget.findChild(QtWidgets.QPushButton, 'btn_createfolderstruc') self.sp_genericassets = self.widget.findChild(QtWidgets.QSpinBox, 'sp_genericassets') self.btn_creategenericassets = self.widget.findChild(QtWidgets.QPushButton, 'btn_creategenericassets') self.cb_assettype = self.widget.findChild(QtWidgets.QComboBox, 'cb_assettype') self.sp_bpclasses = self.widget.findChild(QtWidgets.QSpinBox, 'sp_bpclasses') self.btn_createbpclasses = self.widget.findChild(QtWidgets.QPushButton, 'btn_createbpclasses') self.btn_duplicate = self.widget.findChild(QtWidgets.QPushButton, 'btn_duplicate') self.sp_duplicate = self.widget.findChild(QtWidgets.QSpinBox, 'sp_duplicate') # renamer tool UI self.btn_rename = self.widget.findChild(QtWidgets.QPushButton, 'btn_rename') self.line_search = self.widget.findChild(QtWidgets.QLineEdit, 'line_search') self.line_replace = self.widget.findChild(QtWidgets.QLineEdit, 'line_replace') self.cb_usecase = self.widget.findChild(QtWidgets.QCheckBox, 'cb_usecase') self.btn_autoprefix = self.widget.findChild(QtWidgets.QPushButton, 'btn_autoprefix') self.btn_autosuffix = self.widget.findChild(QtWidgets.QPushButton, 'btn_autosuffix') self.cb_conventional = self.widget.findChild(QtWidgets.QCheckBox, 'cb_conventional') self.line_customvalue = self.widget.findChild(QtWidgets.QLineEdit, 'line_customvalue') # cleanup tools UI self.btn_autoorganise = self.widget.findChild(QtWidgets.QPushButton, 'btn_autoorganise') self.btn_outlinersort = self.widget.findChild(QtWidgets.QPushButton, 'btn_outlinersort') self.btn_removeunused = self.widget.findChild(QtWidgets.QPushButton, 'btn_removeunused') self.btn_deleteempfolders = self.widget.findChild(QtWidgets.QPushButton, 'btn_deleteempfolders') self.rb_trash = self.widget.findChild(QtWidgets.QRadioButton, 'rb_trash') self.rb_delete = self.widget.findChild(QtWidgets.QRadioButton, 'rb_delete') # create actors UI self.btn_createactor = self.widget.findChild(QtWidgets.QPushButton, 'btn_createactor') self.sp_noactors = self.widget.findChild(QtWidgets.QSpinBox, 'sp_noactors') self.dsb_locX = self.widget.findChild(QtWidgets.QDoubleSpinBox, 'dsb_locX') self.dsb_locY = self.widget.findChild(QtWidgets.QDoubleSpinBox, 'dsb_locY') self.dsb_locZ = self.widget.findChild(QtWidgets.QDoubleSpinBox, 'dsb_locZ') self.dsb_rotX = self.widget.findChild(QtWidgets.QDoubleSpinBox, 'dsb_rotX') self.dsb_rotY = self.widget.findChild(QtWidgets.QDoubleSpinBox, 'dsb_rotY') self.dsb_rotZ = self.widget.findChild(QtWidgets.QDoubleSpinBox, 'dsb_rotZ') self.sp_rotationvalue = self.widget.findChild(QtWidgets.QSpinBox, 'sp_rotationvalue') self.sp_offsetpos = self.widget.findChild(QtWidgets.QSpinBox, 'sp_offsetpos') self.btn_automatassign = self.widget.findChild(QtWidgets.QPushButton, 'btn_automatassign') self.btn_copytrans = self.widget.findChild(QtWidgets.QPushButton, 'btn_copytrans') self.cb_transform = self.widget.findChild(QtWidgets.QCheckBox, 'cb_transform') self.cb_location = self.widget.findChild(QtWidgets.QCheckBox, 'cb_location') self.cb_rotation = self.widget.findChild(QtWidgets.QCheckBox, 'cb_rotation') self.cb_scale = self.widget.findChild(QtWidgets.QCheckBox, 'cb_scale') # import export UI self.btn_import = self.widget.findChild(QtWidgets.QPushButton, 'btn_import') self.rb_autoimport = self.widget.findChild(QtWidgets.QRadioButton, 'rb_autoimport') self.rb_manualimport = self.widget.findChild(QtWidgets.QRadioButton, 'rb_manualimport') self.btn_export = self.widget.findChild(QtWidgets.QPushButton, 'btn_export') self.rb_autoexport = self.widget.findChild(QtWidgets.QRadioButton, 'rb_autoexport') self.rb_manualexport = self.widget.findChild(QtWidgets.QRadioButton, 'rb_manualexport') # misc tools self.sp_materialinstance = self.widget.findChild(QtWidgets.QSpinBox, 'sp_materialinstance') self.btn_multimatinstances = self.widget.findChild(QtWidgets.QPushButton, 'btn_multimatinstances') # console text UI self.warning_console = self.widget.findChild(QtWidgets.QLabel, 'warning_console') self.btn_dark = self.widget.findChild(QtWidgets.QPushButton, 'btn_dark') self.btn_light = self.widget.findChild(QtWidgets.QPushButton, 'btn_light') # self.btn_close = self.widget.findChild(QtWidgets.QPushButton, 'btn_close') # assign clicked handler to buttons self.btn_rename.clicked.connect(self.renameassets) self.btn_autoprefix.clicked.connect(self.autoprefix) self.btn_autosuffix.clicked.connect(self.autosuffix) self.btn_createfolderstruc.clicked.connect(self.createprojectfolder) self.btn_createbpclasses.clicked.connect(self.createbpclasses) self.btn_duplicate.clicked.connect(self.duplicate) self.btn_autoorganise.clicked.connect(self.autoorganise) self.btn_outlinersort.clicked.connect(self.sortoutliner) self.btn_removeunused.clicked.connect(self.removeunused) self.btn_deleteempfolders.clicked.connect(self.deleteemptyfolder) self.btn_import.clicked.connect(self.importassets) self.btn_creategenericassets.clicked.connect(self.creategenericassets) self.btn_automatassign.clicked.connect(self.assignmatauto) self.btn_copytrans.clicked.connect(self.copytransform) self.btn_createactor.clicked.connect(self.createactor) self.btn_export.clicked.connect(self.exportselectedassets) self.btn_multimatinstances.clicked.connect(self.multimaterialinstacer) self.btn_dark.clicked.connect(self.darkmode) self.btn_light.clicked.connect(self.lightmode) # self.btn_close.clicked.connect(self.closewindow) for button in self.widget.findChildren(QtWidgets.QPushButton): self.setbtnappearance(button) """ Custom Methods """ @staticmethod def setbtnappearance(button): button.setStyleSheet('background-color: rgb(56, 56, 56);color: rgb(255, 255, 255);border-radius : 10;border-style:inset') def darkmode(self): self.widget.setStyleSheet( 'background-color: rgb(21, 21, 21);color: rgb(255, 255, 255);QToolBox{color:rgb(0,0,0);};QPushButton{border-radius : 25px;}') self.warning_console.setStyleSheet( 'color: rgb(255, 255, 0)') def lightmode(self): self.widget.setStyleSheet( 'background-color: rgb(255, 255, 255);color: rgb(0, 0, 0);QToolBox{color:rgb(0,0,0);QLabel{color:rgb(0,0,0)}') self.warning_console.setStyleSheet( 'color: rgb(0, 0, 0)') # project setup tools def createprojectfolder(self): """ setup most commonly used folders in UE """ # instances of unreal classes editor_util = unreal.EditorAssetLibrary() folder_path = "/Game/" folder_name = self.line_parentfolder.text() if folder_name == "": folder_name = "MyProject" full_folder_path = folder_path + "_" + folder_name # make parent folder try: editor_util.make_directory(full_folder_path) self.warning_console.setText("Folder {} created successfully at {}".format(folder_name,folder_path)) except OSError as e: self.warning_console.setText("Error creating folder at {} : {}".format(folder_path, e)) # make subfolders editor_util.make_directory(full_folder_path + "/Art") editor_util.make_directory(full_folder_path + "/project/") editor_util.make_directory(full_folder_path + "/project/") editor_util.make_directory(full_folder_path + "/project/") editor_util.make_directory(full_folder_path + "/project/") editor_util.make_directory(full_folder_path + "/project/") editor_util.make_directory(full_folder_path + "/project/") editor_util.make_directory(full_folder_path + "/project/") editor_util.make_directory(full_folder_path + "/Blueprints") editor_util.make_directory(full_folder_path + "/UI") editor_util.make_directory(full_folder_path + "/project/") editor_util.make_directory(full_folder_path + "/project/") editor_util.make_directory(full_folder_path + "/Cinematics") editor_util.make_directory(full_folder_path + "/Audio") editor_util.make_directory(full_folder_path + "/Maps") def creategenericassets(self): """ Create commonly used assets instantly """ editorasset_lib = unreal.EditorAssetLibrary() asset_tools = unreal.AssetToolsHelpers.get_asset_tools() no_assets = self.sp_genericassets.value() if self.cb_assettype.currentIndex() == 0: factory = unreal.LevelSequenceFactoryNew() asset_class = unreal.LevelSequence new_asset_name = "LS_CustomLS_%d" destination_path = '/project/' progress_text = "Creating new Level Sequence..." elif self.cb_assettype.currentIndex() == 1: factory = unreal.MaterialFactoryNew() asset_class = unreal.Material new_asset_name = "M_CustomM_%d" destination_path = '/project/' progress_text = "Creating new Material..." elif self.cb_assettype.currentIndex() == 2: factory = unreal.WorldFactory() asset_class = unreal.World new_asset_name = "W_CustomLS_%d" destination_path = '/project/' progress_text = "Creating new Maps..." elif self.cb_assettype.currentIndex() == 3: factory = unreal.NiagaraScriptFactoryNew() asset_class = unreal.NiagaraSystem new_asset_name = "PS_CustomPS_%d" destination_path = '/project/' progress_text = "Creating new Niagara Systems..." else: pass with unreal.ScopedSlowTask(no_assets, progress_text) as ST: ST.make_dialog(True) for x in range(no_assets): if ST.should_cancel(): break new_asset = asset_tools.create_asset(new_asset_name%(x), destination_path, asset_class, factory) editorasset_lib.save_loaded_asset(new_asset) self.warning_console.setText("Created new assets in {}".format(destination_path)) ST.enter_progress_frame(1) def createbpclasses(self): """ Create multiple bp classes with dialog """ # instances of unreal classes assettool_lib = unreal.AssetToolsHelpers totalNumberOfBPs = self.sp_bpclasses.value() textDisplay = "Creating Blueprint Classes..." BPPath = "/Game" BPName = "New_BP_%d" factory = unreal.BlueprintFactory() assetTools = assettool_lib.get_asset_tools() with unreal.ScopedSlowTask(totalNumberOfBPs, textDisplay) as ST: ST.make_dialog(True) for i in range(totalNumberOfBPs): if ST.should_cancel(): break; myNewFile = assetTools.create_asset_with_dialog(BPName % (i), BPPath, None, factory) unreal.EditorAssetLibrary.save_loaded_asset(myNewFile) self.warning_console.setText("Blueprint classes created") ST.enter_progress_frame(1) def duplicate(self): """ Make multiple copes """ editor_util = unreal.EditorUtilityLibrary() editor_asset_lib = unreal.EditorAssetLibrary() # get the selected assets selected_assets = editor_util.get_selected_assets() num_assets = len(selected_assets) # hard coded value num_copies = self.sp_duplicate.value() total_num_copies = num_copies * num_copies progress_text_label = "Duplicating Assets..." running = True with unreal.ScopedSlowTask(total_num_copies, progress_text_label) as slow_tasks: # display dialog slow_tasks.make_dialog(True) for asset in selected_assets: # get the asset name and the path to be duplicated asset_name = asset.get_fname() asset_path = editor_asset_lib.get_path_name_for_loaded_asset(asset) source_path = os.path.dirname(asset_path) for i in range(num_copies): # if cancel btn is pressed if slow_tasks.should_cancel(): running = False break new_name = "{}_{}".format(asset_name, i) dest_path = os.path.join(source_path, new_name) duplicate = editor_asset_lib.duplicate_asset(asset_path, dest_path) slow_tasks.enter_progress_frame(1) if duplicate is None: self.warning_console.setText("Duplicate from {} at {} already exists".format(source_path, dest_path)) if not running: break self.warning_console.setText("{} assets duplicated".format(num_assets)) # renamer tools def renameassets(self): """ rename Selected Assets """ # instances of unreal classes system_lib = unreal.SystemLibrary() editor_util = unreal.EditorUtilityLibrary() string_lib = unreal.StringLibrary() search_pattern = self.line_search.text() replace_pattern = self.line_replace.text() use_case = self.cb_usecase.isChecked() # get the selected assets selected_assets = editor_util.get_selected_assets() num_assets = len(selected_assets) replaced = 0 # unreal.log("Selected {} assets".format(num_assets)) # loop over each asset and then rename for asset in selected_assets: asset_name = system_lib.get_object_name(asset) # check if asset name contains the string to be replaced if string_lib.contains(asset_name, search_pattern, use_case=use_case): search_case = unreal.SearchCase.CASE_SENSITIVE if use_case else unreal.SearchCase.IGNORE_CASE replaced_name = string_lib.replace(asset_name, search_pattern, replace_pattern, search_case=search_case) editor_util.rename_asset(asset, replaced_name) replaced += 1 self.warning_console.setText("Replaced {} with {}".format(asset_name, replaced_name)) else: self.warning_console.setText("{} did not match the search pattern, was skipped.".format(asset_name)) self.warning_console.setText("Replaced {} of {} assets".format(replaced, num_assets)) def autoprefix(self): """ Auto prefix assets based on standard/custom naming conventions or based on user inputs """ # instances of unreal classes editor_util = unreal.EditorUtilityLibrary() system_lib = unreal.SystemLibrary() custom_prefix = self.line_customvalue.text() conventional = self.cb_conventional.isChecked() # prefix mapping prefix_mapping = {} with open( "/project/-Project\\msccavepipelineandtdproject24-RahulChandra99\\unreal-automation\\prefix_mapping.json", "r") as json_file: prefix_mapping = json.loads(json_file.read()) # get the selected assets selected_assets = editor_util.get_selected_assets() num_assets = len(selected_assets) prefixed = 0 for asset in selected_assets: # get the class instance and text name asset_name = system_lib.get_object_name(asset) asset_class = asset.get_class() class_name = system_lib.get_class_display_name(asset_class) # get the prefix for the given class class_prefix = prefix_mapping.get(class_name, None) if conventional else custom_prefix if class_prefix is None: self.warning_console.setText("No mapping for asset {} of type {}".format(asset_name, class_name)) continue if not asset_name.startswith(class_prefix): # rename the asset and add prefix new_name = class_prefix + asset_name editor_util.rename_asset(asset, new_name) prefixed += 1 else: self.warning_console.setText( "Asset {} of type {} is already prefixed with {}".format(asset_name, class_name, class_prefix)) self.warning_console.setText("Prefixed {} of {} assets".format(prefixed, num_assets)) def autosuffix(self): """ Auto suffix assets based on standard/custom naming conventions or based on user inputs """ # instances of unreal classes editor_util = unreal.EditorUtilityLibrary() system_lib = unreal.SystemLibrary() custom_suffix = self.line_customvalue.text() conventional = self.cb_conventional.isChecked() # suffix mapping suffix_mapping = {} with open( "/project/-Project\\msccavepipelineandtdproject24-RahulChandra99\\unreal-automation\\suffix_mapping.json", "r") as json_file: suffix_mapping = json.loads(json_file.read()) # get the selected assets selected_assets = editor_util.get_selected_assets() num_assets = len(selected_assets) suffixed = 0 for asset in selected_assets: # get the class instance and text name asset_name = system_lib.get_object_name(asset) asset_class = asset.get_class() class_name = system_lib.get_class_display_name(asset_class) # get the prefix for the given class class_suffix = suffix_mapping.get(class_name, None) if conventional else custom_suffix if class_suffix is None: self.warning_console.setText("No mapping for asset {} of type {}".format(asset_name, class_name)) continue if not asset_name.endswith(class_suffix): # rename the asset and add prefix new_name = asset_name + class_suffix editor_util.rename_asset(asset, new_name) suffixed += 1 else: self.warning_console.setText( "Asset {} of type {} is already suffixed with {}".format(asset_name, class_name, class_suffix)) self.warning_console.setText("Suffixed {} of {} assets".format(suffixed, num_assets)) # cleanup tools def autoorganise(self): """ Organise objects into folders automatically """ # instances fo unreal classes editor_util = unreal.EditorUtilityLibrary() system_lib = unreal.SystemLibrary() editor_asset_lib = unreal.EditorAssetLibrary() # get the selected assets selected_assets = editor_util.get_selected_assets() num_assets = len(selected_assets) organised = 0 # to organise within the Content folder parent_dir = "\\Game" # to organise within custom sub folder if num_assets > 0: asset_path = editor_asset_lib.get_path_name_for_loaded_asset(selected_assets[0]) parent_dir = os.path.dirname(asset_path) for asset in selected_assets: # get the class instance and text name asset_name = system_lib.get_object_name(asset) asset_class = asset.get_class() class_name = system_lib.get_class_display_name(asset_class) # assemble new path and relocate assets try: new_path = os.path.join(parent_dir, class_name, asset_name) editor_asset_lib.rename_loaded_asset(asset, new_path) organised += 1 self.warning_console.setText("Cleaned up {} to {}".format(asset_name, new_path)) except Exception as err: self.warning_console.setText("Could not move {} to new location{}".format(asset_name,new_path)) self.warning_console.setText("Cleaned up {} of {} assets".format(organised, num_assets)) def sortoutliner(self): """ Organise the world outliner into folders """ # instances of unreal classes editor_level_lib = unreal.EditorLevelLibrary() editor_filter_lib = unreal.EditorFilterLibrary() # get all actors and filter down to specific elements actors = editor_level_lib.get_all_level_actors() static_meshes = editor_filter_lib.by_class(actors, unreal.StaticMeshActor) reflection_cap = editor_filter_lib.by_class(actors, unreal.ReflectionCapture) sound = editor_filter_lib.by_class(actors, unreal.AmbientSound) blueprints = editor_filter_lib.by_id_name(actors, "BP_") moved = 0 # create a mapping between folder names and arrays mapping = { "StaticMeshActors": static_meshes, "ReflectionCaptures": reflection_cap, "Blueprints": blueprints, "Audio": sound } for folder_name in mapping: # for every list of actors, set new folder path for actor in mapping[folder_name]: actor_name = actor.get_fname() actor.set_folder_path(folder_name) self.warning_console.setText("Moved {} into {}".format(actor_name, folder_name)) moved += 1 self.warning_console.setText("Moved {} actors into folders".format(moved)) def deleteemptyfolder(self): """ Delete folders that don't have any assets """ # instances of unreal classes editor_asset_lib = unreal.EditorAssetLibrary() # set source dir and options source_dir = "/Game" include_subfolders = True deleted = 0 folder_exception = "Hello" # get all assets in source dir assets = editor_asset_lib.list_assets(source_dir, recursive=include_subfolders, include_folder=True) for asset in assets: if editor_asset_lib.does_directory_exist(asset): # check if folder has assets has_assets = editor_asset_lib.does_directory_have_assets(asset) if not has_assets: # delete folder editor_asset_lib.delete_directory(asset) deleted += 1 self.warning_console.setText("Folder {} without assets was deleted".format(asset)) self.warning_console.setText("Deleted {} empty folders without assets".format(deleted)) def removeunused(self): """ Delete or move unused objects to Trash folder """ # instances of unreal classes editor_util = unreal.EditorUtilityLibrary() editor_asset_lib = unreal.EditorAssetLibrary() # get the selected assets selected_assets = editor_util.get_selected_assets() num_assets = len(selected_assets) removed = 0 # instantly delete assets or move to Trash folder if self.rb_delete.isChecked(): instant_delete = True else: instant_delete = False trash_folder = os.path.join(os.sep, "Game", "Trash") to_be_deleted = [] for asset in selected_assets: asset_name = asset.get_fname() asset_path = editor_asset_lib.get_path_name_for_loaded_asset(asset) # get a list of reference for this asset asset_references = editor_asset_lib.find_package_referencers_for_asset(asset_path) if len(asset_references) == 0: to_be_deleted.append(asset) for asset in to_be_deleted: asset_name = asset.get_fname() # instant delete if instant_delete: deleted = editor_asset_lib.delete_loaded_asset(asset) if not deleted: self.warning_console.setText("Asset {} could not be deleted".format(asset_name)) continue removed += 1 # move the assets to the trash folder else: new_path = os.path.join(trash_folder, str(asset_name)) moved = editor_asset_lib.rename_loaded_asset(asset, new_path) if not moved: self.warning_console.setText("Asset {} could not be moved to Trash".format(asset_name)) continue removed += 1 output_test = "removed" if instant_delete else "moved to Trash folder" self.warning_console.setText( "{} out of {} assets deleted, of {} selected, {}".format(removed, len(to_be_deleted), num_assets, output_test)) # actors tool def createactor(self): """ Create Actors """ # instances of unreal classes editorutil_lib = unreal.EditorUtilityLibrary() num_actors = self.sp_noactors.value() actor_location = unreal.Vector(self.dsb_locX.value(), self.dsb_locY.value(), self.dsb_locZ.value()) actor_rotation = unreal.Rotator(self.dsb_rotX.value(), self.dsb_rotY.value(), self.dsb_rotZ.value()) progress_text_label = "Creating actors in the level..." # get the selected assets selected_assets = editorutil_lib.get_selected_assets() num_assets = len(selected_assets) created = 0 with unreal.ScopedSlowTask(num_actors, progress_text_label) as ST: ST.make_dialog(True) for x in range(num_actors): if ST.should_cancel(): break; if selected_assets is None: self.warning_console.setText("Nothing is selected") else: for y in range(len(selected_assets)): actor = unreal.EditorLevelLibrary.spawn_actor_from_object(selected_assets[y], actor_location, actor_rotation) # Edit Tags actor_tags = actor.get_editor_property('tags') actor_tags.append('My Python Tag') actor.set_editor_property('tags', actor_tags) created += 1 ST.enter_progress_frame(1) self.warning_console.setText("{} new actor(s) are spawned".format(created)) def assignmatauto(self): """ Assign material to selectors actors in the scene """ # inst of unreal classes editor_util = unreal.EditorUtilityLibrary() layer_sys = unreal.LayersSubsystem() editor_filter_lib = unreal.EditorFilterLibrary() # get selected material and selected static mesh actors selected_assets = editor_util.get_selected_assets() materials = editor_filter_lib.by_class(selected_assets, unreal.Material) if len(materials) < 1: self.warning_console.setText("Select atleast one material from the content browser") else: material = materials[0] material_name = material.get_fname() actors = layer_sys.get_selected_actors() static_mesh_actors = editor_filter_lib.by_class(actors, unreal.StaticMeshActor) for actor in static_mesh_actors: actor_name = actor.get_fname() # get the static mesh component and assign the material actor_mesh_component = actor.static_mesh_component actor_mesh_component.set_material(0,material) self.warning_console.setText("Assigning material {} to actor {}".format(material_name, actor_name)) def copytransform(self): """ Copy transform of one actor to another """ # instances of unreal classes editorlevel_lib = unreal.EditorLevelLibrary() # get world outliner reference world = editorlevel_lib.get_world() if len(editorlevel_lib.get_selected_level_actors()) < 2: self.warning_console.setText("Select atleast 2 actors to perform this function") else: # reference of actor's transform you want to copy and get the transform actor_to_copy = editorlevel_lib.get_selected_level_actors()[0] actor1_transform = actor_to_copy.get_actor_transform() actor1_scale = actor_to_copy.get_actor_scale3d() actor1_rotation = actor_to_copy.get_actor_rotation() actor1_location = actor_to_copy.get_actor_location() selected_actors = editorlevel_lib.get_selected_level_actors() # reference of actor's transform you want to copy to and assign the transforms for x in range(len(selected_actors)): actor_to_paste_to = selected_actors[x] if self.cb_transform.isChecked(): actor_to_paste_to.set_actor_transform(actor1_transform, sweep=False, teleport=True) if self.cb_scale.isChecked(): actor_to_paste_to.set_actor_scale3d(actor1_scale) if self.cb_rotation.isChecked(): actor_to_paste_to.set_actor_rotation(actor1_rotation, teleport_physics=True) if self.cb_location.isChecked(): actor_to_paste_to.set_actor_location(actor1_location, sweep=False, teleport=True) self.warning_console.setText( "Copying transform values from {} to {}".format(actor_to_copy.get_name(), actor_to_paste_to.get_name())) unreal.log( "Copying transform values from {} to {}".format(actor_to_copy.get_name(), actor_to_paste_to.get_name())) # import and export def importassets(self): """ Import assets into project. """ # create asset tools object assettools = unreal.AssetToolsHelpers.get_asset_tools() # create asset import data object assetimportdata = unreal.AutomatedAssetImportData() # list of files to import fileNames = [ "/project/" ] # set assetImportData attributes assetimportdata.destination_path = '/project/' assetimportdata.filenames = fileNames assetimportdata.replace_existing = True if self.rb_manualimport.isChecked(): self.warning_console.setText("Importing Assets using Dialog into Content Folder") imported_assets = assettools.import_assets_with_dialog(assetimportdata.destination_path) else: self.warning_console.setText("Importing Assets automatically into Content Folder") imported_assets = assettools.import_assets_automated(assetimportdata) self.warning_console.setText("{} are imported".format(imported_assets)) def exportselectedassets(self): """ Export Selected Assets """ # instances of unreal classes editorutility_lib = unreal.EditorUtilityLibrary() # create asset tools object assettools = unreal.AssetToolsHelpers.get_asset_tools() # get selected assets selected_assets = editorutility_lib.get_selected_assets() export_path = 'C://' if self.rb_manualexport.isChecked(): self.warning_console.setText("Exporting Assets using Dialog ") assettools.export_assets_with_dialog(selected_assets, prompt_for_individual_filenames=True) else: self.warning_console.setText("Exporting Assets automatically into Destination Folder") assettools.export_assets(selected_assets, export_path) # misc tools def materialinstancecreate(self): """ """ editorasset_lib = unreal.EditorAssetLibrary() material_parent = editorasset_lib.load_asset('') def multimaterialinstacer(self): """ Create multiple material instances for one or more materials """ # instances of unreal classes globaleditor = unreal.GlobalEditorUtilityBase matediting_lib = unreal.MaterialEditingLibrary editorutil_lib = unreal.EditorUtilityLibrary() new_asset_name = '' source_asset_path = '' created_asset_path = '' number_of_instances = self.sp_materialinstance.value() factory = unreal.MaterialInstanceConstantFactoryNew() asset_tools = unreal.AssetToolsHelpers.get_asset_tools() # get selected assets selected_assets = editorutil_lib.get_selected_assets() if not selected_assets: self.warning_console.setText("Select atleast one material") for selected_asset in selected_assets: if isinstance(selected_asset, unreal.Material): new_asset_name = selected_asset.get_name() + "_%s_%d" source_asset_path = selected_asset.get_path_name() created_asset_path = source_asset_path.replace(selected_asset.get_name(), "-") created_asset_path = created_asset_path.replace("-.-", "") for x in range (number_of_instances): new_asset = asset_tools.create_asset(new_asset_name %("inst", x+1), created_asset_path, None, factory) matediting_lib.set_material_instance_parent(new_asset, selected_asset) else: self.warning_console.setText("Select a material") def resizeEvent(self, event): """ Called on automatically generated resize event """ self.widget.resize(self.width(), self.height()) def closewindow(self): """ Close the window. """ self.destroy() def openwindow(): """ Create tool window. """ if QtWidgets.QApplication.instance(): # id any current instances of tool and destroy for win in (QtWidgets.QApplication.allWindows()): if 'toolWindow' in win.objectName(): # update this name to match name below win.destroy() else: QtWidgets.QApplication(sys.argv) # load UI into QApp instance UnrealWidget.window = UnrealWidget() UnrealWidget.window.show() UnrealWidget.window.setObjectName('toolWindow') # update this with something unique to your tool UnrealWidget.window.setWindowTitle('Quick Assistant : The Editor Toolkit') unreal.parent_external_window_to_slate(UnrealWidget.window.winId()) openwindow()
import unreal objs : list[object] = unreal.EditorLevelLibrary.get_selected_level_actors() print(objs) grid_num : int # UI Binded Value grid_cnt : int # UI Binded Value offset = 200 offset_vector = unreal.Vector(x=0.0, y=0.0, z=0.0) for obj in objs : current_location = obj.get_actor_location() new_loc = current_location + offset_vector if offset_vector.x >= offset * (grid_num - 1) : offset_vector = unreal.Vector(x=0.0, y=offset * grid_cnt, z=0.0) grid_cnt += 1 else : offset_vector += unreal.Vector(x=offset, y=0.0, z=0.0) obj.set_actor_location(new_loc, 0, 1) print(obj.get_actor_location())
import unreal selected_assets: list[unreal.Object] = unreal.EditorUtilityLibrary.get_selected_assets() loaded_subsystem = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem) selected_sm:unreal.SkeletalMesh = selected_assets[0] ## set data asset target_da_path = "/project/" destination_path_array = selected_sm.get_path_name().split('/') new_da_path = '/'.join(destination_path_array[:-1]) + '/DA_' + selected_sm.get_name() ## duplicate and save loaded_subsystem.duplicate_asset(target_da_path, new_da_path) loaded_subsystem.save_asset(new_da_path) print('data asset set done')
import unreal # '''BP setting end''' def make_NA(index): num = index BaseBP = '/project/' BaseAnimBP = '/project/' Basepath = '/project/' + str(num) + '/' assetPath = Basepath + '/project/' bsNames = ["IdleRun_BS_Peaceful", "IdleRun_BS_Battle", "Down_BS", "Groggy_BS", "LockOn_BS", "Airborne_BS"] #animNames = ['Result_State_KnockDown_L'] #애니메이션 리스트 지정 Base1D = Basepath + "Base_BS_1D" Base2D = Basepath + "Base_BS_2D" #공용 BlendSample 제작 defaultSamplingVector = unreal.Vector(0.0, 0.0, 0.0) defaultSampler = unreal.BlendSample() defaultSampler.set_editor_property("sample_value",defaultSamplingVector) for i in bsNames: bsDir = assetPath + i #2D BS로 제작해야할 경우 / LockOn_BS if i == "LockOn_BS": unreal.EditorAssetLibrary.duplicate_asset(Base2D,bsDir) else: BSLoaded = unreal.EditorAssetLibrary.duplicate_asset(Base1D,bsDir) '''BP setting start''' BPPath = Basepath + '/Blueprints/' + "CH_M_NA_" + str(num) + "_Blueprint" AnimBPPath = Basepath + '/Blueprints/' + "CH_M_NA_" + str(num) + "_AnimBP" SkeletonPath = Basepath + "CH_M_NA_" + str(num) + "_Skeleton" Skeleton = unreal.EditorAssetLibrary.load_asset(SkeletonPath) unreal.EditorAssetLibrary.duplicate_asset(BaseBP,BPPath) AnimBP = unreal.EditorAssetLibrary.duplicate_asset(BaseAnimBP,AnimBPPath) AnimBP.set_editor_property("target_skeleton", Skeleton)
# Copyright Epic Games, Inc. All Rights Reserved """ This script handles processing jobs for a specific sequence """ import unreal from getpass import getuser from .render_queue_jobs import render_jobs from .utils import ( movie_pipeline_queue, project_settings, get_asset_data ) def setup_sequence_parser(subparser): """ This method adds a custom execution function and args to a sequence subparser :param subparser: Subparser for processing custom sequences """ # We will use the level sequence and the map as our context for # other subsequence arguments. subparser.add_argument( "sequence", type=str, help="The level sequence that will be rendered." ) subparser.add_argument( "map", type=str, help="The map the level sequence will be loaded with for rendering.", ) # Get some information for the render queue subparser.add_argument( "mrq_preset", type=str, help="The MRQ preset used to render the current job.", ) # Function to process arguments subparser.set_defaults(func=_process_args) def render_current_sequence( sequence_name, sequence_map, mrq_preset, user=None, shots=None, is_remote=False, is_cmdline=False, remote_batch_name=None, remote_job_preset=None, executor_instance=None, output_dir_override=None, output_filename_override=None ): """ Renders a sequence with a map and mrq preset :param str sequence_name: Sequence to render :param str sequence_map: Map to load sequence :param str mrq_preset: MRQ preset for rendering sequence :param str user: Render user :param list shots: Shots to render :param bool is_remote: Flag to determine if the job should be executed remotely :param bool is_cmdline: Flag to determine if the render was executed via commandline :param str remote_batch_name: Remote render batch name :param str remote_job_preset: deadline job Preset Library :param executor_instance: Movie Pipeline executor Instance :param str output_dir_override: Movie Pipeline output directory override :param str output_filename_override: Movie Pipeline filename format override :return: MRQ executor """ # The queue subsystem behaves like a singleton so # clear all the jobs in the current queue. movie_pipeline_queue.delete_all_jobs() render_job = movie_pipeline_queue.allocate_new_job( unreal.SystemLibrary.conv_soft_class_path_to_soft_class_ref( project_settings.default_executor_job ) ) render_job.author = user or getuser() sequence_data_asset = get_asset_data(sequence_name, "LevelSequence") # Create a job in the queue unreal.log(f"Creating render job for `{sequence_data_asset.asset_name}`") render_job.job_name = sequence_data_asset.asset_name unreal.log( f"Setting the job sequence to `{sequence_data_asset.asset_name}`" ) render_job.sequence = sequence_data_asset.to_soft_object_path() map_data_asset = get_asset_data(sequence_map, "World") unreal.log(f"Setting the job map to `{map_data_asset.asset_name}`") render_job.map = map_data_asset.to_soft_object_path() mrq_preset_data_asset = get_asset_data( mrq_preset, "MoviePipelineMasterConfig" ) unreal.log( f"Setting the movie pipeline preset to `{mrq_preset_data_asset.asset_name}`" ) render_job.set_configuration(mrq_preset_data_asset.get_asset()) # MRQ added the ability to enable and disable jobs. Check to see is a job # is disabled and enable it. The assumption is we want to render this # particular job. # Note this try/except block is for backwards compatibility try: if not render_job.enabled: render_job.enabled = True except AttributeError: pass # If we have a shot list, iterate over the shots in the sequence # and disable anything that's not in the shot list. If no shot list is # provided render all the shots in the sequence if shots: for shot in render_job.shot_info: if shot.inner_name in shots or (shot.outer_name in shots): shot.enabled = True else: unreal.log_warning( f"Disabling shot `{shot.inner_name}` from current render job `{render_job.job_name}`" ) shot.enabled = False try: # Execute the render. This will execute the render based on whether # its remote or local executor = render_jobs( is_remote, remote_batch_name=remote_batch_name, remote_job_preset=remote_job_preset, is_cmdline=is_cmdline, executor_instance=executor_instance, output_dir_override=output_dir_override, output_filename_override=output_filename_override ) except Exception as err: unreal.log_error( f"An error occurred executing the render.\n\tError: {err}" ) raise return executor def _process_args(args): """ Function to process the arguments for the sequence subcommand :param args: Parsed Arguments from parser """ return render_current_sequence( args.sequence, args.map, args.mrq_preset, user=args.user, shots=args.shots, is_remote=args.remote, is_cmdline=args.cmdline, remote_batch_name=args.batch_name, remote_job_preset=args.deadline_job_preset, output_dir_override=args.output_override, output_filename_override=args.filename_override )
import unreal from Lib import __lib_topaz__ as topaz import importlib importlib.reload(topaz) assets = topaz.get_selected_assets() for selected in assets : if selected.__class__ == unreal.Blueprint: #print('Blueprint') comps = topaz.get_component_by_class(selected, unreal.StaticMeshComponent) comps.__len__() for i in comps : asset = i.static_mesh topaz.disable_ray_tracing(asset) print(str(asset) + ' : ray tracing disabled') elif selected.__class__ == unreal.StaticMesh: #print('static mesh') topaz.disable_ray_tracing(selected) print(str(selected) + ' : ray tracing disabled') else : print(str(selected) + 'is not static mesh or blueprint asset')
# -*- coding: utf-8 -*- import unreal import sys import pydoc import inspect import os import json from enum import IntFlag class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] def has_instance(cls): return cls in cls._instances def get_instance(cls): if cls in cls._instances: return cls._instances[cls] return None def cast(object_to_cast, object_class): try: return object_class.cast(object_to_cast) except: return None # short cut for print dir def d(obj, subString=''): subString = subString.lower() for x in dir(obj): if subString == '' or subString in x.lower(): print(x) def l(obj, subString='', bPrint = True): ''' 输出物体详细信息:函数、属性,editorProperty等,并以log形式输出 :param obj: Object实例或者类 :param subString: 过滤用字符串 :return: 无 ''' def _simplifyDoc(content): bracketS, bracketE = content.find('('), content.find(')') arrow = content.find('->') funcDocPos = len(content) endSign = ['--', '\n', '\r'] for s in endSign: p = content.find(s) if p != -1 and p < funcDocPos: funcDocPos = p funcDoc = content[:funcDocPos] param = content[bracketS + 1: bracketE].strip() return funcDoc, param def _getEditorProperties(content, obj): lines = content.split('\r') signFound = False allInfoFound = False result = [] for line in lines: if not signFound and '**Editor Properties:**' in line: signFound = True if signFound: #todo re nameS, nameE = line.find('``') + 2, line.find('`` ') if nameS == -1 or nameE == -1: continue typeS, typeE = line.find('(') + 1, line.find(')') if typeS == -1 or typeE == -1: continue rwS, rwE = line.find('[') + 1, line.find(']') if rwS == -1 or rwE == -1: continue name = line[nameS: nameE] type = line[typeS: typeE] rws = line[rwS: rwE] descript = line[rwE + 2:] allInfoFound = True result.append((name, type, rws, descript)) if signFound: if not allInfoFound: unreal.log_warning("not all info found {}".format(obj)) else: unreal.log_warning("can't find editor properties in {}".format(obj)) return result if obj == None: unreal.log_warning("obj == None") return None if inspect.ismodule(obj): return None ignoreList = ['__delattr__', '__getattribute__', '__hash__', '__init__', '__setattr__'] propertiesNames = [] builtinCallableNames = [] otherCallableNames = [] for x in dir(obj): if subString == '' or subString in x.lower(): attr = getattr(obj, x) if callable(attr): if inspect.isbuiltin(attr): # or inspect.isfunction(attr) or inspect.ismethod(attr): builtinCallableNames.append(x) else: # Not Built-in otherCallableNames.append(x) else: # Properties propertiesNames.append(x) # 1 otherCallables otherCallables = [] for name in otherCallableNames: descriptionStr = "" if name == "__doc__": resultStr = "ignored.." #doc太长,不输出 else: resultStr = "{}".format(getattr(obj, name)) otherCallables.append([name, (), descriptionStr, resultStr]) # 2 builtinCallables builtinCallables = [] for name in builtinCallableNames: attr = getattr(obj, name) descriptionStr = "" resultStr = "" bHasParameter = False if hasattr(attr, '__doc__'): docForDisplay, paramStr = _simplifyDoc(attr.__doc__) if paramStr == '': # Method with No params descriptionStr = docForDisplay[docForDisplay.find(')') + 1:] if '-> None' not in docForDisplay: resultStr = "{}".format(attr.__call__()) else: resultStr = 'skip call' else: # 有参函数 descriptionStr = paramStr bHasParameter = True resultStr = "" else: pass builtinCallables.append([name, (bHasParameter,), descriptionStr, resultStr]) # 3 properties editorPropertiesInfos = [] editorPropertiesNames = [] if hasattr(obj, '__doc__') and isinstance(obj, unreal.Object): editorPropertiesInfos = _getEditorProperties(obj.__doc__, obj) for name, _, _, _ in editorPropertiesInfos: editorPropertiesNames.append(name) properties = [] for name in propertiesNames: descriptionStr = "" if name == "__doc__": resultStr = "ignored.." #doc太长,不输出 else: try: resultStr = "{}".format(getattr(obj, name)) except: resultStr = "" isAlsoEditorProperty = name in editorPropertiesNames #是否同时是EditorProprty同时也是property properties.append([name, (isAlsoEditorProperty,), descriptionStr, resultStr]) # 4 editorProperties editorProperties = [] propertyAlsoEditorPropertyCount = 0 for info in editorPropertiesInfos: name, type, rw, descriptionStr = info if subString == '' or subString in name.lower(): #过滤掉不需要的 try: value = eval('obj.get_editor_property("{}")'.format(name)) except: value = "" descriptionStr = "[{}]".format(rw) resultStr = "{}".format(value) isAlsoProperty = name in propertiesNames if isAlsoProperty: propertyAlsoEditorPropertyCount += 1 editorProperties.append( [name, (isAlsoProperty,), descriptionStr, resultStr]) strs = [] strs.append("Detail: {}".format(obj)) formatWidth = 70 for info in otherCallables: name, flags, descriptionStr, resultStr = info # line = "\t{} {}{}{}".format(name, descriptionStr, " " *(formatWidth -1 - len(name) - len(descriptionStr)), resultStr) line = "\t{} {}".format(name, descriptionStr) line += "{}{}".format(" " * (formatWidth-len(line)+1-4), resultStr) strs.append(line) for info in builtinCallables: name, flags, descriptionStr, resultStr = info if flags[0]: # 有参函数 # line = "\t{}({}) {} {}".format(name, descriptionStr, " " * (formatWidth - 5 - len(name) - len(descriptionStr)), resultStr) line = "\t{}({})".format(name, descriptionStr) line += "{}{}".format(" " * (formatWidth-len(line)+1-4), resultStr) else: # line = "\t{}() {} |{}| {}".format(name, descriptionStr, "-" * (formatWidth - 7 - len(name) - len(descriptionStr)), resultStr) line = "\t{}() {}".format(name, descriptionStr) line += "|{}| {}".format("-" * (formatWidth-len(line)+1-4-3), resultStr) strs.append(line) for info in properties: name, flags, descriptionStr, resultStr = info sign = "**" if flags[0] else "" # line = "\t\t{} {} {}{}{}".format(name, sign, descriptionStr, " " * (formatWidth - 6 - len(name) -len(sign) - len(descriptionStr)), resultStr) line = "\t\t{} {} {}".format(name, sign, descriptionStr) line += "{}{}".format(" " * (formatWidth-len(line)+2-8), resultStr) strs.append(line) strs.append("Special Editor Properties:") for info in editorProperties: name, flags, descriptionStr, resultStr = info if flags[0]: pass # 已经输出过跳过 else: sign = "*" # line = "\t\t{0} {1} {3}{4} {2}".format(name, sign, descriptionStr, " " * (formatWidth - 3 - len(name) -len(sign) ), resultStr) #descriptionStr 中是[rw]放到最后显示 line = "\t\t{} {}".format(name, sign) line += "{}{} {}".format(" " * (formatWidth-len(line)+2-8), resultStr, descriptionStr) # descriptionStr 中是[rw]放到最后显示 strs.append(line) if bPrint: for l in strs: print(l) print("'*':Editor Property, '**':Editor Property also object attribute.") print("{}: matched, builtinCallable: {} otherCallables: {} prop: {} EditorProps: {} both: {}".format(obj , len(builtinCallables), len(otherCallables), len(properties), len(editorProperties), propertyAlsoEditorPropertyCount)) return otherCallables, builtinCallables, properties, editorProperties # short cut for print type def t(obj): print(type(obj)) # unreal type to Python dict def ToJson(v): tp = type(v) if tp == unreal.Transform: result = {'translation': ToJson(v.translation), 'rotation': ToJson(v.rotation), 'scale3d': ToJson(v.scale3d)} return result elif tp == unreal.Vector: return {'x': v.x, 'y': v.y, 'z': v.z} elif tp == unreal.Quat: return {'x': v.x, 'y': v.y, 'z': v.z, 'w': v.w} else: print("Error type: " + str(tp) + " not implemented.") return None def get_selected_comps(): return unreal.PythonBPLib.get_selected_components() def get_selected_comp(): comps = unreal.PythonBPLib.get_selected_components() return comps[0] if len(comps) > 0 else None def get_selected_asset(): selected = unreal.PythonBPLib.get_selected_assets_paths() if selected: return unreal.load_asset(unreal.PythonBPLib.get_selected_assets_paths()[0]) else: return None def get_selected_assets(): assets = [] for path in unreal.PythonBPLib.get_selected_assets_paths(): asset = unreal.load_asset(path) if (asset != None): assets.append(asset) return assets def get_selected_actors(): return unreal.get_editor_subsystem(unreal.EditorActorSubsystem).get_selected_level_actors() def get_selected_actor(): actors = unreal.get_editor_subsystem(unreal.EditorActorSubsystem).get_selected_level_actors() return actors[0] if len(actors) > 0 else None def set_preview_es31(): unreal.PythonBPLib.set_preview_platform("GLSL_ES3_1_ANDROID", "ES3_1") def set_preview_sm5(): unreal.PythonBPLib.set_preview_platform("", "SM5") # todo: create export tools for create help/dir to file def export_dir(filepath, cls): f = open(filepath, 'w') sys.stdout = f for x in sorted(dir(cls)): print(x) sys.stdout = sys.__stdout__ f.close() def export_help(filepath, cls): f = open(filepath, 'w') sys.stdout = f pydoc.help(cls) sys.stdout = sys.__stdout__ f.close() # 修改site.py 文件中的Encoding def set_default_encoding(encodingStr): pythonPath = os.path.dirname(sys.path[0]) if not os.path.exists(pythonPath): unreal.PythonBPLib.message_dialog("can't find python folder: {}".format(pythonPath), "Warning") return sitePyPath = pythonPath + "/project/.py" if not os.path.exists(sitePyPath): unreal.PythonBPLib.message_dialog("can't find site.py: {}".format(sitePyPath), "Warning") return #简单查找字符串替换 with open(sitePyPath, "r") as f: lines = f.readlines() startLine = -1 endLine = -1 for i in range(len(lines)): if startLine == -1 and lines[i][:len('def setencoding():')] == 'def setencoding():': startLine = i continue if endLine == -1 and startLine > -1 and lines[i].startswith('def '): endLine = i print("startLine: {} endLine: {}".format(startLine, endLine)) changedLineCount = 0 if -1 < startLine and startLine < endLine: linePosWithIf = [] for i in range(startLine + 1, endLine): if lines[i].lstrip().startswith('if '): linePosWithIf.append(i) print(lines[i]) if len(linePosWithIf) != 4: unreal.PythonBPLib.message_dialog("Find pos failed: {}".format(sitePyPath), "Warning") print(linePosWithIf) return lines[linePosWithIf[2]] = lines[linePosWithIf[2]].replace("if 0", "if 1") # 简单修改第三个if所在行的内容 changedLineCount += 1 for i in range(linePosWithIf[2] + 1, linePosWithIf[3]): line = lines[i] if "encoding=" in line.replace(" ", ""): s = line.find('"') e = line.find('"', s+1) if s > 0 and e > s: lines[i] = line[:s+1] + encodingStr + line[e:] changedLineCount += 1 break if changedLineCount == 2: with open(sitePyPath, 'w') as f: f.writelines(lines) unreal.PythonBPLib.notification("Success: {}".format(sitePyPath), 0) currentEncoding = sys.getdefaultencoding() if currentEncoding == encodingStr: unreal.PythonBPLib.notification("已将default encoding设置为{}".format(currentEncoding), 0) else: unreal.PythonBPLib.message_dialog("已将default encoding设置为{},需要重启编辑器以便生效".format(encodingStr), "Warning") else: unreal.PythonBPLib.message_dialog("Find content failed: {}".format(sitePyPath), "Warning") def get_actors_at_location(location, error_tolerance): allActors = unreal.get_editor_subsystem(unreal.EditorActorSubsystem).get_selected_level_actors() result = [_actor for _actor in allActors if _actor.get_actor_location().is_near_equal(location, error_tolerance)] return result def select_actors_at_location(location, error_tolerance, actorTypes=None): actors = get_actors_at_location(location, error_tolerance) if len(actors) > 1: print("Total {} actor(s) with the same locations.".format(len(actors))) if actorTypes is not None: actors = [actor for actor in actors if type(actor) in actorTypes] unreal.get_editor_subsystem(unreal.EditorActorSubsystem).set_selected_level_actors(actors) return actors else: print("None actor with the same locations.") return [] def select_actors_with_same_location(actor, error_tolerance): if actor is not None: actors = select_actors_at_location(actor.get_actor_location(), error_tolerance, [unreal.StaticMeshActor, unreal.SkeletalMeshActor]) return actors else: print("actor is None.") return [] def get_chameleon_tool_instance(json_name): found_count = 0 result = None for var in globals(): if hasattr(var, "jsonPath") and hasattr(var, "data"): if isinstance(var.data, unreal.ChameleonData): if var.jsonPath.endswith(json_name): found_count += 1 result = var if found_count == 1: return result if found_count > 1: unreal.log_warning(f"Found Multi-ToolsInstance by name: {json_name}, count: {found_count}") return None # # Flags describing an object instance # class EObjectFlags(IntFlag): # Do not add new flags unless they truly belong here. There are alternatives. # if you change any the bit of any of the RF_Load flags, then you will need legacy serialization RF_NoFlags = 0x00000000, #< No flags, used to avoid a cast # This first group of flags mostly has to do with what kind of object it is. Other than transient, these are the persistent object flags. # The garbage collector also tends to look at these. RF_Public =0x00000001, #< Object is visible outside its package. RF_Standalone =0x00000002, #< Keep object around for editing even if unreferenced. RF_MarkAsNative =0x00000004, #< Object (UField) will be marked as native on construction (DO NOT USE THIS FLAG in HasAnyFlags() etc) RF_Transactional =0x00000008, #< Object is transactional. RF_ClassDefaultObject =0x00000010, #< This object is its class's default object RF_ArchetypeObject =0x00000020, #< This object is a template for another object - treat like a class default object RF_Transient =0x00000040, #< Don't save object. # This group of flags is primarily concerned with garbage collection. RF_MarkAsRootSet =0x00000080, #< Object will be marked as root set on construction and not be garbage collected, even if unreferenced (DO NOT USE THIS FLAG in HasAnyFlags() etc) RF_TagGarbageTemp =0x00000100, #< This is a temp user flag for various utilities that need to use the garbage collector. The garbage collector itself does not interpret it. # The group of flags tracks the stages of the lifetime of a uobject RF_NeedInitialization =0x00000200, #< This object has not completed its initialization process. Cleared when ~FObjectInitializer completes RF_NeedLoad =0x00000400, #< During load, indicates object needs loading. RF_KeepForCooker =0x00000800, #< Keep this object during garbage collection because it's still being used by the cooker RF_NeedPostLoad =0x00001000, #< Object needs to be postloaded. RF_NeedPostLoadSubobjects =0x00002000, #< During load, indicates that the object still needs to instance subobjects and fixup serialized component references RF_NewerVersionExists =0x00004000, #< Object has been consigned to oblivion due to its owner package being reloaded, and a newer version currently exists RF_BeginDestroyed =0x00008000, #< BeginDestroy has been called on the object. RF_FinishDestroyed =0x00010000, #< FinishDestroy has been called on the object. # Misc. Flags RF_BeingRegenerated =0x00020000, #< Flagged on UObjects that are used to create UClasses (e.g. Blueprints) while they are regenerating their UClass on load (See FLinkerLoad::CreateExport()), as well as UClass objects in the midst of being created RF_DefaultSubObject =0x00040000, #< Flagged on subobjects that are defaults RF_WasLoaded =0x00080000, #< Flagged on UObjects that were loaded RF_TextExportTransient =0x00100000, #< Do not export object to text form (e.g. copy/paste). Generally used for sub-objects that can be regenerated from data in their parent object. RF_LoadCompleted =0x00200000, #< Object has been completely serialized by linkerload at least once. DO NOT USE THIS FLAG, It should be replaced with RF_WasLoaded. RF_InheritableComponentTemplate = 0x00400000, #< Archetype of the object can be in its super class RF_DuplicateTransient =0x00800000, #< Object should not be included in any type of duplication (copy/paste, binary duplication, etc.) RF_StrongRefOnFrame =0x01000000, #< References to this object from persistent function frame are handled as strong ones. RF_NonPIEDuplicateTransient =0x02000000, #< Object should not be included for duplication unless it's being duplicated for a PIE session RF_Dynamic =0x04000000, #< Field Only. Dynamic field. UE_DEPRECATED(5.0, "RF_Dynamic should no longer be used. It is no longer being set by engine code.") - doesn't get constructed during static initialization, can be constructed multiple times # @todo: BP2CPP_remove RF_WillBeLoaded =0x08000000, #< This object was constructed during load and will be loaded shortly RF_HasExternalPackage =0x10000000, #< This object has an external package assigned and should look it up when getting the outermost package # RF_Garbage and RF_PendingKill are mirrored in EInternalObjectFlags because checking the internal flags is much faster for the Garbage Collector # while checking the object flags is much faster outside of it where the Object pointer is already available and most likely cached. # RF_PendingKill is mirrored in EInternalObjectFlags because checking the internal flags is much faster for the Garbage Collector # while checking the object flags is much faster outside of it where the Object pointer is already available and most likely cached. RF_PendingKill = 0x20000000, #< Objects that are pending destruction (invalid for gameplay but valid objects). UE_DEPRECATED(5.0, "RF_PendingKill should not be used directly. Make sure references to objects are released using one of the existing engine callbacks or use weak object pointers.") This flag is mirrored in EInternalObjectFlags as PendingKill for performance RF_Garbage =0x40000000, #< Garbage from logical point of view and should not be referenced. UE_DEPRECATED(5.0, "RF_Garbage should not be used directly. Use MarkAsGarbage and ClearGarbage instead.") This flag is mirrored in EInternalObjectFlags as Garbage for performance RF_AllocatedInSharedPage =0x80000000, #< Allocated from a ref-counted page shared with other UObjects class EMaterialValueType(IntFlag): MCT_Float1 = 1, MCT_Float2 = 2, MCT_Float3 = 4, MCT_Float4 = 8, MCT_Texture2D = 1 << 4, MCT_TextureCube = 1 << 5, MCT_Texture2DArray = 1 << 6, MCT_TextureCubeArray = 1 << 7, MCT_VolumeTexture = 1 << 8, MCT_StaticBool = 1 << 9, MCT_Unknown = 1 << 10, MCT_MaterialAttributes = 1 << 11, MCT_TextureExternal = 1 << 12, MCT_TextureVirtual = 1 << 13, MCT_VTPageTableResult = 1 << 14, MCT_ShadingModel = 1 << 15, MCT_Strata = 1 << 16, MCT_LWCScalar = 1 << 17, MCT_LWCVector2 = 1 << 18, MCT_LWCVector3 = 1 << 19, MCT_LWCVector4 = 1 << 20, MCT_Execution = 1 << 21, MCT_VoidStatement = 1 << 22, def guess_instance_name(json_file_path): try: with open(json_file_path, 'r', encoding='utf-8') as f: py_cmd = json.load(f).get("InitPyCmd", "") print(next(line[:line.find('=')].strip() for line in py_cmd.split(";") if "%jsonpath" in line.lower())) except (FileNotFoundError, KeyError) as e: print(f"guess_instance_name failed: {e}")
#!/project/ python3 # -*- coding: utf-8 -*- """ Terminal Grounds - Metro Underground Performance Validation Framework Unreal Engine 5.6 Performance Testing and Optimization This script validates and optimizes the Metro Underground level for 60+ FPS performance targets with comprehensive testing protocols. """ import unreal import json import time from dataclasses import dataclass from typing import List, Dict, Any @dataclass class PerformanceTarget: """Performance targets for Terminal Grounds Phase 1""" target_fps: float = 60.0 frame_time_budget_ms: float = 16.67 max_draw_calls: int = 800 max_triangle_count: int = 150000 max_texture_memory_mb: int = 512 max_static_mesh_actors: int = 200 @dataclass class PerformanceMetrics: """Current performance metrics""" current_fps: float = 0.0 frame_time_ms: float = 0.0 draw_calls: int = 0 triangle_count: int = 0 texture_memory_mb: int = 0 static_mesh_count: int = 0 light_count: int = 0 actor_count: int = 0 class TGPerformanceValidator: def __init__(self): self.targets = PerformanceTarget() self.metrics = PerformanceMetrics() self.world = None self.validation_results = {} def initialize(self): """Initialize performance validation system""" self.world = unreal.EditorLevelLibrary.get_editor_world() if not self.world: print("ERROR: No valid world found!") return False print("Performance Validator Initialized") print(f"Target FPS: {self.targets.target_fps}") print(f"Frame Time Budget: {self.targets.frame_time_budget_ms}ms") return True def collect_performance_metrics(self): """Collect current level performance metrics""" print("Collecting performance metrics...") # Get all actors in level all_actors = unreal.EditorLevelLibrary.get_all_level_actors() self.metrics.actor_count = len(all_actors) # Count specific actor types static_mesh_actors = [] light_actors = [] total_triangles = 0 for actor in all_actors: if isinstance(actor, unreal.StaticMeshActor): static_mesh_actors.append(actor) # Get triangle count from static mesh mesh_component = actor.get_component_by_class(unreal.StaticMeshComponent) if mesh_component and mesh_component.get_static_mesh(): static_mesh = mesh_component.get_static_mesh() # Approximate triangle count (UE5 doesn't expose exact count easily) total_triangles += 1000 # Placeholder - would need proper implementation elif isinstance(actor, (unreal.Light, unreal.PointLight, unreal.SpotLight, unreal.DirectionalLight)): light_actors.append(actor) self.metrics.static_mesh_count = len(static_mesh_actors) self.metrics.light_count = len(light_actors) self.metrics.triangle_count = total_triangles print(f"Total Actors: {self.metrics.actor_count}") print(f"Static Mesh Actors: {self.metrics.static_mesh_count}") print(f"Light Actors: {self.metrics.light_count}") print(f"Estimated Triangles: {self.metrics.triangle_count}") return self.metrics def validate_geometry_complexity(self): """Validate geometry complexity for performance""" print("\nValidating Geometry Complexity...") results = { 'status': 'PASS', 'issues': [], 'recommendations': [] } # Check triangle count if self.metrics.triangle_count > self.targets.max_triangle_count: results['status'] = 'FAIL' results['issues'].append(f"Triangle count ({self.metrics.triangle_count}) exceeds target ({self.targets.max_triangle_count})") results['recommendations'].append("Consider LOD implementation or mesh optimization") # Check static mesh count if self.metrics.static_mesh_count > self.targets.max_static_mesh_actors: results['status'] = 'WARNING' results['issues'].append(f"Static mesh count ({self.metrics.static_mesh_count}) near limit ({self.targets.max_static_mesh_actors})") results['recommendations'].append("Consider instanced static meshes for repeated elements") print(f"Geometry Complexity: {results['status']}") for issue in results['issues']: print(f" - {issue}") return results def validate_lighting_performance(self): """Validate lighting setup for performance""" print("\nValidating Lighting Performance...") results = { 'status': 'PASS', 'issues': [], 'recommendations': [] } # Get all lights all_actors = unreal.EditorLevelLibrary.get_all_level_actors() dynamic_lights = [] shadow_casting_lights = [] for actor in all_actors: if isinstance(actor, unreal.PointLight): dynamic_lights.append(actor) light_component = actor.get_component_by_class(unreal.PointLightComponent) if light_component and light_component.get_cast_shadows(): shadow_casting_lights.append(actor) elif isinstance(actor, unreal.SpotLight): dynamic_lights.append(actor) light_component = actor.get_component_by_class(unreal.SpotLightComponent) if light_component and light_component.get_cast_shadows(): shadow_casting_lights.append(actor) # Validate dynamic light count max_dynamic_lights = 12 # Conservative limit for good performance if len(dynamic_lights) > max_dynamic_lights: results['status'] = 'WARNING' results['issues'].append(f"Dynamic lights ({len(dynamic_lights)}) may impact performance") results['recommendations'].append("Consider baking lighting or reducing dynamic light count") # Validate shadow-casting lights max_shadow_lights = 4 # Very conservative for good performance if len(shadow_casting_lights) > max_shadow_lights: results['status'] = 'WARNING' results['issues'].append(f"Shadow-casting lights ({len(shadow_casting_lights)}) may impact performance") results['recommendations'].append("Disable shadows on non-essential lights") print(f"Lighting Performance: {results['status']}") print(f" Dynamic Lights: {len(dynamic_lights)}") print(f" Shadow-Casting Lights: {len(shadow_casting_lights)}") for issue in results['issues']: print(f" - {issue}") return results def validate_level_streaming(self): """Validate level streaming and occlusion setup""" print("\nValidating Level Streaming...") results = { 'status': 'PASS', 'issues': [], 'recommendations': [] } # Check for nav mesh bounds nav_bounds = [] all_actors = unreal.EditorLevelLibrary.get_all_level_actors() for actor in all_actors: if isinstance(actor, unreal.NavMeshBoundsVolume): nav_bounds.append(actor) if not nav_bounds: results['status'] = 'WARNING' results['issues'].append("No NavMeshBoundsVolume found") results['recommendations'].append("Add NavMeshBoundsVolume for AI pathfinding") # Check level bounds - ensure not too large level_bounds = self.calculate_level_bounds() max_level_size = 8000 # 8000 units max recommended if level_bounds['size'] > max_level_size: results['status'] = 'WARNING' results['issues'].append(f"Level size ({level_bounds['size']:.0f}) is large - may impact streaming") results['recommendations'].append("Consider level streaming or sub-level division") print(f"Level Streaming: {results['status']}") print(f" Level Size: {level_bounds['size']:.0f} units") print(f" Nav Mesh Volumes: {len(nav_bounds)}") return results def calculate_level_bounds(self): """Calculate the bounds of the level""" all_actors = unreal.EditorLevelLibrary.get_all_level_actors() min_x = min_y = min_z = float('inf') max_x = max_y = max_z = float('-inf') for actor in all_actors: if isinstance(actor, (unreal.StaticMeshActor, unreal.Brush)): location = actor.get_actor_location() min_x = min(min_x, location.x) max_x = max(max_x, location.x) min_y = min(min_y, location.y) max_y = max(max_y, location.y) min_z = min(min_z, location.z) max_z = max(max_z, location.z) size_x = max_x - min_x size_y = max_y - min_y size_z = max_z - min_z size = max(size_x, size_y) # Use largest horizontal dimension return { 'min': {'x': min_x, 'y': min_y, 'z': min_z}, 'max': {'x': max_x, 'y': max_y, 'z': max_z}, 'size': size } def validate_gameplay_elements(self): """Validate gameplay elements for proper setup""" print("\nValidating Gameplay Elements...") results = { 'status': 'PASS', 'issues': [], 'recommendations': [] } all_actors = unreal.EditorLevelLibrary.get_all_level_actors() # Count spawn points spawn_points = [actor for actor in all_actors if isinstance(actor, unreal.PlayerStart)] if len(spawn_points) < 8: results['status'] = 'WARNING' results['issues'].append(f"Only {len(spawn_points)} spawn points found - recommend 8+ for full gameplay") results['recommendations'].append("Add more PlayerStart actors for 8-player support") # Validate spawn point spacing spawn_positions = [] for spawn in spawn_points: pos = spawn.get_actor_location() spawn_positions.append((pos.x, pos.y, pos.z)) # Check for spawn point clustering (too close together) min_spawn_distance = 400 # Minimum distance between spawns clustered_spawns = [] for i, pos1 in enumerate(spawn_positions): for j, pos2 in enumerate(spawn_positions[i+1:], i+1): distance = ((pos1[0] - pos2[0])**2 + (pos1[1] - pos2[1])**2)**0.5 if distance < min_spawn_distance: clustered_spawns.append((i, j)) if clustered_spawns: results['status'] = 'WARNING' results['issues'].append(f"Found {len(clustered_spawns)} spawn point pairs too close together") results['recommendations'].append("Increase spacing between spawn points to prevent spawn camping") print(f"Gameplay Elements: {results['status']}") print(f" Spawn Points: {len(spawn_points)}") return results def run_comprehensive_validation(self): """Run complete performance validation suite""" print("="*60) print("TERMINAL GROUNDS - METRO UNDERGROUND PERFORMANCE VALIDATION") print("="*60) if not self.initialize(): return False # Collect metrics self.collect_performance_metrics() # Run all validation tests validation_results = { 'geometry': self.validate_geometry_complexity(), 'lighting': self.validate_lighting_performance(), 'streaming': self.validate_level_streaming(), 'gameplay': self.validate_gameplay_elements() } # Generate overall status overall_status = self.determine_overall_status(validation_results) # Generate recommendations recommendations = self.generate_optimization_recommendations(validation_results) # Output final report self.generate_validation_report(validation_results, overall_status, recommendations) return True def determine_overall_status(self, validation_results): """Determine overall validation status""" statuses = [result['status'] for result in validation_results.values()] if 'FAIL' in statuses: return 'FAIL' elif 'WARNING' in statuses: return 'WARNING' else: return 'PASS' def generate_optimization_recommendations(self, validation_results): """Generate optimization recommendations""" all_recommendations = [] for category, results in validation_results.items(): all_recommendations.extend(results['recommendations']) # Add general performance recommendations general_recommendations = [ "Enable Nanite virtualized geometry for detailed meshes", "Use Lumen for global illumination instead of baked lighting", "Implement World Partition for large levels (if needed in future)", "Consider Chaos Physics optimization for destructible elements", "Use instanced static meshes for repeated elements (columns, lights)", "Implement texture streaming for distant objects", "Add LOD models for complex static meshes", "Use impostor sprites for distant background elements" ] return list(set(all_recommendations + general_recommendations)) def generate_validation_report(self, validation_results, overall_status, recommendations): """Generate comprehensive validation report""" print("\n" + "="*60) print("PERFORMANCE VALIDATION REPORT") print("="*60) print(f"\nOVERALL STATUS: {overall_status}") if overall_status == 'PASS': print("✓ Level meets performance targets for Phase 1 deployment") elif overall_status == 'WARNING': print("⚠ Level has performance concerns but is playable") else: print("✗ Level fails performance requirements - optimization needed") print(f"\nLEVEL METRICS:") print(f" Total Actors: {self.metrics.actor_count}") print(f" Static Meshes: {self.metrics.static_mesh_count}") print(f" Lights: {self.metrics.light_count}") print(f" Estimated Triangles: {self.metrics.triangle_count:,}") print(f"\nPERFORMACE TARGETS:") print(f" Target FPS: {self.targets.target_fps}") print(f" Frame Time Budget: {self.targets.frame_time_budget_ms}ms") print(f" Max Draw Calls: {self.targets.max_draw_calls:,}") print(f" Max Triangles: {self.targets.max_triangle_count:,}") print(f"\nVALIDATION RESULTS:") for category, results in validation_results.items(): print(f" {category.title()}: {results['status']}") for issue in results['issues']: print(f" - {issue}") print(f"\nOPTIMIZATION RECOMMENDATIONS:") for i, recommendation in enumerate(recommendations, 1): print(f" {i}. {recommendation}") print(f"\nNEXT STEPS:") if overall_status == 'PASS': print(" 1. Proceed with gameplay testing") print(" 2. Integrate AI-generated assets") print(" 3. Begin Phase 2 development") elif overall_status == 'WARNING': print(" 1. Address high-priority performance warnings") print(" 2. Conduct performance profiling") print(" 3. Re-validate before deployment") else: print(" 1. CRITICAL: Address all performance failures") print(" 2. Re-run validation after optimization") print(" 3. Consider level redesign if issues persist") # Save report to file report_data = { 'overall_status': overall_status, 'metrics': { 'actor_count': self.metrics.actor_count, 'static_mesh_count': self.metrics.static_mesh_count, 'light_count': self.metrics.light_count, 'triangle_count': self.metrics.triangle_count }, 'validation_results': validation_results, 'recommendations': recommendations } with open('TG_MetroUnderground_Performance_Report.json', 'w') as f: json.dump(report_data, f, indent=2) print(f"\nReport saved: TG_MetroUnderground_Performance_Report.json") print("="*60) def apply_automatic_optimizations(self): """Apply automatic performance optimizations""" print("Applying automatic optimizations...") all_actors = unreal.EditorLevelLibrary.get_all_level_actors() optimized_count = 0 # Optimize lighting for actor in all_actors: if isinstance(actor, unreal.PointLight): light_component = actor.get_component_by_class(unreal.PointLightComponent) if light_component: # Disable shadows on emergency lights (performance optimization) if "Emergency" in actor.get_actor_label(): light_component.set_cast_shadows(False) optimized_count += 1 # Optimize static meshes for actor in all_actors: if isinstance(actor, unreal.StaticMeshActor): mesh_component = actor.get_component_by_class(unreal.StaticMeshComponent) if mesh_component: # Enable distance culling for small objects if "Column" in actor.get_actor_label(): mesh_component.set_visibility_based_anim_tick_option(unreal.VisibilityBasedAnimTickOption.ONLY_TICK_POSE_WHEN_RENDERED) optimized_count += 1 print(f"Applied {optimized_count} automatic optimizations") return optimized_count def run_performance_validation(): """Main execution function for performance validation""" validator = TGPerformanceValidator() return validator.run_comprehensive_validation() def apply_optimizations(): """Apply automatic optimizations""" validator = TGPerformanceValidator() validator.initialize() return validator.apply_automatic_optimizations() # Execute if run directly if __name__ == "__main__": run_performance_validation()
# _ # (_) # _ __ ___ __ _ _ __ ___ ___ _ __ _ ___ _ __ ___ # | '_ ` _ \ / _` | '_ ` _ \ / _ \| '_ \| |/ _ \ '_ ` _ \ # | | | | | | (_| | | | | | | (_) | | | | | __/ | | | | | # |_| |_| |_|\__,_|_| |_| |_|\___/|_| |_|_|\___|_| |_| |_| # www.mamoniem.com # www.ue4u.xyz #Copyright 2022 Muhammad A.Moniem (@_mamoniem). All Rights Reserved. # import unreal @unreal.uclass() class GetEditorUtility(unreal.GlobalEditorUtilityBase): pass @unreal.uclass() class GetAnimationLibrary(unreal.AnimationLibrary): pass editorUtility = GetEditorUtility() animLib = GetAnimationLibrary() selectedAssets = editorUtility.get_selected_assets() for selectedAsset in selectedAssets: selectedAsset.modify(True) animLib.remove_all_animation_notify_tracks(selectedAsset)
''' File: Author: Date: Description: Other Notes: ''' import time import unreal unreal.SystemLibrary.execute_console_command(unreal.EditorLevelLibrary.get_editor_world(), "HighResShot 2") # unreal.EditorLoadingAndSavingUtils.flush_async_loading() # editor_util = unreal.AnalyticsLibrary() # editor_util.flush_events() # unreal.AsyncDelayComplete() # unreal.EditorTick().tick(unreal.EditorLevelLibrary, 0.0) # editor = unreal.EditorLoadingAndSavingUtils # editor.save_dirty_packages(True, True) unreal.SystemLibrary.execute_console_command(unreal.EditorLevelLibrary.get_editor_world(), "HighResShot 2")
import unreal import os import subprocess def openCodeFolder(): pythondir = os.path.join(unreal.SystemLibrary.get_project_directory(), os.pardir, 'PythonCode') print(pythondir) #subprocess.Popen(r'explorer /select, os.path.join(unreal.SystemLibrary.get_project_directory(), os.pardir, 'PythonCode')') os.popen(pythondir) print('Completed') #subprocess.Popen(r'explorer /select, "E:"') #subprocess.Popen(r'explorer /select,"/project/"') subprocess.run(['explorer', os.path.realpath(pythondir)]) openCodeFolder()
# Copyright (c) <2021> Side Effects Software Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. The name of Side Effects Software may not be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN # NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unreal """ Example script for instantiating an asset, cooking it and baking all of its outputs. """ _g_wrapper = None def get_test_hda_path(): return '/project/.pig_head_subdivider_v01' def get_test_hda(): return unreal.load_object(None, get_test_hda_path()) def on_post_instantiation(in_wrapper): print('on_post_instantiation') # in_wrapper.on_post_instantiation_state_exited_delegate_delegate.remove_callable(on_post_instantiation) # Set parameter values for the next cook # in_wrapper.set_bool_parameter_value('add_instances', True) # in_wrapper.set_int_parameter_value('num_instances', 8) in_wrapper.set_parameter_tuples({ 'add_instances': unreal.HoudiniParameterTuple(bool_values=(True, )), 'num_instances': unreal.HoudiniParameterTuple(int32_values=(8, )), }) # Print all parameter values param_tuples = in_wrapper.get_parameter_tuples() print('parameter tuples: {}'.format(len(param_tuples) if param_tuples else 0)) if param_tuples: for param_tuple_name, param_tuple in param_tuples.items(): print('parameter tuple name: {}'.format(param_tuple_name)) print('\tbool_values: {}'.format(param_tuple.bool_values)) print('\tfloat_values: {}'.format(param_tuple.float_values)) print('\tint32_values: {}'.format(param_tuple.int32_values)) print('\tstring_values: {}'.format(param_tuple.string_values)) # Force a cook/recook in_wrapper.recook() def on_post_bake(in_wrapper, success): in_wrapper.on_post_bake_delegate.remove_callable(on_post_bake) print('bake complete ... {}'.format('success' if success else 'failed')) # Delete the hda after the bake in_wrapper.delete_instantiated_asset() global _g_wrapper _g_wrapper = None def on_post_process(in_wrapper): print('on_post_process') # in_wrapper.on_post_processing_delegate.remove_callable(on_post_process) # Print out all outputs generated by the HDA num_outputs = in_wrapper.get_num_outputs() print('num_outputs: {}'.format(num_outputs)) if num_outputs > 0: for output_idx in range(num_outputs): identifiers = in_wrapper.get_output_identifiers_at(output_idx) print('\toutput index: {}'.format(output_idx)) print('\toutput type: {}'.format(in_wrapper.get_output_type_at(output_idx))) print('\tnum_output_objects: {}'.format(len(identifiers))) if identifiers: for identifier in identifiers: output_object = in_wrapper.get_output_object_at(output_idx, identifier) output_component = in_wrapper.get_output_component_at(output_idx, identifier) is_proxy = in_wrapper.is_output_current_proxy_at(output_idx, identifier) print('\t\tidentifier: {}'.format(identifier)) print('\t\toutput_object: {}'.format(output_object.get_name() if output_object else 'None')) print('\t\toutput_component: {}'.format(output_component.get_name() if output_component else 'None')) print('\t\tis_proxy: {}'.format(is_proxy)) print('') # bind to the post bake delegate in_wrapper.on_post_bake_delegate.add_callable(on_post_bake) # Bake all outputs to actors print('baking all outputs to actors') in_wrapper.bake_all_outputs_with_settings( unreal.HoudiniEngineBakeOption.TO_ACTOR, replace_previous_bake=False, remove_temp_outputs_on_success=False) def run(): # get the API singleton api = unreal.HoudiniPublicAPIBlueprintLib.get_api() global _g_wrapper # instantiate an asset, disabling auto-cook of the asset (so we have to # call wrapper.reCook() to cook it) _g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform(), enable_auto_cook=False) # Bind to the on post instantiation delegate (before the first cook) _g_wrapper.on_post_instantiation_delegate.add_callable(on_post_instantiation) # Bind to the on post processing delegate (after a cook and after all # outputs have been generated in Unreal) _g_wrapper.on_post_processing_delegate.add_callable(on_post_process) if __name__ == '__main__': run()
import unreal import os def remove_unused(bool_value): # instances of unreal classes editor_util = unreal.EditorUtilityLibrary() editor_asset_lib = unreal.EditorAssetLibrary() # get the selected assets selected_assets = editor_util.get_selected_assets() num_assets = len(selected_assets) removed = 0 # instantly delete assets or move to Trash folder instant_delete = bool_value trash_folder = os.path.join(os.sep, "Game", "Trash") to_be_deleted = [] for asset in selected_assets: asset_name = asset.get_fname() asset_path = editor_asset_lib.get_path_name_for_loaded_asset(asset) # get a list of reference for this asset asset_references = editor_asset_lib.find_package_referencers_for_asset(asset_path) if len(asset_references) == 0: to_be_deleted.append(asset) for asset in to_be_deleted: asset_name = asset.get_fname() # instant delete if instant_delete: deleted = editor_asset_lib.delete_loaded_asset(asset) if not deleted: unreal.log_warning("Asset {} could not be deleted".format(asset_name)) continue removed += 1 # move the assets to the trash folder else: new_path = os.path.join(trash_folder, str(asset_name)) moved = editor_asset_lib.rename_loaded_asset(asset, new_path) if not moved: unreal.log_warning("Asset {} could not be moved to Trash".format(asset_name)) continue removed += 1 output_test = "removed" if instant_delete else "moved to Trash folder" unreal.log(output_test) unreal.log("{} of {} to be deleted assets, of {} selected, removed".format(removed, len(to_be_deleted), num_assets))
# unreal.SystemLibrary # https://api.unrealengine.com/project/.html import unreal import random # active_viewport_only: bool : If True, will only affect the active viewport # actor: obj unreal.Actor : The actor you want to snap to def focusViewportOnActor(active_viewport_only=True, actor=None): command = 'CAMERA ALIGN' if active_viewport_only: command += ' ACTIVEVIEWPORTONLY' if actor: command += ' NAME=' + actor.get_name() executeConsoleCommand(command) # Cpp ######################################################################################################################################################################################## # Note: This is the real Python function but it does not work in editor : unreal.SystemLibrary.execute_console_command(unreal.EditorLevelLibrary.get_editor_world(), 'stat unit') # console_command: str : The console command def executeConsoleCommand(console_command=''): unreal.CppLib.execute_console_command(console_command) # return: int : The index of the active viewport def getActiveViewportIndex(): return unreal.CppLib.get_active_viewport_index() # viewport_index: int : The index of the viewport you want to affect # location: obj unreal.Vector : The viewport location # rotation: obj unreal.Rotator : The viewport rotation def setViewportLocationAndRotation(viewport_index=1, location=unreal.Vector(), rotation=unreal.Rotator()): unreal.CppLib.set_viewport_location_and_rotation(viewport_index, location, rotation) # viewport_index: int : The index of the viewport you want to affect # actor: obj unreal.Actor : The actor you want to snap to def snapViewportToActor(viewport_index=1, actor=None): setViewportLocationAndRotation(viewport_index, actor.get_actor_location(), actor.get_actor_rotation())
import unreal def get_project_dir () -> str : path : str = unreal.Paths.game_source_dir() path = path.replace ('CINEVStudio/Source/', 'CINEVStudio/project/') return path root_path : str = get_project_dir() print(root_path)
# -*- coding: utf-8 -*- import unreal import os from Utilities.Utils import Singleton from Utilities.Utils import cast import Utilities import QueryTools import re import collections try: # For Python 3.10 and later from collections.abc import Iterable except ImportError: from collections import Iterable import types from .import Utils global _r COLUMN_COUNT = 2 class DetailData(object): def __init__(self): self.filter_str = "" self.filteredIndexToIndex = [] self.hisCrumbObjsAndNames = [] #list[(obj, propertyName)] self.attributes = None self.filtered_attributes = None self.plains = [] self.riches = [] self.selected = set() def check_line_id(self, line_id, column_count): from_line = line_id * column_count to_line = (line_id + 1) * column_count assert len(self.plains) == len(self.riches), "len(self.plains) != len(self.riches)" if 0 <= from_line < len(self.plains) and 0 <= to_line <= len(self.plains): return True else: unreal.log_error(f"Check Line Id Failed: {line_id}, plains: {len(self.plains)}, rich: {len(self.riches)}") return False def get_plain(self, line_id, column_count): assert self.check_line_id(line_id, column_count), "check line id failed." return self.plains[line_id * 2 : line_id * 2 + 2] def get_rich(self, line_id, column_count): assert self.check_line_id(line_id, column_count), "check line id failed." return self.riches[line_id * 2: line_id * 2 + 2] class ObjectDetailViewer(metaclass=Singleton): def __init__(self, jsonPath): self.jsonPath = jsonPath self.data = unreal.PythonBPLib.get_chameleon_data(self.jsonPath) self.ui_checkbox_single_mode = "CheckBoxSingleMode" self.ui_checkbox_compare_mode = "CheckBoxCompareMode" self.ui_left_group = "LeftDetailGroup" self.ui_right_group = "RightDetailGroup" self.ui_button_refresh = "RefreshCompareButton" self.ui_detailListLeft = "ListViewLeft" self.ui_detailListRight = "ListViewRight" self.ui_hisObjsBreadcrumbLeft = 'ObjectHisBreadcrumbLeft' self.ui_hisObjsBreadcrumbRight = 'ObjectHisBreadcrumbRight' # self.ui_headRowLeft = "HeaderRowLeft" # self.ui_headRowRight = "HeaderRowRight" self.ui_labelLeft = "LabelLeft" self.ui_labelRight = "LabelRight" self.ui_info_output = "InfoOutput" self.ui_rightButtonsGroup = "RightButtonsGroup" # used for compare mode self.ui_rightListGroup = "RightListGroup" self.ui_refreshButtonGroup = "RefreshButtonGroup" self.reset() def on_close(self): self.reset() def on_map_changed(self, map_change_type_str): # remove the reference, avoid memory leaking when load another map. if map_change_type_str == "TearDownWorld": self.reset(bResetParameter=False) else: pass # skip: LoadMap, SaveMap, NewMap def reset(self, bResetParameter=True): if bResetParameter: self.showBuiltin = True self.showOther = True self.showProperties = True self.showEditorProperties = True self.showParamFunction = True self.compareMode = False self.left = None self.right = None self.leftSearchText = "" self.rightSearchText = "" self.left_rich = None self.left_plain = None self.var = None self.diff_count = 0 self.clear_ui_info() def clear_ui_info(self): for text_ui in [self.ui_info_output, self.ui_labelLeft, self.ui_labelRight]: self.data.set_text(text_ui, "") self.data.set_list_view_multi_column_items(self.ui_detailListLeft, [], 2) self.data.set_list_view_multi_column_items(self.ui_detailListRight, [], 2) for ui_breadcrumb in [self.ui_hisObjsBreadcrumbRight, self.ui_hisObjsBreadcrumbLeft]: crumbCount = self.data.get_breadcrumbs_count_string(ui_breadcrumb) for i in range(crumbCount): self.data.pop_breadcrumb_string(ui_breadcrumb) def update_log_text(self, bRight): bShowRight = self.compareMode result = "" for side_str in ["left", "right"] if bShowRight else ["left"]: bRight = side_str != "left" ui_breadcrumb = self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft breadcrumbs = self.right.hisCrumbObjsAndNames if bRight else self.left.hisCrumbObjsAndNames crumbCount = self.data.get_breadcrumbs_count_string(ui_breadcrumb) if bRight: result += "\t\t\t" result += "{} crumb: {} hisObj: {}".format(side_str, crumbCount, len(breadcrumbs)) if self.compareMode: result = f"{result}\t\t\tdiff count: {self.diff_count}" self.data.set_text(self.ui_info_output, result) def get_color_by(self, attr : Utils.attr_detail): if attr.bCallable_builtin: return "DarkTurquoise".lower() if attr.bCallable_other: return "RoyalBlue".lower() if attr.bEditorProperty: return "LimeGreen".lower() if attr.bOtherProperty: return "yellow" def get_color(self, typeStr): if typeStr == "property": return 'white' if typeStr == "return_type": return 'gray' if typeStr == "param": return 'gray' def get_name_with_rich_text(self, attr:Utils.attr_detail): name_color = self.get_color_by(attr) param_color = self.get_color("param") return_type_color = self.get_color("return_type") if attr.bProperty: return "\t<RichText.{}>{}</>".format(name_color, attr.name) else: if attr.param_str: return "\t<RichText.{}>{}(</><RichText.{}>{}</><RichText.{}>)</>".format(name_color, attr.name , param_color, attr.param_str , name_color) else: if attr.bCallable_other: return "\t<RichText.{}>{}</>".format(name_color, attr.name) else: return "\t<RichText.{}>{}()</><RichText.{}> {}</>".format(name_color, attr.name , return_type_color, attr.return_type_str) def get_name_with_plain_text(self, attr:Utils.attr_detail): if attr.bProperty: return "\t{}".format(attr.name) else: if attr.param_str: return "\t{}({})".format( attr.name, attr.param_str) else: if attr.bCallable_other: return "\t{}".format( attr.name) else: return "\t{}() {}".format(attr.name,attr.return_type_str) def filter(self, data:DetailData): result = [] indices = [] for i, attr in enumerate(data.attributes): if not self.showEditorProperties and attr.bEditorProperty: continue if not self.showProperties and attr.bOtherProperty: continue if not self.showParamFunction and attr.bHasParamFunction: continue if not self.showBuiltin and attr.bCallable_builtin: continue if not self.showOther and attr.bCallable_other: continue if data.filter_str: if data.filter_str.lower() not in attr.display_result.lower() and data.filter_str not in attr.display_name.lower() : continue result.append(attr) indices.append(i) return result, indices def show_data(self, data:DetailData, ui_listView): flatten_list_items = [] flatten_list_items_plain = [] for i, attr in enumerate(data.filtered_attributes): # print(f"{i}: {attr.name} {attr.display_name}, {attr.display_result} ") attr.check() assert attr.display_name, f"display name null {attr.display_name}" assert isinstance(attr.display_result, str), f"display result null {attr.display_result}" result_str = attr.display_result if len(result_str) > 200: result_str = result_str[:200] + "......" flatten_list_items.extend([self.get_name_with_rich_text(attr), result_str]) flatten_list_items_plain.extend([self.get_name_with_plain_text(attr), result_str]) data.riches = flatten_list_items data.plains = flatten_list_items_plain data.selected.clear() self.data.set_list_view_multi_column_items(ui_listView, flatten_list_items, 2) def query_and_push(self, obj, propertyName, bPush, bRight): #bPush: whether add Breadcrumb nor not, call by property if bRight: ui_Label = self.ui_labelRight ui_listView = self.ui_detailListRight ui_breadcrumb = self.ui_hisObjsBreadcrumbRight else: ui_Label = self.ui_labelLeft ui_listView = self.ui_detailListLeft ui_breadcrumb = self.ui_hisObjsBreadcrumbLeft data = self.right if bRight else self.left data.attributes = Utils.ll(obj) data.filtered_attributes, data.filteredIndexToIndex = self.filter(data) self.show_data(data, ui_listView) # set breadcrumb if propertyName and len(propertyName) > 0: label = propertyName else: if isinstance(obj, unreal.Object): label = obj.get_name() else: try: label = obj.__str__() except TypeError: label = f"{obj}" if bPush: # push # print(f"%%% push: {propertyName}, label {label}") data.hisCrumbObjsAndNames.append((obj, propertyName)) self.data.push_breadcrumb_string(ui_breadcrumb, label, label) self.data.set_text(ui_Label, "{} type: {}".format(label, type(obj)) ) crumbCount = self.data.get_breadcrumbs_count_string(ui_breadcrumb) if bRight: assert len(self.right.hisCrumbObjsAndNames) == crumbCount, "hisCrumbObjsAndNames count not match {} {}".format(len(self.right.hisCrumbObjsAndNames), crumbCount) else: assert len(self.left.hisCrumbObjsAndNames) == crumbCount, "hisCrumbObjsAndNames count not match {} {}".format(len(self.left.hisCrumbObjsAndNames), crumbCount) self.update_log_text(bRight) def clear_and_query(self, obj, bRight): # first time query self.data.clear_breadcrumbs_string(self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft) if not self.right: self.right = DetailData() if not self.left: self.left = DetailData() data = self.right if bRight else self.left data.hisCrumbObjsAndNames = [] #clear his-Object at first time query if bRight: assert len(self.right.hisCrumbObjsAndNames) == 0, "len(self.right.hisCrumbObjsAndNames) != 0" else: assert len(self.left.hisCrumbObjsAndNames) == 0, "len(self.left.hisCrumbObjsAndNames) != 0" self.query_and_push(obj, "", bPush=True, bRight= bRight) self.apply_compare_if_needed() self.update_log_text(bRight) def update_ui_by_mode(self): self.data.set_is_checked(self.ui_checkbox_compare_mode, self.compareMode) self.data.set_is_checked(self.ui_checkbox_single_mode, not self.compareMode) bCollapsed = not self.compareMode self.data.set_collapsed(self.ui_rightButtonsGroup, bCollapsed) self.data.set_collapsed(self.ui_right_group, bCollapsed) self.data.set_collapsed(self.ui_button_refresh, bCollapsed) def on_checkbox_SingleMode_Click(self, state): self.compareMode = False self.update_ui_by_mode() def on_checkbox_CompareMode_Click(self, state): self.compareMode = True self.update_ui_by_mode() def on_button_Refresh_click(self): self.apply_compare_if_needed() def on_button_SelectAsset_click(self, bRightSide): selectedAssets = Utilities.Utils.get_selected_assets() if len(selectedAssets) == 0: return self.clear_and_query(selectedAssets[0], bRightSide) def on_button_QuerySelected_click(self, bRightSide): # query component when any component was selected, otherwise actor obj = Utilities.Utils.get_selected_comp() if not obj: obj = Utilities.Utils.get_selected_actor() if obj: self.clear_and_query(obj, bRightSide) def on_drop(self, bRightSide, *args, **kwargs): if "assets" in kwargs and kwargs["assets"]: asset = unreal.load_asset(kwargs["assets"][0]) if asset: self.clear_and_query(asset, bRightSide) return if "actors" in kwargs and kwargs["actors"]: actor = unreal.PythonBPLib.find_actor_by_name(kwargs["actors"][0], unreal.EditorLevelLibrary.get_editor_world()) if actor: print(actor) self.clear_and_query(actor, bRightSide) return item_count = 0 for k, v in kwargs.items(): item_count += len(v) if item_count == 0: selected_comp = Utilities.Utils.get_selected_comp() if selected_comp: self.clear_and_query(selected_comp, bRightSide) def log_r_warning(self): unreal.log_warning("Assign the global var: '_r' with the MenuItem: 'select X --> _r' on Python Icon menu") def on_button_Query_R_click(self, r_obj, bRightSide=False): print("on_button_Query_R_click call") if not r_obj: return self.clear_and_query(r_obj, bRightSide) def on_list_double_click_do(self, index, bRight): # print ("on_listview_DetailList_mouse_button_double_click {} bRight: {}".format(index, bRight)) data = self.right if bRight else self.left typeBlacklist = [int, float, str, bool] #, types.NotImplementedType] real_index = data.filteredIndexToIndex[index] if data.filteredIndexToIndex else index assert 0 <= real_index < len(data.attributes) currentObj, _ = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames) - 1] attr_name = data.attributes[real_index].name objResult, propertyName = self.try_get_object(data, currentObj, attr_name) if objResult == NotImplemented: return if not objResult or objResult is currentObj: # equal return if isinstance(objResult, str) and "skip call" in objResult.lower(): return if type(objResult) in typeBlacklist: return if isinstance(objResult, Iterable): if type(objResult[0]) in typeBlacklist: return nextObj = objResult[0] nextPropertyName = str(propertyName) + "[0]" else: nextObj = objResult nextPropertyName = str(propertyName) self.query_and_push(nextObj, nextPropertyName, bPush=True, bRight=bRight) self.apply_compare_if_needed() self.update_log_text(bRight) def on_listview_DetailListRight_mouse_button_double_click(self, index): self.on_list_double_click_do(index, bRight=True) def on_listview_DetailListLeft_mouse_button_double_click(self, index): self.on_list_double_click_do(index, bRight=False) def on_breadcrumbtrail_click_do(self, item, bRight): ui_hisObjsBreadcrumb = self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft data = self.right if bRight else self.left count = self.data.get_breadcrumbs_count_string(ui_hisObjsBreadcrumb) print ("on_breadcrumbtrail_ObjectHis_crumb_click: {} count: {} len(data.hisCrumbObjsAndNames): {}".format(item, count, len(data.hisCrumbObjsAndNames))) while len(data.hisCrumbObjsAndNames) > count: data.hisCrumbObjsAndNames.pop() nextObj, name = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames) - 1] if not bRight: assert self.left.hisCrumbObjsAndNames == data.hisCrumbObjsAndNames, "self.left.hisCrumbObjsAndNames = data.hisCrumbObjsAndNames" self.query_and_push(nextObj, name, bPush=False, bRight=False) self.apply_compare_if_needed() self.update_log_text(bRight=False) def on_breadcrumbtrail_ObjectHisLeft_crumb_click(self, item): self.on_breadcrumbtrail_click_do(item, bRight=False) def on_breadcrumbtrail_ObjectHisRight_crumb_click(self, item): self.on_breadcrumbtrail_click_do(item, bRight=True) def remove_address_str(self, strIn): return re.sub(r'\(0x[0-9,A-F]{16}\)', '', strIn) def apply_compare_if_needed(self): if not self.compareMode: return lefts = self.left.filtered_attributes if self.left.filtered_attributes else self.left.attributes rights = self.right.filtered_attributes if self.right.filtered_attributes else self.right.attributes if not lefts: lefts = [] if not rights: rights = [] leftIDs = [] rightIDs = [] for i, left_attr in enumerate(lefts): for j, right_attr in enumerate(rights): if right_attr.name == left_attr.name: if right_attr.result != left_attr.result: if isinstance(right_attr.result, unreal.Transform): if right_attr.result.is_near_equal(left_attr.result, location_tolerance=1e-20, rotation_tolerance=1e-20, scale3d_tolerance=1e-20): continue leftIDs.append(i) rightIDs.append(j) break self.data.set_list_view_multi_column_selections(self.ui_detailListLeft, leftIDs) self.data.set_list_view_multi_column_selections(self.ui_detailListRight, rightIDs) self.diff_count = len(leftIDs) def apply_search_filter(self, text, bRight): _data = self.right if bRight else self.left _data.filter_str = text if len(text) else "" _data.filtered_attributes, _data.filteredIndexToIndex = self.filter(_data) ui_listView = self.ui_detailListRight if bRight else self.ui_detailListLeft self.show_data(_data, ui_listView) self.apply_compare_if_needed() def on_searchbox_FilterLeft_text_changed(self, text): self.apply_search_filter(text if text is not None else "", bRight=False) def on_searchbox_FilterLeft_text_committed(self, text): self.apply_search_filter(text if text is not None else "", bRight=False) def on_searchbox_FilterRight_text_changed(self, text): self.apply_search_filter(text if text is not None else "", bRight=True) def on_searchbox_FilterRight_text_committed(self, text): self.apply_search_filter(text if text is not None else "", bRight=True) def apply_filter(self): _datas = [self.left, self.right] _isRight = [False, True] for data, bRight in zip(_datas, _isRight): if len(data.hisCrumbObjsAndNames) > 0: nextObj, name = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames)-1] self.query_and_push(nextObj, name, bPush=False, bRight=bRight) self.apply_compare_if_needed() self.update_log_text(bRight=False) # def try_get_object(self, data, obj, name:str): index = -1 attribute = None for i, attr in enumerate(data.attributes): if attr.name == name: index = i attribute = attr assert index >= 0 return attribute.result, name def ui_on_checkbox_ShowBuiltin_state_changed(self, bEnabled): self.showBuiltin = bEnabled self.apply_filter() def ui_on_checkbox_ShowOther_state_changed(self, bEnabled): self.showOther = bEnabled self.apply_filter() def ui_on_checkbox_ShowProperties_state_changed(self, bEnabled): self.showProperties = bEnabled self.apply_filter() def ui_on_checkbox_ShowEditorProperties_state_changed(self, bEnabled): self.showEditorProperties = bEnabled self.apply_filter() def ui_on_checkbox_ShowParamFunction_state_changed(self, bEnabled): self.showParamFunction = bEnabled self.apply_filter() def ui_on_listview_DetailList_selection_changed(self, bRight): data = [self.left, self.right][bRight] list_view = [self.ui_detailListLeft, self.ui_detailListRight][bRight] selected_indices = set(self.data.get_list_view_multi_column_selection(list_view)) added = selected_indices - data.selected de_selected = data.selected - selected_indices for i, lineId in enumerate(added): self.data.set_list_view_multi_column_line(list_view, lineId, data.get_plain(lineId, column_count=COLUMN_COUNT) , rebuild_list=True if i == len(added)-1 and len(de_selected) == 0 else False) for i, lineId in enumerate(de_selected): self.data.set_list_view_multi_column_line(list_view, lineId, data.get_rich(lineId, column_count=COLUMN_COUNT) , rebuild_list=True if i == len(de_selected)-1 else False) data.selected = selected_indices
"""Import generated images into Unreal and tag metadata.""" from __future__ import annotations import argparse import json import pathlib import unreal ASSET_DST_PATH = "/project/" def import_image(img_path: pathlib.Path) -> list[str]: task = unreal.AssetImportTask() task.filename = str(img_path) task.destination_path = ASSET_DST_PATH task.automated = True task.replace_identical = True unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks([task]) return task.imported_object_paths def set_metadata(asset_path: str, meta: dict) -> None: asset = unreal.load_asset(asset_path) for key, value in meta.items(): unreal.EditorAssetLibrary.set_metadata_tag( asset, str(key), json.dumps(value) if isinstance(value, (dict, list)) else str(value) ) unreal.EditorAssetLibrary.save_loaded_asset(asset) def run_batch(folder: str) -> None: for img in pathlib.Path(folder).rglob("*.png"): imported = import_image(img) if imported: meta_path = img.with_suffix(img.suffix + ".json") try: meta = json.loads(meta_path.read_text()) except FileNotFoundError: print(f"Warning: Metadata file not found for {img}. Skipping metadata tagging.") continue except json.JSONDecodeError as e: print(f"Warning: Invalid JSON in {meta_path}: {e}. Skipping metadata tagging.") continue for asset in imported: set_metadata(asset, meta) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Import generated images into Unreal and tag metadata.") parser.add_argument("folder", nargs="?", default=r"/project/", help="Folder containing images to import") args = parser.parse_args() run_batch(args.folder)
# _ # (_) # _ __ ___ __ _ _ __ ___ ___ _ __ _ ___ _ __ ___ # | '_ ` _ \ / _` | '_ ` _ \ / _ \| '_ \| |/ _ \ '_ ` _ \ # | | | | | | (_| | | | | | | (_) | | | | | __/ | | | | | # |_| |_| |_|\__,_|_| |_| |_|\___/|_| |_|_|\___|_| |_| |_| # www.mamoniem.com # www.ue4u.xyz #Copyright 2022 Muhammad A.Moniem (@_mamoniem). All Rights Reserved. # import unreal @unreal.uclass() class GetEditorUtility(unreal.GlobalEditorUtilityBase): pass @unreal.uclass() class GetEditorAssetLibrary(unreal.EditorAssetLibrary): pass @unreal.uclass() class GetAnimationLibrary(unreal.AnimationLibrary): pass editorUtility = GetEditorUtility() animLib = GetAnimationLibrary() selectedAssets = editorUtility.get_selected_assets() for selectedAsset in selectedAssets: allEventsForSelectedAsset = animLib.get_animation_notify_events(selectedAsset) if len(allEventsForSelectedAsset) != 0: print("For the animation [%s] found [%d] notifies" % (selectedAsset.get_name(), len(allEventsForSelectedAsset))) selectedAsset.modify(True) for notifyEvent in allEventsForSelectedAsset: notifyEvent.set_editor_property("trigger_on_dedicated_server", False) notifyEvent.set_editor_property("trigger_on_follower", True) notifyEvent.set_editor_property("notify_trigger_chance", 0.5) #Can also change the memebr variables right away, they are exposed as memebers to python API #notifyEvent.trigger_on_dedicated_server = False #notifyEvent.trigger_on_follower = True #notifyEvent.notify_trigger_chance = 0.5 #Can get some more detials about the notify, like it's name & color notifyItself = notifyEvent.notify Notifycolor = notifyItself.notify_color NotifyName = notifyItself.get_notify_name() print("The notify [%s] has the color is {%d, %d, %d, %d}" % (NotifyName, Notifycolor.r, Notifycolor.g, Notifycolor.b, Notifycolor.a)) #Can also change the notify colors. Keep in mind we can't use the notifyItself.notify_color as it is read-only, but we can use the set_editor_property("notify_color", VALUE) clr = unreal.Color(0, 0, 255, 255) notifyItself.set_editor_property("notify_color", clr) else: print("No notifies found within the animation [%s]" % (selectedAsset.get_name()))
import unreal import argparse # Info about Python with IKRigs here: # https://docs.unrealengine.com/5.2/en-US/using-python-to-create-and-edit-ik-rigs-in-unreal-engine/ # https://docs.unrealengine.com/5.2/en-US/using-python-to-create-and-edit-ik-retargeter-assets-in-unreal-engine/ parser = argparse.ArgumentParser(description = 'Creates an IKRig given a SkeletalMesh') parser.add_argument('--skeletalMesh', help='Skeletal Mesh to Use') args = parser.parse_args() # Find or Create the IKRig asset_tools = unreal.AssetToolsHelpers.get_asset_tools() package_path = args.skeletalMesh.rsplit('/', 1)[0] + '/' asset_name = args.skeletalMesh.split('.')[-1] + '_IKRig' ikr = skel_mesh = unreal.load_asset(name = package_path + asset_name ) if not ikr: ikr = asset_tools.create_asset( asset_name=asset_name, package_path=package_path, asset_class=unreal.IKRigDefinition, factory=unreal.IKRigDefinitionFactory()) # Get the controller ikr_controller = unreal.IKRigController.get_controller(ikr) # Set the skeletal mesh skel_mesh = unreal.load_asset(name = args.skeletalMesh) ikr_controller.set_skeletal_mesh(skel_mesh) # Get the bone list bone_names = unreal.DazToUnrealBlueprintUtils.get_bone_list(ikr) # Use bone list to guess character type character_type = "unknown" if all(x in bone_names for x in ['hip', 'pelvis', 'spine1', 'spine4']): character_type = 'Genesis9' if all(x in bone_names for x in ['hip', 'abdomenLower', 'abdomenUpper', 'chestUpper']): character_type = 'Genesis8' if all(x in bone_names for x in ['hip', 'abdomenLower', 'abdomenUpper', 'chestUpper', 'lHeel']): character_type = 'Genesis3' if all(x in bone_names for x in ['Hips', 'HeadTop_End']): character_type = 'Mixamo' if not character_type == "unknown": # Setup goal names chains = [] CHAIN_NAME = 0 CHAIN_START = 1 CHAIN_END = 2 CHAIN_GOAL = 3 # Define the retarget chains based on the character if character_type == 'Genesis9': retarget_root_name = 'hip' chains.append(['Spine', 'spine1', 'spine4', None]) chains.append(['Head', 'neck1', 'head', None]) chains.append(['LeftArm', 'l_upperarm', 'l_hand', 'l_hand_Goal']) chains.append(['RightArm', 'r_upperarm', 'r_hand', 'r_hand_Goal']) chains.append(['LeftClavicle', 'l_shoulder', 'l_shoulder', None]) chains.append(['RightClavicle', 'r_shoulder', 'r_shoulder', None]) chains.append(['LeftLeg', 'l_thigh', 'l_toes', 'l_toes_Goal']) chains.append(['RightLeg', 'r_thigh', 'r_toes', 'r_toes_Goal']) chains.append(['LeftPinky', 'l_pinky1', 'l_pinky3', None]) chains.append(['RightPinky', 'r_pinky1', 'r_pinky3', None]) chains.append(['LeftRing', 'l_ring1', 'l_ring3', None]) chains.append(['RightRing', 'r_ring1', 'r_ring3', None]) chains.append(['LeftMiddle', 'l_mid1', 'l_mid3', None]) chains.append(['RightMiddle', 'r_mid1', 'r_mid3', None]) chains.append(['LeftIndex', 'l_index1', 'l_index3', None]) chains.append(['RightIndex', 'r_index1', 'r_index3', None]) chains.append(['LeftThumb', 'l_thumb1', 'l_thumb3', None]) chains.append(['RightThumb', 'r_thumb1', 'r_thumb3', None]) chains.append(['HandRootIK', 'ik_hand_root', 'ik_hand_root', None]) chains.append(['RightHandIK', 'ik_hand_r', 'ik_hand_r', None]) chains.append(['HandGunIK', 'ik_hand_gun', 'ik_hand_gun', None]) chains.append(['FootRootIK', 'ik_foot_root', 'ik_foot_root', None]) chains.append(['LeftFootIK', 'ik_foot_l', 'ik_foot_l', None]) chains.append(['RightFootIK', 'ik_foot_r', 'ik_foot_r', None]) chains.append(['Root', 'root', 'root', None]) if character_type == 'Genesis8' or character_type == 'Genesis3': retarget_root_name = 'hip' chains.append(['Spine', 'abdomenLower', 'chestUpper', None]) chains.append(['Head', 'neckLower', 'head', None]) chains.append(['LeftArm', 'lShldrBend', 'lHand', 'lHand_Goal']) chains.append(['RightArm', 'rShldrBend', 'rHand', 'rHand_Goal']) chains.append(['LeftClavicle', 'lCollar', 'lCollar', None]) chains.append(['RightClavicle', 'rCollar', 'rCollar', None]) chains.append(['LeftLeg', 'lThighBend', 'lToe', 'lToe_Goal']) chains.append(['RightLeg', 'rThighBend', 'rToe', 'rToe_Goal']) chains.append(['LeftPinky', 'lPinky1', 'lPinky3', None]) chains.append(['RightPinky', 'rPinky1', 'rPinky3', None]) chains.append(['LeftRing', 'lRing1', 'lRing3', None]) chains.append(['RightRing', 'rRing1', 'rRing3', None]) chains.append(['LeftMiddle', 'lMid1', 'lMid3', None]) chains.append(['RightMiddle', 'rMid1', 'rMid3', None]) chains.append(['LeftIndex', 'lIndex1', 'lIndex3', None]) chains.append(['RightIndex', 'rIndex1', 'rIndex3', None]) chains.append(['LeftThumb', 'lThumb1', 'lThumb3', None]) chains.append(['RightThumb', 'rThumb1', 'rThumb3', None]) chains.append(['HandRootIK', 'ik_hand_root', 'ik_hand_root', None]) chains.append(['RightHandIK', 'ik_hand_r', 'ik_hand_r', None]) chains.append(['HandGunIK', 'ik_hand_gun', 'ik_hand_gun', None]) chains.append(['FootRootIK', 'ik_foot_root', 'ik_foot_root', None]) chains.append(['LeftFootIK', 'ik_foot_l', 'ik_foot_l', None]) chains.append(['RightFootIK', 'ik_foot_r', 'ik_foot_r', None]) chains.append(['Root', 'root', 'root', None]) if character_type == 'Mixamo': retarget_root_name = 'Hips' chains.append(['Spine', 'Spine', 'Spine2', None]) chains.append(['Head', 'Neck', 'Head', None]) chains.append(['LeftArm', 'LeftArm', 'LeftHand', 'LeftHand_Goal']) chains.append(['RightArm', 'RightArm', 'RightHand', 'RightHand_Goal']) chains.append(['LeftClavicle', 'LeftShoulder', 'LeftShoulder', None]) chains.append(['RightClavicle', 'RightShoulder', 'RightShoulder', None]) chains.append(['LeftLeg', 'LeftUpLeg', 'LeftToeBase', 'LeftToeBase_Goal']) chains.append(['RightLeg', 'RightUpLeg', 'RightToeBase', 'RightToeBase_Goal']) chains.append(['LeftPinky', 'LeftHandPinky1', 'LeftHandPinky3', None]) chains.append(['RightPinky', 'RightHandPinky1', 'RightHandPinky3', None]) chains.append(['LeftRing', 'LeftHandRing1', 'LeftHandRing3', None]) chains.append(['RightRing', 'RightHandRing1', 'RightHandRing3', None]) chains.append(['LeftMiddle', 'LeftHandMiddle1', 'LeftHandMiddle3', None]) chains.append(['RightMiddle', 'RightHandMiddle1', 'RightHandMiddle3', None]) chains.append(['LeftIndex', 'LeftHandIndex1', 'LeftHandIndex3', None]) chains.append(['RightIndex', 'RightHandIndex1', 'RightHandIndex3', None]) chains.append(['LeftThumb', 'LeftHandThumb1', 'LeftHandThumb3', None]) chains.append(['RightThumb', 'RightHandThumb1', 'RightHandThumb3', None]) # Create the solver, remove any existing ones while ikr_controller.get_solver_at_index(0): ikr_controller.remove_solver(0) fbik_index = ikr_controller.add_solver(unreal.IKRigFBIKSolver) # Setup root ikr_controller.set_root_bone(retarget_root_name, fbik_index) ikr_controller.set_retarget_root(retarget_root_name) # Remove existing goals for goal in ikr_controller.get_all_goals(): ikr_controller.remove_goal(goal.get_editor_property('goal_name')) # Create the goals for chain in chains: if chain[CHAIN_GOAL]: ikr_controller.add_new_goal(chain[CHAIN_GOAL], chain[CHAIN_END]) ikr_controller.connect_goal_to_solver(chain[CHAIN_GOAL], fbik_index) # Remove old Retarget Chains for chain in ikr_controller.get_retarget_chains(): ikr_controller.remove_retarget_chain(chain.get_editor_property('chain_name')) # Setup Retarget Chains for chain in chains: if chain[CHAIN_GOAL]: ikr_controller.add_retarget_chain(chain[CHAIN_NAME], chain[CHAIN_START], chain[CHAIN_END], chain[CHAIN_GOAL]) else: ikr_controller.add_retarget_chain(chain[CHAIN_NAME], chain[CHAIN_START], chain[CHAIN_END], '')
# -*- coding: utf-8 -*- """Extract camera from Unreal.""" import os import unreal from ayon_core.pipeline import publish from ayon_core.hosts.unreal.api.pipeline import UNREAL_VERSION class ExtractCamera(publish.Extractor): """Extract a camera.""" label = "Extract Camera" hosts = ["unreal"] families = ["camera"] optional = True def process(self, instance): ar = unreal.AssetRegistryHelpers.get_asset_registry() # Define extract output file path staging_dir = self.staging_dir(instance) fbx_filename = "{}.fbx".format(instance.name) # Perform extraction self.log.info("Performing extraction..") # Check if the loaded level is the same of the instance if UNREAL_VERSION.major == 5: world = unreal.UnrealEditorSubsystem().get_editor_world() else: world = unreal.EditorLevelLibrary.get_editor_world() current_level = world.get_path_name() assert current_level == instance.data.get("level"), \ "Wrong level loaded" for member in instance.data.get('members'): data = ar.get_asset_by_object_path(member) if UNREAL_VERSION.major == 5: is_level_sequence = ( data.asset_class_path.asset_name == "LevelSequence") else: is_level_sequence = (data.asset_class == "LevelSequence") if is_level_sequence: sequence = data.get_asset() if UNREAL_VERSION.major == 5 and UNREAL_VERSION.minor >= 1: params = unreal.SequencerExportFBXParams( world=world, root_sequence=sequence, sequence=sequence, bindings=sequence.get_bindings(), master_tracks=sequence.get_master_tracks(), fbx_file_name=os.path.join(staging_dir, fbx_filename) ) unreal.SequencerTools.export_level_sequence_fbx(params) elif UNREAL_VERSION.major == 4 and UNREAL_VERSION.minor == 26: unreal.SequencerTools.export_fbx( world, sequence, sequence.get_bindings(), unreal.FbxExportOption(), os.path.join(staging_dir, fbx_filename) ) else: # Unreal 5.0 or 4.27 unreal.SequencerTools.export_level_sequence_fbx( world, sequence, sequence.get_bindings(), unreal.FbxExportOption(), os.path.join(staging_dir, fbx_filename) ) if not os.path.isfile(os.path.join(staging_dir, fbx_filename)): raise RuntimeError("Failed to extract camera") if "representations" not in instance.data: instance.data["representations"] = [] fbx_representation = { 'name': 'fbx', 'ext': 'fbx', 'files': fbx_filename, "stagingDir": staging_dir, } instance.data["representations"].append(fbx_representation)
# Rewrite import part of unreal remote call in dependencies.unreal, # whose data parse is complex for other DCC tools except for Blender. # Only import model mesh (static mesh) currently, mostly using default import setting in unreal import os import json import time import sys import inspect try: import unreal except (ModuleNotFoundError if sys.version_info.major == 3 else ImportError): pass try: from .dependencies import unreal as ue from .dependencies.rpc import factory from .dependencies.unreal import Unreal except ImportError: from dependencies import unreal as ue from dependencies.rpc import factory from dependencies.unreal import Unreal if sys.version_info.major == 2: from imp import reload reload(ue) reload(factory) class UnrealImportAsset(Unreal): def __init__(self, file_path, asset_data, property_data): """ Initializes the import with asset data and property data. :param str file_path: The full path to the file to import. :param dict asset_data: A dictionary that contains various data about the asset. :param PropertyData property_data: A property data instance that contains all property values of the tool. """ self._file_path = file_path self._asset_data = asset_data self._property_data = property_data self._import_task = unreal.AssetImportTask() self._options = None def set_static_mesh_import_options(self): """ Sets the static mesh import options. """ if not self._asset_data.get('skeletal_mesh') and not self._asset_data.get('animation'): self._options.mesh_type_to_import = unreal.FBXImportType.FBXIT_STATIC_MESH self._options.static_mesh_import_data.import_mesh_lo_ds = False import_data = unreal.FbxStaticMeshImportData() self.set_settings( self._property_data.get('static_mesh_import_data', {}), import_data ) self._options.static_mesh_import_data = import_data self._options.set_editor_property('import_as_skeletal', False) self._options.set_editor_property('import_animations', False) def set_fbx_import_task_options(self): """ Sets the FBX import options. """ self._import_task.set_editor_property('filename', self._file_path) self._import_task.set_editor_property('destination_path', self._asset_data.get('asset_folder')) self._import_task.set_editor_property('replace_existing', True) self._import_task.set_editor_property('replace_existing_settings', True) self._import_task.set_editor_property( 'automated', not self._property_data.get('advanced_ui_import', {}).get('value', False) ) self._import_task.set_editor_property('save', True) import_mesh = self._asset_data.get('import_mesh', False) # set the options self._options = unreal.FbxImportUI() self._options.set_editor_property('import_mesh', import_mesh) # not import textures and material currently self._options.set_editor_property('import_materials', False) self._options.set_editor_property('import_textures', False) # unreal.FbxStaticMeshImportData self._options.static_mesh_import_data.set_editor_property('combine_meshes', True) self._options.static_mesh_import_data.set_editor_property('auto_generate_collision', True) # set the static mesh import options self.set_static_mesh_import_options() def run_import(self): # assign the options object to the import task and import the asset self._import_task.options = self._options unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks([self._import_task]) return list(self._import_task.get_editor_property('imported_object_paths')) @factory.remote_class(ue.remote_unreal_decorator) class UnrealRemoteCalls: @staticmethod def asset_exists(asset_path): """ Checks to see if an asset exist in unreal. :param str asset_path: The path to the unreal asset. :return bool: Whether or not the asset exists. """ return unreal.EditorAssetLibrary.does_asset_exist(asset_path) @staticmethod def directory_exists(asset_path): """ Checks to see if a directory exist in unreal. :param str asset_path: The path to the unreal asset. :return bool: Whether or not the asset exists. """ # TODO fix this when the unreal API is fixed where it queries the registry correctly # https://jira.it.epicgames.com/project/-142234 # return unreal.EditorAssetLibrary.does_directory_exist(asset_path) return True @staticmethod def delete_asset(asset_path): """ Deletes an asset in unreal. :param str asset_path: The path to the unreal asset. :return bool: Whether or not the asset was deleted. """ if unreal.EditorAssetLibrary.does_asset_exist(asset_path): unreal.EditorAssetLibrary.delete_asset(asset_path) @staticmethod def delete_directory(directory_path): """ Deletes an folder and its contents in unreal. :param str directory_path: The game path to the unreal project folder. :return bool: Whether or not the directory was deleted. """ # API BUG:cant check if exists https://jira.it.epicgames.com/project/-142234 # if unreal.EditorAssetLibrary.does_directory_exist(directory_path): unreal.EditorAssetLibrary.delete_directory(directory_path) @staticmethod def import_asset(file_path, asset_data, property_data, file_type='fbx'): """ Imports an asset to unreal based on the asset data in the provided dictionary. :param str file_path: The full path to the file to import. :param dict asset_data: A dictionary of import parameters. :param dict property_data: A dictionary representation of the properties. :param str file_type: The import file type. """ unreal_import_asset = UnrealImportAsset( file_path=file_path, asset_data=asset_data, property_data=property_data ) if file_type.lower() == 'fbx': unreal_import_asset.set_fbx_import_task_options() # run the import task return unreal_import_asset.run_import() @staticmethod def create_asset(asset_path, asset_class=None, asset_factory=None, unique_name=True): """ Creates a new unreal asset. :param str asset_path: The project path to the asset. :param str asset_class: The name of the unreal asset class. :param str asset_factory: The name of the unreal factory. :param bool unique_name: Whether or not the check if the name is unique before creating the asset. """ asset_tools = unreal.AssetToolsHelpers.get_asset_tools() if unique_name: asset_path, _ = asset_tools.create_unique_asset_name( base_package_name=asset_path, suffix='' ) path = asset_path.rsplit("/", 1)[0] name = asset_path.rsplit("/", 1)[1] asset_tools.create_asset( asset_name=name, package_path=path, asset_class=asset_class, factory=asset_factory ) @staticmethod def get_project_path(): return unreal.Paths.project_dir() @staticmethod def create_and_open_new_level(asset_path): unreal.EditorLevelLibrary.new_level(asset_path) @staticmethod def load_level(asset_path): unreal.EditorLevelLibrary.save_current_level() unreal.EditorLevelLibrary.load_level(asset_path) @staticmethod def add_asset_to_current_level(transformation_data, asset_path): # actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.StaticMeshActor, unreal.Vector(10.0, 20.0, 30.0), unreal.Rotator(0.0, 0.0, 0.0)) # mesh_component = actor.get_component_by_class(unreal.StaticMeshComponent) # mesh = unreal.EditorAssetLibrary.load_asset('/project/') # mesh_component.set_static_mesh(mesh) for mesh_name, transformation in transformation_data.items(): location_data = transformation.get('location', (0.0, 0.0, 0.0)) rotation_data = transformation.get('rotation', (0.0, 0.0, 0.0)) scale_data = transformation.get('scale', (1.0, 1.0, 1.0)) location = unreal.Vector(location_data[0], location_data[2], location_data[1]) rotation = unreal.Rotator(rotation_data[0], rotation_data[2], rotation_data[1]) scale = unreal.Vector(scale_data[0], scale_data[2], scale_data[1]) # spawn actor(object) in current level actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.StaticMeshActor, location, rotation) mesh_component = actor.get_component_by_class(unreal.StaticMeshComponent) mesh_component.set_world_scale3d(scale) mesh = unreal.EditorAssetLibrary.load_asset(os.path.join(asset_path, mesh_name).replace(os.sep,'/')) mesh_component.set_static_mesh(mesh)
# 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()
import unreal AssetTools = unreal.AssetToolsHelpers.get_asset_tools() MaterialEditLibrary = unreal.MaterialEditingLibrary EditorAssetLibrary = unreal.EditorAssetLibrary AssetPath = "/project/" # check if the material exists if EditorAssetLibrary.do_assets_exist(AssetPath): #If it does make a copy NewAssetPath = "/project/" EditorAssetLibrary.duplicate_asset(AssetPath, NewAssetPath) MeshMaterial = EditorAssetLibrary.load_asset(NewAssetPath) else: #if it doesn't create a new one MeshMaterial = AssetTools.create_asset("M_MeshPaint", "/project/", unreal.Material, unreal.MaterialFactoryNew()) # Add texture parameter nodes for each surface base_colors = [] normals = [] orms = [] """ #Create Tiling Nodes #Create Texture Coordinate nodes for each surface TC_SurfaceA = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionTextureCoordinate.static_class(), -800, -600) TC_SurfaceB = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionTextureCoordinate.static_class(), -800, -500) """ # Create a Vertex Color node VertexColorNode_Color = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionVertexColor.static_class(), -500, -300) VertexColorNode_Color.set_editor_property('Desc', 'Vertex Color Base_Color') VertexColorNode_Normal = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionVertexColor.static_class(), -500, -400) VertexColorNode_Normal.set_editor_property('Desc', 'Vertex Color Normal') # Create a Vertex Color node for each ORM channel VertexColorNode_ORM_R = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionVertexColor.static_class(), -500, -150) VertexColorNode_ORM_R.set_editor_property('Desc', 'Vertex Color ORM_R') VertexColorNode_ORM_G = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionVertexColor.static_class(), -500, 0) VertexColorNode_ORM_G.set_editor_property('Desc', 'Vertex Color ORM_G') VertexColorNode_ORM_B = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionVertexColor.static_class(), -500, 150) VertexColorNode_ORM_B.set_editor_property('Desc', 'VertexColor ORM_B') # Create a 1-x nodes for each channel so that the textures from 5 to 1 can loop OneMinusNodeColor = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionOneMinus.static_class(), 0, -300) OneMinusNodeNormal = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionOneMinus.static_class(), 0, -400) OneMinusNode_R = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionOneMinus.static_class(), 0, -500) OneMinusNode_G = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionOneMinus.static_class(), 0, -600) OneMinusNode_B = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionOneMinus.static_class(), 0, -600) for i in range(5): # Create base color, normal, and ORM texture parameter nodes BaseColorParam = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionTextureSampleParameter2D.static_class(), -384, -300 + i * 150) NormalParam = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionTextureSampleParameter2D.static_class(), -384 + 300, -300 + i * 150) OrmParam = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionTextureSampleParameter2D.static_class(), -384 + 600, -300 + i * 150) # Set names and other properties for the nodes BaseColorParam.set_editor_property("ParameterName", unreal.Name("BaseColor_{}".format(i))) BaseColorParam.set_editor_property('sampler_source', unreal.SamplerSourceMode.SSM_WRAP_WORLD_GROUP_SETTINGS) NormalParam.set_editor_property("ParameterName", unreal.Name("Normal_{}".format(i))) NormalParam.set_editor_property('sampler_source', unreal.SamplerSourceMode.SSM_WRAP_WORLD_GROUP_SETTINGS) NormalParam.set_editor_property('sampler_type', unreal.MaterialSamplerType.SAMPLERTYPE_NORMAL) OrmParam.set_editor_property("ParameterName", unreal.Name("ORM_{}".format(i))) OrmParam.set_editor_property('sampler_source', unreal.SamplerSourceMode.SSM_WRAP_WORLD_GROUP_SETTINGS) OrmParam.set_editor_property('sampler_type', unreal.MaterialSamplerType.SAMPLERTYPE_LINEAR_COLOR) base_colors.append(BaseColorParam) normals.append(NormalParam) orms.append(OrmParam) # Create lerp nodes for the base color, normals, and orms base_color_lerps = [] normal_lerps = [] orm_r_lerps = [] orm_g_lerps = [] orm_b_lerps = [] for i in range(5): base_color_lerp = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionLinearInterpolate.static_class(), -192, -300 + i * 150) normal_lerp = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionLinearInterpolate.static_class(), -192 + 300, -300 + i * 150) orm_r_lerp = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionLinearInterpolate.static_class(), -192 + 600, -300 + i * 150) orm_g_lerp = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionLinearInterpolate.static_class(), -192 + 600, -300 + i * 150 + 200) orm_b_lerp = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionLinearInterpolate.static_class(), -192 + 600, -300 + i * 150 + 400) base_color_lerps.append(base_color_lerp) normal_lerps.append(normal_lerp) orm_r_lerps.append(orm_r_lerp) orm_g_lerps.append(orm_g_lerp) orm_b_lerps.append(orm_b_lerp) #Connect Texture Parameters to Lerps MaterialEditLibrary.connect_material_expressions(base_colors[0], '', base_color_lerps[0], 'B') MaterialEditLibrary.connect_material_expressions(base_colors[1], '', base_color_lerps[1], 'B') MaterialEditLibrary.connect_material_expressions(base_colors[2], '', base_color_lerps[2], 'B') MaterialEditLibrary.connect_material_expressions(base_colors[3], '', base_color_lerps[3], 'B') MaterialEditLibrary.connect_material_expressions(base_colors[4], '', base_color_lerps[4], 'B') MaterialEditLibrary.connect_material_expressions(base_colors[4], '', base_color_lerps[0], 'A') MaterialEditLibrary.connect_material_expressions(OneMinusNodeColor, '', base_color_lerps[0], 'Alpha') #Connect Vertex Color Node to base Color Lerps MaterialEditLibrary.connect_material_expressions(VertexColorNode_Color, 'A', OneMinusNodeColor, '') MaterialEditLibrary.connect_material_expressions(VertexColorNode_Color, 'R', base_color_lerps[1], 'Alpha') MaterialEditLibrary.connect_material_expressions(VertexColorNode_Color, 'G', base_color_lerps[2], 'Alpha') MaterialEditLibrary.connect_material_expressions(VertexColorNode_Color, 'B', base_color_lerps[3], 'Alpha') MaterialEditLibrary.connect_material_expressions(VertexColorNode_Color, 'A', base_color_lerps[4], 'Alpha') # Make Lerp Connections MaterialEditLibrary.connect_material_expressions(base_color_lerps[0], '', base_color_lerps[1], 'A') MaterialEditLibrary.connect_material_expressions(base_color_lerps[1], '', base_color_lerps[2], 'A') MaterialEditLibrary.connect_material_expressions(base_color_lerps[2], '', base_color_lerps[3], 'A') MaterialEditLibrary.connect_material_expressions(base_color_lerps[3], '', base_color_lerps[4], 'A') # Connect last Lerp to the Base Color Channel of the Material MaterialEditLibrary.connect_material_property(base_color_lerps[4], '', unreal.MaterialProperty.MP_BASE_COLOR) # Connect Texture Parameters to Lerps MaterialEditLibrary.connect_material_expressions(normals[0], '', normal_lerps[0], 'B') MaterialEditLibrary.connect_material_expressions(normals[1], '', normal_lerps[1], 'B') MaterialEditLibrary.connect_material_expressions(normals[2], '', normal_lerps[2], 'B') MaterialEditLibrary.connect_material_expressions(normals[3], '', normal_lerps[3], 'B') MaterialEditLibrary.connect_material_expressions(normals[4], '', normal_lerps[4], 'B') MaterialEditLibrary.connect_material_expressions(normals[4], '', normal_lerps[0], 'A') MaterialEditLibrary.connect_material_expressions(OneMinusNodeNormal, '', normal_lerps[0], 'Alpha') # Connect Vertex Color Node to base Color Lerps MaterialEditLibrary.connect_material_expressions(VertexColorNode_Normal, 'A', OneMinusNodeNormal, '') MaterialEditLibrary.connect_material_expressions(VertexColorNode_Normal, 'R', normal_lerps[1], 'Alpha') MaterialEditLibrary.connect_material_expressions(VertexColorNode_Normal, 'G', normal_lerps[2], 'Alpha') MaterialEditLibrary.connect_material_expressions(VertexColorNode_Normal, 'B', normal_lerps[3], 'Alpha') MaterialEditLibrary.connect_material_expressions(VertexColorNode_Normal, 'A', normal_lerps[4], 'Alpha') # Make Lerp Connections MaterialEditLibrary.connect_material_expressions(normal_lerps[0], '', normal_lerps[1], 'A') MaterialEditLibrary.connect_material_expressions(normal_lerps[1], '', normal_lerps[2], 'A') MaterialEditLibrary.connect_material_expressions(normal_lerps[2], '', normal_lerps[3], 'A') MaterialEditLibrary.connect_material_expressions(normal_lerps[3], '', normal_lerps[4], 'A') # Connect last Lerp to the Base Color Channel of the Material MaterialEditLibrary.connect_material_property(normal_lerps[4], '', unreal.MaterialProperty.MP_NORMAL) # Connect Texture Parameters to Lerps MaterialEditLibrary.connect_material_expressions(orms[0], 'R', orm_r_lerps[0], 'B') MaterialEditLibrary.connect_material_expressions(orms[1], 'R', orm_r_lerps[1], 'B') MaterialEditLibrary.connect_material_expressions(orms[2], 'R', orm_r_lerps[2], 'B') MaterialEditLibrary.connect_material_expressions(orms[3], 'R', orm_r_lerps[3], 'B') MaterialEditLibrary.connect_material_expressions(orms[4], 'R', orm_r_lerps[4], 'B') MaterialEditLibrary.connect_material_expressions(orms[4], 'R', orm_r_lerps[0], 'A') MaterialEditLibrary.connect_material_expressions(OneMinusNode_R, '', orm_r_lerps[0], 'Alpha') # Connect Vertex Color Node to base Color Lerps MaterialEditLibrary.connect_material_expressions(VertexColorNode_ORM_R, 'A', OneMinusNode_R, '') MaterialEditLibrary.connect_material_expressions(VertexColorNode_ORM_R, 'R', orm_r_lerps[1], 'Alpha') MaterialEditLibrary.connect_material_expressions(VertexColorNode_ORM_R, 'G', orm_r_lerps[2], 'Alpha') MaterialEditLibrary.connect_material_expressions(VertexColorNode_ORM_R, 'B', orm_r_lerps[3], 'Alpha') MaterialEditLibrary.connect_material_expressions(VertexColorNode_ORM_R, 'A', orm_r_lerps[4], 'Alpha') # Make Lerp Connections MaterialEditLibrary.connect_material_expressions(orm_r_lerps[0], '', orm_r_lerps[1], 'A') MaterialEditLibrary.connect_material_expressions(orm_r_lerps[1], '', orm_r_lerps[2], 'A') MaterialEditLibrary.connect_material_expressions(orm_r_lerps[2], '', orm_r_lerps[3], 'A') MaterialEditLibrary.connect_material_expressions(orm_r_lerps[3], '', orm_r_lerps[4], 'A') # Connect last Lerp to the Base Color Channel of the Material MaterialEditLibrary.connect_material_property(orm_r_lerps[4], '', unreal.MaterialProperty.MP_AMBIENT_OCCLUSION) # Connect Texture Parameters to Lerps MaterialEditLibrary.connect_material_expressions(orms[0], 'G', orm_g_lerps[0], 'B') MaterialEditLibrary.connect_material_expressions(orms[1], 'G', orm_g_lerps[1], 'B') MaterialEditLibrary.connect_material_expressions(orms[2], 'G', orm_g_lerps[2], 'B') MaterialEditLibrary.connect_material_expressions(orms[3], 'G', orm_g_lerps[3], 'B') MaterialEditLibrary.connect_material_expressions(orms[4], 'G', orm_g_lerps[4], 'B') MaterialEditLibrary.connect_material_expressions(orms[4], 'G', orm_g_lerps[0], 'A') MaterialEditLibrary.connect_material_expressions(OneMinusNode_G, '', orm_g_lerps[0], 'Alpha') # Connect Vertex Color Node to base Color Lerps MaterialEditLibrary.connect_material_expressions(VertexColorNode_ORM_G, 'A', OneMinusNode_G, '') MaterialEditLibrary.connect_material_expressions(VertexColorNode_ORM_G, 'R', orm_g_lerps[1], 'Alpha') MaterialEditLibrary.connect_material_expressions(VertexColorNode_ORM_G, 'G', orm_g_lerps[2], 'Alpha') MaterialEditLibrary.connect_material_expressions(VertexColorNode_ORM_G, 'B', orm_g_lerps[3], 'Alpha') MaterialEditLibrary.connect_material_expressions(VertexColorNode_ORM_G, 'A', orm_g_lerps[4], 'Alpha') # Make Lerp Connections MaterialEditLibrary.connect_material_expressions(orm_g_lerps[0], '', orm_g_lerps[1], 'A') MaterialEditLibrary.connect_material_expressions(orm_g_lerps[1], '', orm_g_lerps[2], 'A') MaterialEditLibrary.connect_material_expressions(orm_g_lerps[2], '', orm_g_lerps[3], 'A') MaterialEditLibrary.connect_material_expressions(orm_g_lerps[3], '', orm_g_lerps[4], 'A') # Connect last Lerp to the Base Color Channel of the Material MaterialEditLibrary.connect_material_property(orm_g_lerps[4], '', unreal.MaterialProperty.MP_ROUGHNESS) # Connect Texture Parameters to Lerps MaterialEditLibrary.connect_material_expressions(orms[0], 'B', orm_b_lerps[0], 'B') MaterialEditLibrary.connect_material_expressions(orms[1], 'B', orm_b_lerps[1], 'B') MaterialEditLibrary.connect_material_expressions(orms[2], 'B', orm_b_lerps[2], 'B') MaterialEditLibrary.connect_material_expressions(orms[3], 'B', orm_b_lerps[3], 'B') MaterialEditLibrary.connect_material_expressions(orms[4], 'B', orm_b_lerps[4], 'B') MaterialEditLibrary.connect_material_expressions(orms[4], 'B', orm_b_lerps[0], 'A') MaterialEditLibrary.connect_material_expressions(OneMinusNode_B, '', orm_b_lerps[0], 'Alpha') # Connect Vertex Color Node to base Color Lerps MaterialEditLibrary.connect_material_expressions(VertexColorNode_ORM_B, 'A', OneMinusNode_B, '') MaterialEditLibrary.connect_material_expressions(VertexColorNode_ORM_B, 'R', orm_b_lerps[1], 'Alpha') MaterialEditLibrary.connect_material_expressions(VertexColorNode_ORM_B, 'G', orm_b_lerps[2], 'Alpha') MaterialEditLibrary.connect_material_expressions(VertexColorNode_ORM_B, 'B', orm_b_lerps[3], 'Alpha') MaterialEditLibrary.connect_material_expressions(VertexColorNode_ORM_B, 'A', orm_b_lerps[4], 'Alpha') # Make Lerp Connections MaterialEditLibrary.connect_material_expressions(orm_b_lerps[0], '', orm_b_lerps[1], 'A') MaterialEditLibrary.connect_material_expressions(orm_b_lerps[1], '', orm_b_lerps[2], 'A') MaterialEditLibrary.connect_material_expressions(orm_b_lerps[2], '', orm_b_lerps[3], 'A') MaterialEditLibrary.connect_material_expressions(orm_b_lerps[3], '', orm_b_lerps[4], 'A') # Connect last Lerp to the Base Color Channel of the Material MaterialEditLibrary.connect_material_property(orm_b_lerps[4], '', unreal.MaterialProperty.MP_METALLIC) EditorAssetLibrary.save_asset("/project/", True) #Create Material Instance MeshPaintInstance = AssetTools.create_asset("MeshPaintInstance", "/project/", unreal.MaterialInstanceConstant, unreal.MaterialInstanceConstantFactoryNew()) MaterialEditLibrary.set_material_instance_parent(MeshPaintInstance, MeshMaterial) MeshPaintInstance.set_editor_property("Parent", MeshMaterial) MaterialEditLibrary.update_material_instance(MeshPaintInstance) EditorAssetLibrary.save_asset("/project/", True) EditorAssetLibrary.save_asset("/project/", True)
import unreal print("This is for begining Unreal-Python script \n Type : from importlib import reload") # 언리얼 파이썬 API : 언리얼의 다양한 기능을 파이썬으로 제어하는 기능이다. 쯧.. # 4 def listAssetPaths(): # print paths of all assets under project root directory EAL = unreal.EditorAssetLibrary assetPaths = EAL.list_assets('/Game') for assetPath in assetPaths: print(assetPath) # 5 def getSelectionContentBrowser(): # print objects selected in content browser EUL = unreal.EditorUtilityLibrary selectedAssets = EUL.get_selected_assets() for selectedAsset in selectedAssets : print(selectedAsset) # 5 def getAllActors(): # print all actors in level EAS = unreal.EditorActorSubsystem() actors = EAS.get_all_level_actors() for actor in actors : print(actor) # 5 def getSelectedActors(): # print selected actors in level EAS = unreal.EditorActorSubsystem() selectedActors = EAS.get_selected_level_actors() for selectedActor in selectedActors : print(selectedActor) # 6 deprecated *A # def getAssetClass(classType): # # EAL = unreal.EditorAssetLibrary # # assetPaths = EAL.list_assets('/Game') # # assets = [] # # for assetPath in assetPaths: # assetData = EAL.find_asset_data(assetPath) # assetClass = assetData.asset_class # if assetClass == classType: # assets.append(assetData.get_asset()) # # #for asset in assets : print(asset) # return assets # *A def get_asset_class(class_type): # AssetRegistry 인스턴스 생성 -> 매우중요 asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() # 에셋 필터 설정 filter = unreal.ARFilter(class_names=[class_type], package_paths=['/Game'], recursive_paths=True) # 필터에 맞는 에셋 갖고옴 assets_data = asset_registry.get_assets(filter) # 실제 에셋 인스턴스 반환 assets = [data.get_asset() for data in assets_data] #for asset in assets : print(asset) return assets # 7 def getStaticMeshData(): staticMeshes = get_asset_class('StaticMesh') for staticMesh in staticMeshes: # assetImportData = staticMesh.get_editor_property('asset_import_data') # fbxFilePath = assetImportData.extract_filenames() # 파일 경로로 갖고옴 # print(fbxFilePath) lodGroupInfo = staticMesh.get_editor_property('lod_group') # 스태틱 메쉬의 프로퍼티를 갖고오는 방법 print(lodGroupInfo) # LOD가 1개인 애들을 모두 LargeProp 바꿔주는 추가 기능임 경우에 따라 주석 if lodGroupInfo == 'None': if staticMesh.get_num_lods() == 1: staticMesh.set_editor_property('lod_group', 'LargeProp') # print(staticMesh.get_name()) # print(staticMesh.get_num_lods()) # 8 def getStaticMeshLodData(): # get detail data from staticMeshdata PML = unreal.ProceduralMeshLibrary staticMeshes = get_asset_class('StaticMesh') for staticMesh in staticMeshes: staticMeshTriCount = [] numLODs = staticMesh.get_num_lods() for i in range (numLODs): numSections = staticMesh.get_num_sections(i) LODTriCount = 0 for j in range(numSections): sectionData = PML.get_section_from_static_mesh(staticMesh, i, j) #print(len(sectionData)) #for item in sectionData[0] : print (item) # 0번째 메쉬의 버텍스 좌표 전부나옴 #print(len(sectionData[0])) # 0번째 메쉬의 버텍스 개수 나옴 sectionTriCount = (len(sectionData[1]) / 3) LODTriCount += sectionTriCount staticMeshTriCount.append(LODTriCount) staticMeshReductions = [100] for i in range(1, len(staticMeshTriCount)): staticMeshReductions.append(int(staticMeshTriCount[i]/staticMeshTriCount[0]) * 100) print (staticMesh.get_name()) print (staticMeshTriCount) print (staticMeshReductions) print ('_____') def getSelectedActorsAttribute(): EAS = unreal.EditorActorSubsystem() selectedActors = EAS.get_selected_level_actors() if not selectedActors: unreal.log_warning("Warning : No SelectedActor") return for actor in selectedActors: attributes = dir(actor) for attribute in attributes: print(attribute) # P2U : 함수 호출 테스트 -> deprecated 파이썬에서 언리얼 함수를 호출하는 기능은 지양하자 def test(): # U2P 레벨에 있는 액터들 정보 # deprecated: actors = unreal.EditorLevelLibrary.get_all_level_actors() EAS = unreal.EditorActorSubsystem() actors = EAS.get_all_level_actors() a = 10; for actor in actors: print(a) if isinstance(actor, unreal.PyActor): actor.z_print()
# Copyright Epic Games, Inc. All Rights Reserved. import unreal import tempfile import unrealcmd import subprocess #------------------------------------------------------------------------------- def _build_include_tool(exec_context, ue_context): # Work out where MSBuild is vswhere = ( "vswhere.exe", "-latest", "-find MSBuild/*/project/.exe", ) proc = subprocess.Popen(" ".join(vswhere), stdout=subprocess.PIPE) msbuild_exe = next(iter(proc.stdout.readline, b""), b"").decode().rstrip() proc.stdout.close() msbuild_exe = msbuild_exe or "MSBuild.exe" # Get MSBuild to build IncludeTool engine = ue_context.get_engine() csproj_path = engine.get_dir() / "Source/project/.csproj" msbuild_args = ( "/target:Restore;Build", "/property:Configuration=Release,Platform=AnyCPU", "/v:m", str(csproj_path) ) return exec_context.create_runnable(msbuild_exe, *msbuild_args).run() == 0 #------------------------------------------------------------------------------- def _run_include_tool(exec_context, ue_context, target, variant, *inctool_args): temp_dir = tempfile.TemporaryDirectory() engine = ue_context.get_engine() it_bin_path = engine.get_dir() / "Binaries/project/.exe" if not it_bin_path.is_file(): it_bin_path = engine.get_dir() / "Binaries/project/.exe" it_args = ( "-Mode=Scan", "-Target=" + target, "-Platform=Linux", "-Configuration=" + variant, "-WorkingDir=" + temp_dir.name, *inctool_args, ) return exec_context.create_runnable(str(it_bin_path), *it_args).run() #------------------------------------------------------------------------------- class RunIncludeTool(unrealcmd.MultiPlatformCmd): """ Runs IncludeTool.exe """ target = unrealcmd.Arg(str, "The target to run the IncludeTool on") variant = unrealcmd.Arg("development", "Build variant to be processed (default=development)") inctoolargs = unrealcmd.Arg([str], "Arguments to pass through to IncludeTool") def complete_target(self, prefix): return ("editor", "game", "client", "server") def main(self): self.use_platform("linux") exec_context = self.get_exec_context() ue_context = self.get_unreal_context() # Establish the target to use try: target = unreal.TargetType[self.args.target.upper()] target = ue_context.get_target_by_type(target).get_name() except: target = self.args.target # Build self.print_info("Building IncludeToole") if not _build_include_tool(exec_context, ue_context): self.print_error("Failed to build IncludeTool") return False # Run variant = self.args.variant self.print_info("Running on", target + "/" + variant) return _run_include_tool(exec_context, ue_context, target, variant, *self.args.inctoolargs)
"""Spawn actors on the map based on map export data produced by MapExport.py. Should be used with internal UE API""" import os.path import unreal import json import re # Change me! map_data_filepath = "C:/project/ Projects/project/" \ "MapData/project/.json" PATH_TO_FILTER = None EXCLUDE_ENGINE_ASSETS = False level_library = unreal.EditorLevelLibrary editor_asset_library = unreal.EditorAssetLibrary relative_offset_loc = unreal.Vector(0, 0, 0) # + unreal.Vector(25400, # -76200, # 0) # relative_offset_loc = unreal.Vector(0, 0, 0) with open("C:/project/ Projects/project/" "MapData/project/.json", "r") as f: path_replacing_map = json.load(f) with open(map_data_filepath, "rb") as f: data = json.load(f) for element in data: path, transform = element["path"], element["transform"] path = re.search(r"\w+\s(?P<path>[\/\w]+).\w+", path).group("path") path = path_replacing_map.get(path, path) if PATH_TO_FILTER and path != PATH_TO_FILTER: continue print(path) if path.startswith("/") and editor_asset_library.does_asset_exist(path): if path.startswith("/Engine/") and EXCLUDE_ENGINE_ASSETS: continue asset = editor_asset_library.find_asset_data(path).get_asset() actor = level_library.spawn_actor_from_object(asset, transform["loc"]) if actor: actor.set_actor_rotation( unreal.Rotator(pitch=transform["rot"][0], roll=transform["rot"][1], yaw=transform["rot"][2]), True) actor.set_actor_scale3d(transform["scale"]) current_location = actor.get_actor_location() actor.set_actor_location(current_location + relative_offset_loc, False, False) else: print(f"Error: Couldn't spawn actor for {path}") else: print(f"Error: Asset {path} doesn't exist")
# -*- coding: utf-8 -*- """ https://blog.csdn.net/project/ """ # Import future modules from __future__ import absolute_import from __future__ import division from __future__ import print_function __author__ = "timmyliang" __email__ = "[email protected]" __date__ = "2022-04-02 20:48:10" # Import built-in modules import json import os import tempfile # Import local modules import unreal tmp_dir = tempfile.gettempdir() rot_path = os.path.join(tmp_dir, "test_unreal_rot.json") def main(): with open(rot_path) as rf: quat_dict = json.load(rf) for _, v in quat_dict.items(): quat = unreal.Quat(v[0], -v[1], v[2], -v[3]) rotator = quat.rotator() for actor in unreal.EditorLevelLibrary.get_selected_level_actors(): # NOTES(timmyliang): Maya DirectionalLight default rotation is point to the ground # NOTES(timmyliang): So we need to compensate this offset if isinstance(actor, unreal.DirectionalLight): rotator = rotator.delta(unreal.Rotator(0, 90, 0)) actor.set_actor_rotation(rotator, False) if __name__ == "__main__": main()
import unreal import os import json import tkinter as tk from tkinter import filedialog from tkinter import ttk def clean_texture_name(raw_name): if raw_name.startswith("Texture2D'") and raw_name.endswith("'"): raw_name = raw_name[len("Texture2D'"):-1] raw_name = os.path.splitext(raw_name)[0] return raw_name def parse_texture_params(json_data): texture_params = {} try: properties = json_data[0]['Properties'] except Exception as e: unreal.log_error(f"Error reading JSON properties: {e}") return texture_params for tex_param in properties.get('TextureParameterValues', []): param_info = tex_param.get('ParameterInfo', {}) param_name = param_info.get('Name', '').lower() param_value = tex_param.get('ParameterValue', {}) if isinstance(param_value, dict): raw_tex_name = param_value.get('ObjectName', '') cleaned_tex_name = clean_texture_name(raw_tex_name) texture_params[param_name] = cleaned_tex_name return texture_params def create_material_from_textures(material_name, texture_params, textures_root_path='/Game'): asset_tools = unreal.AssetToolsHelpers.get_asset_tools() factory = unreal.MaterialFactoryNew() package_path = '/project/' existing_material = unreal.EditorAssetLibrary.find_asset_data(f"{package_path}/{material_name}").get_asset() if existing_material: unreal.log_warning(f"Material '{material_name}' already exists. Skipping.") return existing_material new_material = asset_tools.create_asset(material_name, package_path, None, factory) if not new_material: unreal.log_error(f"Failed to create material: {material_name}") return None material_lib = unreal.MaterialEditingLibrary sample_nodes = {} x_pos = -384 y_pos = 0 for param_name, tex_name in texture_params.items(): tex_asset_path = f"{textures_root_path}/{tex_name}" texture_asset = unreal.EditorAssetLibrary.load_asset(tex_asset_path) if not texture_asset: alt_path = tex_asset_path.replace('/Game/', '/project/') texture_asset = unreal.EditorAssetLibrary.load_asset(alt_path) if not texture_asset: unreal.log_warning(f"Texture asset not found: {tex_asset_path}") continue tex_sample_node = material_lib.create_material_expression(new_material, unreal.MaterialExpressionTextureSample, x_pos, y_pos) tex_sample_node.texture = texture_asset if 'normal' in param_name: tex_sample_node.sampler_type = unreal.MaterialSamplerType.SAMPLERTYPE_NORMAL else: tex_sample_node.sampler_type = unreal.MaterialSamplerType.SAMPLERTYPE_COLOR sample_nodes[param_name] = tex_sample_node y_pos += 200 def connect_property(param, channel, target): if param in sample_nodes: material_lib.connect_material_property(sample_nodes[param], channel, getattr(unreal.MaterialProperty, target, unreal.MaterialProperty.MP_BASE_COLOR)) connect_property('albedo', 'RGB', 'MP_BASE_COLOR') connect_property('basecolor', 'RGB', 'MP_BASE_COLOR') connect_property('normal', 'RGB', 'MP_NORMAL') connect_property('roughness', 'R', 'MP_ROUGHNESS') connect_property('metallic', 'R', 'MP_METALLIC') connect_property('specular', 'R', 'MP_SPECULAR') connect_property('ao', 'R', 'MP_AMBIENT_OCCLUSION') connect_property('ambientocclusion', 'R', 'MP_AMBIENT_OCCLUSION') connect_property('emissive', 'RGB', 'MP_EMISSIVE_COLOR') connect_property('displacement', 'R', 'MP_WORLD_POSITION_OFFSET') material_lib.recompile_material(new_material) unreal.EditorAssetLibrary.save_loaded_asset(new_material) unreal.log(f"✅ Created material '{material_name}' with textures: {list(sample_nodes.keys())}") return new_material def process_json_folder_with_progress(folder_path): json_files = [f for f in os.listdir(folder_path) if f.endswith('.json')] # Tkinter setup for progress bar root = tk.Tk() root.title("Material Creation Progress") root.geometry("500x100") label = tk.Label(root, text="Creating materials...") label.pack(pady=5) progress = ttk.Progressbar(root, orient="horizontal", length=400, mode="determinate", maximum=len(json_files)) progress.pack(pady=10) root.update() for idx, json_file in enumerate(json_files, start=1): full_path = os.path.join(folder_path, json_file) unreal.log(f"📄 Processing: {full_path}") try: with open(full_path, 'r') as f: json_data = json.load(f) except Exception as e: unreal.log_error(f"Failed to load JSON file {json_file}: {e}") continue material_name = json_data[0].get('Name', os.path.splitext(json_file)[0]) texture_params = parse_texture_params(json_data) if not texture_params: unreal.log_warning(f"⚠️ No textures found in {json_file}") continue create_material_from_textures(material_name, texture_params) progress["value"] = idx root.update_idletasks() label.config(text="Done!") root.after(1500, root.destroy) root.mainloop() def choose_json_folder(): root = tk.Tk() root.withdraw() folder_path = filedialog.askdirectory(title="Select JSON Folder") return folder_path # Run the full process selected_folder = choose_json_folder() if selected_folder: process_json_folder_with_progress(selected_folder) else: unreal.log_warning("❌ No folder selected. Exiting.")
""" This script is used to fix collision properties of static actors in a game level. Usage: - Call the `fix_static_actors_collision()` function to fix collision for static actors at the current level. Functions: - `fix_static_actors_collision()`: Fixes the collision properties of static actors at the current level. Note: - The script assumes the presence of the `get_component_by_class()` """ import unreal from Common import get_component_by_class def fix_static_actors_collision(): complex_as_simple = int(unreal.CollisionTraceFlag.CTF_USE_COMPLEX_AS_SIMPLE.value) for actor in unreal.EditorLevelLibrary.get_all_level_actors(): print(f"Setup collision for: {actor.get_name()}") component = get_component_by_class(actor, unreal.StaticMeshComponent) static_mesh = component.static_mesh unreal.Cloud9ToolsLibrary.set_collision_complexity(static_mesh, complex_as_simple) unreal.EditorStaticMeshLibrary.remove_collisions(static_mesh) if __name__ == '__main__': fix_static_actors_collision()
import unreal from Lib import __lib_topaz__ as topaz base_MI : str = "/project/.MI_VrmMToonOptLitOpaque" # edit this to your liking #E:/project/.uasset selected : list[unreal.Texture2D] = topaz.get_selected_assets()[0] print( selected) unreal.SkeletalMesh.get_all_ # for i in selected : # i is unreal.Texture2D # newname : str = i.get_path_name().rsplit(".", 1)[0] # print(newname) # debug # material_instance : unreal.MaterialInstanceConstant = unreal.EditorAssetLibrary.duplicate_asset(base_MI,newname + "_MI") # print ( material_instance.get_texture_parameter_value('gltf_tex_diffuse') ) # print ( material_instance.get_texture_parameter_value('mtoon_tex_ShadeTexture') ) # unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value(material_instance, 'gltf_tex_diffuse', i) # unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value(material_instance, 'mtoon_tex_ShadeTexture', i)
# -*- coding: utf-8 -*- """Load Skeletal Mesh alembics.""" 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 SkeletalMeshAlembicLoader(plugin.Loader): """Load Unreal SkeletalMesh from Alembic""" product_types = {"pointcache", "skeletalMesh"} label = "Import Alembic Skeletal Mesh" representations = ["abc"] icon = "cube" color = "orange" root = AYON_ASSET_DIR @staticmethod def get_task(filename, asset_dir, asset_name, replace, default_conversion): task = unreal.AssetImportTask() options = unreal.AbcImportSettings() conversion_settings = unreal.AbcConversionSettings( preset=unreal.AbcConversionPreset.CUSTOM, flip_u=False, flip_v=False, rotation=[0.0, 0.0, 0.0], scale=[1.0, 1.0, 1.0]) 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( 'import_type', unreal.AlembicImportType.SKELETAL) if not default_conversion: conversion_settings = unreal.AbcConversionSettings( preset=unreal.AbcConversionPreset.CUSTOM, flip_u=False, flip_v=False, rotation=[0.0, 0.0, 0.0], scale=[1.0, 1.0, 1.0]) options.conversion_settings = conversion_settings task.options = options return task def import_and_containerize( self, filepath, asset_dir, asset_name, container_name, default_conversion=False ): unreal.EditorAssetLibrary.make_directory(asset_dir) task = self.get_task( filepath, asset_dir, asset_name, False, default_conversion) 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_path = context["folder"]["path"] folder_name = context["folder"]["name"] suffix = "_CON" asset_name = f"{folder_name}_{name}" if folder_name else f"{name}" version = context["version"]["version"] # Check if version is hero version and use different name if version < 0: name_version = f"{name}_hero" else: name_version = f"{name}_v{version:03d}" default_conversion = False if options.get("default_conversion"): default_conversion = options.get("default_conversion") 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, default_conversion) product_type = context["product"]["productType"] self.imprint( folder_path, 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 folder 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)
import unreal totalFrames = 100000 textDisplay = "i love python, an i guess i'll be using this for a while!" with unreal.ScopredSlowTask(totalFrames, textDisplay) as ST: ST.make_dialog(True) for i in range (totalFrames): if ST.should_cancel(): break unreal.log("one step!!!") ST.enter_progress_frame(1)
import unreal def get_component_handles(blueprint_asset_path): subsystem = unreal.get_engine_subsystem(unreal.SubobjectDataSubsystem) blueprint_asset = unreal.load_asset(blueprint_asset_path) subobject_data_handles = subsystem.k2_gather_subobject_data_for_blueprint(blueprint_asset) return subobject_data_handles def get_component_objects(blueprint_asset_path): objects = [] handles = get_component_handles(blueprint_asset_path) for handle in handles: data = unreal.SubobjectDataBlueprintFunctionLibrary.get_data(handle) object = unreal.SubobjectDataBlueprintFunctionLibrary.get_object(data) objects.append(object) return objects ## 함수 선언부 base_bp : str = '/project/' actor_comp_assets = [] asset_list = unreal.EditorUtilityLibrary.get_selected_assets() # selected Editor Asset List asset = asset_list[0] if len(asset_list) > 0 : for each in asset_list : component_objects = get_component_objects(base_bp) static_mesh_comp = component_objects[1] __static_mesh__ = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(each) __static_mesh_path_ = __static_mesh__.rsplit('/', 1)[0] __static_mesh_name_ = __static_mesh__.rsplit('/', 1)[1] __static_mesh_name_ = __static_mesh_name_.rsplit('.',1)[0] __static_mesh_name_ = __static_mesh_name_.replace('SM_','BP_') destination = __static_mesh_path_ + '/' + __static_mesh_name_ try: unreal.EditorAssetLibrary.delete_asset(destination) except: print('no pre-generated Asset') static_mesh_comp.set_editor_property('static_mesh',each) duplicated_bp = unreal.EditorAssetLibrary.duplicate_asset(base_bp,destination)
# Copyright Epic Games, Inc. All Rights Reserved import os from abc import abstractmethod import traceback from deadline_rpc.client import RPCClient import unreal import __main__ class _RPCContextManager: """ Context manager used for automatically marking a task as complete after the statement is done executing """ def __init__(self, proxy, task_id): """ Constructor """ # RPC Client proxy self._proxy = proxy # Current task id self._current_task_id = task_id def __enter__(self): return self._proxy def __exit__(self, exc_type, exc_val, exc_tb): """ Called when the context manager exits """ # Tell the server the task is complete self._proxy.complete_task(self._current_task_id) class BaseRPC: """ Base class for communicating with a Deadline RPC server. It is recommended this class is subclassed for any script that need to communicate with deadline. The class automatically handles connecting and marking tasks as complete when some abstract methods are implemented """ def __init__(self, port=None, ignore_rpc=False, verbose=False): """ This allows you to get an instance of the class without expecting an automatic connection to a rpc server. This will allow you to have a class that can both be executed in a deadline commandline interface or as a class instance. :param port: Optional port to connect to :param ignore_rpc: Flag to short circuit connecting to a rpc server """ self._ignore_rpc = ignore_rpc self._proxy = None if not self._ignore_rpc: if not port: try: port = os.environ["DEADLINE_RPC_PORT"] except KeyError: raise RuntimeError( "There was no port specified for the rpc server" ) self._port = int(port) # Make a connection to the RPC server self._proxy = self.__establish_connection() self.current_task_id = -1 # Setting this to -1 allows us to # render the first task. i.e task 0 self._get_next_task = True self._tick_handle = None self._verbose_logging = verbose # Set up a property to notify the class when a task is complete self.__create_on_task_complete_global() self.task_complete = False self._sent_task_status = False # Start getting tasks to process self._execute() @staticmethod def __create_on_task_complete_global(): """ Creates a property in the globals that allows fire and forget tasks to notify the class when a task is complete and allowing it to get the next task :return: """ if not hasattr(__main__, "__notify_task_complete__"): __main__.__notify_task_complete__ = False return __main__.__notify_task_complete__ def __establish_connection(self): """ Makes a connection to the Deadline RPC server """ print(f"Connecting to rpc server on port `{self._port}`") try: _client = RPCClient(port=int(self._port)) proxy = _client.proxy proxy.connect() except Exception: raise else: if not proxy.is_connected(): raise RuntimeError( "A connection could not be made with the server" ) print(f"Connection to server established!") return proxy def _wait_for_next_task(self, delta_seconds): """ Checks to see if there are any new tasks and executes when there is :param delta_seconds: :return: """ # skip if our task is the same as previous if self.proxy.get_task_id() == self.current_task_id: if self._verbose_logging: print("Waiting on next task..") return print("New task received!") # Make sure we are explicitly told the task is complete by clearing # the globals when we get a new task __main__.__notify_task_complete__ = False self.task_complete = False # Unregister the tick handle and execute the task unreal.unregister_slate_post_tick_callback(self._tick_handle) self._tick_handle = None # Set the current task and execute self.current_task_id = self.proxy.get_task_id() self._get_next_task = False print(f"Executing task `{self.current_task_id}`") self.proxy.set_status_message("Executing task command") # Execute the next task # Make sure we fail the job if we encounter any exceptions and # provide the traceback to the proxy server try: self.execute() except Exception: trace = traceback.format_exc() print(trace) self.proxy.fail_render(trace) raise # Start a non-blocking loop that waits till its notified a task is # complete self._tick_handle = unreal.register_slate_post_tick_callback( self._wait_on_task_complete ) def _wait_on_task_complete(self, delta_seconds): """ Waits till a task is mark as completed :param delta_seconds: :return: """ if self._verbose_logging: print("Waiting on task to complete..") if not self._sent_task_status: self.proxy.set_status_message("Waiting on task completion..") self._sent_task_status = True if __main__.__notify_task_complete__ or self.task_complete: # Exiting the waiting loop unreal.unregister_slate_post_tick_callback(self._tick_handle) self._tick_handle = None print("Task marked complete. Getting next Task") self.proxy.set_status_message("Task complete!") # Reset the task status notification self._sent_task_status = False # Automatically marks a task complete when the execute function # exits with _RPCContextManager(self.proxy, self.current_task_id): self._get_next_task = True # This will allow us to keep getting tasks till the process is # closed self._execute() def _execute(self): """ Start the execution process """ if self._get_next_task and not self._ignore_rpc: # register a callback with the editor that will check and execute # the task on editor tick self._tick_handle = unreal.register_slate_post_tick_callback( self._wait_for_next_task ) @property def proxy(self): """ Returns an instance of the Client proxy :return: """ if not self._proxy: raise RuntimeError("There is no connected proxy!") return self._proxy @property def is_connected(self): """ Property that returns if a connection was made with the server :return: """ return self.proxy.is_connected() @abstractmethod def execute(self): """ Abstract methods that is executed to perform a task job/command. This method must be implemented when communicating with a Deadline RPC server :return: """ pass
import unittest import unreal from sound_utils import * from tests.test_config import * class TestSoundUtils(unittest.TestCase): def setUp(self): """Set up test environment before each test.""" self.test_package_path = TEST_SOUND_PATH self.test_sound_name = TEST_SOUND_NAME self.test_sound_file = "/project/.wav" # You'll need to provide a test sound file def test_create_sound_wave(self): """Test sound wave creation.""" sound_wave = create_sound_wave( self.test_sound_name, self.test_package_path, self.test_sound_file ) self.assertIsNotNone(sound_wave) self.assertIsInstance(sound_wave, unreal.SoundWave) def test_create_sound_cue(self): """Test sound cue creation.""" sound_cue = create_sound_cue( self.test_sound_name, self.test_package_path ) self.assertIsNotNone(sound_cue) self.assertIsInstance(sound_cue, unreal.SoundCue) def test_add_sound_to_cue(self): """Test adding sound to cue.""" sound_wave = create_sound_wave( "TestWave", self.test_package_path, self.test_sound_file ) sound_cue = create_sound_cue( self.test_sound_name, self.test_package_path ) result = add_sound_to_cue(sound_cue, sound_wave) self.assertIsNotNone(result) self.assertTrue(result) def test_create_sound_mix(self): """Test sound mix creation.""" sound_mix = create_sound_mix( "TestMix", self.test_package_path ) self.assertIsNotNone(sound_mix) self.assertIsInstance(sound_mix, unreal.SoundMix) def test_add_effect_to_sound_mix(self): """Test adding effect to sound mix.""" sound_mix = create_sound_mix( "TestMix", self.test_package_path ) effect = add_effect_to_sound_mix( sound_mix, unreal.SoundEffectSourcePreset, "TestEffect" ) self.assertIsNotNone(effect) self.assertEqual(effect.get_editor_property('EffectName'), "TestEffect") def test_create_sound_class(self): """Test sound class creation.""" sound_class = create_sound_class( "TestClass", self.test_package_path ) self.assertIsNotNone(sound_class) self.assertIsInstance(sound_class, unreal.SoundClass) def test_set_sound_class_properties(self): """Test setting sound class properties.""" sound_class = create_sound_class( "TestClass", self.test_package_path ) set_sound_class_properties( sound_class, volume=0.8, pitch=1.2, low_pass_filter_frequency=1000.0 ) self.assertEqual(sound_class.get_editor_property('Volume'), 0.8) self.assertEqual(sound_class.get_editor_property('Pitch'), 1.2) self.assertEqual(sound_class.get_editor_property('LowPassFilterFrequency'), 1000.0) def test_create_sound_attenuation(self): """Test sound attenuation creation.""" attenuation = create_sound_attenuation( "TestAttenuation", self.test_package_path ) self.assertIsNotNone(attenuation) self.assertIsInstance(attenuation, unreal.SoundAttenuation) def test_set_attenuation_properties(self): """Test setting attenuation properties.""" attenuation = create_sound_attenuation( "TestAttenuation", self.test_package_path ) set_attenuation_properties( attenuation, falloff_distance=2000.0, spatialization=True ) self.assertEqual(attenuation.get_editor_property('FalloffDistance'), 2000.0) self.assertTrue(attenuation.get_editor_property('bSpatialize')) def tearDown(self): """Clean up after each test.""" # Add cleanup code here if needed pass if __name__ == '__main__': unittest.main()
# coding: utf-8 import unreal import argparse print("VRM4U python begin") print (__file__) parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") parser.add_argument("-meta") args = parser.parse_args() print(args.vrm) #print(dummy[3]) humanoidBoneList = [ "hips", "leftUpperLeg", "rightUpperLeg", "leftLowerLeg", "rightLowerLeg", "leftFoot", "rightFoot", "spine", "chest", "upperChest", # 9 optional "neck", "head", "leftShoulder", "rightShoulder", "leftUpperArm", "rightUpperArm", "leftLowerArm", "rightLowerArm", "leftHand", "rightHand", "leftToes", "rightToes", "leftEye", "rightEye", "jaw", "leftThumbProximal", # 24 "leftThumbIntermediate", "leftThumbDistal", "leftIndexProximal", "leftIndexIntermediate", "leftIndexDistal", "leftMiddleProximal", "leftMiddleIntermediate", "leftMiddleDistal", "leftRingProximal", "leftRingIntermediate", "leftRingDistal", "leftLittleProximal", "leftLittleIntermediate", "leftLittleDistal", "rightThumbProximal", "rightThumbIntermediate", "rightThumbDistal", "rightIndexProximal", "rightIndexIntermediate", "rightIndexDistal", "rightMiddleProximal", "rightMiddleIntermediate", "rightMiddleDistal", "rightRingProximal", "rightRingIntermediate", "rightRingDistal", "rightLittleProximal", "rightLittleIntermediate", "rightLittleDistal", #54 ] humanoidBoneParentList = [ "", #"hips", "hips",#"leftUpperLeg", "hips",#"rightUpperLeg", "leftUpperLeg",#"leftLowerLeg", "rightUpperLeg",#"rightLowerLeg", "leftLowerLeg",#"leftFoot", "rightLowerLeg",#"rightFoot", "hips",#"spine", "spine",#"chest", "chest",#"upperChest" 9 optional "chest",#"neck", "neck",#"head", "chest",#"leftShoulder", # <-- upper.. "chest",#"rightShoulder", "leftShoulder",#"leftUpperArm", "rightShoulder",#"rightUpperArm", "leftUpperArm",#"leftLowerArm", "rightUpperArm",#"rightLowerArm", "leftLowerArm",#"leftHand", "rightLowerArm",#"rightHand", "leftFoot",#"leftToes", "rightFoot",#"rightToes", "head",#"leftEye", "head",#"rightEye", "head",#"jaw", "leftHand",#"leftThumbProximal", "leftThumbProximal",#"leftThumbIntermediate", "leftThumbIntermediate",#"leftThumbDistal", "leftHand",#"leftIndexProximal", "leftIndexProximal",#"leftIndexIntermediate", "leftIndexIntermediate",#"leftIndexDistal", "leftHand",#"leftMiddleProximal", "leftMiddleProximal",#"leftMiddleIntermediate", "leftMiddleIntermediate",#"leftMiddleDistal", "leftHand",#"leftRingProximal", "leftRingProximal",#"leftRingIntermediate", "leftRingIntermediate",#"leftRingDistal", "leftHand",#"leftLittleProximal", "leftLittleProximal",#"leftLittleIntermediate", "leftLittleIntermediate",#"leftLittleDistal", "rightHand",#"rightThumbProximal", "rightThumbProximal",#"rightThumbIntermediate", "rightThumbIntermediate",#"rightThumbDistal", "rightHand",#"rightIndexProximal", "rightIndexProximal",#"rightIndexIntermediate", "rightIndexIntermediate",#"rightIndexDistal", "rightHand",#"rightMiddleProximal", "rightMiddleProximal",#"rightMiddleIntermediate", "rightMiddleIntermediate",#"rightMiddleDistal", "rightHand",#"rightRingProximal", "rightRingProximal",#"rightRingIntermediate", "rightRingIntermediate",#"rightRingDistal", "rightHand",#"rightLittleProximal", "rightLittleProximal",#"rightLittleIntermediate", "rightLittleIntermediate",#"rightLittleDistal", ] for i in range(len(humanoidBoneList)): humanoidBoneList[i] = humanoidBoneList[i].lower() for i in range(len(humanoidBoneParentList)): humanoidBoneParentList[i] = humanoidBoneParentList[i].lower() ###### reg = unreal.AssetRegistryHelpers.get_asset_registry(); ## rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r #rig = rigs[10] hierarchy = unreal.ControlRigBlueprintLibrary.get_hierarchy(rig) h_con = hierarchy.get_controller() #elements = h_con.get_selection() #sk = rig.get_preview_mesh() #k = sk.skeleton #print(k) #print(sk.bone_tree) # #kk = unreal.RigElementKey(unreal.RigElementType.BONE, "hipssss"); #kk.name = "" #kk.type = 1; #print(h_con.get_bone(kk)) #print(h_con.get_elements()) ### 全ての骨 modelBoneListAll = [] modelBoneNameList = [] #for e in reversed(h_con.get_elements()): # if (e.type != unreal.RigElementType.BONE): # h_con.remove_element(e) for e in hierarchy.get_bones(): if (e.type == unreal.RigElementType.BONE): modelBoneListAll.append(e) modelBoneNameList.append("{}".format(e.name).lower()) # else: # h_con.remove_element(e) print(modelBoneListAll[0]) #exit #print(k.get_editor_property("bone_tree")[0].get_editor_property("translation_retargeting_mode")) #print(k.get_editor_property("bone_tree")[0].get_editor_property("parent_index")) #unreal.select #vrmlist = unreal.VrmAssetListObject #vrmmeta = vrmlist.vrm_meta_object #print(vrmmeta.humanoid_bone_table) #selected_actors = unreal.EditorLevelLibrary.get_selected_level_actors() #selected_static_mesh_actors = unreal.EditorFilterLibrary.by_class(selected_actors,unreal.StaticMeshActor.static_class()) #static_meshes = np.array([]) ## meta 取得 reg = unreal.AssetRegistryHelpers.get_asset_registry(); a = reg.get_all_assets(); if (args.meta): for aa in a: if (aa.get_editor_property("object_path") == args.meta): v:unreal.VrmMetaObject = aa vv = aa.get_asset() if (vv == None): for aa in a: if (aa.get_editor_property("object_path") == args.vrm): v:unreal.VrmAssetListObject = aa vv = v.get_asset().vrm_meta_object print(vv) meta = vv #v:unreal.VrmAssetListObject = None #if (True): # a = reg.get_assets_by_path(args.vrm) # a = reg.get_all_assets(); # for aa in a: # if (aa.get_editor_property("object_path") == args.vrm): # v:unreal.VrmAssetListObject = aa #v = unreal.VrmAssetListObject.cast(v) #print(v) #unreal.VrmAssetListObject.vrm_meta_object #meta = v.vrm_meta_object() #meta = unreal.EditorFilterLibrary.by_class(asset,unreal.VrmMetaObject.static_class()) print (meta) #print(meta[0].humanoid_bone_table) ### モデル骨のうち、ヒューマノイドと同じもの ### 上の変換テーブル humanoidBoneToModel = {"" : ""} humanoidBoneToModel.clear() ### modelBoneでループ #for bone_h in meta.humanoid_bone_table: for bone_h_base in humanoidBoneList: bone_h = None for e in meta.humanoid_bone_table: if ("{}".format(e).lower() == bone_h_base): bone_h = e; break; print("{}".format(bone_h)) if (bone_h==None): continue bone_m = meta.humanoid_bone_table[bone_h] try: i = modelBoneNameList.index(bone_m.lower()) except: i = -1 if (i < 0): continue if ("{}".format(bone_h).lower() == "upperchest"): continue; humanoidBoneToModel["{}".format(bone_h).lower()] = "{}".format(bone_m).lower() if ("{}".format(bone_h).lower() == "chest"): #upperchestがあれば、これの次に追加 bh = 'upperchest' print("upperchest: check begin") for e in meta.humanoid_bone_table: if ("{}".format(e).lower() != 'upperchest'): continue bm = "{}".format(meta.humanoid_bone_table[e]).lower() if (bm == ''): continue humanoidBoneToModel[bh] = bm humanoidBoneParentList[10] = "upperchest" humanoidBoneParentList[12] = "upperchest" humanoidBoneParentList[13] = "upperchest" print("upperchest: find and insert parent") break print("upperchest: check end") parent=None control_to_mat={None:None} count = 0 ### 骨名からControlへのテーブル name_to_control = {"dummy_for_table" : None} print("loop begin") ###### root key = unreal.RigElementKey(unreal.RigElementType.NULL, 'root_s') space = hierarchy.find_null(key) if (space.get_editor_property('index') < 0): space = h_con.add_null('root_s', space_type=unreal.RigSpaceType.SPACE) else: space = key key = unreal.RigElementKey(unreal.RigElementType.CONTROL, 'root_c') control = hierarchy.find_control(key) if (control.get_editor_property('index') < 0): control = h_con.add_control('root_c', space_name=space.name, gizmo_color=[1.0, 0.0, 0.0, 1.0], ) else: control = key h_con.set_parent(control, space) parent = control setting = h_con.get_control_settings(control) setting.shape_visible = False h_con.set_control_settings(control, setting) for ee in humanoidBoneToModel: element = humanoidBoneToModel[ee] humanoidBone = ee modelBoneNameSmall = element # 対象の骨 #modelBoneNameSmall = "{}".format(element.name).lower() #humanoidBone = modelBoneToHumanoid[modelBoneNameSmall]; boneNo = humanoidBoneList.index(humanoidBone) print("{}_{}_{}__parent={}".format(modelBoneNameSmall, humanoidBone, boneNo,humanoidBoneParentList[boneNo])) # 親 if count != 0: parent = name_to_control[humanoidBoneParentList[boneNo]] # 階層作成 bIsNew = False name_s = "{}_s".format(humanoidBone) key = unreal.RigElementKey(unreal.RigElementType.NULL, name_s) space = hierarchy.find_null(key) if (space.get_editor_property('index') < 0): space = h_con.add_space(name_s, space_type=unreal.RigSpaceType.SPACE) bIsNew = True else: space = key name_c = "{}_c".format(humanoidBone) key = unreal.RigElementKey(unreal.RigElementType.CONTROL, name_c) control = hierarchy.find_control(key) if (control.get_editor_property('index') < 0): control = h_con.add_control(name_c, space_name=space.name, gizmo_color=[1.0, 0.0, 0.0, 1.0], ) #h_con.get_control(control).gizmo_transform = gizmo_trans if (24<=boneNo & boneNo<=53): gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.1, 0.1, 0.1]) else: gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1, 1, 1]) if (17<=boneNo & boneNo<=18): gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1, 1, 1]) cc = h_con.get_control(control) cc.set_editor_property('gizmo_transform', gizmo_trans) cc.set_editor_property('control_type', unreal.RigControlType.ROTATOR) h_con.set_control(cc) #h_con.set_control_value_transform(control,gizmo_trans) bIsNew = True else: control = key if (bIsNew == True): h_con.set_parent(control, space) # テーブル登録 name_to_control[humanoidBone] = control print(humanoidBone) # ロケータ 座標更新 # 不要な上層階層を考慮 gTransform = hierarchy.get_global_transform(modelBoneListAll[modelBoneNameList.index(modelBoneNameSmall)]) if count == 0: bone_initial_transform = gTransform else: #bone_initial_transform = h_con.get_initial_transform(element) bone_initial_transform = gTransform.multiply(control_to_mat[parent].inverse()) hierarchy.set_global_transform(space, gTransform, True) control_to_mat[control] = gTransform # 階層修正 h_con.set_parent(space, parent) count += 1 if (count >= 500): break
import unreal actors = unreal.EditorLevelLibrary.get_all_level_actors() for actor in actors: components = actor.get_components_by_class(unreal.MeshComponent) for comp in components: material_count = comp.get_num_materials() for idx in range(material_count): material_interface = comp.get_material(idx) if material_interface: # get_base_material() 호출 base_material = material_interface.get_base_material() print(f"{actor.get_name()} - Slot {idx} Base Material: {base_material.get_name()}") unreal.AssetToolsHelpers.get_asset_tools().open_editor_for_assets([base_material])
import unreal import sys from os.path import dirname, basename, isfile, join import glob import importlib import traceback dir_name = dirname(__file__) dir_basename = basename(dir_name) modules = glob.glob(join(dir_name, "*.py")) __all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')] unreal.log("""@ #################### Load UI Library #################### """) for m in __all__: # __import__(m, locals(), globals()) try: mod = importlib.import_module("{}.{}".format(dir_basename, m)) if m in globals(): unreal.log("""@ #################### ReLoad UI Library #################### """) try: reload(mod) except: importlib.reload(mod) unreal.log("Successfully import {}".format(m)) except Exception as why: unreal.log_error("Fail to import {}.\n {}".format(m, why)) traceback.print_exc(file=sys.stdout) unreal.log("""@ #################### """)
import unreal import os import math MATERIAL_DIR = "/project/" SPACING = 1000.0 BLOCK_SPACING = 4500.0 # 文件夹分块间距 SPHERE_HEIGHT = 100.0 TEXT_HEIGHT = 300.0 BLOCK_TITLE_HEIGHT = 800.0 # block标题高度 TEXT_SIZE = 100.0 BLOCK_TITLE_SIZE = 200.0 # block标题字体大小 FOLDER_NAME = "material" SPHERE_MESH_PATH = '/project/' BOARD_MATERIAL_PATH = "/project/" def get_best_grid(n): x = math.ceil(math.sqrt(n)) y = math.ceil(n / x) return x, y def get_color_by_index(idx, total): """根据索引生成不同的颜色(RGB 0-1)""" hue = (idx / total) % 1.0 color = unreal.LinearColor() color.set_random_hue() return color.to_rgbe() def create_spheres_for_materials(): asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() assets = asset_registry.get_assets_by_path(MATERIAL_DIR, recursive=True) # 按文件夹分组 folder_dict = {} for asset in assets: asset: unreal.AssetData folder_name = os.path.basename(str(asset.package_path)) if folder_name not in folder_dict: folder_dict[folder_name] = [] folder_dict[folder_name].append((str(asset.package_name), folder_name, str(asset.asset_name))) sphere_mesh = unreal.EditorAssetLibrary.load_asset(SPHERE_MESH_PATH) box_mesh = unreal.EditorAssetLibrary.load_asset('/project/') board_material = unreal.EditorAssetLibrary.load_asset(BOARD_MATERIAL_PATH) # block grid 计算 block_names = list(folder_dict.keys()) block_count = len(block_names) block_cols, block_rows = get_best_grid(block_count) # 计算每个block的宽高 block_sizes = [] for mats in folder_dict.values(): cols, rows = get_best_grid(len(mats)) width = (cols - 1) * SPACING if cols > 1 else 0 height = (rows - 1) * SPACING if rows > 1 else 0 block_sizes.append((width, height, cols, rows)) # block grid整体居中 total_grid_width = block_cols * BLOCK_SPACING total_grid_height = block_rows * BLOCK_SPACING start_x = -total_grid_width / 2 + BLOCK_SPACING / 2 start_y = -total_grid_height / 2 + BLOCK_SPACING / 2 for block_idx, folder in enumerate(block_names): mats = folder_dict[folder] block_width, block_height, cols, rows = block_sizes[block_idx] grid_row = block_idx // block_cols grid_col = block_idx % block_cols # block左上角坐标 block_origin_x = start_x + grid_col * BLOCK_SPACING - block_width / 2 block_origin_y = start_y + grid_row * BLOCK_SPACING - block_height / 2 folder_path = f"{FOLDER_NAME}/{folder}" if folder else FOLDER_NAME # 生成block大标题(放到folder目录下) block_title_location = unreal.Vector( block_origin_x + block_width / 2, block_origin_y - SPACING, BLOCK_TITLE_HEIGHT ) block_title_actor:unreal.TextRenderActor = unreal.EditorLevelLibrary.spawn_actor_from_class( unreal.TextRenderActor, block_title_location ) block_title_actor.set_actor_label(f"BlockTitle_{folder}") block_title_actor.set_folder_path(folder_path) block_title_comp = block_title_actor.text_render block_title_comp.set_text(folder) block_title_comp.set_horizontal_alignment(unreal.HorizTextAligment.EHTA_CENTER) block_title_comp.set_vertical_alignment(unreal.VerticalTextAligment.EVRTA_TEXT_CENTER) block_title_comp.set_world_size(BLOCK_TITLE_SIZE) block_color = get_color_by_index(block_idx, block_count) block_title_comp.set_text_render_color(block_color) # 生成底板 board_location = unreal.Vector( block_origin_x + block_width / 2, block_origin_y + block_height / 2, SPHERE_HEIGHT - 120 ) board_actor:unreal.StaticMeshActor = unreal.EditorLevelLibrary.spawn_actor_from_class( unreal.StaticMeshActor, board_location ) board_actor.set_actor_label(f"BlockBoard_{folder}") board_actor.set_folder_path(folder_path) board_actor.static_mesh_component.set_static_mesh(box_mesh) board_actor.set_actor_scale3d(unreal.Vector( max(cols * 1.1, 1) * SPACING / 100, max(rows * 1.1, 1) * SPACING / 100, 0.2 )) if board_material and isinstance(board_material, unreal.MaterialInterface): board_actor.static_mesh_component.set_material(0, board_material) # 生成球体和文字 for idx, (mat_path, mat_folder, mat_name) in enumerate(mats): row = idx // cols col = idx % cols x = block_origin_x + col * SPACING y = block_origin_y + row * SPACING location = unreal.Vector(x, y, SPHERE_HEIGHT) sphere_actor = unreal.EditorLevelLibrary.spawn_actor_from_class( unreal.StaticMeshActor, location ) sphere_actor.set_actor_label(f"Sphere_{mat_name}") sphere_actor.static_mesh_component.set_static_mesh(sphere_mesh) sphere_actor.set_folder_path(folder_path) material = unreal.EditorAssetLibrary.load_asset(mat_path) if material and isinstance(material, unreal.MaterialInterface): sphere_actor.static_mesh_component.set_material(0, material) else: unreal.log_warning(f"{mat_path} 不是有效的材质,未设置到球体上。") text_location = unreal.Vector(x, y, TEXT_HEIGHT) text_actor = unreal.EditorLevelLibrary.spawn_actor_from_class( unreal.TextRenderActor, text_location ) text_actor.attach_to_actor(sphere_actor, "", unreal.AttachmentRule.KEEP_WORLD, unreal.AttachmentRule.KEEP_WORLD, unreal.AttachmentRule.KEEP_WORLD) text_actor.set_actor_label(f"Text_{mat_name}") text_actor.set_folder_path(folder_path) text_comp = text_actor.text_render text_comp.set_text(mat_name) text_comp.set_horizontal_alignment(unreal.HorizTextAligment.EHTA_CENTER) text_comp.set_vertical_alignment(unreal.VerticalTextAligment.EVRTA_TEXT_CENTER) text_comp.set_world_size(TEXT_SIZE) unreal.log(f"Created spheres by folder with title from {MATERIAL_DIR}") if __name__ == "__main__": create_spheres_for_materials()
# coding: utf-8 import unreal import os import sys sys.path.append('C:/project/-packages') from PySide.QtGui import * from PySide import QtUiTools WINDOW_NAME = 'Qt Window Three' UI_FILE_FULLNAME = os.path.join(os.path.dirname(__file__), 'ui', 'window_scale.ui').replace('\\','/') class QtWindowThree(QWidget): def __init__(self, parent=None): super(QtWindowThree, self).__init__(parent) self.aboutToClose = None self.widget = QtUiTools.QUiLoader().load(UI_FILE_FULLNAME) self.widget.setParent(self) self.setWindowTitle(WINDOW_NAME) self.setGeometry(100, 100, self.widget.width(),self.widget.height()) self.initialiseWidget() def clossEvent(self, event): if self.aboutToClose: self.aboutToClose(self) event.accept() def eventTick(self, delta_seconds): self.myTick(delta_seconds) def initialiseWidget(self): self.time_while_this_window_is_open = 0.0 self.random_actor = None self.random_actor_is_going_up = True self.widget.pushButton.clicked.connect(self.scaleRandomActorInScene) def scaleRandomActorInScene(self): import random import WorldFunctions_2 all_actors = WorldFunctions_2.sortActors(use_selection=False, actor_class=unreal.StaticMeshActor, actor_tag=None) rand = random.randrange(0, len(all_actors)) self.random_actor = all_actors[rand] def myTick(self, delta_seconds): self.time_while_this_window_is_open += delta_seconds self.widget.label.setText("{} Seconds".format(self.time_while_this_window_is_open)) if self.random_actor: actor_scale = self.random_actor.get_actor_scale3d() speed = 3.0 * delta_seconds if self.random_actor_is_going_up: if actor_scale.z > 2.0: self.random_actor_is_going_up = False else: speed = -speed if actor_scale.z < 0.5: self.random_actor_is_going_up = True self.random_actor.set_actor_scale3d(unreal.Vector(actor_scale.x + speed, actor_scale.y + speed, actor_scale.z + speed))
# 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 spawns some actors and then uses the API to instantiate an HDA and set the actors as world inputs. The inputs are set during post instantiation (before the first cook). After the first cook and output creation (post processing) the input structure is fetched and logged. """ import unreal _g_wrapper = None def get_test_hda_path(): return '/project/.subnet_test_2_0' def get_test_hda(): return unreal.load_object(None, get_test_hda_path()) def get_geo_asset_path(): return '/project/.Cube' def get_geo_asset(): return unreal.load_object(None, get_geo_asset_path()) def get_cylinder_asset_path(): return '/project/.Cylinder' def get_cylinder_asset(): return unreal.load_object(None, get_cylinder_asset_path()) def configure_inputs(in_wrapper): print('configure_inputs') # Unbind from the delegate in_wrapper.on_post_instantiation_delegate.remove_callable(configure_inputs) # Spawn some actors actors = spawn_actors() # Create a world input world_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPIWorldInput) # Set the input objects/assets for this input world_input.set_input_objects(actors) # copy the input data to the HDA as node input 0 in_wrapper.set_input_at_index(0, world_input) # We can now discard the API input object world_input = None # Set the subnet_test HDA to output its first input in_wrapper.set_int_parameter_value('enable_geo', 1) def print_api_input(in_input): print('\t\tInput type: {0}'.format(in_input.__class__)) print('\t\tbKeepWorldTransform: {0}'.format(in_input.keep_world_transform)) print('\t\tbImportAsReference: {0}'.format(in_input.import_as_reference)) if isinstance(in_input, unreal.HoudiniPublicAPIWorldInput): print('\t\tbPackBeforeMerge: {0}'.format(in_input.pack_before_merge)) print('\t\tbExportLODs: {0}'.format(in_input.export_lo_ds)) print('\t\tbExportSockets: {0}'.format(in_input.export_sockets)) print('\t\tbExportColliders: {0}'.format(in_input.export_colliders)) print('\t\tbIsWorldInputBoundSelector: {0}'.format(in_input.is_world_input_bound_selector)) print('\t\tbWorldInputBoundSelectorAutoUpdate: {0}'.format(in_input.world_input_bound_selector_auto_update)) 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 spawn_actors(): actors = [] # Spawn a static mesh actor and assign a cylinder to its static mesh # component actor = unreal.EditorLevelLibrary.spawn_actor_from_class( unreal.StaticMeshActor, location=(0, 0, 0)) actor.static_mesh_component.set_static_mesh(get_cylinder_asset()) actor.set_actor_label('Cylinder') actor.set_actor_transform( unreal.Transform( (-200, 0, 0), (0, 0, 0), (2, 2, 2), ), sweep=False, teleport=True ) actors.append(actor) # Spawn a static mesh actor and assign a cube to its static mesh # component actor = unreal.EditorLevelLibrary.spawn_actor_from_class( unreal.StaticMeshActor, location=(0, 0, 0)) actor.static_mesh_component.set_static_mesh(get_geo_asset()) actor.set_actor_label('Cube') actor.set_actor_transform( unreal.Transform( (200, 0, 100), (45, 0, 45), (2, 2, 2), ), sweep=False, teleport=True ) actors.append(actor) return actors def run(): # get the API singleton api = unreal.HoudiniPublicAPIBlueprintLib.get_api() global _g_wrapper # instantiate an asset with auto-cook enabled _g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform()) # Configure inputs on_post_instantiation, after instantiation, but before first cook _g_wrapper.on_post_instantiation_delegate.add_callable(configure_inputs) # Bind on_post_processing, after cook + output creation _g_wrapper.on_post_processing_delegate.add_callable(print_inputs) if __name__ == '__main__': run()
import unreal '''NA Number''' num = 39 '''NA Number''' '''Default Directories''' Basepath = '/project/' + str(num) + '/' BSAssetPath = Basepath + '/project/' AnimAssetPath = Basepath + '/Animation/' '''Default Directories''' bsNames = ["IdleRun_BS_Peaceful", "IdleRun_BS_Battle", "Down_BS", "Groggy_BS", "LockOn_BS", "Airborne_BS"] '''Value Set''' runSpeed = 400 walkSpeed = 150 defaultSamplingVector = unreal.Vector(0.0, 0.0, 0.0) defaultSampler = unreal.BlendSample() defaultSampler.set_editor_property("sample_value",defaultSamplingVector) Anims = unreal.EditorAssetLibrary.list_assets(AnimAssetPath) '''Value Set end''' '''BS Samplers Setting START ''' BS_idle_peace_path = BSAssetPath + bsNames[1] BS_idle_peace = unreal.EditorAssetLibrary.load_asset(BS_idle_peace_path) defaultSampler.set_editor_property("animation", '''BS Samplers Setting END ''' i=0 while i < len(Anims): found_word = Anims[i].find('idle') if found_word != -1: print('yes')
import unreal swap1_material = unreal.EditorAssetLibrary.load_asset("Material'/project/-ON-002-MEADOWS-ARCH-3DView-_3D_-_anurag_saini_ltl_/project/'") if swap1_material is None: print "The swap1 material can't be loaded" quit() swap2_material = unreal.EditorAssetLibrary.load_asset("Material'/project/'") if swap2_material is None: print "The swap2 material can't be loaded" quit() # Find all StaticMesh Actor in the Level actor_list = unreal.EditorLevelLibrary.get_all_level_actors() actor_list = unreal.EditorFilterLibrary.by_class(actor_list, unreal.StaticMeshActor.static_class()) unreal.EditorLevelLibrary.replace_mesh_components_materials_on_actors(actor_list, swap1_material, swap2_material)
import unreal import os # instances of unreal classes editor_util = unreal.EditorUtilityLibrary() editor_asset_lib = unreal.EditorAssetLibrary() # get the selected assets selected_assets = editor_util.get_selected_assets() num_assets = len(selected_assets) removed = 0 # instantly delete assets or move to Trash folder instant_delete = True trash_folder = os.path.join(os.sep, "Game","Trash") to_be_deleted = [] for asset in selected_assets: # get the full path to be duplicated asset asset_name = asset.get_fname() asset_path = editor_asset_lib.get_path_name_for_loaded_asset(asset) # get a list of references for this asset asset_references = editor_asset_lib.find_package_referencers_for_asset(asset_path) if len(asset_references) == 0: to_be_deleted.append(asset) for asset in to_be_deleted: asset_name = asset.get_fname() # instantly delete the assets if instant_delete: deleted = editor_asset_lib.delete_loaded_asset(asset) if not deleted: unreal.log_warning("Asset {} could not be deleted".format(asset_name)) continue removed +=1 # move the assets to the trash folder else: new_path = os.path.join(trash_folder, str(asset_name)) moved = editor_asset_lib.rename_loaded_asset(asset, new_path) if not moved: unreal.log_warning("Asset {} could not be moved to trash".format(asset_name)) continue removed +=1 output_test = "removed" if instant_delete else "moved to trahs folder" unreal.log_warning("{} of {} to be deleted assets, of {} selected, {}".format(removed, len(to_be_deleted), num_assets, output_test))
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/project/-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unreal def organise_assets_into_folders() -> None: editor_util = unreal.EditorUtilityLibrary() system_lib = unreal.SystemLibrary() asset_lib = unreal.EditorAssetLibrary() selected_assets = editor_util.get_selected_assets() asset_count = len(selected_assets) organised_asset_count: int = 0 unreal.log("Selected {} assets".format(asset_count)) top_level_dir = r'\Game' for asset in selected_assets: # Get the name of the assets asset_name = system_lib.get_object_name(asset) class_name = system_lib.get_class_display_name(asset.get_class()) # Derive a new name for the asset. Hardcoded and ugly now but could # follow better rules in the future new_asset_name = os.path.join(top_level_dir, class_name, asset_name) result = asset_lib.rename_loaded_asset(asset, new_asset_name) if result: unreal.log(f"Renamed asset named '{asset_name}' with class {class_name} to '{new_asset_name}'") organised_asset_count += 1 else: unreal.log(f"Failed to rename asset named '{asset_name}' with class {class_name} to '{new_asset_name}'") unreal.log(f"Organised #{organised_asset_count} asset(s) into required directories") organise_assets_into_folders()
# coding: utf-8 from asyncio.windows_events import NULL from platform import java_ver import unreal import argparse print("VRM4U python begin") print (__file__) parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") parser.add_argument("-meta") args = parser.parse_args() print(args.vrm) reg = unreal.AssetRegistryHelpers.get_asset_registry(); ## rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r #rig = rigs[10] hierarchy = unreal.ControlRigBlueprintLibrary.get_hierarchy(rig) h_con = hierarchy.get_controller() r_con = rig.get_controller() graph = r_con.get_graph() node = graph.get_nodes() def checkAndSwapPinBoneToContorl(pin): subpins = pin.get_sub_pins() #print(subpins) if (len(subpins) != 2): return; typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') #if (typePin==None or namePin==None): if (typePin==None): return; #if (typePin.get_default_value() == '' or namePin.get_default_value() == ''): if (typePin.get_default_value() == ''): return; if (typePin.get_default_value() != 'Bone'): return; print(typePin.get_default_value() + ' : ' + namePin.get_default_value()) r_con.set_pin_default_value(typePin.get_pin_path(), 'Control', True, False) print('swap end') #end check pin bonePin = None controlPin = None while(len(hierarchy.get_bones()) > 0): e = hierarchy.get_bones()[-1] h_con.remove_all_parents(e) h_con.remove_element(e) h_con.import_bones(unreal.ControlRigBlueprintLibrary.get_preview_mesh(rig).skeleton) ## for n in node: pins = n.get_pins() for pin in pins: if (pin.is_array()): if (pin.get_array_size() > 40): # long bone list typePin = pin.get_sub_pins()[0].find_sub_pin('Type') if (typePin != None): if (typePin.get_default_value() == 'Bone'): bonePin = pin continue if (typePin.get_default_value() == 'Control'): if ('Name="pelvis"' in r_con.get_pin_default_value(n.find_pin('Items').get_pin_path())): controlPin = pin continue for item in pin.get_sub_pins(): checkAndSwapPinBoneToContorl(item) else: checkAndSwapPinBoneToContorl(pin) for e in hierarchy.get_controls(): tmp = "{}".format(e.name) if (tmp.endswith('_ctrl') == False): continue if (tmp.startswith('thumb_0') or tmp.startswith('index_0') or tmp.startswith('middle_0') or tmp.startswith('ring_0') or tmp.startswith('pinky_0')): print('') else: continue c = hierarchy.find_control(e) print(e.name) #ttt = unreal.RigComputedTransform(transform=[[0.0, 0.0, 2.0], [90.0, 0.0, 0.0], [0.03, 0.03, 0.25]]) #ttt = unreal.RigComputedTransform(transform=[[0.0, 0.0, 2.0], [90.0, 0.0, 0.0], [0.03, 0.03, 0.25]]) ttt = unreal.Transform(location=[0.0, 0.0, 2.0], rotation=[0.0, 0.0, 90.0], scale=[0.03, 0.03, 0.25]) hierarchy.set_control_shape_transform(e, ttt, True) ''' shape = c.get_editor_property('shape') init = shape.get_editor_property('initial') #init = shape.get_editor_property('current') local = init.get_editor_property('local') local = ttt init.set_editor_property('local', local) gl = init.get_editor_property('global_') gl = ttt init.set_editor_property('global_', gl) shape.set_editor_property('initial', init) shape.set_editor_property('current', init) c.set_editor_property('shape', shape) ''' ### swapBoneTable = [ ["Root",""], ["Pelvis","hips"], ["spine_01","spine"], ["spine_02","chest"], ["spine_03","upperChest"], ["clavicle_l","leftShoulder"], ["UpperArm_L","leftUpperArm"], ["lowerarm_l","leftLowerArm"], ["Hand_L","leftHand"], ["index_01_l","leftIndexProximal"], ["index_02_l","leftIndexIntermediate"], ["index_03_l","leftIndexDistal"], ["middle_01_l","leftMiddleProximal"], ["middle_02_l","leftMiddleIntermediate"], ["middle_03_l","leftMiddleDistal"], ["pinky_01_l","leftLittleProximal"], ["pinky_02_l","leftLittleIntermediate"], ["pinky_03_l","leftLittleDistal"], ["ring_01_l","leftRingProximal"], ["ring_02_l","leftRingIntermediate"], ["ring_03_l","leftRingDistal"], ["thumb_01_l","leftThumbProximal"], ["thumb_02_l","leftThumbIntermediate"], ["thumb_03_l","leftThumbDistal"], ["lowerarm_twist_01_l",""], ["upperarm_twist_01_l",""], ["clavicle_r","rightShoulder"], ["UpperArm_R","rightUpperArm"], ["lowerarm_r","rightLowerArm"], ["Hand_R","rightHand"], ["index_01_r","rightIndexProximal"], ["index_02_r","rightIndexIntermediate"], ["index_03_r","rightIndexDistal"], ["middle_01_r","rightMiddleProximal"], ["middle_02_r","rightMiddleIntermediate"], ["middle_03_r","rightMiddleDistal"], ["pinky_01_r","rightLittleProximal"], ["pinky_02_r","rightLittleIntermediate"], ["pinky_03_r","rightLittleDistal"], ["ring_01_r","rightRingProximal"], ["ring_02_r","rightRingIntermediate"], ["ring_03_r","rightRingDistal"], ["thumb_01_r","rightThumbProximal"], ["thumb_02_r","rightThumbIntermediate"], ["thumb_03_r","rightThumbDistal"], ["lowerarm_twist_01_r",""], ["upperarm_twist_01_r",""], ["neck_01","neck"], ["head","head"], ["Thigh_L","leftUpperLeg"], ["calf_l","leftLowerLeg"], ["calf_twist_01_l",""], ["Foot_L","leftFoot"], ["ball_l","leftToes"], ["thigh_twist_01_l",""], ["Thigh_R","rightUpperLeg"], ["calf_r","rightLowerLeg"], ["calf_twist_01_r",""], ["Foot_R","rightFoot"], ["ball_r","rightToes"], ["thigh_twist_01_r",""], ["index_metacarpal_l",""], ["index_metacarpal_r",""], ["middle_metacarpal_l",""], ["middle_metacarpal_r",""], ["ring_metacarpal_l",""], ["ring_metacarpal_r",""], ["pinky_metacarpal_l",""], ["pinky_metacarpal_r",""], #custom ["eye_l", "leftEye"], ["eye_r", "rightEye"], ] humanoidBoneList = [ "hips", "leftUpperLeg", "rightUpperLeg", "leftLowerLeg", "rightLowerLeg", "leftFoot", "rightFoot", "spine", "chest", "upperChest", # 9 optional "neck", "head", "leftShoulder", "rightShoulder", "leftUpperArm", "rightUpperArm", "leftLowerArm", "rightLowerArm", "leftHand", "rightHand", "leftToes", "rightToes", "leftEye", "rightEye", "jaw", "leftThumbProximal", # 24 "leftThumbIntermediate", "leftThumbDistal", "leftIndexProximal", "leftIndexIntermediate", "leftIndexDistal", "leftMiddleProximal", "leftMiddleIntermediate", "leftMiddleDistal", "leftRingProximal", "leftRingIntermediate", "leftRingDistal", "leftLittleProximal", "leftLittleIntermediate", "leftLittleDistal", "rightThumbProximal", "rightThumbIntermediate", "rightThumbDistal", "rightIndexProximal", "rightIndexIntermediate", "rightIndexDistal", "rightMiddleProximal", "rightMiddleIntermediate", "rightMiddleDistal", "rightRingProximal", "rightRingIntermediate", "rightRingDistal", "rightLittleProximal", "rightLittleIntermediate", "rightLittleDistal", #54 ] for i in range(len(humanoidBoneList)): humanoidBoneList[i] = humanoidBoneList[i].lower() for i in range(len(swapBoneTable)): swapBoneTable[i][0] = swapBoneTable[i][0].lower() swapBoneTable[i][1] = swapBoneTable[i][1].lower() ### 全ての骨 modelBoneElementList = [] modelBoneNameList = [] for e in hierarchy.get_bones(): if (e.type == unreal.RigElementType.BONE): modelBoneElementList.append(e) modelBoneNameList.append("{}".format(e.name)) ## meta 取得 reg = unreal.AssetRegistryHelpers.get_asset_registry(); a = reg.get_all_assets(); if (args.meta): for aa in a: print(aa.get_editor_property("package_name")) print(aa.get_editor_property("asset_name")) if ((unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("package_name"))+"."+unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("asset_name"))) == unreal.StringLibrary.conv_name_to_string(args.meta)): #if (aa.get_editor_property("object_path") == args.meta): v:unreal.VrmMetaObject = aa vv = aa.get_asset() break if (vv == None): for aa in a: if ((unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("package_name"))+"."+unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("asset_name"))) == unreal.StringLibrary.conv_name_to_string(args.meta)): #if (aa.get_editor_property("object_path") == args.vrm): v:unreal.VrmAssetListObject = aa vv = v.get_asset().vrm_meta_object break meta = vv # Backwards Bone Names allBackwardsNode = [] def r_nodes(node): b = False try: allBackwardsNode.index(node) except: b = True if (b == True): allBackwardsNode.append(node) linknode = node.get_linked_source_nodes() for n in linknode: r_nodes(n) linknode = node.get_linked_target_nodes() for n in linknode: r_nodes(n) for n in node: if (n.get_node_title() == 'Backwards Solve'): r_nodes(n) print(len(allBackwardsNode)) print(len(node)) def boneOverride(pin): subpins = pin.get_sub_pins() if (len(subpins) != 2): return typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') if (typePin==None): return if (namePin==None): return controlName = namePin.get_default_value() if (controlName==''): return if (controlName.endswith('_ctrl')): return if (controlName.endswith('_space')): return r_con.set_pin_default_value(typePin.get_pin_path(), 'Bone', True, False) table = [i for i in swapBoneTable if i[0]==controlName] if (len(table) == 0): # use node or no control return if (table[0][0] == 'root'): metaTable = "{}".format(hierarchy.get_bones()[0].name) else: metaTable = meta.humanoid_bone_table.get(table[0][1]) if (metaTable == None): metaTable = 'None' #print(table[0][1]) #print('<<') #print(controlName) #print('<<<') #print(metaTable) r_con.set_pin_default_value(namePin.get_pin_path(), metaTable, True, False) #for e in meta.humanoid_bone_table: for n in allBackwardsNode: pins = n.get_pins() for pin in pins: if (pin.is_array()): # finger 無変換チェック linknode = n.get_linked_target_nodes() if (len(linknode) == 1): if (linknode[0].get_node_title()=='At'): continue for p in pin.get_sub_pins(): boneOverride(p) else: boneOverride(pin) #sfsdjfkasjk ### 骨名対応表。Humanoid名 -> Model名 humanoidBoneToModel = {"" : ""} humanoidBoneToModel.clear() humanoidBoneToMannequin = {"" : ""} humanoidBoneToMannequin.clear() # humanoidBone -> modelBone のテーブル作る for searchHumanoidBone in humanoidBoneList: bone_h = None for e in meta.humanoid_bone_table: if ("{}".format(e).lower() == searchHumanoidBone): bone_h = e; break; if (bone_h==None): # not found continue bone_m = meta.humanoid_bone_table[bone_h] try: i = modelBoneNameList.index(bone_m) except: i = -1 if (i < 0): # no bone continue humanoidBoneToModel["{}".format(bone_h).lower()] = "{}".format(bone_m) #humanoidBoneToMannequin["{}".format(bone_h).lower()] = "{}".format(bone_m).lower(bone_h) #print(humanoidBoneToModel) #print(bonePin) #print(controlPin) if (bonePin != None and controlPin !=None): r_con.clear_array_pin(bonePin.get_pin_path()) r_con.clear_array_pin(controlPin.get_pin_path()) #c.clear_array_pin(v.get_pin_path()) #tmp = '(Type=Control,Name=' #tmp += "{}".format('aaaaa') #tmp += ')' #r_con.add_array_pin(bonePin.get_pin_path(), default_value=tmp) for e in swapBoneTable: try: i = 0 humanoidBoneToModel[e[1]] except: i = -1 if (i < 0): # no bone continue #e[0] -> grayman #e[1] -> humanoid #humanoidBoneToModel[e[1]] -> modelBone bone = unreal.RigElementKey(unreal.RigElementType.BONE, humanoidBoneToModel[e[1]]) space = unreal.RigElementKey(unreal.RigElementType.NULL, "{}_s".format(e[0])) #print('aaa') #print(bone) #print(space) #p = hierarchy.get_first_parent(humanoidBoneToModel[result[0][1]]) t = hierarchy.get_global_transform(bone) #print(t) hierarchy.set_global_transform(space, t, True) if (bonePin != None and controlPin !=None): tmp = '(Type=Control,Name=' tmp += "{}".format(e[0]) tmp += ')' r_con.add_array_pin(controlPin.get_pin_path(), default_value=tmp, setup_undo_redo=False) tmp = '(Type=Bone,Name=' tmp += "\"{}\"".format(humanoidBoneToModel[e[1]]) tmp += ')' r_con.add_array_pin(bonePin.get_pin_path(), default_value=tmp, setup_undo_redo=False) # for bone name space namePin = bonePin.get_sub_pins()[-1].find_sub_pin('Name') r_con.set_pin_default_value(namePin.get_pin_path(), "{}".format(humanoidBoneToModel[e[1]]), True, False) # skip invalid bone, controller # disable node def disableNode(toNoneNode): print(toNoneNode) print("gfgf") pins = toNoneNode.get_pins() for pin in pins: typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') if (typePin==None or namePin==None): continue print(f'DisablePin {typePin.get_default_value()} : {namePin.get_default_value()}') # control key = unreal.RigElementKey(unreal.RigElementType.CONTROL, "{}".format(namePin.get_default_value())) # disable node r_con.set_pin_default_value(namePin.get_pin_path(), 'None', True, False) if (typePin.get_default_value() == 'Control'): #disable control if (hierarchy.contains(key) == True): settings = h_con.get_control_settings(key) if ("5.1." in unreal.SystemLibrary.get_engine_version()): settings.set_editor_property('shape_visible', False) else: settings.set_editor_property('shape_enabled', False) ttt = hierarchy.get_global_control_shape_transform(key, True) ttt.scale3d.set(0.001, 0.001, 0.001) hierarchy.set_control_shape_transform(key, ttt, True) h_con.set_control_settings(key, settings) for n in node: pins = n.get_pins() for pin in pins: if (pin.is_array()): continue else: typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') if (typePin==None or namePin==None): continue if (typePin.get_default_value() != 'Bone'): continue if (namePin.is_u_object() == True): continue if (len(n.get_linked_source_nodes()) > 0): continue key = unreal.RigElementKey(unreal.RigElementType.BONE, namePin.get_default_value()) if (hierarchy.contains(key) == True): continue print(f'disable linked node from {typePin.get_default_value()} : {namePin.get_default_value()}') for toNoneNode in n.get_linked_target_nodes(): disableNode(toNoneNode) ## morph # -vrm vrm -rig rig -debugeachsave 0 #args.vrm #args.rig command = 'VRM4U_CreateMorphTargetControllerUE5.py ' + '-vrm ' + args.vrm + ' -rig ' + args.rig + ' -debugeachsave 0' print(command) unreal.PythonScriptLibrary.execute_python_command(command) unreal.ControlRigBlueprintLibrary.recompile_vm(rig)
# AdvancedSkeleton To ControlRig # Copyright (C) Animation Studios # email: [email protected] # exported using AdvancedSkeleton version:x.xx import unreal import re utilityBase = unreal.GlobalEditorUtilityBase.get_default_object() selectedAssets = utilityBase.get_selected_assets() if len(selectedAssets)<1: raise Exception('Nothing selected, you must select a ControlRig') selectedAsset = selectedAssets[0] if selectedAsset.get_class().get_name() != 'ControlRigBlueprint': raise Exception('Selected object is not a ControlRigBlueprint, you must select a ControlRigBlueprint') ControlRigBlueprint = selectedAsset HierarchyModifier = ControlRigBlueprint.get_hierarchy_modifier() try: RigVMController = ControlRigBlueprint.get_editor_property('controller') #UE4 except: RigVMController = ControlRigBlueprint.get_controller() #UE5 PreviousArrayInfo = dict() global ASCtrlNr global PreviousEndPlug global PreviousEndPlugInv global sp global nonTransformFaceCtrlNr ASCtrlNr = 0 nonTransformFaceCtrlNr = -1 sp = '/project/.RigUnit_' PreviousEndPlug = 'RigUnit_BeginExecution.ExecuteContext' PreviousEndPlugInv = 'RigUnit_InverseExecution.ExecuteContext' def asAddCtrl (name, parent, joint, type, arrayInfo, gizmoName, ws, size, offT, color): global PreviousEndPlug global PreviousEndPlugInv global PreviousArrayInfo global ctrlBoxSize global ASCtrlNr global nonTransformFaceCtrlNr endPlug = name+'_CON.ExecuteContext' RigVMGraph = ControlRigBlueprint.model numNodes = len(RigVMGraph.get_nodes()) y = ASCtrlNr*400 ASCtrlNr=ASCtrlNr+1 ASDrivenNr = int() RootScale = unreal.Vector(x=1.0, y=1.0, z=1.0) ParentRigBone = unreal.RigBone() ParentRigBoneName = parent.replace("FK", "") hasCon = True x = joint.split("_") if len(x)>1: baseName = x[0] side = '_'+x[1] x = ParentRigBoneName.split("_") if len(x)>1: ParentRigBoneBaseName = x[0] RigElementKeys = HierarchyModifier.get_elements() for key in RigElementKeys: if (key.name == 'Root_M'): RootScale = HierarchyModifier.get_bone (key).get_editor_property('global_transform').scale3d if (key.name == ParentRigBoneName): if (key.type == 1):#Bone ParentRigBone = HierarchyModifier.get_bone (key) RigControl = asAddController (name, parent, joint, type, gizmoName, ws, size, offT, color) if name=='Main': return #GT GT = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GT') RigVMController.set_node_position (GT, [-500, y]) RigVMController.set_pin_default_value(name+'_GT.Item.Type','Control') RigVMController.set_pin_default_value(name+'_GT.Item.Name',name) if name=='RootX_M': #CON CON = asAddNode (sp+'TransformConstraintPerItem','Execute',node_name=name+'_CON') RigVMController.set_node_position (CON, [100, y-90]) RigVMController.set_pin_default_value(name+'_CON.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_CON.Item.Name',joint) RigVMController.add_array_pin(name+'_CON.Targets') RigVMController.add_link(name+'_GT.Transform' , name+'_CON.Targets.0.Transform') RigVMController.add_link(PreviousEndPlug , name+'_CON.ExecuteContext') endPlug = name+'_CON.ExecuteContext' else: #ST ST = asAddNode (sp+'SetTransform','Execute',node_name=name+'_ST') RigVMController.set_node_position (ST, [100, y]) RigVMController.set_pin_default_value(name+'_ST.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_ST.Item.Name',joint) RigVMController.add_link(name+'_GT.Transform' , name+'_ST.Transform') RigVMController.set_pin_default_value(name+'_ST.bPropagateToChildren','True') RigVMController.add_link(PreviousEndPlug , name+'_ST.ExecuteContext') endPlug = name+'_ST.ExecuteContext' if type=='FK': if "twistJoints" in PreviousArrayInfo: inbetweenJoints = int (PreviousArrayInfo["twistJoints"]) key = HierarchyModifier.add_bone ('UnTwist'+ParentRigBoneName,parent_name=joint) UnTwistBone = HierarchyModifier.get_bone (key) UnTwistBone.set_editor_property('local_transform', unreal.Transform()) asParent ('UnTwist'+ParentRigBoneName,'TwistSystem') asAlign (ParentRigBoneName,'UnTwist'+ParentRigBoneName) #GTParent constraintTo = str(ParentRigBone.get_editor_property('parent_name')) x = re.search("Part", constraintTo) if x: constraintTo = ParentRigBoneName GTParent = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTParent') RigVMController.set_node_position (GTParent, [600, y]) RigVMController.set_pin_default_value(name+'_GTParent.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_GTParent.Item.Name',constraintTo) #CONUnTwist CONUnTwist = asAddNode (sp+'TransformConstraintPerItem','Execute',node_name=name+'_CONUnTwist') RigVMController.set_node_position (CONUnTwist, [1000, y]) RigVMController.set_pin_default_value(name+'_CONUnTwist.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_CONUnTwist.Item.Name','UnTwist'+ParentRigBoneName) RigVMController.add_array_pin(name+'_CONUnTwist.Targets') RigVMController.add_link(name+'_GTParent.Transform' , name+'_CONUnTwist.Targets.0.Transform') RigVMController.add_link(endPlug , name+'_CONUnTwist.ExecuteContext') Items = asAddNode (sp+'CollectionItems','Execute',node_name=name+'_Items') RigVMController.set_node_position (Items, [1450, y]) RigVMController.set_pin_default_value(name+'_Items.Items.0.Name','UnTwist'+ParentRigBoneName) for x in range(1,inbetweenJoints+3): RigVMController.add_array_pin(name+'_Items.Items') RigVMController.set_pin_default_value(name+'_Items.Items.'+str(x)+'.Name',ParentRigBoneBaseName+'Part'+str((x-1))+side) RigVMController.set_pin_default_value(name+'_Items.Items.'+str(x)+'.Type','Bone') RigVMController.set_pin_default_value(name+'_Items.Items.1.Name',ParentRigBoneName) RigVMController.set_pin_default_value(name+'_Items.Items.'+str((inbetweenJoints+2))+'.Name',joint) Twist = asAddNode (sp+'TwistBonesPerItem','Execute',node_name=name+'_Twist') RigVMController.set_node_position (Twist, [1750, y]) RigVMController.add_link(name+'_Items.Collection' , name+'_Twist.Items') RigVMController.add_link(name+'_CONUnTwist.ExecuteContext' , name+'_Twist.ExecuteContext') endPlug = name+'_Twist.ExecuteContext' if "inbetweenJoints" in arrayInfo: inbetweenJoints = int (arrayInfo["inbetweenJoints"]) Chain = asAddNode (sp+'CollectionChain','Execute',node_name=name+'_Chain') RigVMController.set_node_position (Chain, [1350, y]) RigVMController.set_pin_default_value(name+'_Chain.FirstItem.Name',baseName+'Part1'+side) RigVMController.set_pin_default_value(name+'_Chain.LastItem.Name',baseName+'Part'+str(inbetweenJoints)+side) #GTDistr GTDistr = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTDistr') RigVMController.set_node_position (GTDistr, [1700, y]) RigVMController.set_pin_default_value(name+'_GTDistr.Item.Type','Control') RigVMController.set_pin_default_value(name+'_GTDistr.Item.Name',name) RigVMController.set_pin_default_value(name+'_GTDistr.Space','LocalSpace') #Distr Distr = asAddNode (sp+'DistributeRotationForCollection','Execute',node_name=name+'_Distr') RigVMController.set_node_position (Distr, [2100, y]) weight = (1.0 / inbetweenJoints) RigVMController.set_pin_default_value(name+'_Distr.Weight',str(weight)) RigVMController.add_link(name+'_Chain.Collection' , name+'_Distr.Items') RigVMController.add_array_pin(name+'_Distr.Rotations') RigVMController.add_link(name+'_GTDistr.Transform.Rotation' , name+'_Distr.Rotations.0.Rotation') RigVMController.add_link(PreviousEndPlug , name+'_Distr.ExecuteContext') endPlug = name+'_Distr.ExecuteContext' if "inbetweenJoints" in PreviousArrayInfo: Transform = RigControl.get_editor_property('offset_transform') SpaceKey = HierarchyModifier.add_space ('Space'+joint) Space = HierarchyModifier.get_space (SpaceKey) Space.set_editor_property('initial_transform', Transform) HierarchyModifier.set_space (Space) RigControl.set_editor_property('offset_transform', unreal.Transform()) HierarchyModifier.set_control (RigControl) asParent (name,'Space'+joint) asParent ('Space'+joint,parent) #GTSpace GTSpace = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTSpace') RigVMController.set_node_position (GTSpace, [600, y]) RigVMController.set_pin_default_value(name+'_GTSpace.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_GTSpace.Item.Name',joint) #STSpace STSpace = asAddNode (sp+'SetTransform','Execute',node_name=name+'_STSpace') RigVMController.set_node_position (STSpace, [950, y]) RigVMController.set_pin_default_value(name+'_STSpace.Item.Type','Space') RigVMController.set_pin_default_value(name+'_STSpace.Item.Name','Space'+joint) RigVMController.add_link(name+'_GTSpace.Transform' , name+'_STSpace.Transform') RigVMController.set_pin_default_value(name+'_STSpace.bPropagateToChildren','True') RigVMController.add_link(PreviousEndPlug , name+'_STSpace.ExecuteContext') if not "inbetweenJoints" in arrayInfo: RigVMController.add_link(name+'_STSpace.ExecuteContext' , name+'_ST.ExecuteContext') else: RigVMController.add_link(name+'_STSpace.ExecuteContext' , name+'_Distr.ExecuteContext') if "global" in arrayInfo and float(arrayInfo["global"])==10: SpaceKey = HierarchyModifier.add_space ('Global'+name) SpaceObj = HierarchyModifier.get_space (SpaceKey) asParent ('Global'+name, parent) asAlign (name,'Global'+name) RigControl.set_editor_property('offset_transform', unreal.Transform()) HierarchyModifier.set_control (RigControl) asParent (name,'Global'+name) PNPGlobal = asAddNode (sp+'ProjectTransformToNewParent','Execute',node_name=name+'_PNPGlobal') RigVMController.set_node_position (PNPGlobal, [-1200, y]) RigVMController.set_pin_default_value(name+'_PNPGlobal.Child.Type','Control') RigVMController.set_pin_default_value(name+'_PNPGlobal.Child.Name',name) RigVMController.set_pin_default_value(name+'_PNPGlobal.OldParent.Type','Control') RigVMController.set_pin_default_value(name+'_PNPGlobal.OldParent.Name','Main') RigVMController.set_pin_default_value(name+'_PNPGlobal.NewParent.Type','Control') RigVMController.set_pin_default_value(name+'_PNPGlobal.NewParent.Name','Main') #SRGlobal SRGlobal = asAddNode (sp+'SetRotation','Execute',node_name=name+'_SRGlobal') RigVMController.set_node_position (SRGlobal, [-850, y]) RigVMController.set_pin_default_value(name+'_SRGlobal.Item.Type','Space') RigVMController.set_pin_default_value(name+'_SRGlobal.Item.Name','Global'+name) RigVMController.set_pin_default_value(name+'_SRGlobal.bPropagateToChildren','True') RigVMController.add_link(name+'_PNPGlobal.Transform.Rotation' , name+'_SRGlobal.Rotation') RigVMController.add_link(PreviousEndPlug , name+'_SRGlobal.ExecuteContext') #STGlobal STGlobal = asAddNode (sp+'SetTranslation','Execute',node_name=name+'_STGlobal') RigVMController.set_node_position (STGlobal, [-850, y+250]) RigVMController.set_pin_default_value(name+'_STGlobal.Item.Type','Space') RigVMController.set_pin_default_value(name+'_STGlobal.Item.Name','Global'+name) RigVMController.set_pin_default_value(name+'_STGlobal.Space','LocalSpace') RigVMController.set_pin_default_value(name+'_STGlobal.bPropagateToChildren','True') Transform = HierarchyModifier.get_initial_transform(SpaceKey) RigVMController.set_pin_default_value(name+'_STGlobal.Translation.X',str(Transform.translation.x)) RigVMController.set_pin_default_value(name+'_STGlobal.Translation.Y',str(Transform.translation.y)) RigVMController.set_pin_default_value(name+'_STGlobal.Translation.Z',str(Transform.translation.z)) RigVMController.add_link(name+'_SRGlobal.ExecuteContext' , name+'_STGlobal.ExecuteContext') RigVMController.add_link(name+'_STGlobal.ExecuteContext' , endPlug) if type=='IK': RigControl = asAddController ('Pole'+name, parent, joint, type, 'Box_Solid', ws, size/5.0, offT, color) RigControl.set_editor_property('offset_transform', unreal.Transform(location=[float(arrayInfo["ppX"])*RootScale.x,float(arrayInfo["ppZ"])*RootScale.y,float(arrayInfo["ppY"])*RootScale.z],scale=RootScale)) HierarchyModifier.set_control (RigControl) #IK(Basic IK) IK = asAddNode (sp+'TwoBoneIKSimplePerItem','Execute',node_name=name+'_IK') RigVMController.set_node_position (IK, [600, y-130]) RigVMController.set_pin_default_value(name+'_IK.ItemA.Name',arrayInfo["startJoint"]) RigVMController.set_pin_default_value(name+'_IK.ItemB.Name',arrayInfo["middleJoint"]) RigVMController.set_pin_default_value(name+'_IK.EffectorItem.Name',arrayInfo["endJoint"]) RigVMController.set_pin_default_value(name+'_IK.PrimaryAxis.X',arrayInfo["paX"]) RigVMController.set_pin_default_value(name+'_IK.PrimaryAxis.Y',arrayInfo["paY"]) RigVMController.set_pin_default_value(name+'_IK.PrimaryAxis.Z',arrayInfo["paZ"]) RigVMController.set_pin_default_value(name+'_IK.SecondaryAxis.X',arrayInfo["saX"]) RigVMController.set_pin_default_value(name+'_IK.SecondaryAxis.Y',arrayInfo["paY"]) RigVMController.set_pin_default_value(name+'_IK.SecondaryAxis.Z',arrayInfo["paZ"]) RigVMController.set_pin_default_value(name+'_IK.PoleVectorKind','Location') RigVMController.set_pin_default_value(name+'_IK.PoleVectorSpace.Type','Control') RigVMController.set_pin_default_value(name+'_IK.PoleVectorSpace.Name','Pole'+name) RigVMController.set_pin_default_value(name+'_IK.bPropagateToChildren','True') RigVMController.add_link(name+'_GT.Transform' , name+'_IK.Effector') RigVMController.add_link(PreviousEndPlug , name+'_IK.ExecuteContext') endPlug = name+'_IK.ExecuteContext' #GTSpace GTSpace = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTSpace') RigVMController.set_node_position (GTSpace, [1000, y]) RigVMController.set_pin_default_value(name+'_GTSpace.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_GTSpace.Item.Name',arrayInfo["endJoint"]) #modify _GT to use a local-oriented child of ws controller key = HierarchyModifier.add_control (name+'LS',parent_name=name) RigControl = HierarchyModifier.get_control (key) RigControl.set_editor_property('gizmo_enabled',False) HierarchyModifier.set_control (RigControl) RigVMController.set_pin_default_value(name+'_GT.Item.Name',name+'LS') for key in RigElementKeys: if (key.name == arrayInfo["endJoint"]): endJointObject = HierarchyModifier.get_bone (key) EndJointTransform = endJointObject.get_editor_property('global_transform') Rotation = EndJointTransform.rotation.rotator() Transform = unreal.Transform(location=[0,0,0],rotation=Rotation,scale=[1,1,1]) RigControl.set_editor_property('offset_transform', Transform) HierarchyModifier.set_control (RigControl) #Backwards solve nodes (IK) PNPinvIK = asAddNode (sp+'ProjectTransformToNewParent','Execute',node_name=name+'_PNPinvIK') RigVMController.set_node_position (PNPinvIK, [-2900, y]) RigVMController.set_pin_default_value(name+'_PNPinvIK.Child.Type','Control') RigVMController.set_pin_default_value(name+'_PNPinvIK.Child.Name',name) RigVMController.set_pin_default_value(name+'_PNPinvIK.OldParent.Type','Control') RigVMController.set_pin_default_value(name+'_PNPinvIK.OldParent.Name',name+'LS') RigVMController.set_pin_default_value(name+'_PNPinvIK.NewParent.Type','Bone') RigVMController.set_pin_default_value(name+'_PNPinvIK.NewParent.Name',joint) #STinvIK STinvIK = asAddNode (sp+'SetTransform','Execute',node_name=name+'_STinvIK') RigVMController.set_node_position (STinvIK, [-2500, y]) RigVMController.set_pin_default_value(name+'_STinvIK.Item.Type','Control') RigVMController.set_pin_default_value(name+'_STinvIK.Item.Name',name) RigVMController.add_link(name+'_GTSpace.Transform' , name+'_STinvIK.Transform') RigVMController.set_pin_default_value(name+'_STinvIK.bPropagateToChildren','True') RigVMController.add_link(name+'_PNPinvIK.Transform' , name+'_STinvIK.Transform') RigVMController.add_link(PreviousEndPlugInv , name+'_STinvIK.ExecuteContext') #GTinvPole GTinvPole = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTinvPole') RigVMController.set_node_position (GTinvPole, [-1700, y]) RigVMController.set_pin_default_value(name+'_GTinvPole.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_GTinvPole.Item.Name',arrayInfo["middleJoint"]) #STinvPole STinvPole = asAddNode (sp+'SetTransform','Execute',node_name=name+'_STinvPole') RigVMController.set_node_position (STinvPole, [-1300, y]) RigVMController.set_pin_default_value(name+'_STinvPole.Item.Type','Control') RigVMController.set_pin_default_value(name+'_STinvPole.Item.Name','Pole'+name) RigVMController.add_link(name+'_GTSpace.Transform' , name+'_STinvPole.Transform') RigVMController.set_pin_default_value(name+'_STinvPole.bPropagateToChildren','True') RigVMController.add_link(name+'_GTinvPole.Transform' , name+'_STinvPole.Transform') RigVMController.add_link(name+'_STinvIK.ExecuteContext' , name+'_STinvPole.ExecuteContext') endPlugInv = name+'_STinvPole.ExecuteContext' PreviousEndPlugInv = endPlugInv if "twistJoints" in arrayInfo or "inbetweenJoints" in arrayInfo: PreviousArrayInfo = arrayInfo else: PreviousArrayInfo.clear() #DrivingSystem if type=='DrivingSystem' or type=='ctrlBox': if type=='DrivingSystem': RigVMController.set_pin_default_value(name+'_GT.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_GT.Item.Name',joint) RigVMController.set_pin_default_value(name+'_ST.Item.Type','Control') RigVMController.set_pin_default_value(name+'_ST.Item.Name',name) if type=='ctrlBox': Transform = RigControl.get_editor_property('gizmo_transform') if name=='ctrlBox': RigControl.offset_transform.translation = [Transform.translation.z,(Transform.translation.y*-1),Transform.translation.x] ctrlBoxSize = float (arrayInfo["ctrlBoxSize"]) Scale = [0.07,0.15,0.1] ctrlBoxScale = [ctrlBoxSize,ctrlBoxSize,ctrlBoxSize] RigControl.offset_transform.scale3d = ctrlBoxScale RigControl.gizmo_transform.scale3d = Scale RigControl.gizmo_transform.translation = [0,0,-1.5] #guestimate HierarchyModifier.set_control (RigControl) return nonTransformFaceCtrl = False if name=='ctrlEmotions_M' or name=='ctrlPhonemes_M' or name=='ctrlARKit_M' or name=='ctrlBoxRobloxHead_M': nonTransformFaceCtrl = True nonTransformFaceCtrlNr = nonTransformFaceCtrlNr+1 RigControl.set_editor_property('gizmo_enabled',False) HierarchyModifier.set_control (RigControl) if type=='ctrlBox': RigVMController.remove_node(RigVMGraph.find_node_by_name(name+'_GT')) RigVMController.remove_node(RigVMGraph.find_node_by_name(name+'_ST')) RigControl.set_editor_property('control_type',unreal.RigControlType.VECTOR2D) RigControl.set_editor_property('primary_axis',unreal.RigControlAxis.Y) RigControl.offset_transform.translation = Transform.translation * (1.0/ctrlBoxSize) RigControl.gizmo_transform.scale3d = [0.05,0.05,0.05] RigControl.limit_translation = True value = unreal.RigControlValue() RigControl.maximum_value = value RigControl.gizmo_transform.translation = [0,0,0] HierarchyModifier.set_control (RigControl) maxXform = unreal.Transform(location=[1,1,1]) minXform = unreal.Transform(location=[-1,-1,-1]) if name=='ctrlMouth_M': maxXform = unreal.Transform(location=[1,1,0]) if re.search("^ctrlCheek_", name) or re.search("^ctrlNose_", name): minXform = unreal.Transform(location=[-1,-1,0]) RigElementKeys = HierarchyModifier.get_elements() for key in RigElementKeys: if (key.name == name): RigControlKey = key HierarchyModifier.set_control_value_transform (RigControlKey, maxXform, value_type=unreal.RigControlValueType.MAXIMUM) HierarchyModifier.set_control_value_transform (RigControlKey, minXform, value_type=unreal.RigControlValueType.MINIMUM) HierarchyModifier.set_control (HierarchyModifier.get_control (RigControlKey)) endPlug = PreviousEndPlug if type=='ctrlBox': AttrGrpkey = HierarchyModifier.add_control (name+"_Attributes",parent_name=parent) else: AttrGrpkey = HierarchyModifier.add_control (name+"_Attributes",parent_name=name) AttrGrpRigControl = HierarchyModifier.get_control (AttrGrpkey) AttrGrpRigControl.set_editor_property('gizmo_transform', unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[0,0,0])) Transform = RigControl.get_editor_property('offset_transform').copy() if type=='ctrlBox': Transform.translation.x = -5.0 Transform.translation.z += 0.8 if re.search("_L", name) or re.search("_M", name): Transform.translation.x = 4.0 if nonTransformFaceCtrl: Transform.translation.z = -5.5-(nonTransformFaceCtrlNr*2) # stack rows of sliders downwards else: numAttrs = 0 for Attr in arrayInfo.keys(): if not re.search("-set", Attr): numAttrs=numAttrs+1 Transform = unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[1,1,1]) Transform.translation.x = offT[0] Transform.translation.y = numAttrs*0.5*(size/4.0)*-0.5 Transform.translation.z = size/8.0 if re.search("_L", name): Transform.translation.z *= -1 Transform.scale3d=[size/4.0,size/4.0,size/4.0] AttrGrpRigControl.set_editor_property('offset_transform', Transform) HierarchyModifier.set_control (AttrGrpRigControl) Attrs = arrayInfo.keys() attrNr = 0 for Attr in Attrs: if re.search("-set", Attr): if re.search("-setLimits", Attr): DictDrivens = arrayInfo.get(Attr) min = float(list(DictDrivens.keys())[0]) max = float(list(DictDrivens.values())[0]) minXform = unreal.Transform(location=[min,min,min]) RigElementKeys = HierarchyModifier.get_elements() for key in RigElementKeys: if key.name == name+"_"+Attr.replace("-setLimits", ""): HierarchyModifier.set_control_value_transform (key, minXform, value_type=unreal.RigControlValueType.MINIMUM) HierarchyModifier.set_control (HierarchyModifier.get_control (key)) continue transformAttrDriver = True if not re.search("translate", Attr) or re.search("rotate", Attr) or re.search("scale", Attr): key = HierarchyModifier.add_control (name+"_"+Attr,parent_name=parent) AttrRigControl = HierarchyModifier.get_control (key) AttrRigControl = asParent (name+"_"+Attr, name+"_Attributes") AttrRigControl.set_editor_property('control_type',unreal.RigControlType.FLOAT) AttrRigControl.set_editor_property('gizmo_color', unreal.LinearColor(r=1.0, g=0.0, b=0.0, a=0.0)) AttrRigControl.set_editor_property('gizmo_transform', unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[0.035,0.035,0.035])) Transform = unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[1,1,1]) Transform.translation = [0,attrNr*0.5,0] if type=='ctrlBox': Transform.translation = [0,0,attrNr*-0.5] if nonTransformFaceCtrl or re.search("_M", name): AttrRigControl.set_editor_property('primary_axis',unreal.RigControlAxis.Z) Transform.translation = [attrNr,0,0] attrNr = attrNr+1 AttrRigControl.set_editor_property('offset_transform', Transform) AttrRigControl.limit_translation = True HierarchyModifier.set_control (AttrRigControl) maxXform = unreal.Transform(location=[1,1,1]) RigElementKeys = HierarchyModifier.get_elements() for key in RigElementKeys: if (key.name == name+"_"+Attr): RigControlKey = key HierarchyModifier.set_control_value_transform (RigControlKey, maxXform, value_type=unreal.RigControlValueType.MAXIMUM) HierarchyModifier.set_control (HierarchyModifier.get_control (RigControlKey)) transformAttrDriver = False DictDrivens = arrayInfo.get(Attr) KeysDrivens = DictDrivens.keys() for Driven in KeysDrivens: Value = float(DictDrivens.get(Driven)) x2 = ASDrivenNr*1200 dNr = str(ASDrivenNr) ASDrivenNr = ASDrivenNr+1 x = Driven.split(".") obj = x[0] attr = '_'+x[1] axis = attr[-1] valueMult = 1 if re.search("rotate", attr): if axis == 'X' or axis=='Z': valueMult = -1 if re.search("translate", attr): if axis=='Y': valueMult = -1 multiplier = Value*valueMult asFaceBSDriven = False if re.search("asFaceBS[.]", Driven):#asFaceBS asFaceBSDriven = True if not (asFaceBSDriven): RigElementKeys = HierarchyModifier.get_elements() for key in RigElementKeys: if key.name == obj: objObject = HierarchyModifier.get_control(key) if not asObjExists ('Offset'+obj): SpaceKey = HierarchyModifier.add_space ('Offset'+obj) SpaceObj = HierarchyModifier.get_space (SpaceKey) objParent = str(objObject.get_editor_property('parent_name')) asParent ('Offset'+obj, objParent) asAlign (obj,'Offset'+obj) parentTo = 'Offset'+obj for x in range(1,9): sdk = 'SDK'+obj+"_"+str(x) if not asObjExists (sdk): break if x>1: parentTo = 'SDK'+obj+"_"+str(x-1) SpaceKey = HierarchyModifier.add_space (sdk) asParent (sdk,parentTo) objObject.set_editor_property('offset_transform', unreal.Transform()) HierarchyModifier.set_control (objObject) asParent (obj,sdk) #GTDriver if transformAttrDriver: GTDriver = asAddNode (sp+'GetControlVector2D','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_GTDriver') RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_GTDriver.Control',name) gtPlug = name+"_"+obj+"_"+attr+dNr+'_GTDriver.Vector.'+Attr[-1]#Attr[-1] is DriverAxis else: GTDriver = asAddNode (sp+'GetControlFloat','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_GTDriver') RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_GTDriver.Control',name+"_"+Attr) gtPlug = name+"_"+obj+"_"+attr+dNr+'_GTDriver.FloatValue' RigVMController.set_node_position (GTDriver, [500+x2, y]) #MFM MFM = asAddNode (sp+'MathFloatMul','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_MFM') RigVMController.set_node_position (MFM, [900+x2, y]) RigVMController.add_link(gtPlug , name+"_"+obj+"_"+attr+dNr+'_MFM.A') RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_MFM.B',str(multiplier)) if asFaceBSDriven: #Clamp Clamp = asAddNode (sp+'MathFloatClamp','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_Clamp') RigVMController.set_node_position (Clamp, [900+x2, y+100]) RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_Clamp.Maximum','5.0') RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_MFM.Result' , name+"_"+obj+"_"+attr+dNr+'_Clamp.Value') #STDriven STDriven = asAddNode (sp+'SetCurveValue','Execute',node_name=name+"_"+Attr+"_"+attr+'_STDriven') RigVMController.set_node_position (STDriven, [1100+x2, y]) RigVMController.set_pin_default_value(name+"_"+Attr+"_"+attr+'_STDriven.Curve',Driven.split(".")[1]) RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_Clamp.Result' , name+"_"+Attr+"_"+attr+'_STDriven.Value') RigVMController.add_link(endPlug , name+"_"+Attr+"_"+attr+'_STDriven.ExecuteContext') endPlug =name+"_"+Attr+"_"+attr+'_STDriven.ExecuteContext' else: #STDriven STDriven = asAddNode (sp+'SetTransform','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_STDriven') RigVMController.set_node_position (STDriven, [1300+x2, y]) RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_STDriven.Item.Type','Space') RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_STDriven.Item.Name',sdk) RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_STDriven.Space','LocalSpace') RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_STDriven.bPropagateToChildren','True') RigVMController.add_link(endPlug , name+"_"+obj+"_"+attr+dNr+'_STDriven.ExecuteContext') endPlug = name+"_"+obj+"_"+attr+dNr+'_STDriven.ExecuteContext' #TFSRT TFSRT = asAddNode (sp+'MathTransformFromSRT','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_TFSRT') RigVMController.set_node_position (TFSRT, [900+x2, y+150]) if re.search("translate", attr): RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_MFM.Result' , name+"_"+obj+"_"+attr+dNr+'_TFSRT.Location.'+axis) if re.search("rotate", attr): RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_MFM.Result' , name+"_"+obj+"_"+attr+dNr+'_TFSRT.Rotation.'+axis) if re.search("scale", attr): #scale just add 1, not accurate but simplified workaround MFA = asAddNode (sp+'MathFloatAdd','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_MFA') RigVMController.set_node_position (MFA, [1100+x2, y]) RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_MFM.Result' , name+"_"+obj+"_"+attr+dNr+'_MFA.A') RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_MFA.B','1') RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_MFA.Result' , name+"_"+obj+"_"+attr+dNr+'_TFSRT.Scale.'+axis) RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_TFSRT.Transform', name+"_"+obj+"_"+attr+dNr+'_STDriven.Transform') #face if re.search("Teeth_M", name): RigControl.set_editor_property('gizmo_enabled',False) HierarchyModifier.set_control (RigControl) if name=="Jaw_M": RigControl.set_editor_property('gizmo_name','HalfCircle_Thick') RigControl.set_editor_property('gizmo_name','HalfCircle_Thick') Transform = RigControl.get_editor_property('gizmo_transform') Transform.rotation=[0,0,180] RigControl.set_editor_property('gizmo_transform', Transform) HierarchyModifier.set_control (RigControl) PreviousEndPlug = endPlug def asObjExists (obj): RigElementKeys = HierarchyModifier.get_elements() LocObject = None for key in RigElementKeys: if key.name == obj: return True return False def asAddController (name, parent, joint, type, gizmoName, ws, size, offT, color): x = re.search("^Space.*", parent) if x: key = HierarchyModifier.add_control (name,space_name=parent) else: key = HierarchyModifier.add_control (name,parent_name=parent) RigControl = HierarchyModifier.get_control (key) RigElementKeys = HierarchyModifier.get_elements() LocObject = None jointIsBone = False for key in RigElementKeys: if key.name == joint: if key.type == 1: #BONE jointObject = HierarchyModifier.get_bone(key) jointIsBone = True if key.name == 'Loc'+name: LocObject = HierarchyModifier.get_bone(key) OffsetTransform = unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[1,1,1]) GizmoLocation = [offT[0],offT[2],offT[1]] GizmoRotation = [0,0,0] if ws is 0: GizmoRotation = [90,0,0] GizmoLocation = [offT[0],offT[1]*-1,offT[2]] if type=="DrivingSystem": GizmoRotation = [0,0,0] if type=="ctrlBox": GizmoRotation = [0,0,90] if re.search("^Eye_.*", name) or re.search("^Iris_.*", name) or re.search("^Pupil_.*", name): GizmoRotation = [0,90,0] RigControl.set_editor_property('gizmo_visible',False) x = re.search("^Pole.*", name) if x: GizmoLocation = [0,0,0] s = 0.01*size Scale = [s,s,s] if LocObject==None: LocKey = HierarchyModifier.add_bone ('Loc'+name,'LocBones') LocObject = HierarchyModifier.get_bone (LocKey) if jointIsBone: jointTransform = jointObject.get_editor_property('global_transform') if ws is 1: jointTransform.rotation = [0,0,0] OffsetTransform = jointTransform if name!='Main': LocObject.set_editor_property('initial_transform', jointTransform) HierarchyModifier.set_bone (LocObject) if parent!='': for key in RigElementKeys: if key.name == 'Loc'+parent: ParentLocObject = HierarchyModifier.get_bone(key) LocTransform = ParentLocObject.get_editor_property('global_transform') if jointIsBone: OffsetTransform = jointTransform.make_relative(LocTransform) RigControl.set_editor_property('offset_transform', OffsetTransform) RigControl.set_editor_property('gizmo_name',gizmoName) RigControl.set_editor_property('gizmo_transform', unreal.Transform(location=GizmoLocation,rotation=GizmoRotation,scale=Scale)) Color = unreal.Color(b=color[2]*255, g=color[1]*255, r=color[0]*255, a=0) LinearColor = unreal.LinearColor() LinearColor.set_from_srgb(Color) RigControl.set_editor_property('gizmo_color',LinearColor) HierarchyModifier.set_control (RigControl) return RigControl def asParent (child,parent): RigElementKeys = HierarchyModifier.get_elements() for key in RigElementKeys: if (key.name == child): childKey = key for key in RigElementKeys: if (key.name == parent): parentKey = key if not HierarchyModifier.reparent_element (childKey, parentKey): #bug in UE4.27: n`th Space, can not be child of n`th Ctrl, making a new space HierarchyModifier.rename_element (childKey, child+'SpaceParentX') childKey = HierarchyModifier.add_space (child) if not HierarchyModifier.reparent_element (childKey, parentKey): raise Exception('Failed to parent:'+child+' to '+parent) asParent (child+'SpaceParentX','Spaces') return asGetRigElement(child) def asGetRigElement (elementName): RigElementKeys = HierarchyModifier.get_elements() for key in RigElementKeys: if key.name == elementName: if key.type == 1: #BONE element = HierarchyModifier.get_bone(key) if key.type == 2: #SPACE element = HierarchyModifier.get_space(key) if key.type == 4: #CONTROL element = HierarchyModifier.get_control(key) return element def asAlign (source,dest): RigElementKeys = HierarchyModifier.get_elements() for key in RigElementKeys: if (key.name == source): if key.type == 1: #BONE sourceObject = HierarchyModifier.get_bone(key) sourceType = 'Bone' if key.type == 2: #SPACE sourceObject = HierarchyModifier.get_space(key) sourceType = 'Space' if key.type == 4: #CONTROL sourceObject = HierarchyModifier.get_control(key) sourceType = 'Control' if (key.name == dest): if key.type == 1: #BONE destObject = HierarchyModifier.get_bone(key) destType = 'Bone' if key.type == 2: #SPACE destObject = HierarchyModifier.get_space(key) destType = 'Space' if key.type == 4: #CONTROL destObject = HierarchyModifier.get_control(key) destType = 'Control' if sourceType != 'Bone': for key in RigElementKeys: if key.name == 'Loc'+source: source = 'Loc'+source sourceObject = HierarchyModifier.get_bone(key) sourceType = 'Bone' Transform = sourceObject.get_editor_property('global_transform') #Relative to parent LocDestParent = None DestParent = destObject.get_editor_property('parent_name') for key in RigElementKeys: if key.name == 'Loc'+str(DestParent): LocDestParent = HierarchyModifier.get_bone(key) LocDestParentTransform = LocDestParent.get_editor_property('global_transform') Transform = Transform.make_relative(LocDestParentTransform) destObject.set_editor_property('initial_transform', Transform) if destType == 'Bone': HierarchyModifier.set_bone (destObject) if destType == 'Space': HierarchyModifier.set_space (destObject) if destType == 'Control': HierarchyModifier.set_control (destObject) def asAddNode (script_struct_path, method_name, node_name): #RigVMController. #add_struct_node_from_struct_path UE4 #add_unit_node_from_struct_path UE5 try: node = RigVMController.add_struct_node_from_struct_path(script_struct_path,method_name,node_name=node_name) #UE4 except: node = RigVMController.add_unit_node_from_struct_path(script_struct_path,method_name,node_name=node_name) #UE5 return node def main (): global PreviousEndPlugInv RigElementKeys = HierarchyModifier.get_elements() RigVMGraph = ControlRigBlueprint.model #Clear out existing rig-setup nodes = RigVMGraph.get_nodes() for node in nodes: RigVMController.remove_node(node) #Clear out existing controllers for key in RigElementKeys: if key.name == 'MotionSystem': HierarchyModifier.remove_element(key) if not (key.type==1 or key.type==8): #BONE try: HierarchyModifier.remove_element(key) except: pass BeginExecutionNode = asAddNode (sp+'BeginExecution','Execute',node_name='RigUnit_BeginExecution') RigVMController.set_node_position (BeginExecutionNode, [-300, -100]) InverseExecutionNode = asAddNode (sp+'InverseExecution','Execute',node_name='RigUnit_InverseExecution') RigVMController.set_node_position (InverseExecutionNode, [-1900, -100]) #Backwards solve nodes GTinvRoot = asAddNode (sp+'GetTransform','Execute',node_name='Root_M_GTinvRoot') RigVMController.set_node_position (GTinvRoot, [-2100, 400]) RigVMController.set_pin_default_value('Root_M_GTinvRoot.Item.Type','Bone') RigVMController.set_pin_default_value('Root_M_GTinvRoot.Item.Name','Root_M') CONinvRoot = asAddNode (sp+'TransformConstraintPerItem','Execute',node_name='Root_M_CONinvRoot') RigVMController.set_node_position (CONinvRoot, [-1500, 400-90]) RigVMController.set_pin_default_value('Root_M_CONinvRoot.Item.Type','Control') RigVMController.set_pin_default_value('Root_M_CONinvRoot.Item.Name','RootX_M') RigVMController.add_array_pin('Root_M_CONinvRoot.Targets') RigVMController.add_link('Root_M_GTinvRoot.Transform' , 'Root_M_CONinvRoot.Targets.0.Transform') RigVMController.add_link('RigUnit_InverseExecution.ExecuteContext' , 'Root_M_CONinvRoot.ExecuteContext') CCinv = asAddNode (sp+'CollectionChildren','Execute',node_name='CCinv') RigVMController.set_node_position (CCinv, [-2600, 1000]) RigVMController.set_pin_default_value('CCinv.Parent.Type','Bone') RigVMController.set_pin_default_value('CCinv.Parent.Name','Root_M') RigVMController.set_pin_default_value('CCinv.bRecursive','True') RigVMController.set_pin_default_value('CCinv.TypeToSearch','Bone') CLinv = asAddNode (sp+'CollectionLoop','Execute',node_name='CLinv') RigVMController.set_node_position (CLinv, [-2150, 1000]) RigVMController.add_link('Root_M_CONinvRoot.ExecuteContext' , 'CLinv.ExecuteContext') RigVMController.add_link('CCinv.Collection' , 'CLinv.Collection') PreviousEndPlugInv = 'CLinv.Completed' NCinv = asAddNode (sp+'NameConcat','Execute',node_name='NCinv') RigVMController.set_node_position (NCinv, [-1900, 900]) RigVMController.set_pin_default_value('NCinv.A','FK') RigVMController.add_link('CLinv.Item.Name' , 'NCinv.B') GTinv = asAddNode (sp+'GetTransform','Execute',node_name='GTinv') RigVMController.set_node_position (GTinv, [-1900, 1000]) RigVMController.add_link('CLinv.Item.Name' , 'GTinv.Item.Name') IEinv = asAddNode (sp+'ItemExists','Execute',node_name='IEinv') RigVMController.set_node_position (IEinv, [-1700, 700]) RigVMController.set_pin_default_value('IEinv.Item.Type','Control') RigVMController.add_link('NCinv.Result' , 'IEinv.Item.Name') BRinv = RigVMController.add_branch_node(node_name='BRinv') RigVMController.set_node_position (BRinv, [-1650, 850]) RigVMController.add_link('IEinv.Exists' , 'BRinv.Condition') RigVMController.add_link('CLinv.ExecuteContext' , 'BRinv.ExecuteContext') STinv = asAddNode (sp+'SetTransform','Execute',node_name='STinv') RigVMController.set_node_position (STinv, [-1500, 1000]) RigVMController.set_pin_default_value('STinv.Item.Type','Control') RigVMController.add_link('NCinv.Result' , 'STinv.Item.Name') RigVMController.add_link('GTinv.Transform' , 'STinv.Transform') RigVMController.add_link('BRinv.True' , 'STinv.ExecuteContext') HierarchyModifier.add_bone ('MotionSystem') HierarchyModifier.add_bone ('TwistSystem') HierarchyModifier.add_bone ('LocBones') HierarchyModifier.add_bone ('DrivingSystem') HierarchyModifier.add_bone ('Spaces') asParent ('TwistSystem','MotionSystem') asParent ('LocBones','MotionSystem') asParent ('DrivingSystem','MotionSystem') asParent ('Spaces','MotionSystem') selectedAsset.get_class().modify(True)#tag dirty #//-- ASControllers Starts Here --// #//-- ASControllers Ends Here --// # selectedAsset.get_class().modify(True)#tag dirty # Unreal un-sets `dirty` flag upon opening of ControlRigEditor, causing non-prompt for save upon exit and loss of ControlRig, therefor just save # unreal.EditorAssetLibrary.save_asset(selectedAsset.get_path_name()) #Removed since this requires "Editor Scripting Utilities" plugin selectedAsset.get_class().modify(False) print ("ControlRig created") if __name__ == "__main__": main()
import asyncio import logging import time import os import traceback from typing import Any, Awaitable, Callable, Sequence import uuid import anyio from mcp.types import AnyFunction, EmbeddedResource, ImageContent, TextContent import unreal from mcp.server.fastmcp import FastMCP from mcp.server.fastmcp.server import Settings import uvicorn import socket from foundation import global_context max_tick_count = 86400 logger = logging.getLogger() class UnrealMCP(FastMCP): def __init__(self, name: str | None = None, instructions: str | None = None, **settings: Any): super().__init__(name=name, instructions=instructions, **settings) self.server = None self.force_exit = False self.tick_count = 0 self.should_exit = False self.uuid = uuid.uuid4() self.task_queue = asyncio.Queue() # 用于存储任务的队列 self._game_thread_tool_set = set[str]() #self.tick_loop = asyncio.SelectorEventLoop() def sync_run_func(self, function: Any) -> None: # 运行函数 loop = global_context.get_event_loop() loop.run_until_complete(function()) unreal.log("MCP complete run") pass def run(self): self.init_bridge() async def async_run(self): # self.init_bridge() # await self.init_server() # await self.server._serve() try: await self.start_up() except Exception as e: unreal.log_error("Error initializing bridge: " + str(e)) await self.shutdown() return while not self.should_exit : await self.server.on_tick(self.tick_count) await asyncio.sleep(1) # tick在主线程驱动 #unreal.log("Tick " + str(not self.should_exit)) await self.shutdown() pass def sync_tick(self): anyio.run(self.tick) pass def init_bridge(self): context = unreal.MCPObject() context.bridge = unreal.MCPBridgeFuncDelegate() context.bridge.bind_callable(self.on_bridge) context.tick = unreal.MCPObjectEventFunction() context.tick.bind_callable(self.sync_tick) context.guid = str(self.uuid) context.python_object_handle = unreal.create_python_object_handle(self) unreal.get_editor_subsystem(unreal.MCPSubsystem).setup_object(context) unreal.log("Bridge setup " + str(self.uuid)) def clear_bridge(self): unreal.get_editor_subsystem(unreal.MCPSubsystem).clear_object() def on_bridge(self, type: unreal.MCPBridgeFuncType, message: str): unreal.log("Bridge Message: " + message) if type == unreal.MCPBridgeFuncType.EXIT: self.should_exit = True self.clear_bridge() if type == unreal.MCPBridgeFuncType.START: self.sync_run_func(self.async_run)() pass async def init_server(self) -> None: """Run the server using SSE transport.""" starlette_app = self.sse_app() config = uvicorn.Config( starlette_app, host=self.settings.host, port=self.settings.port, #timeout_graceful_shutdown = 10, log_level=self.settings.log_level.lower(), ) self.server = uvicorn.Server(config) async def start_up_server(self, server: uvicorn.Server, sockets: list[socket.socket] | None = None) -> None: process_id = os.getpid() config = server.config if not config.loaded: config.load() server.lifespan = config.lifespan_class(config) message = "Started server process " + str(process_id) unreal.log(message) await server.startup(sockets=sockets) async def start_up(self) -> None: await self.init_server() await self.start_up_server(self.server) #self.init_bridge() unreal.log("Server started " + str(self.uuid)) async def shutdown(self): unreal.log("begin stop") await self.tick() self.server.force_exit = True await self.server.shutdown(sockets=None) # self.clear_bridge() unreal.log("Server stopped " + str(self.uuid)) async def tick(self) -> bool: self.tick_count += 1 self.tick_count = self.tick_count % max_tick_count await self.do_task() return True async def do_task(self) -> None: # 运行任务 while not self.task_queue.empty(): func, args, kwargs,future = await self.task_queue.get() try: result = func(*args, **kwargs) if isinstance(result, Awaitable): result = await result future.set_result(result) unreal.log(f"Executed tool: {func.__name__}, Result: {result}") except Exception as e: error_info = f"Error executing tool {func.__name__}: {str(e)}" logger.info(error_info) future.set_result(error_info) return error_info async def to_tick_thread(self, func:Callable, *args: Any, **kwargs: Any) -> Any: # 将函数添加到任务队列 unreal.log("Add task to game thread task queue") future = asyncio.Future() await self.task_queue.put((func, args, kwargs, future)) return await future async def call_tool(self, name: str, arguments: dict[str, Any]) -> Sequence[TextContent | ImageContent | EmbeddedResource]: """Call a tool by name with arguments.""" try: unreal.log(f"call_tool {name} {arguments}" ) if(self._game_thread_tool_set.__contains__(name)): # 在闭包外获取父类方法的引用 parent_call_tool = FastMCP.call_tool # 使用闭包捕获所需的参数和方法 async def wrapped_call_tool(self_ref=self, name_ref=name, args_ref=arguments, parent_method=parent_call_tool): return await parent_method(self_ref, name_ref, args_ref) return await self.to_tick_thread(wrapped_call_tool) return await super().call_tool(name, arguments) except Exception as e: info = f"Error calling tool {name}: {str(e)}" unreal.log_error(info) return info def game_thread_tool( self, name: str | None = None, description: str | None = None ) -> Callable[[AnyFunction], AnyFunction]: """Decorator to register a tool.""" # Check if user passed function directly instead of calling decorator if callable(name): raise TypeError( "The @tool decorator was used incorrectly. " "Did you forget to call it? Use @tool() instead of @tool" ) def decorator(fn: AnyFunction) -> AnyFunction: fn_desc = f'(GameThread){description or fn.__doc__}' func_name = name or fn.__name__ self._game_thread_tool_set.add(func_name) #unreal.log(f"Registering tool: {func_name} - {fn_desc}") self.add_tool(fn, func_name, fn_desc) return fn return decorator global_mcp:UnrealMCP = None
import unreal from unreal import ( MaterialInstanceConstant ) # input material_instance: MaterialInstanceConstant material_path0: str material_path1: str # output result: bool = True log_str: str = "" def is_shader_path_valid(shader_path: str, path0: str, path1: str) -> bool: """判断shader路径是否不在指定的两个目录下""" return (shader_path.startswith(path0) or shader_path.startswith(path1)) def check_material_instance_shader_path(material_instance: MaterialInstanceConstant, path0: str, path1: str) -> tuple: """ 检查材质实例的母材质路径是否在path0和path1以外 :param material_instance: 材质实例 :param path0: 允许的目录0 :param path1: 允许的目录1 :return: (bool, log_str) - True为合规,False为不合规 """ if not material_instance: return False, "未传入有效的材质实例" base_material = material_instance.get_base_material() shader_path = base_material.get_path_name() if not is_shader_path_valid(shader_path, path0, path1): log_str = f"角色材质实例 {material_instance.get_name()} 的Shader只能使用 {path0} 或 {path1} 下的" return False, log_str return True, "" result, log_str = check_material_instance_shader_path(material_instance, material_path0, material_path1)
import unreal # retrieves selected actors in the world outliner actorsubsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) staticmeshsubsystem = unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem) actors = actorsubsystem.get_selected_level_actors() for actor in actors: static_mesh = actor.static_mesh_component.static_mesh box = static_mesh.get_bounding_box() tiling = 1.0 pos = (box.min + box.max) * 0.5 rot = unreal.Rotator() bounding_box_size = box.max - box.min max_edge = max([bounding_box_size.x, bounding_box_size.y, bounding_box_size.z]) box_uv_size = unreal.Vector(max_edge/tiling, max_edge/tiling, max_edge/tiling) staticmeshsubsystem.generate_box_uv_channel(static_mesh, 0, 0, pos, rot, box_uv_size)
# coding: utf-8 # ノードの骨指定部分を _c のControllerに置き換える from asyncio.windows_events import NULL from platform import java_ver import unreal import time import argparse print("VRM4U python begin") print (__file__) parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") parser.add_argument("-meta") args = parser.parse_args() print(args.vrm) with unreal.ScopedSlowTask(1, "Convert Bone") as slow_task_root: slow_task_root.make_dialog() reg = unreal.AssetRegistryHelpers.get_asset_registry() rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r #rig = rigs[10] hierarchy = unreal.ControlRigBlueprintLibrary.get_hierarchy(rig) h_con = hierarchy.get_controller() r_con = rig.get_controller() graph = r_con.get_graph() node = graph.get_nodes() def checkAndSwapPinBoneToContorl(pin): subpins = pin.get_sub_pins() #print(subpins) if (len(subpins) != 2): return; typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') #if (typePin==None or namePin==None): if (typePin==None): return; #if (typePin.get_default_value() == '' or namePin.get_default_value() == ''): if (typePin.get_default_value() == ''): return; if (typePin.get_default_value() != 'Bone'): return; #print(typePin.get_default_value() + ' : ' + namePin.get_default_value()) r_con.set_pin_default_value(typePin.get_pin_path(), 'Control', True, False) r_con.set_pin_default_value(namePin.get_pin_path(), namePin.get_default_value() + '_c', True, False) #print('swap end') #end check pin bonePin = None controlPin = None with unreal.ScopedSlowTask(1, "Replace Bone to Controller") as slow_task: slow_task.make_dialog() for n in node: pins = n.get_pins() for pin in pins: if (pin.is_array()): for item in pin.get_sub_pins(): checkAndSwapPinBoneToContorl(item) else: checkAndSwapPinBoneToContorl(pin)
import unreal import random import math from itertools import cycle import csv ELL = unreal.EditorLevelLibrary() EAL = unreal.EditorAssetLibrary() def spawnCam(): cam = unreal.CineCameraActor().get_class() allActors = ELL.get_all_level_actors() print(allActors) meshes = [] cams = [] for actor in allActors: #print(actor.get_class().get_name()) if actor.get_class().get_name() == "BP_MH_C": meshes.append(actor) for actor in meshes: bounds = actor.get_actor_bounds(False) location = actor.get_actor_location() + (actor.get_actor_right_vector()*200) location.z = bounds[1].z*2-random.randrange(20,45) location.x += random.randrange(-20,20) rotation = unreal.Rotator(0,0,-90) #rotation = unreal.Rotator(random.randrange(-25,25),0,-90) camera = ELL.spawn_actor_from_class(cam,location,rotation,transient=False) cams.append(camera) return meshes, cams def createSequencer(nums,cameraDistance,queueSet): KeijiPath = EAL.load_blueprint_class('/project/') ValPath = EAL.load_blueprint_class('/project/') MylesPath = EAL.load_blueprint_class('/project/') OskarPath = EAL.load_blueprint_class('/project/') HudsonPath = EAL.load_blueprint_class('/project/') LexiPath = EAL.load_blueprint_class('/project/') VivianPath = EAL.load_blueprint_class('/project/') mhpaths = [HudsonPath,LexiPath]#[MylesPath,OskarPath]#[KeijiPath,ValPath,MylesPath,OskarPath,HudsonPath,LexiPath,VivianPath] mhCycler = cycle(mhpaths) alex = EAL.load_asset('/project/') cubeAlex = EAL.load_blueprint_class('/project/') alexspawn = ELL.spawn_actor_from_object(alex,location=unreal.Vector(0,0,0),rotation=unreal.Rotator(0,0,0)) alexspawn2 = ELL.spawn_actor_from_class(cubeAlex,location=unreal.Vector(0,0,0),rotation=unreal.Rotator(0,0,0)) attachCube = EAL.load_asset('/project/') attachCubeSpawn = ELL.spawn_actor_from_object(attachCube,location=unreal.Vector(0,0,0),rotation=unreal.Rotator(0,0,0)) attachCubeSpawn.set_mobility(unreal.ComponentMobility.MOVABLE) # attachCubeSpawn.attach_to_actor(alexspawn2,'Alex_Neck',unreal.AttachmentRule.SNAP_TO_TARGET,unreal.AttachmentRule.SNAP_TO_TARGET,unreal.AttachmentRule.KEEP_RELATIVE,False) # #anim_assets= metahumanAnims.anim_assets #cycler=cycle(anim_assets) #cam = unreal.CineCameraActor().get_class() # camLocation = unreal.Vector(0,300,130) # camRotation = unreal.Rotator(0,0,-90) # camSpawn = ELL.spawn_actor_from_class(cam,camLocation,camRotation,transient=False) sequenceName = 'lvl_sequence' + '%d' #+'%d'#'%s' sequencerPaths = [] sequencerWorlds = [] #for i,(mesh,cam) in enumerate(zip(meshes,cams)): for i in range(nums): currWorld = alexspawn.get_world().get_name() assetTools = unreal.AssetToolsHelpers.get_asset_tools() sequence = assetTools.create_asset(asset_name=sequenceName%(i), package_path='/project/', asset_class=unreal.LevelSequence, factory=unreal.LevelSequenceFactoryNew()) randStart = random.randrange(40,150) sequence.set_playback_start(randStart) sequence.set_playback_end(randStart+30) #adding the mesh into the sequencer mesh_binding = sequence.add_spawnable_from_instance(next(mhCycler)) alex_binding = sequence.add_possessable(alexspawn) alex_bindingTrack = sequence.add_possessable(alexspawn2) cubeSpawnTrack = sequence.add_possessable(attachCubeSpawn) cubeAttachTrack = cubeSpawnTrack.add_track(unreal.MovieScene3DAttachTrack) cubeAttachSection = cubeAttachTrack.add_section() cubeAttachSection.set_editor_property('constraint_binding_id',alex_bindingTrack.get_binding_id()) cubeAttachSection.set_editor_property('attach_component_name',"SkeletalMesh") cubeAttachSection.set_editor_property('attach_socket_name',"Alex_Head") # camLoc = camSpawn.get_actor_location() # camLoc.z += random.randrange(-55,55) # camLoc.x += random.randrange(-35,35) # camSpawnLoop = ELL.spawn_actor_from_object(camSpawn,camLoc,camRotation) camSpawn = randomCircleSpawn(cameraDistance)#+random.randrange(-5,5)) camera_binding = sequence.add_possessable(camSpawn) alex_binding.set_parent(mesh_binding) #adding a animtrack anim_track = mesh_binding.add_track(unreal.MovieSceneSkeletalAnimationTrack) anim_track2 = alex_bindingTrack.add_track(unreal.MovieSceneSkeletalAnimationTrack) #adding section to track to manipulate range and params anim_section = anim_track.add_section() anim_section2 = anim_track2.add_section() start_frame = 0#sequence.get_playback_start()-random.randrange(50,70) end_frame = sequence.get_playback_end() #adding an anim to the track anim_section.set_range(start_frame,end_frame) anim_section2.set_range(start_frame,end_frame) cubeAttachSection.set_range(start_frame,end_frame) animforthisloop = assetWalk() anim_section.params.animation = animforthisloop anim_section2.params.animation = animforthisloop #add camera cuts master track cameraCutsTrack = sequence.add_master_track(unreal.MovieSceneCameraCutTrack) cameraCutsSection = cameraCutsTrack.add_section() cameraCutsSection.set_range(start_frame,end_frame) #adding camera camera_binding_id = unreal.MovieSceneObjectBindingID() camera_binding_id.set_editor_property('guid',camera_binding.get_id()) cameraCutsSection.set_camera_binding_id(camera_binding_id) sequencerPaths.append(sequence.get_path_name()) sequencerWorlds.append(currWorld) return sequencerPaths, sequencerWorlds #to try to straighten the above code out a little bit #we created a level sequence object called sequence #level sequence inherits from movieSceneSequence which has a add_track and add_master_track method #movieSceneSequence also has add_possessable method in it which is how we add possessable objects in our new sequencer #which returns a moviescenebindingproxy object #in that class there's a add track method which requires a moviescene track class type obj to create a new track #which is why we're inputting the class and not creating an instance of it #it returns a moviescenetrack object #movieSceneSequence also has a add_master_track method with asks for a umoviescenetrack class and returns moviescene track def levelTravel(): ELL.save_current_level() currLev = ELL.get_editor_world().get_name() if currLev == 'PythonEmptyTest': ELL.load_level('/project/') else: ELL.load_level('/project/') def main(*params): seqNum,camDist,qs = params #spawnMH(params) #meshes,cams = spawnCam() seqpaths, seqworlds = createSequencer(seqNum,camDist,qs) return seqpaths,seqworlds def assetWalk(): 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 randomCircleSpawn(distance_offset): cam = unreal.CineCameraActor() 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) camRot = unreal.Rotator(0,0,0) #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) camSpawn = unreal.EditorLevelLibrary().spawn_actor_from_object(cam,camLoc,camRot) return camSpawn #return camLoc,camRot def alignTracking(): allCams = [] attach = None allactors = unreal.EditorLevelLibrary().get_all_level_actors() for actor in allactors: if actor.get_class().get_name() == 'CineCameraActor': allCams.append(actor) elif actor.get_name()=='StaticMeshActor_0': attach = actor for cam in allCams: 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',25) cam.lookat_tracking_settings = trackingSettings def randomizeExposure(): allCams = [] allactors = unreal.EditorLevelLibrary().get_all_level_actors() for actor in allactors: if actor.get_class().get_name() == 'CineCameraActor': allCams.append(actor) for cam in allCams: pps = cam.get_cine_camera_component().get_editor_property('post_process_settings') fs = cam.get_cine_camera_component().get_editor_property('focus_settings') fb = cam.get_cine_camera_component().get_editor_property('filmback') # pps.set_editor_property('override_auto_exposure_method',True) # pps.set_editor_property('auto_exposure_method',unreal.AutoExposureMethod.AEM_MANUAL) # pps.set_editor_property('override_auto_exposure_bias',True) # pps.set_editor_property('auto_exposure_bias',random.uniform(8,12)) fs.set_editor_property('focus_method',unreal.CameraFocusMethod.DISABLE) fb.set_editor_property('sensor_width',12.52) fb.set_editor_property('sensor_height',7.58) def CameraPosDump(): AllCams= unreal.EditorLevelLibrary.get_all_level_actors() file =open('/project/.csv','a',newline='') writer = csv.writer(file) camloc=[] for cam in AllCams: if cam.get_class().get_name()=='CineCameraActor': loc= cam.get_actor_location().to_tuple() tempList = [loc[0],loc[1],loc[2]] camloc.append(tempList) writer.writerows(camloc) file.close() def seqCheck(): # seq = unreal.EditorAssetLibrary.load_asset('/project/') # seqBindings = seq.get_bindings() # for b in seqBindings: # print(b.get_display_name()) # print(seqBindings[4].get_tracks()[0].get_sections()) # print(dir(seqBindings[4].get_tracks()[1].get_sections()[0])) #print(seqBindings[3].get_tracks()[0].get_sections()[0].get_editor_property('section_range')) #MSE = unreal.MovieSceneSectionExtensions() #seqBindings[3].get_tracks()[0].get_sections()[0].set_range(0,200) asset = unreal.EditorLevelLibrary.get_selected_level_actors() print(asset[0]) trackingSettings = unreal.CameraLookatTrackingSettings() trackingSettings.set_editor_property('enable_look_at_tracking',True) trackingSettings.set_editor_property("actor_to_track",asset[1]) trackingSettings.set_editor_property('look_at_tracking_interp_speed',2) asset[0].lookat_tracking_settings = trackingSettings #al = seqBindings[2] # aiBID = al.get_editor_property('binding_id') # sections = seqBindings[3].get_tracks()[0].get_sections() # compName = sections[0].get_editor_property('attach_component_name') # cubeBID = sections[0].get_constraint_binding_id() # # print(sections[0].get_editor_property('attach_socket_name')) # print(f'name: {al.get_display_name()}, binding id:{al.get_binding_id()}') # print(f'name:{type(sections[0])}, binding_id:{cubeBID}') def test(): val = EAL.load_blueprint_class('/project/') alex = EAL.load_asset('/project/') alexspawn = ELL.spawn_actor_from_object(alex,location=unreal.Vector(0,0,0),rotation=unreal.Rotator(0,0,0)) assetTools = unreal.AssetToolsHelpers.get_asset_tools() seq = assetTools.create_asset(asset_name='retarget', package_path='/project/', asset_class=unreal.LevelSequence, factory=unreal.LevelSequenceFactoryNew()) print(val) print(type(val)) valbind = seq.add_spawnable_from_instance(val) alexbind = seq.add_possessable(alexspawn) anim_track = valbind.add_track(unreal.MovieSceneSkeletalAnimationTrack) anim_section = anim_track.add_section() anim_section.set_range(-50,300) anim_section.params.animation = EAL.load_asset('/project/') alexbind.set_parent(valbind) #rendering the movie out to the saved dir with default capture settings def render(sequencer): for sequencer in sequencer: capture_settings = unreal.AutomatedLevelSequenceCapture() capture_settings.level_sequence_asset = unreal.SoftObjectPath(sequencer) capture_settings.get_editor_property('settings').set_editor_property('output_format','{world}{sequence}') unreal.SequencerTools.render_movie(capture_settings,unreal.OnRenderMovieStopped()) def spawnSK(nums): SK2filePath = EAL.load_asset('/project/') SKfilePath = EAL.load_asset('/project/') for i in range(nums): location=unreal.Vector(random.randrange(-1000,1000),random.randrange(-1000,1000),0.0) rotation=unreal.Rotator(0.0,0.0,0.0) if i%2==0: ELL.spawn_actor_from_object(SKfilePath,location,rotation) else: ELL.spawn_actor_from_object(SK2filePath,location,rotation) def spawnMH(nums): KeijiPath = EAL.load_blueprint_class('/project/') ValPath = EAL.load_blueprint_class('/project/') MHPaths = [KeijiPath,ValPath] cycler=cycle(MHPaths) for i in range(nums): location= unreal.Vector(random.randrange(-1000,1000),random.randrange(-1000,1000),0.0) rotation= unreal.Rotator(0.0,0.0,0.0) #ELL.spawn_actor_from_class(next(cycler),location,rotation) def timetest(): world = unreal.UnrealEditorSubsystem().get_game_world() gps = unreal.GameplayStatics() gps.set_global_time_dilation(world,5) def etest(): level_actors = unreal.EditorLevelLibrary.get_all_level_actors() character_actor = None for actor in level_actors: if actor.get_class().get_name() == "BP_Lexi_C": character_actor = actor break comps = character_actor.root_component.get_children_components(True) cam = None for c in comps: if c.get_name() == "CineCamera": cam = c camLoc,camRot = randomCircleSpawn(80) print(camLoc) cam.set_world_rotation(unreal.Rotator(0,0,-85),False,False) cam.set_world_location(camLoc,False,False) at = unreal.AssetToolsHelpers.get_asset_tools() seq = at.create_asset( asset_name= 'test', package_path='/project/', asset_class=unreal.LevelSequence, factory=unreal.LevelSequenceFactoryNew(), ) lex_bind = seq.add_possessable(character_actor) anim_bind = None for comp in comps: if comp.get_name() == 'alexwboxes': anim_bind = seq.add_possessable(comp) anim_bind.set_parent(lex_bind) elif comp.get_name() == 'CineCamera': cam_bind = seq.add_possessable(comp) cam_bind.set_parent(lex_bind) else: track = seq.add_possessable(comp) track.set_parent(lex_bind) anim_track = lex_bind.add_track(unreal.MovieSceneSkeletalAnimationTrack) anim_section = anim_track.add_section() anim_section.params.animation = unreal.EditorAssetLibrary.load_asset('/project/') anim_section.set_range(0,seq.get_playback_end())
# coding: utf-8 import unreal import time import argparse parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") parser.add_argument("-debugeachsave") args = parser.parse_args() #print(args.vrm) ###### with unreal.ScopedSlowTask(1, "Convert MorphTarget") as slow_task_root: slow_task_root.make_dialog() rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r hierarchy = unreal.ControlRigBlueprintLibrary.get_hierarchy(rig) h_con = hierarchy.get_controller() print(unreal.SystemLibrary.get_engine_version()) if (unreal.SystemLibrary.get_engine_version()[0] == '5'): c = rig.get_controller() else: c = rig.controller g = c.get_graph() n = g.get_nodes() mesh = rig.get_preview_mesh() morphList = mesh.get_all_morph_target_names() morphListWithNo = morphList[:] morphListRenamed = [] morphListRenamed.clear() for i in range(len(morphList)): morphListWithNo[i] = '{}'.format(morphList[i]) print(morphListWithNo) bRemoveElement = False if ("5." in unreal.SystemLibrary.get_engine_version()): if ("5.0." in unreal.SystemLibrary.get_engine_version()): bRemoveElement = True else: bRemoveElement = True if (bRemoveElement): while(len(hierarchy.get_bones()) > 0): e = hierarchy.get_bones()[-1] h_con.remove_all_parents(e) h_con.remove_element(e) h_con.import_bones(unreal.ControlRigBlueprintLibrary.get_preview_mesh(rig).skeleton) h_con.import_curves(unreal.ControlRigBlueprintLibrary.get_preview_mesh(rig).skeleton) dset = rig.get_editor_property('rig_graph_display_settings') dset.set_editor_property('node_run_limit', 0) rig.set_editor_property('rig_graph_display_settings', dset) ###### root key = unreal.RigElementKey(unreal.RigElementType.NULL, 'MorphControlRoot_s') space = hierarchy.find_null(key) if (space.get_editor_property('index') < 0): space = h_con.add_null('MorphControlRoot_s', space_type=unreal.RigSpaceType.SPACE) else: space = key #a:unreal.RigUnit_CollectionItems = unreal.RigUnit_CollectionItems() #print(a) # 配列ノード追加 values_forCurve:unreal.RigVMStructNode = [] items_forControl:unreal.RigVMStructNode = [] items_forCurve:unreal.RigVMStructNode = [] for node in n: #print(node) #print(node.get_node_title()) # set curve num if (node.get_node_title() == 'For Loop'): #print(node) pin = node.find_pin('Count') #print(pin) c.set_pin_default_value(pin.get_pin_path(), str(len(morphList)), True, False) # curve name array pin if (node.get_node_title() == 'Select'): #print(node) pin = node.find_pin('Values') #print(pin) #print(pin.get_array_size()) #print(pin.get_default_value()) values_forCurve.append(pin) # items if (node.get_node_title() == 'Collection from Items'): if ("Type=Curve," in c.get_pin_default_value(node.find_pin('Items').get_pin_path())): items_forCurve.append(node.find_pin('Items')) elif (node.find_pin('Items').get_array_size() == 40): items_forControl.append(node.find_pin('Items')) print(items_forControl) print(values_forCurve) # reset controller for e in reversed(hierarchy.get_controls()): if (len(hierarchy.get_parents(e)) == 0): continue if (hierarchy.get_parents(e)[0].name == 'MorphControlRoot_s'): #if (str(e.name).rstrip('_c') in morphList): # continue print('delete') #print(str(e.name)) if (bRemoveElement): h_con.remove_element(e) # curve array for v in values_forCurve: c.clear_array_pin(v.get_pin_path(), False) for morph in morphList: tmp = "{}".format(morph) c.add_array_pin(v.get_pin_path(), default_value=tmp, setup_undo_redo=False) # curve controller for morph in morphListWithNo: name_c = "{}_c".format(morph) key = unreal.RigElementKey(unreal.RigElementType.CONTROL, name_c) settings = unreal.RigControlSettings() settings.shape_color = [1.0, 0.0, 0.0, 1.0] settings.control_type = unreal.RigControlType.FLOAT try: control = hierarchy.find_control(key) if (control.get_editor_property('index') < 0): k = h_con.add_control(name_c, space, settings, unreal.RigControlValue(), setup_undo=False) control = hierarchy.find_control(k) except: k = h_con.add_control(name_c, space, settings, unreal.RigControlValue(), setup_undo=False) control = hierarchy.find_control(k) shape_t = unreal.Transform(location=[0.0, 0.0, 0.0], rotation=[0.0, 0.0, 0.0], scale=[0.001, 0.001, 0.001]) hierarchy.set_control_shape_transform(k, shape_t, True) morphListRenamed.append(control.key.name) if (args.debugeachsave == '1'): try: unreal.EditorAssetLibrary.save_loaded_asset(rig) except: print('save error') #unreal.SystemLibrary.collect_garbage() # eye controller eyeControllerTable = [ "VRM4U_EyeUD_left", "VRM4U_EyeLR_left", "VRM4U_EyeUD_right", "VRM4U_EyeLR_right", ] # eye controller for eyeCon in eyeControllerTable: name_c = "{}_c".format(eyeCon) key = unreal.RigElementKey(unreal.RigElementType.CONTROL, name_c) settings = unreal.RigControlSettings() settings.shape_color = [1.0, 0.0, 0.0, 1.0] settings.control_type = unreal.RigControlType.FLOAT try: control = hierarchy.find_control(key) if (control.get_editor_property('index') < 0): k = h_con.add_control(name_c, space, settings, unreal.RigControlValue(), setup_undo=False) control = hierarchy.find_control(k) except: k = h_con.add_control(name_c, space, settings, unreal.RigControlValue(), setup_undo=False) control = hierarchy.find_control(k) shape_t = unreal.Transform(location=[0.0, 0.0, 0.0], rotation=[0.0, 0.0, 0.0], scale=[0.001, 0.001, 0.001]) hierarchy.set_control_shape_transform(k, shape_t, True) # curve Control array with unreal.ScopedSlowTask(len(items_forControl)*len(morphListRenamed), "Add Control") as slow_task: slow_task.make_dialog() for v in items_forControl: c.clear_array_pin(v.get_pin_path(), False) for morph in morphListRenamed: slow_task.enter_progress_frame(1) tmp = '(Type=Control,Name=' tmp += "{}".format(morph) tmp += ')' c.add_array_pin(v.get_pin_path(), default_value=tmp, setup_undo_redo=False) # curve Float array with unreal.ScopedSlowTask(len(items_forCurve)*len(morphList), "Add Curve") as slow_task: slow_task.make_dialog() for v in items_forCurve: c.clear_array_pin(v.get_pin_path(), False) for morph in morphList: slow_task.enter_progress_frame(1) tmp = '(Type=Curve,Name=' tmp += "{}".format(morph) tmp += ')' c.add_array_pin(v.get_pin_path(), default_value=tmp, setup_undo_redo=False)
"""Provides functionality for animation data export.""" import unreal from ...utils.logging_config import logger def export_animation_sequence(file_path: str, target_skeleton: str, output_path: str): """ Import and process animation sequence from file. Args: file_path: Path to the animation file target_skeleton: Path to the target skeleton output_path: Destination path for the processed animation Returns: unreal.AnimSequence or None: The processed animation sequence """ try: import_settings = _create_import_settings() imported_asset = _import_animation_file(file_path, output_path, import_settings) if not imported_asset: raise RuntimeError("Animation import failed") animation_sequence = imported_asset.get_asset() _retarget_animation(animation_sequence, target_skeleton) unreal.EditorAssetLibrary.save_loaded_asset(animation_sequence) return animation_sequence except Exception as e: logger.error(f"Animation export failed: {str(e)}") return None def _create_import_settings(): """Create and configure import settings.""" settings = unreal.FbxImportUI() settings.set_editor_property("skeleton", unreal.load_asset("/project/")) settings.set_editor_property("import_as_skeletal", True) settings.skeleton_import_data.set_editor_property("snap_to_closest_frame", True) settings.anim_sequence_import_data.set_editor_property("import_custom_attribute", True) return settings def _import_animation_file(file_path: str, output_path: str, settings): """Import animation file using specified settings.""" return unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks([ unreal.AssetImportTask( filename=file_path, destination_path=output_path, options=settings ) ])[0] def _retarget_animation(sequence, target_skeleton: str): """Retarget animation to specified skeleton.""" target = unreal.load_asset(target_skeleton) if not target: raise ValueError(f"Failed to load target skeleton: {target_skeleton}") sequence.set_editor_property("target_skeleton", target.skeleton)
import unreal from . import helpers, assets def generate_texture_import_task( filename, destination_path, destination_name=None, replace_existing=True, automated=True, save=True, import_options=None, ): """ Creates and configures an Unreal AssetImportTask to import a texture file. :param str filename: texture 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 texture. If not given, the name will be the file name without the extension. :param bool replace_existing: :param bool automated: :param bool save: :param dict import_options: dictionary containing all the texture settings to use. :return: Unreal AssetImportTask that handles the import of the texture 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 texture_factory = unreal.TextureFactory() task.factory = texture_factory import_options = import_options or dict() for name, value in import_options.items(): try: task.factory.set_editor_property(name, value) except Exception: unreal.log_warning( "Was not possible to set FBX Import property: {}: {}".format( name, value ) ) return task def import_texture_asset( filename, destination_path, destination_name=None, import_options=None ): """ Imports a texture asset into Unreal Content Browser. :param str filename: texture file to import. :param str destination_path: Content Browser path where the texture will be placed. :param str or None destination_name: optional name of the imported texture. If not given, the name will be the filename without the extension. :param dict import_options: dictionary containing all the texture import settings to use. :return: path to the imported texture asset. :rtype: str """ tasks = list() tasks.append( generate_texture_import_task( filename, destination_path, destination_name=destination_name, import_options=import_options, ) ) return helpers.get_first_in_list(assets.import_assets(tasks), default="")
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 # get all selected browser assets # IMPORTANT: calling the function EditorUtilityLibrary from unreal has been deprecated in 5.5 # To get around this, what I have done is call the Editor Utility Library function as a from unreal import # this seems to work correctly, though i still get a deprecation warning. def get_selected_content_browser_assets(): editor_utility = unreal.EditorUtilityLibrary() selected_assets = editor_utility.get_selected_assets() return selected_assets # This way is technically correct and accurate, however it is slightly less easy to modify later # down the road. The newer version allows for a config for easy updating. Otherwise the functionaltiy # is the same #def name_change(asset): #name = asset.get_name() #inheritance is important. Material Instance inherits from Material, so MUST be checked first # if isinstance(asset,unreal.MaterialInstance) and not name.startswith("MI_"): # return "MI_" + asset.get_name() # elif isinstance(asset,unreal.Material) and not name.startswith("M_"): # return "M_" + asset.get_name() # elif isinstance(asset,unreal.Texture) and not name.startswith("T_"): # return "T_" + asset.get_name() # elif isinstance(asset,unreal.NiagaraSystem) and not name.startswith("NS_"): # return "NS_" + asset.get_name() # elif isinstance(asset,unreal.StaticMesh) and not name.startswith("SM_"): # return "SM_" + asset.get_name() # else: # return asset.get_name() def name_change(asset): rename_config = { "prefixes_per_type": [ {"type": unreal.MaterialInstance, "prefix": "MI_"}, {"type": unreal.Material, "prefix": "M_"}, {"type": unreal.Texture, "prefix": "T_"}, {"type": unreal.NiagaraSystem, "prefix": "NS_"}, {"type": unreal.StaticMesh, "prefix": "SM_"}, {"type": unreal.ParticleSystem, "prefix": "C_"} ] } name = asset.get_name() print (f"Asset {name} is a {type(asset)}") for i in range(len(rename_config["prefixes_per_type"])): prefix_config = rename_config["prefixes_per_type"][i] prefix = prefix_config["prefix"] asset_type = prefix_config["type"] if isinstance(asset,asset_type) and not name.startswith(prefix): return prefix + name def rename_assets(assets): for i in assets: asset = i # get the old name, path, and folder information for asset old_name = asset.get_name() asset_old_path = asset.get_path_name() asset_folder = unreal.Paths.get_path(asset_old_path) # set new name and path new_name = name_change(asset) new_path = f"{asset_folder}/{new_name}" print (f"{old_name} -> {new_name}") rename_success = unreal.EditorAssetLibrary.rename_asset(asset_old_path,new_path) if not rename_success: unreal.log_error("Could not rename: " + asset_old_path) def run(): selected_assets = get_selected_content_browser_assets() rename_assets(selected_assets) # it appears super important to have a run function for major functionatliy in python in UE. # I think it may be because the "run" functionality in UE is looking for a "run" function in the python # script. So use this knowledge going forward. 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))
import unreal import pandas as pd def parse_terms(term_string): terms = [] if pd.notna(term_string): term_parts = term_string.split() term_name = term_parts[0] properties = [] for i in range(1, len(term_parts), 2): if i+1 < len(term_parts): prop_name = term_parts[i] prop_value = term_parts[i+1] properties.append({'name': prop_name, 'value': prop_value}) terms.append({'name': term_name, 'properties': properties}) return terms def process_rules(file_path): if not file_path: unreal.log_error("Invalid file path.") return try: df = pd.read_csv(file_path) except Exception as e: unreal.log_error(f"Failed to read CSV file: {e}") return asset_tools = unreal.AssetToolsHelpers.get_asset_tools() for index, row in df.iterrows(): rule_name = f"Rule_{index + 1}" action = row['Action'] input_terms = [] for col in ['Input1', 'Input2']: input_terms += parse_terms(row.get(col, '')) output_terms = [] for col in ['Output1', 'Output2', 'Output3', 'Output4']: output_terms += parse_terms(row.get(col, '')) original_rule_blueprint_path = "/project/" destination_path = "/project/" new_blueprint_name = f"{rule_name}" original_blueprint = unreal.EditorAssetLibrary.load_asset(original_rule_blueprint_path) duplicated_blueprint = asset_tools.duplicate_asset(new_blueprint_name, destination_path, original_blueprint) duplicated_blueprint_generated_class = unreal.EditorAssetLibrary.load_blueprint_class(duplicated_blueprint.get_path_name()) duplicated_blueprint_instance = unreal.get_default_object(duplicated_blueprint_generated_class) if not duplicated_blueprint_instance: unreal.log_error("Duplicated instance is not valid") continue unreal.EditorAssetLibrary.set_editor_property(duplicated_blueprint_instance, "Name", rule_name) unreal.EditorAssetLibrary.set_editor_property(duplicated_blueprint_instance, "Action", action) input_terms_array = unreal.EditorAssetLibrary.get_editor_property(duplicated_blueprint_instance, "InputsBP") output_terms_array = unreal.EditorAssetLibrary.get_editor_property(duplicated_blueprint_instance, "OutputsBP") if input_terms_array is None: input_terms_array = [] if output_terms_array is None: output_terms_array = [] for term in input_terms: term_blueprint = create_iterm_blueprint(term, rule_name) if term_blueprint: input_terms_array.append(term_blueprint) for term in output_terms: term_blueprint = create_oterm_blueprint(term, rule_name) if term_blueprint: output_terms_array.append(term_blueprint) unreal.EditorAssetLibrary.set_editor_property(duplicated_blueprint_instance, "InputsBP", input_terms_array) unreal.EditorAssetLibrary.set_editor_property(duplicated_blueprint_instance, "OutputsBP", output_terms_array) unreal.EditorAssetLibrary.save_asset(duplicated_blueprint.get_path_name()) def create_iterm_blueprint(term, rule_name): asset_tools = unreal.AssetToolsHelpers.get_asset_tools() original_term_blueprint_path = "/project/" term_path = "/project/" new_term_blueprint_name = f"{rule_name}_Input_{term['name']}_BP" original_term_blueprint = unreal.EditorAssetLibrary.load_asset(original_term_blueprint_path) duplicated_term_blueprint = asset_tools.duplicate_asset(new_term_blueprint_name, term_path, original_term_blueprint) duplicated_term_blueprint_generated_class = unreal.EditorAssetLibrary.load_blueprint_class(duplicated_term_blueprint.get_path_name()) duplicated_term_blueprint_instance = unreal.get_default_object(duplicated_term_blueprint_generated_class) if not duplicated_term_blueprint_instance: unreal.log_error("Duplicated term instance is not valid") return None unreal.EditorAssetLibrary.set_editor_property(duplicated_term_blueprint_instance, "Name", term['name']) properties_array = unreal.EditorAssetLibrary.get_editor_property(duplicated_term_blueprint_instance, "PropertiesBP") if properties_array is None: properties_array = [] for prop in term['properties']: prop_blueprint = create_iproperty_blueprint(prop, term['name'], rule_name) if prop_blueprint: properties_array.append(prop_blueprint) unreal.EditorAssetLibrary.set_editor_property(duplicated_term_blueprint_instance, "PropertiesBP", properties_array) unreal.EditorAssetLibrary.save_asset(duplicated_term_blueprint.get_path_name()) return duplicated_term_blueprint_generated_class def create_oterm_blueprint(term, rule_name): asset_tools = unreal.AssetToolsHelpers.get_asset_tools() original_term_blueprint_path = "/project/" term_path = "/project/" new_term_blueprint_name = f"{rule_name}_Output_{term['name']}_BP" original_term_blueprint = unreal.EditorAssetLibrary.load_asset(original_term_blueprint_path) duplicated_term_blueprint = asset_tools.duplicate_asset(new_term_blueprint_name, term_path, original_term_blueprint) duplicated_term_blueprint_generated_class = unreal.EditorAssetLibrary.load_blueprint_class(duplicated_term_blueprint.get_path_name()) duplicated_term_blueprint_instance = unreal.get_default_object(duplicated_term_blueprint_generated_class) if not duplicated_term_blueprint_instance: unreal.log_error("Duplicated term instance is not valid") return None unreal.EditorAssetLibrary.set_editor_property(duplicated_term_blueprint_instance, "Name", term['name']) properties_array = unreal.EditorAssetLibrary.get_editor_property(duplicated_term_blueprint_instance, "PropertiesBP") if properties_array is None: properties_array = [] for prop in term['properties']: prop_blueprint = create_oproperty_blueprint(prop, term['name'], rule_name) if prop_blueprint: properties_array.append(prop_blueprint) unreal.EditorAssetLibrary.set_editor_property(duplicated_term_blueprint_instance, "PropertiesBP", properties_array) unreal.EditorAssetLibrary.save_asset(duplicated_term_blueprint.get_path_name()) return duplicated_term_blueprint_generated_class def create_oproperty_blueprint(prop, term_name, rule_name): asset_tools = unreal.AssetToolsHelpers.get_asset_tools() original_property_blueprint_path = "/project/" property_path = "/project/" new_property_blueprint_name = f"{rule_name}_Output_{term_name}_{prop['name']}_{prop['value']}_BP" original_property_blueprint = unreal.EditorAssetLibrary.load_asset(original_property_blueprint_path) duplicated_property_blueprint = asset_tools.duplicate_asset(new_property_blueprint_name, property_path, original_property_blueprint) duplicated_property_blueprint_generated_class = unreal.EditorAssetLibrary.load_blueprint_class(duplicated_property_blueprint.get_path_name()) duplicated_property_blueprint_instance = unreal.get_default_object(duplicated_property_blueprint_generated_class) if not duplicated_property_blueprint_instance: unreal.log_error("Duplicated property instance is not valid") return None unreal.EditorAssetLibrary.set_editor_property(duplicated_property_blueprint_instance, "Name", prop['name']) unreal.EditorAssetLibrary.set_editor_property(duplicated_property_blueprint_instance, "Value", prop['value']) unreal.EditorAssetLibrary.save_asset(duplicated_property_blueprint.get_path_name()) return duplicated_property_blueprint_generated_class def create_iproperty_blueprint(prop, term_name, rule_name): asset_tools = unreal.AssetToolsHelpers.get_asset_tools() original_property_blueprint_path = "/project/" property_path = "/project/" new_property_blueprint_name = f"{rule_name}_Input_{term_name}_{prop['name']}_{prop['value']}_BP" original_property_blueprint = unreal.EditorAssetLibrary.load_asset(original_property_blueprint_path) duplicated_property_blueprint = asset_tools.duplicate_asset(new_property_blueprint_name, property_path, original_property_blueprint) duplicated_property_blueprint_generated_class = unreal.EditorAssetLibrary.load_blueprint_class(duplicated_property_blueprint.get_path_name()) duplicated_property_blueprint_instance = unreal.get_default_object(duplicated_property_blueprint_generated_class) if not duplicated_property_blueprint_instance: unreal.log_error("Duplicated property instance is not valid") return None unreal.EditorAssetLibrary.set_editor_property(duplicated_property_blueprint_instance, "Name", prop['name']) unreal.EditorAssetLibrary.set_editor_property(duplicated_property_blueprint_instance, "Value", prop['value']) unreal.EditorAssetLibrary.save_asset(duplicated_property_blueprint.get_path_name()) return duplicated_property_blueprint_generated_class # Example usage # file_path = open_file_dialog() # process_rules(file_path)
import unreal import pandas as pd # Define the enum type mapping TYPE_MAPPING = { 'bool': 'BoolProperty', 'string': 'StringProperty', 'int': 'IntProperty' } def open_file_dialog(): dialog = unreal.SystemLibrary.get_editor_property('file_dialog') file_path = dialog.open_file_dialog(None, 'Select File', '', '', 'CSV Files (*.csv)|*.csv', 1) if file_path and len(file_path) > 0: return file_path[0] return "" def process_file(file_path): # Read the CSV file df = pd.read_csv(file_path) # Get the Asset Tools Helper asset_tools = unreal.AssetToolsHelpers.get_asset_tools() # Iterate over each row in the DataFrame for index, row in df.iterrows(): item_name = row['name'] item_description = row['description'] # Define the paths original_item_blueprint_path = "/project/" destination_path = "/project/" new_blueprint_name = f"{item_name}_BP" # Load the original item blueprint original_blueprint = unreal.EditorAssetLibrary.load_asset(original_item_blueprint_path) # Duplicate the item blueprint duplicated_blueprint = asset_tools.duplicate_asset(new_blueprint_name, destination_path, original_blueprint) duplicated_blueprint_generated_class = unreal.EditorAssetLibrary.load_blueprint_class(duplicated_blueprint.get_path_name()) duplicated_blueprint_instance = unreal.get_default_object(duplicated_blueprint_generated_class) # Set the Name and Description duplicated_blueprint_instance.Name = item_name duplicated_blueprint_instance.Description = item_description # Create an actor with the item component actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.Actor, unreal.Vector(0,0,0)) item_component = unreal.GameplayStatics.add_actor_component(actor, unreal.GameItem, item_name) # Assign the component to the duplicated blueprint duplicated_blueprint_instance.AddInstanceComponent(item_component) # Process item properties for i in range(1, 6): prop_type = row.get(f'Property {i} Type') prop_name = row.get(f'Property {i} Name') prop_value = row.get(f'Property {i} Value') if pd.notna(prop_type) and pd.notna(prop_name) and pd.notna(prop_value): prop_enum = TYPE_MAPPING[prop_type] # Duplicate the property blueprint original_property_blueprint_path = "/project/" new_property_blueprint_name = f"{item_name}_{prop_name}_BP" duplicated_property_blueprint = asset_tools.duplicate_asset(new_property_blueprint_name, destination_path, original_property_blueprint_path) duplicated_property_blueprint_generated_class = unreal.EditorAssetLibrary.load_blueprint_class(duplicated_property_blueprint.get_path_name()) duplicated_property_blueprint_instance = unreal.get_default_object(duplicated_property_blueprint_generated_class) # Set the property values duplicated_property_blueprint_instance.Name = prop_name if prop_enum == 'BoolProperty': duplicated_property_blueprint_instance.Value = prop_value.lower() == 'true' elif prop_enum == 'IntProperty': duplicated_property_blueprint_instance.Value = int(prop_value) else: duplicated_property_blueprint_instance.Value = prop_value # Add the property to the duplicated item blueprint duplicated_blueprint_instance.Properties.append(duplicated_property_blueprint_instance) # Save the duplicated item blueprint unreal.EditorAssetLibrary.save_asset(duplicated_blueprint.get_path_name()) # Example usage # file_path = open_file_dialog() # process_file(file_path)
# Copyright Epic Games, Inc. All Rights Reserved # Built-in import sys from pathlib import Path from deadline_utils import get_editor_deadline_globals from deadline_service import DeadlineService # Third-party import unreal plugin_name = "DeadlineService" # Add the actions path to sys path actions_path = Path(__file__).parent.joinpath("service_actions").as_posix() if actions_path not in sys.path: sys.path.append(actions_path) # 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.") # Create a global instance of the deadline service. This is useful for # unreal classes that are not able to save the instance as an # attribute on the class. Because the Deadline Service is a singleton, # any new instance created from the service module will return the global # instance deadline_globals = get_editor_deadline_globals() try: deadline_globals["__deadline_service_instance__"] = DeadlineService() except Exception as err: raise RuntimeError(f"An error occurred creating a Deadline service instance. \n\tError: {str(err)}") from service_actions import submit_job_action # Register the menu from the render queue actions submit_job_action.register_menu_action()
#!/project/ python3 """ Run Sprite Processor - Direct Execution Script ============================================== Simple one-click execution script for the sprite sheet processor. This script provides the easiest way to run the sprite sheet processor from the Unreal Editor. USAGE METHODS: Method 1 - Python Console (Recommended): Copy and paste this line into the Python console: import unreal; exec(open(unreal.Paths.project_dir() + 'PythonScript/run_sprite_processor.py').read()) Method 2 - Editor Scripting: Run this file directly from the Content Browser as a Python script Method 3 - Blueprint Integration: Call execute_sprite_processor() from Blueprint using Python Script component """ import sys import os import unreal def execute_sprite_processor(texture_name="Warrior_Blue", columns=6, rows=8): """ Execute the sprite sheet processor with specified parameters Args: texture_name (str): Name of texture file (without .png extension) columns (int): Number of columns in sprite grid rows (int): Number of rows in sprite grid Returns: bool: True if processing succeeded, False otherwise """ print("\n" + "="*70) print("🎮 SPRITE SHEET PROCESSOR - PYTHON EDITION 🎮") print("="*70) try: # Add script directory to path script_dir = os.path.join(unreal.Paths.project_dir(), 'PythonScript') if script_dir not in sys.path: sys.path.insert(0, script_dir) # Import the processor from sprite_sheet_processor import SpriteSheetProcessor, SpriteSheetInfo print(f"\n📁 Processing sprite sheet: {texture_name}.png") print(f"📐 Grid dimensions: {columns} columns × {rows} rows") print(f"🎯 Expected output: {columns*rows} sprites, {rows} animations") # Check if source file exists project_dir = unreal.Paths.project_dir() source_path = os.path.join(project_dir, "RawAssets", f"{texture_name}.png") if not os.path.exists(source_path): print(f"\n❌ ERROR: Source file not found!") print(f" Expected location: {source_path}") print(f" Please place your {texture_name}.png file in the RawAssets/ folder") return False print(f"✅ Source file found: {source_path}") # Create processor and configuration processor = SpriteSheetProcessor() sprite_info = SpriteSheetInfo(columns=columns, rows=rows) print(f"\n🚀 Starting sprite sheet processing...") # Process the sprite sheet success = processor.process_sprite_sheet(texture_name, sprite_info) if success: print(f"\n🎉 SUCCESS! Sprite sheet processing completed!") print(f"\n📦 Generated Assets:") print(f" 📄 Imported Texture: /Game/{texture_name}") print(f" 🖼️ Individual Sprites: /project/{texture_name}_R*_C*") print(f" 🎬 Flipbook Animations: /project/") print(f" • Idle, Move, AttackSideways, AttackSideways2") print(f" • AttackDownwards, AttackDownwards2") print(f" • AttackUpwards, AttackUpwards2") print(f"\n💡 Assets are now ready to use in your Paper2D project!") else: print(f"\n❌ FAILED: Sprite sheet processing encountered errors") print(f" Check the Output Log for detailed error messages") return success except Exception as e: print(f"\n💥 EXCEPTION: {e}") import traceback traceback.print_exc() return False def quick_warrior_test(): """Quick test with the default Warrior_Blue sprite sheet""" return execute_sprite_processor("Warrior_Blue", 6, 8) def show_help(): """Display help and usage information""" print("\n" + "="*70) print("📖 SPRITE SHEET PROCESSOR - HELP & USAGE") print("="*70) print("\n🎯 PURPOSE:") print(" Convert sprite sheets into Paper2D sprites and flipbook animations") print("\n📋 REQUIREMENTS:") print(" 1. Place sprite sheet PNG in 'RawAssets/' folder") print(" 2. Sprite sheet should follow grid layout (default: 6×8)") print(" 3. Python Editor Scripting plugin enabled") print(" 4. Paper2D plugin enabled") print("\n⚡ QUICK START:") print(" 1. Place 'Warrior_Blue.png' in RawAssets/ folder") print(" 2. Run: quick_warrior_test()") print(" 3. Check /project/ and /project/ for results") print("\n🔧 CUSTOM USAGE:") print(" execute_sprite_processor('YourTexture', columns=6, rows=8)") print("\n📱 DIRECT CONSOLE EXECUTION:") print(" exec(open('PythonScript/run_sprite_processor.py').read())") print("\n🎬 ANIMATION MAPPING (for 8-row sprite sheets):") animations = [ "Row 0 → Idle animation", "Row 1 → Move animation", "Row 2 → AttackSideways animation", "Row 3 → AttackSideways2 animation", "Row 4 → AttackDownwards animation", "Row 5 → AttackDownwards2 animation", "Row 6 → AttackUpwards animation", "Row 7 → AttackUpwards2 animation" ] for anim in animations: print(f" {anim}") def run_interactive(): """Interactive mode for custom sprite sheet processing""" print("\n" + "="*70) print("🎮 INTERACTIVE SPRITE SHEET PROCESSOR") print("="*70) try: # Get texture name texture_name = input("\n📝 Enter texture name (without .png): ").strip() if not texture_name: texture_name = "Warrior_Blue" print(f" Using default: {texture_name}") # Get grid dimensions try: columns = int(input("📐 Enter number of columns (default 6): ").strip() or "6") rows = int(input("📐 Enter number of rows (default 8): ").strip() or "8") except ValueError: columns, rows = 6, 8 print(" Using default grid: 6×8") return execute_sprite_processor(texture_name, columns, rows) except KeyboardInterrupt: print("\n\n⏹️ Operation cancelled by user") return False except Exception as e: print(f"\n❌ Error in interactive mode: {e}") return False # Main execution if __name__ == "__main__": show_help() # Check for Warrior_Blue.png and auto-run if found try: project_dir = unreal.Paths.project_dir() warrior_path = os.path.join(project_dir, "RawAssets", "Warrior_Blue.png") if os.path.exists(warrior_path): print(f"\n✅ Found Warrior_Blue.png, running automatic test...") quick_warrior_test() else: print(f"\n📌 Warrior_Blue.png not found at: {warrior_path}") print(f" Place your sprite sheet in RawAssets/ and run: quick_warrior_test()") except Exception as e: print(f"\n⚠️ Auto-test failed: {e}") else: # Module imported - show available functions print("🐍 Sprite Sheet Processor Module Loaded!") print("Available functions:") print(" • execute_sprite_processor(name, cols, rows) - Process custom sprite sheet") print(" • quick_warrior_test() - Test with Warrior_Blue.png") print(" • show_help() - Display help information") print(" • run_interactive() - Interactive processing mode")
import unreal @unreal.uclass() class ScirptObject(unreal.ToolMenuEntryScript): @unreal.ufunction(override=True) def execute(self, context): super(ScirptObject, self).execute(context) # print("context",context) obj = context.find_by_class(unreal.Object) print (obj) return False # @unreal.ufunction(override=True) # def can_execute(self,context): # super(ScirptObject,self).can_execute(context) # return True @unreal.ufunction(override=True) def get_label(self, context): super(ScirptObject, self).get_label(context) return "测试 entry script" menus = unreal.ToolMenus.get() menu_name = "ContentBrowser.AddNewContextMenu" menu = menus.find_menu(menu_name) # NOTE 如果已经注册则删除 | 否则无法执行 register_menu if menus.is_menu_registered(menu_name): menus.remove_menu(menu_name) menu = menus.register_menu(menu_name) entry = unreal.ToolMenuEntry(type=unreal.MultiBlockType.MENU_ENTRY) entry.set_label("测试 entry") entry.set_string_command( unreal.ToolMenuStringCommandType.PYTHON, "", 'import unreal;unreal.log("menu call")' ) menu.add_menu_entry("", entry) script = ScirptObject() menu.add_menu_entry_object(script)
import unreal file_a = "/project/.fbx" file_b = "/project/.fbx" imported_scenes_path = "/project/" print 'Preparing import options...' advanced_mesh_options = unreal.DatasmithStaticMeshImportOptions() advanced_mesh_options.set_editor_property('max_lightmap_resolution', unreal.DatasmithImportLightmapMax.LIGHTMAP_512) advanced_mesh_options.set_editor_property('min_lightmap_resolution', unreal.DatasmithImportLightmapMin.LIGHTMAP_64) advanced_mesh_options.set_editor_property('generate_lightmap_u_vs', True) advanced_mesh_options.set_editor_property('remove_degenerates', True) base_options = unreal.DatasmithImportBaseOptions() base_options.set_editor_property('include_geometry', True) base_options.set_editor_property('include_material', True) base_options.set_editor_property('include_light', True) base_options.set_editor_property('include_camera', True) base_options.set_editor_property('include_animation', True) base_options.set_editor_property('static_mesh_options', advanced_mesh_options) base_options.set_editor_property('scene_handling', unreal.DatasmithImportScene.CURRENT_LEVEL) base_options.set_editor_property('asset_options', []) # Not used dg_options = unreal.DatasmithDeltaGenImportOptions() dg_options.set_editor_property('merge_nodes', False) dg_options.set_editor_property('optimize_duplicated_nodes', False) dg_options.set_editor_property('remove_invisible_nodes', False) dg_options.set_editor_property('simplify_node_hierarchy', False) dg_options.set_editor_property('import_var', True) dg_options.set_editor_property('var_path', "") dg_options.set_editor_property('import_pos', True) dg_options.set_editor_property('pos_path', "") dg_options.set_editor_property('import_tml', True) dg_options.set_editor_property('tml_path', "") dg_options.set_editor_property('textures_dir', "") dg_options.set_editor_property('intermediate_serialization', unreal.DatasmithDeltaGenIntermediateSerializationType.DISABLED) dg_options.set_editor_property('colorize_materials', False) dg_options.set_editor_property('generate_lightmap_u_vs', False) dg_options.set_editor_property('import_animations', True) # Direct import to scene and assets: print 'Importing directly to scene...' unreal.DeltaGenLibrary.import_(file_a, imported_scenes_path, base_options, None, False) #2-stage import step 1: print 'Parsing to scene object...' scene = unreal.DatasmithDeltaGenSceneElement.construct_datasmith_scene_from_file(file_b, imported_scenes_path, base_options, dg_options) print 'Resulting datasmith scene: ' + str(scene) print '\tProduct name: ' + str(scene.get_product_name()) print '\tMesh actor count: ' + str(len(scene.get_all_mesh_actors())) print '\tLight actor count: ' + str(len(scene.get_all_light_actors())) print '\tCamera actor count: ' + str(len(scene.get_all_camera_actors())) print '\tCustom actor count: ' + str(len(scene.get_all_custom_actors())) print '\tMaterial count: ' + str(len(scene.get_all_materials())) print '\tAnimationTimeline count: ' + str(len(scene.get_all_animation_timelines())) print '\tVariant count: ' + str(len(scene.get_all_variants())) # Modify one of the Timelines # Warning: The Animation nested structure is all USTRUCTs, which are value types, and the Array accessor returns # a copy. Meaning something like timeline[0].name = 'new_name' will set the name on the COPY of anim_nodes[0] timelines = scene.get_all_animation_timelines() if len(timelines) > 0: tim_0 = timelines[0] old_name = tim_0.name print 'Timeline old name: ' + old_name tim_0.name += '_MODIFIED' modified_name = tim_0.name print 'Anim node modified name: ' + modified_name timelines[0] = tim_0 scene.set_all_animation_timelines(timelines) # Check modification new_timelines = scene.get_all_animation_timelines() print 'Anim node retrieved modified name: ' + new_timelines[0].name assert new_timelines[0].name == modified_name, "Node modification didn't work!" # Restore to previous state tim_0 = new_timelines[0] tim_0.name = old_name new_timelines[0] = tim_0 scene.set_all_animation_timelines(new_timelines) # 2-stage import step 2: print 'Importing assets and actors...' result = scene.import_scene() print 'Import results: ' print '\tImported actor count: ' + str(len(result.imported_actors)) print '\tImported mesh count: ' + str(len(result.imported_meshes)) print '\tImported level sequences: ' + str([a.get_name() for a in result.animations]) print '\tImported level variant sets asset: ' + str(result.level_variant_sets.get_name()) if result.import_succeed: print 'Import succeeded!' else: print 'Import failed!'